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 |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
victorrodri04/Eskaera | Example/Example/ViewController.swift | 1 | 2222 | //
// ViewController.swift
// Example
//
// Created by Victor on 04/11/2016.
// Copyright © 2016 Victor Rodriguez. All rights reserved.
//
import UIKit
import Eskaera
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
let httpClient = HTTPClient()
let queue = HTTPRequestQueue(httpClient: httpClient)
let popularPictures = Pictures.Popular
queue.executeTask(popularPictures)
let countries = Countries.name("Germany")
queue.executeTask(countries)
}
}
enum Countries {
case name(_: String)
case alphaCodes(_: [String])
}
extension Countries: Task {
var baseURL: String {
return "https://restcountries.eu/rest/v1"
}
var path: String {
switch self {
case let .name(name):
return "name/\(name)"
case .alphaCodes:
return "alpha"
}
}
var parameters: [String: String] {
switch self {
case .name:
return ["fullText": "true"]
case let .alphaCodes(codes):
return ["codes": codes.joined(separator: ";")]
}
}
func completed(with response: HTTPResponse) {
switch response {
case .success(let data):
guard let data = data else { return }
print(data)
break
case .failure(let error):
print(error)
break
}
}
}
enum Pictures {
case Popular
}
extension Pictures: Task {
var baseURL: String {
return "https://api.500px.com/v1/"
}
var path: String {
return "photos"
}
var parameters: Parameters {
switch self {
case .Popular:
return ["feature": "popular", "consumer_key": "5j9QJ3HSdf3hyu5YLQDjiWPhLPFzbxJV0rHb7uEX"]
}
}
func completed(with response: HTTPResponse) {
switch response {
case .success(let data):
guard let data = data else { return }
print(data)
break
case .failure(let error):
print(error)
break
}
}
}
| mit | d517c58df8fb03a80999d028b1fd6d07 | 20.563107 | 101 | 0.540297 | 4.363458 | false | false | false | false |
codingvirtual/ios_testing | IOSTestingKitchenSink/LessonsConstants.swift | 1 | 786 | //
// LessonsConstants.swift
// IOSTestingKitchenSink
//
// Created by Grant Kemp on 07/09/2015.
// Copyright (c) 2015 Grant Kemp. All rights reserved.
//
import Foundation
class LessonsConstants {
let numberOfLessons = 1
var lesson = [Int:String]()
init() {
lesson[0] = "Hello World"
// Based on http://osherove.com/tdd-kata-1/
lesson[1] = "String Calculator"
lesson[2] = "isPrime"
lesson[3] = "Concantenation"
lesson[4] = "Regex"
}
// MARK: - Shared Instance
class func sharedInstance() -> LessonsConstants {
struct Singleton {
static var sharedInstance = LessonsConstants()
}
return Singleton.sharedInstance
}
}
| cc0-1.0 | 783df9b8450c9a2b09feddde855f3a3e | 19.684211 | 58 | 0.566158 | 4.072539 | false | false | false | false |
sabensm/playgrounds | polymorphism.playground/Contents.swift | 1 | 1323 | //: Playground - noun: a place where people can play
import UIKit
class Shape {
var area: Double?
func calculateArea() {
}
func printArea() {
print("The area is \(area)")
}
}
class Rectangle: Shape {
var width = 1.0
var height = 1.0
init (width: Double, height: Double) {
self.width = width
self.height = height
}
override func calculateArea() {
area = width * height
}
}
class Circle: Shape {
var radius = 1.0
init(radius: Double) {
self.radius = radius
}
override func calculateArea() {
area = 3.14 * radius * radius
}
}
var circle = Circle(radius: 5.0)
var rectangle = Rectangle(width: 20.0, height: 5.0)
circle.calculateArea()
rectangle.calculateArea()
print(circle.area)
print(rectangle.area)
class Enemy {
var hp = 100
var attackPower = 10
init(hp: Int, attack: Int) {
self.hp = hp
self.attackPower = attack
}
func defendAttack(incAttPwr: Int) {
hp -= incAttPwr
}
}
class AngryTroll: Enemy {
var immunity = 10
override func defendAttack(incAttPwr: Int) {
if incAttPwr <= immunity {
hp += 1
} else {
super.defendAttack(incAttPwr)
}
}
} | mit | 406534a5423493bb745084e90ef7bcb9 | 16.421053 | 52 | 0.555556 | 3.654696 | false | false | false | false |
CosmicMind/Material | Sources/iOS/Text/Editor.swift | 3 | 11632 | /*
* The MIT License (MIT)
*
* Copyright (C) 2019, CosmicMind, Inc. <http://cosmicmind.com>.
* 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
public enum EditorPlaceholderAnimation {
case `default`
case hidden
}
open class Editor: View, Themeable {
/// Reference to textView.
public let textView = TextView()
/// A boolean indicating whether the textView is in edit mode.
open var isEditing: Bool {
return textView.isEditing
}
/// A boolean indicating whether the text is empty.
open var isEmpty: Bool {
return textView.isEmpty
}
/// The placeholder UILabel.
@IBInspectable
open var placeholderLabel: UILabel {
return textView.placeholderLabel
}
/// A Boolean that indicates if the placeholder label is animated.
@IBInspectable
open var isPlaceholderAnimated = true
/// Set the placeholder animation value.
open var placeholderAnimation = EditorPlaceholderAnimation.default {
didSet {
updatePlaceholderVisibility()
}
}
/// Placeholder normal text color.
@IBInspectable
open var placeholderNormalColor = Color.darkText.others {
didSet {
updatePlaceholderLabelColor()
}
}
/// Placeholder active text color.
@IBInspectable
open var placeholderActiveColor = Color.blue.base {
didSet {
updatePlaceholderLabelColor()
}
}
/// The scale of the active placeholder in relation to the inactive.
@IBInspectable
open var placeholderActiveScale: CGFloat = 0.75 {
didSet {
layoutPlaceholderLabel()
}
}
/// This property adds a padding to placeholder y position animation
@IBInspectable
open var placeholderVerticalOffset: CGFloat = 0
/// This property adds a padding to placeholder x position animation
@IBInspectable
open var placeholderHorizontalOffset: CGFloat = 0
/// Divider normal height.
@IBInspectable
open var dividerNormalHeight: CGFloat = 1 {
didSet {
updateDividerHeight()
}
}
/// Divider active height.
@IBInspectable
open var dividerActiveHeight: CGFloat = 2 {
didSet {
updateDividerHeight()
}
}
/// Divider normal color.
@IBInspectable
open var dividerNormalColor = Color.grey.lighten2 {
didSet {
updateDividerColor()
}
}
/// Divider active color.
@IBInspectable
open var dividerActiveColor = Color.blue.base {
didSet {
updateDividerColor()
}
}
/// The detailLabel UILabel that is displayed.
@IBInspectable
public let detailLabel = UILabel()
/// The detailLabel text value.
@IBInspectable
open var detail: String? {
get {
return detailLabel.text
}
set(value) {
detailLabel.text = value
layoutSubviews()
}
}
/// The detailLabel text color.
@IBInspectable
open var detailColor = Color.darkText.others {
didSet {
updateDetailLabelColor()
}
}
/// Vertical distance for the detailLabel from the divider.
@IBInspectable
open var detailVerticalOffset: CGFloat = 8 {
didSet {
layoutSubviews()
}
}
/// A reference to titleLabel.textAlignment observation.
private var placeholderLabelTextObserver: NSKeyValueObservation!
/**
A reference to textView.text observation.
Only observes programmatic changes.
*/
private var textViewTextObserver: NSKeyValueObservation!
deinit {
placeholderLabelTextObserver.invalidate()
placeholderLabelTextObserver = nil
textViewTextObserver.invalidate()
textViewTextObserver = nil
}
open override func prepare() {
super.prepare()
backgroundColor = nil
prepareDivider()
prepareTextView()
preparePlaceholderLabel()
prepareDetailLabel()
prepareNotificationHandlers()
applyCurrentTheme()
}
open override func layoutSubviews() {
super.layoutSubviews()
layoutPlaceholderLabel()
layoutDivider()
layoutBottomLabel(label: detailLabel, verticalOffset: detailVerticalOffset)
}
/**
Applies the given theme.
- Parameter theme: A Theme.
*/
open func apply(theme: Theme) {
placeholderActiveColor = theme.secondary
placeholderNormalColor = theme.onSurface.withAlphaComponent(0.38)
dividerActiveColor = theme.secondary
dividerNormalColor = theme.onSurface.withAlphaComponent(0.12)
detailColor = theme.onSurface.withAlphaComponent(0.38)
textView.tintColor = theme.secondary
}
@discardableResult
open override func becomeFirstResponder() -> Bool {
return textView.becomeFirstResponder()
}
@discardableResult
open override func resignFirstResponder() -> Bool {
return textView.resignFirstResponder()
}
}
private extension Editor {
/// Prepares the divider.
func prepareDivider() {
dividerColor = dividerNormalColor
}
/// Prepares the textView.
func prepareTextView() {
layout(textView).edges()
textView.isPlaceholderLabelEnabled = false
textViewTextObserver = textView.observe(\.text) { [weak self] _, _ in
self?.updateEditorState()
}
}
/// Prepares the placeholderLabel.
func preparePlaceholderLabel() {
addSubview(placeholderLabel)
placeholderLabelTextObserver = placeholderLabel.observe(\.text) { [weak self] _, _ in
self?.layoutPlaceholderLabel()
}
}
/// Prepares the detailLabel.
func prepareDetailLabel() {
detailLabel.font = Theme.font.regular(with: 12)
detailLabel.numberOfLines = 0
detailColor = Color.darkText.others
addSubview(detailLabel)
}
/// Prepares the Notification handlers.
func prepareNotificationHandlers() {
let center = NotificationCenter.default
center.addObserver(self, selector: #selector(handleTextViewTextDidBegin), name: UITextView.textDidBeginEditingNotification, object: textView)
center.addObserver(self, selector: #selector(handleTextViewTextDidChange), name: UITextView.textDidChangeNotification, object: textView)
center.addObserver(self, selector: #selector(handleTextViewTextDidEnd), name: UITextView.textDidEndEditingNotification, object: textView)
}
}
private extension Editor {
/// Updates the placeholderLabel text color.
func updatePlaceholderLabelColor() {
tintColor = placeholderActiveColor
placeholderLabel.textColor = isEditing ? placeholderActiveColor : placeholderNormalColor
}
/// Updates the placeholder visibility.
func updatePlaceholderVisibility() {
guard isEditing else {
placeholderLabel.isHidden = !isEmpty && .hidden == placeholderAnimation
return
}
placeholderLabel.isHidden = .hidden == placeholderAnimation
}
/// Updates the dividerColor.
func updateDividerColor() {
dividerColor = isEditing ? dividerActiveColor : dividerNormalColor
}
/// Updates the dividerThickness.
func updateDividerHeight() {
dividerThickness = isEditing ? dividerActiveHeight : dividerNormalHeight
}
/// Updates the detailLabel text color.
func updateDetailLabelColor() {
detailLabel.textColor = detailColor
}
}
private extension Editor {
/// Layout the placeholderLabel.
func layoutPlaceholderLabel() {
let inset = textView.textContainerInsets
let leftPadding = inset.left + textView.textContainer.lineFragmentPadding
let rightPadding = inset.right + textView.textContainer.lineFragmentPadding
let w = bounds.width - leftPadding - rightPadding
var h = placeholderLabel.sizeThatFits(CGSize(width: w, height: .greatestFiniteMagnitude)).height
h = max(h, textView.minimumTextHeight)
h = min(h, bounds.height - inset.top - inset.bottom)
placeholderLabel.bounds.size = CGSize(width: w, height: h)
guard isEditing || !isEmpty || !isPlaceholderAnimated else {
placeholderLabel.transform = CGAffineTransform.identity
placeholderLabel.frame.origin = CGPoint(x: leftPadding, y: inset.top)
return
}
placeholderLabel.transform = CGAffineTransform(scaleX: placeholderActiveScale, y: placeholderActiveScale)
placeholderLabel.frame.origin.y = -placeholderLabel.frame.height + placeholderVerticalOffset
switch placeholderLabel.textAlignment {
case .left, .natural:
placeholderLabel.frame.origin.x = leftPadding + placeholderHorizontalOffset
case .right:
let scaledWidth = w * placeholderActiveScale
placeholderLabel.frame.origin.x = bounds.width - scaledWidth - rightPadding + placeholderHorizontalOffset
default:break
}
}
/// Layout given label at the bottom with the vertical offset provided.
func layoutBottomLabel(label: UILabel, verticalOffset: CGFloat) {
let c = dividerContentEdgeInsets
label.frame.origin.x = c.left
label.frame.origin.y = bounds.height + verticalOffset
label.frame.size.width = bounds.width - c.left - c.right
label.frame.size.height = label.sizeThatFits(CGSize(width: label.bounds.width, height: .greatestFiniteMagnitude)).height
}
}
private extension Editor {
/// Notification handler for when text editing began.
@objc
func handleTextViewTextDidBegin() {
updateEditorState(isAnimated: true)
}
/// Notification handler for when text changed.
@objc
func handleTextViewTextDidChange() {
updateEditorState()
}
/// Notification handler for when text editing ended.
@objc
func handleTextViewTextDidEnd() {
updateEditorState(isAnimated: true)
}
/// Updates editor.
func updateEditorState(isAnimated: Bool = false) {
updatePlaceholderVisibility()
updatePlaceholderLabelColor()
updateDividerHeight()
updateDividerColor()
guard isAnimated && isPlaceholderAnimated else {
layoutPlaceholderLabel()
return
}
UIView.animate(withDuration: 0.15, animations: layoutPlaceholderLabel)
}
}
public extension Editor {
/// A reference to the textView text.
var text: String! {
get {
return textView.text
}
set(value) {
textView.text = value
}
}
/// A reference to the textView font.
var font: UIFont? {
get {
return textView.font
}
set(value) {
textView.font = value
}
}
/// A reference to the textView placeholder.
var placeholder: String? {
get {
return textView.placeholder
}
set(value) {
textView.placeholder = value
}
}
/// A reference to the textView textAlignment.
var textAlignment: NSTextAlignment {
get {
return textView.textAlignment
}
set(value) {
textView.textAlignment = value
detailLabel.textAlignment = value
}
}
}
| mit | 2bc105f5692d1adf206e4f82adddb1a9 | 27.028916 | 145 | 0.709336 | 4.983719 | false | false | false | false |
SereivoanYong/Charts | Source/Charts/Components/Legend.Entry.swift | 1 | 2111 | //
// LegendEntry.swift
// Charts
//
// Copyright 2015 Daniel Cohen Gindi & Philipp Jahoda
// A port of MPAndroidChart for iOS
// Licensed under Apache License 2.0
//
// https://github.com/danielgindi/Charts
//
import Foundation
extension Legend {
public struct Entry {
/// - parameter label: The legend entry text.
/// A `nil` label will start a group.
/// - parameter form: The form to draw for this entry. Set to nil to use the legend's default.
/// - parameter formSize: Set to nil to use the legend's default.
/// - parameter formLineWidth: Set to nil to use the legend's default.
/// - parameter formLineDash: Set to nil to use the legend's default.
/// - parameter formColor: The color for drawing the form.
public init(label: String?, form: Form?, formSize: CGFloat?, formLineWidth: CGFloat?, formLineDash: CGLineDash?, formColor: UIColor?) {
self.label = label
self.form = form
self.formSize = formSize
self.formLineWidth = formLineWidth
self.formLineDash = formLineDash
self.formColor = formColor
}
/// The legend entry text.
/// A `nil` label will start a group.
public let label: String?
/// The form to draw for this entry.
///
/// `None` will avoid drawing a form, and any related space.
/// `Empty` will avoid drawing a form, but keep its space.
public let form: Legend.Form?
/// Form size will be considered except for when .None is used
///
/// Set as NaN to use the legend's default
public let formSize: CGFloat?
/// Line width used for shapes that consist of lines.
///
/// Set to nil to use the legend's default.
public let formLineWidth: CGFloat?
/// Line dash used for shapes that consist of lines.
///
/// Set to nil to use the legend's default.
public let formLineDash: CGLineDash?
/// The color for drawing the form
public let formColor: UIColor?
}
}
| apache-2.0 | 2d8cb8389e9374d6fcdca6282fa18c93 | 31.984375 | 139 | 0.609664 | 4.569264 | false | false | false | false |
iDevelopper/PBRevealViewController | Example3Swift/Example3Swift/MenuTableViewController.swift | 1 | 3446 | //
// MenuTableViewController.swift
// Example3Swift
//
// Created by Patrick BODET on 06/08/2016.
// Copyright © 2016 iDevelopper. All rights reserved.
//
import UIKit
class MenuTableViewController: UITableViewController {
override func viewDidLoad() {
super.viewDidLoad()
tableView.backgroundColor = UIColor.clear
// No separator where there aren't cells
tableView.tableFooterView = UIView(frame: CGRect.zero)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: - Table view data source
override func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 5
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath)
cell.backgroundColor = UIColor.clear
cell.textLabel?.textColor = UIColor.white
switch (indexPath as NSIndexPath).row {
case 0:
cell.textLabel!.text = "None"
case 1:
cell.textLabel!.text = "CrossDissolve"
case 2:
cell.textLabel!.text = "PushSideView"
case 3:
cell.textLabel!.text = "Spring"
case 4:
cell.textLabel!.text = "Custom"
default:
break
}
return cell
}
// MARK: - Table view delegate
override func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
}
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
tableView.deselectRow(at: indexPath, animated: true)
let storyboard = UIStoryboard(name: "Main", bundle: nil)
let mainViewController = storyboard.instantiateViewController(withIdentifier: "MainViewController") as! MainViewController
switch (indexPath as NSIndexPath).row {
case 0:
self.revealViewController().toggleAnimationType = PBRevealToggleAnimationType.none
mainViewController.image = UIImage(named: "Sunset1")
case 1:
self.revealViewController().toggleAnimationType = PBRevealToggleAnimationType.crossDissolve
mainViewController.image = UIImage(named: "Sunset2")
case 2:
self.revealViewController().toggleAnimationType = PBRevealToggleAnimationType.pushSideView
mainViewController.image = UIImage(named: "Sunset3")
case 3:
self.revealViewController().toggleAnimationType = PBRevealToggleAnimationType.spring
mainViewController.image = UIImage(named: "Sunset4")
case 4:
self.revealViewController().toggleAnimationType = PBRevealToggleAnimationType.custom
mainViewController.image = UIImage(named: "Sunset5")
default: break
}
let nc = UINavigationController(rootViewController: mainViewController)
revealViewController().pushMainViewController(nc, animated:true)
}
}
| mit | aa07f1f53b0253b868ac34ea19909a77 | 31.809524 | 130 | 0.633672 | 5.684818 | false | false | false | false |
Swinject/SwinjectMVVMExample | Carthage/Checkouts/ReactiveSwift/Sources/Scheduler.swift | 2 | 16563 | //
// Scheduler.swift
// ReactiveSwift
//
// Created by Justin Spahr-Summers on 2014-06-02.
// Copyright (c) 2014 GitHub. All rights reserved.
//
import Dispatch
import Foundation
#if os(Linux)
import let CDispatch.NSEC_PER_SEC
#endif
/// Represents a serial queue of work items.
public protocol SchedulerProtocol {
/// Enqueues an action on the scheduler.
///
/// When the work is executed depends on the scheduler in use.
///
/// - returns: Optional `Disposable` that can be used to cancel the work
/// before it begins.
@discardableResult
func schedule(_ action: @escaping () -> Void) -> Disposable?
}
/// A particular kind of scheduler that supports enqueuing actions at future
/// dates.
public protocol DateSchedulerProtocol: SchedulerProtocol {
/// The current date, as determined by this scheduler.
///
/// This can be implemented to deterministically return a known date (e.g.,
/// for testing purposes).
var currentDate: Date { get }
/// Schedules an action for execution at or after the given date.
///
/// - parameters:
/// - date: Starting time.
/// - action: Closure of the action to perform.
///
/// - returns: Optional `Disposable` that can be used to cancel the work
/// before it begins.
@discardableResult
func schedule(after date: Date, action: @escaping () -> Void) -> Disposable?
/// Schedules a recurring action at the given interval, beginning at the
/// given date.
///
/// - parameters:
/// - date: Starting time.
/// - repeatingEvery: Repetition interval.
/// - withLeeway: Some delta for repetition.
/// - action: Closure of the action to perform.
///
/// - returns: Optional `Disposable` that can be used to cancel the work
/// before it begins.
@discardableResult
func schedule(after date: Date, interval: TimeInterval, leeway: TimeInterval, action: @escaping () -> Void) -> Disposable?
}
/// A scheduler that performs all work synchronously.
public final class ImmediateScheduler: SchedulerProtocol {
public init() {}
/// Immediately calls passed in `action`.
///
/// - parameters:
/// - action: Closure of the action to perform.
///
/// - returns: `nil`.
@discardableResult
public func schedule(_ action: @escaping () -> Void) -> Disposable? {
action()
return nil
}
}
/// A scheduler that performs all work on the main queue, as soon as possible.
///
/// If the caller is already running on the main queue when an action is
/// scheduled, it may be run synchronously. However, ordering between actions
/// will always be preserved.
public final class UIScheduler: SchedulerProtocol {
private static let dispatchSpecificKey = DispatchSpecificKey<UInt8>()
private static let dispatchSpecificValue = UInt8.max
private static var __once: () = {
DispatchQueue.main.setSpecific(key: UIScheduler.dispatchSpecificKey,
value: dispatchSpecificValue)
}()
#if os(Linux)
private var queueLength: Atomic<Int32> = Atomic(0)
#else
private var queueLength: Int32 = 0
#endif
/// Initializes `UIScheduler`
public init() {
/// This call is to ensure the main queue has been setup appropriately
/// for `UIScheduler`. It is only called once during the application
/// lifetime, since Swift has a `dispatch_once` like mechanism to
/// lazily initialize global variables and static variables.
_ = UIScheduler.__once
}
/// Queues an action to be performed on main queue. If the action is called
/// on the main thread and no work is queued, no scheduling takes place and
/// the action is called instantly.
///
/// - parameters:
/// - action: Closure of the action to perform on the main thread.
///
/// - returns: `Disposable` that can be used to cancel the work before it
/// begins.
@discardableResult
public func schedule(_ action: @escaping () -> Void) -> Disposable? {
let disposable = SimpleDisposable()
let actionAndDecrement = {
if !disposable.isDisposed {
action()
}
#if os(Linux)
self.queueLength.modify { $0 -= 1 }
#else
OSAtomicDecrement32(&self.queueLength)
#endif
}
#if os(Linux)
let queued = self.queueLength.modify { value -> Int32 in
value += 1
return value
}
#else
let queued = OSAtomicIncrement32(&queueLength)
#endif
// If we're already running on the main queue, and there isn't work
// already enqueued, we can skip scheduling and just execute directly.
if queued == 1 && DispatchQueue.getSpecific(key: UIScheduler.dispatchSpecificKey) == UIScheduler.dispatchSpecificValue {
actionAndDecrement()
} else {
DispatchQueue.main.async(execute: actionAndDecrement)
}
return disposable
}
}
/// A scheduler backed by a serial GCD queue.
public final class QueueScheduler: DateSchedulerProtocol {
/// A singleton `QueueScheduler` that always targets the main thread's GCD
/// queue.
///
/// - note: Unlike `UIScheduler`, this scheduler supports scheduling for a
/// future date, and will always schedule asynchronously (even if
/// already running on the main thread).
public static let main = QueueScheduler(internalQueue: DispatchQueue.main)
public var currentDate: Date {
return Date()
}
public let queue: DispatchQueue
internal init(internalQueue: DispatchQueue) {
queue = internalQueue
}
/// Initializes a scheduler that will target the given queue with its
/// work.
///
/// - note: Even if the queue is concurrent, all work items enqueued with
/// the `QueueScheduler` will be serial with respect to each other.
///
/// - warning: Obsoleted in OS X 10.11
@available(OSX, deprecated:10.10, obsoleted:10.11, message:"Use init(qos:name:targeting:) instead")
@available(iOS, deprecated:8.0, obsoleted:9.0, message:"Use init(qos:name:targeting:) instead.")
public convenience init(queue: DispatchQueue, name: String = "org.reactivecocoa.ReactiveSwift.QueueScheduler") {
self.init(internalQueue: DispatchQueue(label: name, target: queue))
}
/// Initializes a scheduler that creates a new serial queue with the
/// given quality of service class.
///
/// - parameters:
/// - qos: Dispatch queue's QoS value.
/// - name: Name for the queue in the form of reverse domain.
/// - targeting: (Optional) The queue on which this scheduler's work is
/// targeted
@available(OSX 10.10, *)
public convenience init(
qos: DispatchQoS = .default,
name: String = "org.reactivecocoa.ReactiveSwift.QueueScheduler",
targeting targetQueue: DispatchQueue? = nil
) {
self.init(internalQueue: DispatchQueue(
label: name,
qos: qos,
target: targetQueue
))
}
/// Schedules action for dispatch on internal queue
///
/// - parameters:
/// - action: Closure of the action to schedule.
///
/// - returns: `Disposable` that can be used to cancel the work before it
/// begins.
@discardableResult
public func schedule(_ action: @escaping () -> Void) -> Disposable? {
let d = SimpleDisposable()
queue.async {
if !d.isDisposed {
action()
}
}
return d
}
private func wallTime(with date: Date) -> DispatchWallTime {
let (seconds, frac) = modf(date.timeIntervalSince1970)
let nsec: Double = frac * Double(NSEC_PER_SEC)
let walltime = timespec(tv_sec: Int(seconds), tv_nsec: Int(nsec))
return DispatchWallTime(timespec: walltime)
}
/// Schedules an action for execution at or after the given date.
///
/// - parameters:
/// - date: Starting time.
/// - action: Closure of the action to perform.
///
/// - returns: Optional `Disposable` that can be used to cancel the work
/// before it begins.
@discardableResult
public func schedule(after date: Date, action: @escaping () -> Void) -> Disposable? {
let d = SimpleDisposable()
queue.asyncAfter(wallDeadline: wallTime(with: date)) {
if !d.isDisposed {
action()
}
}
return d
}
/// Schedules a recurring action at the given interval and beginning at the
/// given start time. A reasonable default timer interval leeway is
/// provided.
///
/// - parameters:
/// - date: Date to schedule the first action for.
/// - repeatingEvery: Repetition interval.
/// - action: Closure of the action to repeat.
///
/// - returns: Optional disposable that can be used to cancel the work
/// before it begins.
@discardableResult
public func schedule(after date: Date, interval: TimeInterval, action: @escaping () -> Void) -> Disposable? {
// Apple's "Power Efficiency Guide for Mac Apps" recommends a leeway of
// at least 10% of the timer interval.
return schedule(after: date, interval: interval, leeway: interval * 0.1, action: action)
}
/// Schedules a recurring action at the given interval with provided leeway,
/// beginning at the given start time.
///
/// - parameters:
/// - date: Date to schedule the first action for.
/// - repeatingEvery: Repetition interval.
/// - leeway: Some delta for repetition interval.
/// - action: Closure of the action to repeat.
///
/// - returns: Optional `Disposable` that can be used to cancel the work
/// before it begins.
@discardableResult
public func schedule(after date: Date, interval: TimeInterval, leeway: TimeInterval, action: @escaping () -> Void) -> Disposable? {
precondition(interval >= 0)
precondition(leeway >= 0)
let msecInterval = interval * 1000
let msecLeeway = leeway * 1000
let timer = DispatchSource.makeTimerSource(
flags: DispatchSource.TimerFlags(rawValue: UInt(0)),
queue: queue
)
timer.scheduleRepeating(wallDeadline: wallTime(with: date),
interval: .milliseconds(Int(msecInterval)),
leeway: .milliseconds(Int(msecLeeway)))
timer.setEventHandler(handler: action)
timer.resume()
return ActionDisposable {
timer.cancel()
}
}
}
/// A scheduler that implements virtualized time, for use in testing.
public final class TestScheduler: DateSchedulerProtocol {
private final class ScheduledAction {
let date: Date
let action: () -> Void
init(date: Date, action: @escaping () -> Void) {
self.date = date
self.action = action
}
func less(_ rhs: ScheduledAction) -> Bool {
return date.compare(rhs.date) == .orderedAscending
}
}
private let lock = NSRecursiveLock()
private var _currentDate: Date
/// The virtual date that the scheduler is currently at.
public var currentDate: Date {
let d: Date
lock.lock()
d = _currentDate
lock.unlock()
return d
}
private var scheduledActions: [ScheduledAction] = []
/// Initializes a TestScheduler with the given start date.
///
/// - parameters:
/// - startDate: The start date of the scheduler.
public init(startDate: Date = Date(timeIntervalSinceReferenceDate: 0)) {
lock.name = "org.reactivecocoa.ReactiveSwift.TestScheduler"
_currentDate = startDate
}
private func schedule(_ action: ScheduledAction) -> Disposable {
lock.lock()
scheduledActions.append(action)
scheduledActions.sort { $0.less($1) }
lock.unlock()
return ActionDisposable {
self.lock.lock()
self.scheduledActions = self.scheduledActions.filter { $0 !== action }
self.lock.unlock()
}
}
/// Enqueues an action on the scheduler.
///
/// - note: The work is executed on `currentDate` as it is understood by the
/// scheduler.
///
/// - parameters:
/// - action: An action that will be performed on scheduler's
/// `currentDate`.
///
/// - returns: Optional `Disposable` that can be used to cancel the work
/// before it begins.
@discardableResult
public func schedule(_ action: @escaping () -> Void) -> Disposable? {
return schedule(ScheduledAction(date: currentDate, action: action))
}
/// Schedules an action for execution at or after the given date.
///
/// - parameters:
/// - date: Starting date.
/// - action: Closure of the action to perform.
///
/// - returns: Optional disposable that can be used to cancel the work
/// before it begins.
@discardableResult
public func schedule(after delay: TimeInterval, action: @escaping () -> Void) -> Disposable? {
return schedule(after: currentDate.addingTimeInterval(delay), action: action)
}
@discardableResult
public func schedule(after date: Date, action: @escaping () -> Void) -> Disposable? {
return schedule(ScheduledAction(date: date, action: action))
}
/// Schedules a recurring action at the given interval, beginning at the
/// given start time
///
/// - parameters:
/// - date: Date to schedule the first action for.
/// - repeatingEvery: Repetition interval.
/// - action: Closure of the action to repeat.
///
/// - returns: Optional `Disposable` that can be used to cancel the work
/// before it begins.
private func schedule(after date: Date, interval: TimeInterval, disposable: SerialDisposable, action: @escaping () -> Void) {
precondition(interval >= 0)
disposable.innerDisposable = schedule(after: date) { [unowned self] in
action()
self.schedule(after: date.addingTimeInterval(interval), interval: interval, disposable: disposable, action: action)
}
}
/// Schedules a recurring action at the given interval, beginning at the
/// given interval (counted from `currentDate`).
///
/// - parameters:
/// - interval: Interval to add to `currentDate`.
/// - repeatingEvery: Repetition interval.
/// - leeway: Some delta for repetition interval.
/// - action: Closure of the action to repeat.
///
/// - returns: Optional `Disposable` that can be used to cancel the work
/// before it begins.
@discardableResult
public func schedule(after delay: TimeInterval, interval: TimeInterval, leeway: TimeInterval = 0, action: @escaping () -> Void) -> Disposable? {
return schedule(after: currentDate.addingTimeInterval(delay), interval: interval, leeway: leeway, action: action)
}
/// Schedules a recurring action at the given interval with
/// provided leeway, beginning at the given start time.
///
/// - parameters:
/// - date: Date to schedule the first action for.
/// - repeatingEvery: Repetition interval.
/// - leeway: Some delta for repetition interval.
/// - action: Closure of the action to repeat.
///
/// - returns: Optional `Disposable` that can be used to cancel the work
/// before it begins.
public func schedule(after date: Date, interval: TimeInterval, leeway: TimeInterval = 0, action: @escaping () -> Void) -> Disposable? {
let disposable = SerialDisposable()
schedule(after: date, interval: interval, disposable: disposable, action: action)
return disposable
}
/// Advances the virtualized clock by an extremely tiny interval, dequeuing
/// and executing any actions along the way.
///
/// This is intended to be used as a way to execute actions that have been
/// scheduled to run as soon as possible.
public func advance() {
advance(by: Double.ulpOfOne)
}
/// Advances the virtualized clock by the given interval, dequeuing and
/// executing any actions along the way.
///
/// - parameters:
/// - interval: Interval by which the current date will be advanced.
public func advance(by interval: TimeInterval) {
lock.lock()
advance(to: currentDate.addingTimeInterval(interval))
lock.unlock()
}
/// Advances the virtualized clock to the given future date, dequeuing and
/// executing any actions up until that point.
///
/// - parameters:
/// - newDate: Future date to which the virtual clock will be advanced.
public func advance(to newDate: Date) {
lock.lock()
assert(currentDate.compare(newDate) != .orderedDescending)
while scheduledActions.count > 0 {
if newDate.compare(scheduledActions[0].date) == .orderedAscending {
break
}
_currentDate = scheduledActions[0].date
let scheduledAction = scheduledActions.remove(at: 0)
scheduledAction.action()
}
_currentDate = newDate
lock.unlock()
}
/// Dequeues and executes all scheduled actions, leaving the scheduler's
/// date at `NSDate.distantFuture()`.
public func run() {
advance(to: Date.distantFuture)
}
/// Rewinds the virtualized clock by the given interval.
/// This simulates that user changes device date.
///
/// - parameters:
/// - interval: Interval by which the current date will be retreated.
public func rewind(by interval: TimeInterval) {
lock.lock()
let newDate = currentDate.addingTimeInterval(-interval)
assert(currentDate.compare(newDate) != .orderedAscending)
_currentDate = newDate
lock.unlock()
}
}
| mit | 797f09598794195c45b1b28bef222e7d | 31.03675 | 145 | 0.687738 | 3.909134 | false | false | false | false |
hectormatos2011/Bite-About-It | Bite-About-It/Bite About It/APIOperation.swift | 1 | 1773 | //
// APIOperation.swift
// Bite About It
//
// Created by Hector Matos on 8/30/17.
// Copyright © 2017 Hector Matos. All rights reserved.
//
import Foundation
/** MY FIRST SUB, YO. FREAKING THANK YOU, MOFEAR. This superclass of all superclasses is dedicated to you.
*/
public class APIOperation<SuccessType>: Operation {
override public var isAsynchronous: Bool { return false }
override public var isExecuting: Bool { return _executing }
override public var isFinished: Bool { return _finished }
var result: Result<SuccessType>!
private var _executing = false {
willSet { willChangeValue(forKey: "isExecuting") }
didSet { didChangeValue(forKey: "isExecuting") }
}
private var _finished = false {
willSet { willChangeValue(forKey: "isFinished") }
didSet { didChangeValue(forKey: "isFinished") }
}
public func start(completion: @escaping (Result<SuccessType>) -> Void) {
self.completionBlock = { [weak self] in
guard let `self` = self else {
completion(.failure("Operation doesn't exist"))
return
}
completion(self.result)
}
start()
}
override public func start() {
guard !isCancelled else {
finish(result: .failure("Operation was cancelled"))
return
}
_executing = true
execute()
}
func execute() {
fatalError("The function execute() must be overriden")
}
//Type = (Result<SuccessType>) -> Void
func finish(result: Result<SuccessType>) -> Void {
self.result = result
_executing = false
_finished = true
}
}
extension String: Error {}
| mit | d41251e09cb350dd6b1e90b579e1d1c3 | 26.6875 | 106 | 0.595372 | 4.578811 | false | false | false | false |
anatoliyv/RevealMenuController | RevealMenuController/Classes/RevealMenuController.swift | 1 | 13058 | //
// ActionSheetController.swift
// Pods
//
// Created by Anatoliy Voropay on 8/30/16.
//
import UIKit
/// Controller used to display list of items similar to ActionScheet style in `UIAlertController`.
/// Main purpose is to have possibility to group elements and support image icons besides
/// menu item text.
///
/// Basic usage example:
///
/// ```
/// let revealController = RevealMenuController(title: "Contact Support", position: .Center)
/// let webImage = UIImage(named: "IconHome")
/// let emailImage = UIImage(named: "IconEmail")
/// let phoneImage = UIImage(named: "IconCall")
///
/// let webAction = RevealMenuAction(title: "Open web page", image: webImage, handler: { (controller, action) in })
/// revealController.addAction(webAction)
///
/// // Add first group
/// let techGroup = RevealMenuActionGroup(title: "Contact tech. support", actions: [
/// RevealMenuAction(title: "[email protected]", image: emailImage, handler: { (controller, action) in }),
/// RevealMenuAction(title: "1-866-752-7753", image: phoneImage, handler: { (controller, action) in })
/// ])
/// revealController.addAction(techGroup)
///
/// // Add second group
/// let customersGroup = RevealMenuActionGroup(title: "Contact custommers support", actions: [
/// RevealMenuAction(title: "[email protected]", image: emailImage, handler: { (controller, action) in }),
/// RevealMenuAction(title: "1-800-676-2775", image: phoneImage, handler: { (controller, action) in })
/// ])
/// revealController.addAction(customersGroup)
///
/// // Display controller
/// revealController.displayOnController(self)
/// ```
open class RevealMenuController: UIViewController {
/// Position of a menu on a screen. Each position has it's own appearance animation.
///
/// - Parameter top: Menu is on a top of a screen. Appearance animation is top-to-bottom.
/// - Parameter center: Menu is on the center of a screen. Appearance animation is fade-in.
/// - Parameter bottom: Menu is on the bottom of a screen. Appearance animation is bottom-to-top.
public enum Position {
case top
case center
case bottom
}
/// Position of a menu. Default is `Bottom`
open var position: Position = .bottom
/// If `true` cancel menu item will exists in a bottom of a list.
/// Default value is `true`
open var displayCancel: Bool = true
/// If `true` controller will hide if tap outside of items area.
/// Default value is `true`
open var hideOnBackgorundTap: Bool = true
/// Default status bar style
open var statusBarStyle: UIStatusBarStyle = .lightContent
private struct Constants {
static let cellIdentifier = "RevealMenuCell"
static let sideMargin = CGFloat(20)
static let cellHeight = CGFloat(44)
}
/// Actions and/or ActionGgroups that will be displayed.
///
/// - Seealso: `RevealMenuAction`, `RevealMenuActionGroup`
private var items: [RevealMenuActionProtocol] = []
private var openedItems: [RevealMenuActionGroup] = []
/// Representation of active menu items array containing opened groups and
/// other actions.
private var itemsList: [RevealMenuActionProtocol] {
var list: [RevealMenuActionProtocol] = []
for item in items {
if let action = item as? RevealMenuAction {
list.append(action)
} else if let actionGroup = item as? RevealMenuActionGroup {
list.append(actionGroup)
if openedItems.filter({ $0 === actionGroup }).count > 0 {
list.append(contentsOf: actionGroup.actions.map({ (action) -> RevealMenuAction in
return action
}))
}
}
}
return list
}
private lazy var tableView: UITableView = {
let tableView = UITableView(frame: CGRect.zero, style: .plain)
tableView.separatorStyle = .none
tableView.backgroundColor = UIColor.clear
tableView.delegate = self
tableView.dataSource = self
tableView.alwaysBounceVertical = false
tableView.showsVerticalScrollIndicator = false
return tableView
}()
// MARK: - Lifecycle
public init(title: String?, position: Position) {
super.init(nibName: nil, bundle: nil)
self.title = title
self.position = position
}
required public init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
open override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = .clear
registerNibWithName(Constants.cellIdentifier)
let recognizer = UITapGestureRecognizer(target: self, action: #selector(pressedBackground(_:)))
view.addGestureRecognizer(recognizer)
}
private func registerNibWithName(_ name: String) {
let cellNibItem = UINib(nibName: name, bundle: Bundle(for: RevealMenuController.self))
tableView.register(cellNibItem, forCellReuseIdentifier: name)
}
// MARK: - Adding actions
/// Add `RevealMenuAction` or `RevealMenuActionGroup` to current actions array.
///
/// - Seealso: `RevealMenuAction`, `RevealMenuActionGroup`
open func addAction<T: RevealMenuActionProtocol>(_ item: T) {
items.append(item)
}
// MARK: - Appearance and Disappeance
/// Display `RevealMenuController` on a controller with or without animation and completion block.
///
/// - Parameter controller: RevealMenuController will be displayed in this controller
/// - Parameter animated: Will have appearance animation if `true`
/// - Parameter completion: Gets called once appearance animation finished
open func displayOnController(
_ controller: UIViewController, animated: Bool = true, completion: (() -> Void)? = nil) {
modalPresentationStyle = .overCurrentContext
addTableView()
updateTableViewFrame(true)
controller.present(
self,
animated: false,
completion: {
let timeInterval = TimeInterval(animated
? 0.2
: 0)
UIView.animate(withDuration: timeInterval, animations: {
self.updateTableViewFrame(false)
}, completion: { _ in
completion?()
})
})
}
private func addTableView() {
view.addSubview(tableView)
tableView.reloadData()
}
/// Dismiss view controller with animation and completion handler.
open override func dismiss(animated: Bool, completion: (() -> Void)?) {
let timeInterval = TimeInterval(animated
? 0.2
: 0)
UIView.animate(
withDuration: timeInterval,
animations: {
self.updateTableViewFrame(true)
}, completion: { _ in
super.dismiss(animated: false, completion: {
completion?()
})
})
}
private var contentHeight: CGFloat {
var height: CGFloat = CGFloat(Constants.cellHeight) * CGFloat(itemsList.count)
height += displayCancel
? CGFloat(Constants.cellHeight) + 10
: 0
return height
}
private func updateTableViewFrame(_ initial: Bool) {
tableView.alpha = initial
? 0
: 1
var insets: UIEdgeInsets = .zero
if #available(iOS 11.0, *) {
insets = view.safeAreaInsets
}
var width = min(view.bounds.height, view.bounds.width)
var height = max(view.bounds.height, view.bounds.width)
if view.bounds.height < view.bounds.width {
(width, height) = (height, width)
}
let sideSpacing: CGFloat = UIDevice.current.userInterfaceIdiom == .pad
? width / 4
: Constants.sideMargin
let contentHeight = self.contentHeight
var rect: CGRect = .zero
switch position {
case .top:
rect = CGRect(
x: sideSpacing, y: Constants.sideMargin + insets.top,
width: width - 2 * sideSpacing, height: contentHeight)
case .bottom:
rect = CGRect(
x: sideSpacing, y: height - Constants.sideMargin - insets.top - contentHeight,
width: width - 2 * sideSpacing, height: contentHeight)
case .center:
rect = CGRect(
x: sideSpacing,
y: (height - insets.top - contentHeight) / 2,
width: width - 2 * sideSpacing, height: contentHeight)
}
if initial {
switch position {
case .top:
rect = rect.offsetBy(dx: 0, dy: -contentHeight)
case .bottom:
rect = rect.offsetBy(dx: 0, dy: contentHeight)
case .center:
break
}
}
tableView.frame = rect
}
// MARK: - Actions
@objc func pressedBackground(_ sender: AnyObject?) {
guard hideOnBackgorundTap else { return }
dismiss(animated: true, completion: nil)
}
// MARK: - Position table view
open override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) {
super.viewWillTransition(to: size, with: coordinator)
coordinator.animate(alongsideTransition: { _ in
self.updateTableViewFrame(false)
}, completion: nil)
}
}
/// `UITableViewDelegate` protocol implementation
extension RevealMenuController: UITableViewDelegate {
public func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return Constants.cellHeight
}
public func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
guard section != 0 else { return 0 }
return displayCancel
? Constants.sideMargin / 2
: 0
}
}
/// `UITableViewDataSource` protocol implementation
extension RevealMenuController: UITableViewDataSource {
public func numberOfSections(in tableView: UITableView) -> Int {
return displayCancel
? 2
: 1
}
public func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
guard section == 0 else { return 1 }
return itemsList.count
}
public func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: Constants.cellIdentifier, for: indexPath) as! RevealMenuCell
if (indexPath as NSIndexPath).section == 1 {
cell.customizeForCancel()
} else {
let offset = (indexPath as NSIndexPath).row
if let action = itemsList[offset] as? RevealMenuAction {
cell.customizeFor(action: action)
} else if let actionGroup = itemsList[offset] as? RevealMenuActionGroup {
cell.customizeFor(actionGroup: actionGroup)
}
}
cell.customizeCorners(
topCornered: (indexPath as NSIndexPath).row == 0,
bottomCornered: (indexPath as NSIndexPath).section == 1 ||
(indexPath as NSIndexPath).row == itemsList.count - 1)
cell.delegate = self
return cell
}
public func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
return UIView(frame: CGRect.zero)
}
}
/// `RevealMenuCellDelegate` protocol implementation
extension RevealMenuController: RevealMenuCellDelegate {
public func revealMenuCell(_ cell: RevealMenuCell, didPressedWithItem item: RevealMenuActionProtocol) {
if let action = item as? RevealMenuAction {
action.handler?(self, action)
} else if let actionGroup = item as? RevealMenuActionGroup {
if let index = openedItems.index(where: { $0 === actionGroup }) {
openedItems.remove(at: index)
tableView.reloadData()
UIView.animate(
withDuration: 0.2,
animations: {
self.updateTableViewFrame(false)
})
} else {
openedItems.append(actionGroup)
tableView.reloadData()
UIView.animate(
withDuration: 0.2,
animations: {
self.updateTableViewFrame(false)
})
}
} else {
tableView.reloadData()
updateTableViewFrame(false)
}
}
public func revealMenuCellDidPressedCancel(_ cell: RevealMenuCell) {
dismiss(animated: true, completion: nil)
}
}
/// Status bar
extension RevealMenuController {
override open var preferredStatusBarStyle: UIStatusBarStyle {
return statusBarStyle
}
}
| mit | f25209b59576fd9f7f3310996a03d16c | 36.308571 | 125 | 0.614183 | 4.933132 | false | false | false | false |
tkremenek/swift | test/refactoring/ConvertAsync/convert_pattern.swift | 1 | 20767 | // RUN: %empty-directory(%t)
enum E : Error { case e }
func anyCompletion(_ completion: (Any?, Error?) -> Void) {}
func anyResultCompletion(_ completion: (Result<Any?, Error>) -> Void) {}
func stringTupleParam(_ completion: ((String, String)?, Error?) -> Void) {}
func stringTupleParam() async throws -> (String, String) {}
func stringTupleResult(_ completion: (Result<(String, String), Error>) -> Void) {}
func stringTupleResult() async throws -> (String, String) {}
func mixedTupleResult(_ completion: (Result<((Int, Float), String), Error>) -> Void) {}
func mixedTupleResult() async throws -> ((Int, Float), String) {}
func multipleTupleParam(_ completion: ((String, String)?, (Int, Int)?, Error?) -> Void) {}
func multipleTupleParam() async throws -> ((String, String), (Int, Int)) {}
func testPatterns() async throws {
// RUN: %refactor-check-compiles -convert-call-to-async-alternative -dump-text -source-filename %s -pos=%(line+1):3 | %FileCheck -check-prefix=INLINE %s
stringTupleParam { strs, err in
guard let (str1, str2) = strs else { return }
print(str1, str2)
}
// INLINE: let (str1, str2) = try await stringTupleParam()
// INLINE-NEXT: print(str1, str2)
// RUN: %refactor-check-compiles -convert-call-to-async-alternative -dump-text -source-filename %s -pos=%(line+1):3 | %FileCheck -check-prefix=INLINE-VAR %s
stringTupleParam { strs, err in
guard var (str1, str2) = strs else { return }
print(str1, str2)
}
// INLINE-VAR: var (str1, str2) = try await stringTupleParam()
// INLINE-VAR-NEXT: print(str1, str2)
// RUN: %refactor-check-compiles -convert-call-to-async-alternative -dump-text -source-filename %s -pos=%(line+1):3 | %FileCheck -check-prefix=INLINE-BLANK %s
stringTupleParam { strs, err in
guard var (_, str2) = strs else { return }
print(str2)
}
// INLINE-BLANK: var (_, str2) = try await stringTupleParam()
// INLINE-BLANK-NEXT: print(str2)
// RUN: %refactor-check-compiles -convert-call-to-async-alternative -dump-text -source-filename %s -pos=%(line+1):3 | %FileCheck -check-prefix=INLINE-TYPED %s
stringTupleParam { strs, err in
guard let (str1, str2): (String, String) = strs else { return }
print(str1, str2)
}
// INLINE-TYPED: let (str1, str2) = try await stringTupleParam()
// INLINE-TYPED-NEXT: print(str1, str2)
// RUN: %refactor-check-compiles -convert-call-to-async-alternative -dump-text -source-filename %s -pos=%(line+1):3 | %FileCheck -check-prefix=INLINE-CASE %s
stringTupleParam { strs, err in
guard case (let str1, var str2)? = strs else { return }
print(str1, str2)
}
// INLINE-CASE: var (str1, str2) = try await stringTupleParam()
// INLINE-CASE-NEXT: print(str1, str2)
// RUN: %refactor-check-compiles -convert-call-to-async-alternative -dump-text -source-filename %s -pos=%(line+1):3 | %FileCheck -check-prefix=INLINE-CASE-TYPED %s
stringTupleParam { strs, err in
guard case let (str1, str2)?: (String, String)? = strs else { return }
print(str1, str2)
}
// INLINE-CASE-TYPED: let (str1, str2) = try await stringTupleParam()
// INLINE-CASE-TYPED-NEXT: print(str1, str2)
// RUN: %refactor-check-compiles -convert-call-to-async-alternative -dump-text -source-filename %s -pos=%(line+1):3 | %FileCheck -check-prefix=OUT-OF-LINE %s
stringTupleParam { strs, err in
guard let (str1, str2) = strs else { return }
print(str1, str2, strs!)
}
// OUT-OF-LINE: let strs = try await stringTupleParam()
// OUT-OF-LINE-NEXT: let (str1, str2) = strs
// OUT-OF-LINE-NEXT: print(str1, str2, strs)
// RUN: %refactor-check-compiles -convert-call-to-async-alternative -dump-text -source-filename %s -pos=%(line+1):3 | %FileCheck -check-prefix=OUT-OF-LINE-VAR %s
stringTupleParam { strs, err in
guard var (str1, _) = strs else { return }
str1 = ""
print(str1, {strs!})
}
// OUT-OF-LINE-VAR: let strs = try await stringTupleParam()
// OUT-OF-LINE-VAR-NEXT: var (str1, _) = strs
// OUT-OF-LINE-VAR-NEXT: str1 = ""
// OUT-OF-LINE-VAR-NEXT: print(str1, {strs})
// RUN: %refactor-check-compiles -convert-call-to-async-alternative -dump-text -source-filename %s -pos=%(line+1):3 | %FileCheck -check-prefix=OUT-OF-LINE-CASE %s
stringTupleParam { strs, err in
guard case (let str1, var str2)? = strs else { return }
print(str1, str2, strs!)
}
// OUT-OF-LINE-CASE: let strs = try await stringTupleParam()
// OUT-OF-LINE-CASE-NEXT: var (str1, str2) = strs
// OUT-OF-LINE-CASE-NEXT: print(str1, str2, strs)
// RUN: %refactor-check-compiles -convert-call-to-async-alternative -dump-text -source-filename %s -pos=%(line+1):3 | %FileCheck -check-prefix=FALLBACK %s
stringTupleParam { strs, err in
guard let (str1, str2) = strs, str1 == "hi" else { fatalError() }
print(str1, str2, err)
}
// FALLBACK: var strs: (String, String)? = nil
// FALLBACK-NEXT: var err: Error? = nil
// FALLBACK-NEXT: do {
// FALLBACK-NEXT: strs = try await stringTupleParam()
// FALLBACK-NEXT: } catch {
// FALLBACK-NEXT: err = error
// FALLBACK-NEXT: }
// FALLBACK-EMPTY:
// FALLBACK-NEXT: guard let (str1, str2) = strs, str1 == "hi" else { fatalError() }
// FALLBACK-NEXT: print(str1, str2, err)
// RUN: %refactor -convert-call-to-async-alternative -dump-text -source-filename %s -pos=%(line+1):3 | %FileCheck -check-prefix=GUARD-AND-UNHANDLED %s
stringTupleParam { strs, err in
guard let (str1, str2) = strs else { fatalError() }
print(str1, str2)
if .random(), err == nil {
print("yay")
} else {
print("nay")
}
}
// GUARD-AND-UNHANDLED: do {
// GUARD-AND-UNHANDLED-NEXT: let (str1, str2) = try await stringTupleParam()
// GUARD-AND-UNHANDLED-NEXT: print(str1, str2)
// GUARD-AND-UNHANDLED-NEXT: if .random(), <#err#> == nil {
// GUARD-AND-UNHANDLED-NEXT: print("yay")
// GUARD-AND-UNHANDLED-NEXT: } else {
// GUARD-AND-UNHANDLED-NEXT: print("nay")
// GUARD-AND-UNHANDLED-NEXT: }
// GUARD-AND-UNHANDLED-NEXT: } catch let err {
// GUARD-AND-UNHANDLED-NEXT: fatalError()
// GUARD-AND-UNHANDLED-NEXT: }
// RUN: %refactor-check-compiles -convert-call-to-async-alternative -dump-text -source-filename %s -pos=%(line+1):3 | %FileCheck -check-prefix=MIXED-BINDINGS %s
stringTupleParam { strs, err in
guard let x = strs else { return }
guard var (str1, str2) = strs else { return }
guard var y = strs else { return }
guard let z = strs else { return }
y = ("hello", "there")
print(x, y, z, str1, str2)
}
// Make sure that we
// 1. Coalesce the z binding, as it is a let
// 2. Preserve the y binding, as it is a var
// 3. Print the multi-var binding out of line
//
// MIXED-BINDINGS: let x = try await stringTupleParam()
// MIXED-BINDINGS-NEXT: var (str1, str2) = x
// MIXED-BINDINGS-NEXT: var y = x
// MIXED-BINDINGS-NEXT: y = ("hello", "there")
// MIXED-BINDINGS-NEXT: print(x, y, x, str1, str2)
// RUN: %refactor-check-compiles -convert-call-to-async-alternative -dump-text -source-filename %s -pos=%(line+1):3 | %FileCheck -check-prefix=MIXED-BINDINGS2 %s
stringTupleParam { strs, err in
guard var (str1, str2) = strs else { return }
str1 = "hi"
guard var x = strs else { return }
x = ("hello", "there")
print(x, str1, str2)
}
// MIXED-BINDINGS2: var x = try await stringTupleParam()
// MIXED-BINDINGS2-NEXT: var (str1, str2) = x
// MIXED-BINDINGS2-NEXT: str1 = "hi"
// MIXED-BINDINGS2-NEXT: x = ("hello", "there")
// MIXED-BINDINGS2-NEXT: print(x, str1, str2)
// RUN: %refactor-check-compiles -convert-call-to-async-alternative -dump-text -source-filename %s -pos=%(line+1):3 | %FileCheck -check-prefix=MIXED-BINDINGS3 %s
stringTupleParam { strs, err in
guard let (str1, str2) = strs else { return }
guard let x = strs else { return }
print(x, str1, str2)
}
// MIXED-BINDINGS3: let x = try await stringTupleParam()
// MIXED-BINDINGS3-NEXT: let (str1, str2) = x
// MIXED-BINDINGS3-NEXT: print(x, str1, str2)
// RUN: %refactor-check-compiles -convert-call-to-async-alternative -dump-text -source-filename %s -pos=%(line+1):3 | %FileCheck -check-prefix=ALIAS-BINDINGS %s
stringTupleParam { strs, err in
guard let x = strs else { return }
guard let y = strs else { return }
guard let z = strs else { return }
print(x, y, z)
}
// ALIAS-BINDINGS: let x = try await stringTupleParam()
// ALIAS-BINDINGS-NEXT: print(x, x, x)
// RUN: %refactor-check-compiles -convert-call-to-async-alternative -dump-text -source-filename %s -pos=%(line+1):3 | %FileCheck -check-prefix=ALIAS-BINDINGS2 %s
stringTupleParam { strs, err in
guard var x = strs else { return }
guard var y = strs else { return }
guard let z = strs else { return }
print(x, y, z)
}
// ALIAS-BINDINGS2: let z = try await stringTupleParam()
// ALIAS-BINDINGS2-NEXT: var x = z
// ALIAS-BINDINGS2-NEXT: var y = z
// ALIAS-BINDINGS2-NEXT: print(x, y, z)
// RUN: %refactor-check-compiles -convert-call-to-async-alternative -dump-text -source-filename %s -pos=%(line+1):3 | %FileCheck -check-prefix=ALIAS-BINDINGS3 %s
stringTupleParam { strs, err in
guard var x = strs else { return }
guard var y = strs else { return }
guard var z = strs else { return }
print(x, y, z)
}
// ALIAS-BINDINGS3: var x = try await stringTupleParam()
// ALIAS-BINDINGS3-NEXT: var y = x
// ALIAS-BINDINGS3-NEXT: var z = x
// ALIAS-BINDINGS3-NEXT: print(x, y, z)
// RUN: %refactor-check-compiles -convert-call-to-async-alternative -dump-text -source-filename %s -pos=%(line+1):3 | %FileCheck -check-prefix=ALIAS-BINDINGS4 %s
stringTupleParam { strs, err in
guard var x = strs else { return }
guard let y = strs else { return }
guard let z = strs else { return }
print(x, y, z)
}
// ALIAS-BINDINGS4: let y = try await stringTupleParam()
// ALIAS-BINDINGS4-NEXT: var x = y
// ALIAS-BINDINGS4-NEXT: print(x, y, y)
// RUN: %refactor-check-compiles -convert-call-to-async-alternative -dump-text -source-filename %s -pos=%(line+1):3 | %FileCheck -check-prefix=ALIAS-BINDINGS5 %s
stringTupleParam { strs, err in
guard var x = strs else { return }
print(x)
}
// ALIAS-BINDINGS5: var x = try await stringTupleParam()
// ALIAS-BINDINGS5-NEXT: print(x)
// RUN: %refactor-check-compiles -convert-call-to-async-alternative -dump-text -source-filename %s -pos=%(line+1):3 | %FileCheck -check-prefix=STRING-TUPLE-RESULT %s
stringTupleResult { res in
switch res {
case .success((let x, let y)):
print(x, y)
case .failure:
print("oh no")
}
}
// STRING-TUPLE-RESULT: do {
// STRING-TUPLE-RESULT-NEXT: let (x, y) = try await stringTupleResult()
// STRING-TUPLE-RESULT-NEXT: print(x, y)
// STRING-TUPLE-RESULT-NEXT: } catch {
// STRING-TUPLE-RESULT-NEXT: print("oh no")
// STRING-TUPLE-RESULT-NEXT: }
// RUN: %refactor-check-compiles -convert-call-to-async-alternative -dump-text -source-filename %s -pos=%(line+1):3 | %FileCheck -check-prefix=STRING-TUPLE-RESULT %s
stringTupleResult { res in
switch res {
case let .success((x, y)):
print(x, y)
case .failure:
print("oh no")
}
}
// RUN: %refactor-check-compiles -convert-call-to-async-alternative -dump-text -source-filename %s -pos=%(line+1):3 | %FileCheck -check-prefix=MIXED-TUPLE-RESULT %s
mixedTupleResult { res in
if case .failure(let err) = res {
print("oh no")
}
if case .success(((let x, let y), let z)) = res {
print("a", x, y, z)
}
switch res {
case .success(let ((x, _), z)):
print("b", x, z)
case .failure:
print("oh no again")
}
}
// MIXED-TUPLE-RESULT: do {
// MIXED-TUPLE-RESULT-NEXT: let res = try await mixedTupleResult()
// MIXED-TUPLE-RESULT-NEXT: let ((x, y), z) = res
// MIXED-TUPLE-RESULT-NEXT: let ((x1, _), z1) = res
// MIXED-TUPLE-RESULT-NEXT: print("a", x, y, z)
// MIXED-TUPLE-RESULT-NEXT: print("b", x1, z1)
// MIXED-TUPLE-RESULT-NEXT: } catch let err {
// MIXED-TUPLE-RESULT-NEXT: print("oh no")
// MIXED-TUPLE-RESULT-NEXT: print("oh no again")
// MIXED-TUPLE-RESULT-NEXT: }
// RUN: %refactor-check-compiles -convert-call-to-async-alternative -dump-text -source-filename %s -pos=%(line+1):3 | %FileCheck -check-prefix=MIXED-TUPLE-RESULT2 %s
mixedTupleResult { res in
switch res {
case .success(((let x, let _), let z)):
print(x, z)
case .failure(let err):
print("oh no \(err)")
}
}
// MIXED-TUPLE-RESULT2: do {
// MIXED-TUPLE-RESULT2-NEXT: let ((x, _), z) = try await mixedTupleResult()
// MIXED-TUPLE-RESULT2-NEXT: print(x, z)
// MIXED-TUPLE-RESULT2-NEXT: } catch let err {
// MIXED-TUPLE-RESULT2-NEXT: print("oh no \(err)")
// MIXED-TUPLE-RESULT2-NEXT: }
// RUN: %refactor-check-compiles -convert-call-to-async-alternative -dump-text -source-filename %s -pos=%(line+1):3 | %FileCheck -check-prefix=MIXED-TUPLE-RESULT3 %s
mixedTupleResult { res in
if let ((_, y), z) = try? res.get() {
print(y, z)
} else {
print("boo")
}
}
// MIXED-TUPLE-RESULT3: do {
// MIXED-TUPLE-RESULT3-NEXT: let ((_, y), z) = try await mixedTupleResult()
// MIXED-TUPLE-RESULT3-NEXT: print(y, z)
// MIXED-TUPLE-RESULT3-NEXT: } catch {
// MIXED-TUPLE-RESULT3-NEXT: print("boo")
// MIXED-TUPLE-RESULT3-NEXT: }
// RUN: %refactor-check-compiles -convert-call-to-async-alternative -dump-text -source-filename %s -pos=%(line+1):3 | %FileCheck -check-prefix=MULTIPLE-TUPLE-PARAM %s
multipleTupleParam { strs, ints, err in
guard let (str1, str2) = strs, let (int1, int2) = ints else {
print("ohno")
return
}
print(str1, str2, int1, int2)
}
// MULTIPLE-TUPLE-PARAM: do {
// MULTIPLE-TUPLE-PARAM-NEXT: let ((str1, str2), (int1, int2)) = try await multipleTupleParam()
// MULTIPLE-TUPLE-PARAM-NEXT: print(str1, str2, int1, int2)
// MULTIPLE-TUPLE-PARAM-NEXT: } catch let err {
// MULTIPLE-TUPLE-PARAM-NEXT: print("ohno")
// MULTIPLE-TUPLE-PARAM-NEXT: }
// RUN: %refactor-check-compiles -convert-call-to-async-alternative -dump-text -source-filename %s -pos=%(line+1):3 | %FileCheck -check-prefix=MULTIPLE-TUPLE-PARAM2 %s
multipleTupleParam { strs, ints, err in
guard let (str1, str2) = strs, var (int1, int2) = ints else {
print("ohno")
return
}
print(str1, str2, int1, int2)
}
// MULTIPLE-TUPLE-PARAM2: do {
// MULTIPLE-TUPLE-PARAM2-NEXT: var ((str1, str2), (int1, int2)) = try await multipleTupleParam()
// MULTIPLE-TUPLE-PARAM2-NEXT: print(str1, str2, int1, int2)
// MULTIPLE-TUPLE-PARAM2-NEXT: } catch let err {
// MULTIPLE-TUPLE-PARAM2-NEXT: print("ohno")
// MULTIPLE-TUPLE-PARAM2-NEXT: }
// RUN: %refactor-check-compiles -convert-call-to-async-alternative -dump-text -source-filename %s -pos=%(line+1):3 | %FileCheck -check-prefix=MULTIPLE-TUPLE-PARAM3 %s
multipleTupleParam { strs, ints, err in
guard let (str1, str2) = strs, let (int1, int2) = ints else {
print("ohno")
return
}
print(strs!)
print(str1, str2, int1, int2)
}
// MULTIPLE-TUPLE-PARAM3: do {
// MULTIPLE-TUPLE-PARAM3-NEXT: let (strs, (int1, int2)) = try await multipleTupleParam()
// MULTIPLE-TUPLE-PARAM3-NEXT: let (str1, str2) = strs
// MULTIPLE-TUPLE-PARAM3-NEXT: print(strs)
// MULTIPLE-TUPLE-PARAM3-NEXT: print(str1, str2, int1, int2)
// MULTIPLE-TUPLE-PARAM3-NEXT: } catch let err {
// MULTIPLE-TUPLE-PARAM3-NEXT: print("ohno")
// MULTIPLE-TUPLE-PARAM3-NEXT: }
}
// RUN: %refactor -convert-to-async -dump-text -source-filename %s -pos=%(line+1):1 | %FileCheck -check-prefix=NAME-COLLISION %s
func testNameCollision(_ completion: () -> Void) {
let a = ""
stringTupleParam { strs, err in
guard let (a, b) = strs else { return }
print(a, b)
}
let b = ""
stringTupleParam { strs, err in
guard let (a, b) = strs else { return }
print(a, b, strs!)
}
print(a, b)
completion()
}
// TODO: `throws` isn't added to the function declaration
// NAME-COLLISION: func testNameCollision() async {
// NAME-COLLISION-NEXT: let a = ""
// NAME-COLLISION-NEXT: let (a1, b) = try await stringTupleParam()
// NAME-COLLISION-NEXT: print(a1, b)
// NAME-COLLISION-NEXT: let b1 = ""
// NAME-COLLISION-NEXT: let strs = try await stringTupleParam()
// NAME-COLLISION-NEXT: let (a2, b2) = strs
// NAME-COLLISION-NEXT: print(a2, b2, strs)
// NAME-COLLISION-NEXT: print(a, b1)
// NAME-COLLISION-NEXT: return
// NAME-COLLISION-NEXT: }
// RUN: %refactor -convert-to-async -dump-text -source-filename %s -pos=%(line+1):1 | %FileCheck -check-prefix=NAME-COLLISION2 %s
func testNameCollision2(_ completion: () -> Void) {
mixedTupleResult { res in
guard case let .success((x, y), z) = res else { return }
stringTupleParam { strs, err in
if let (x, y) = strs {
print("a", x, y)
}
}
print("b", x, y, z)
}
}
// TODO: `throws` isn't added to the function declaration
// NAME-COLLISION2: func testNameCollision2() async {
// NAME-COLLISION2-NEXT: let ((x, y), z) = try await mixedTupleResult()
// NAME-COLLISION2-NEXT: let (x1, y1) = try await stringTupleParam()
// NAME-COLLISION2-NEXT: print("a", x1, y1)
// NAME-COLLISION2-NEXT: print("b", x, y, z)
// NAME-COLLISION2-NEXT: }
// RUN: %refactor -convert-call-to-async-alternative -dump-text -source-filename %s -pos=%(line+1):1 | %FileCheck -check-prefix=TEST-UNHANDLED %s
anyCompletion { val, err in
if let x = val {
print("a")
}
if let _ = val {
print("b")
}
if case let x? = val {
print("c")
}
if case let _? = val {
print("d")
}
if case E.e? = val {
print("e")
}
if case (let x as String)? = val {
print("f")
}
if case let "" as String = val {
print("g")
}
}
// TEST-UNHANDLED: let x = try await anyCompletion()
// TEST-UNHANDLED-NEXT: print("a")
// TEST-UNHANDLED-NEXT: print("b")
// TEST-UNHANDLED-NEXT: print("c")
// TEST-UNHANDLED-NEXT: print("d")
// TEST-UNHANDLED-NEXT: if case E.e? = <#x#> {
// TEST-UNHANDLED-NEXT: print("e")
// TEST-UNHANDLED-NEXT: }
// TEST-UNHANDLED-NEXT: if case (let x as String)? = <#x#> {
// TEST-UNHANDLED-NEXT: print("f")
// TEST-UNHANDLED-NEXT: }
// TEST-UNHANDLED-NEXT: if case let "" as String = <#x#> {
// TEST-UNHANDLED-NEXT: print("g")
// TEST-UNHANDLED-NEXT: }
// RUN: not %refactor -convert-call-to-async-alternative -dump-text -source-filename %s -pos=%(line+1):1
anyResultCompletion { res in
switch res {
case .success(let unwrapped?):
print(unwrapped)
case .success(let x):
print(x)
case .failure:
print("oh no")
}
}
// RUN: not %refactor -convert-call-to-async-alternative -dump-text -source-filename %s -pos=%(line+1):1
anyResultCompletion { res in
switch res {
case .success(let str as String):
print(str)
case .success(let x):
print(x)
case .failure:
print("oh no")
}
}
// RUN: not %refactor -convert-call-to-async-alternative -dump-text -source-filename %s -pos=%(line+1):1
anyResultCompletion { res in
switch res {
case .success(E.e?):
print("ee")
case .success(let x):
print(x)
case .failure:
print("oh no")
}
}
// RUN: not %refactor -convert-call-to-async-alternative -dump-text -source-filename %s -pos=%(line+1):1
anyResultCompletion { res in
switch res {
case .success("" as String):
print("empty string")
case .success(let x):
print(x)
case .failure:
print("oh no")
}
}
// FIXME: This should ideally be turned into a 'catch let e as E'.
// RUN: not %refactor -convert-call-to-async-alternative -dump-text -source-filename %s -pos=%(line+1):1
anyResultCompletion { res in
switch res {
case .success(let a):
print(a)
case .failure(let e as E):
print("oh no e")
case .failure:
print("oh no")
}
}
// FIXME: This should ideally be turned into a 'catch E.e'.
// RUN: not %refactor -convert-call-to-async-alternative -dump-text -source-filename %s -pos=%(line+1):1
anyResultCompletion { res in
switch res {
case .success(let a):
print(a)
case .failure(E.e):
print("oh no ee")
case .failure:
print("oh no")
}
}
// Make sure we handle a capture list okay.
class C {
// RUN: %refactor -convert-to-async -dump-text -source-filename %s -pos=%(line+1):3 | %FileCheck -check-prefix=CAPTURE %s
func foo() {
let _ = { [weak self] in
print(self!)
}
}
}
// CAPTURE: func foo() async {
// CAPTURE-NEXT: let _ = { [weak self] in
// CAPTURE-NEXT: print(self!)
// CAPTURE-NEXT: }
// CAPTURE-NEXT: }
| apache-2.0 | 21c44f03ab76edb9a03032fe7aaa5326 | 35.820922 | 169 | 0.635865 | 3.00971 | false | false | false | false |
Sharelink/Bahamut | Bahamut/LocationService.swift | 1 | 1518 | //
// SoundService.swift
// Bahamut
//
// Created by AlexChow on 15/10/29.
// Copyright © 2015年 GStudio. All rights reserved.
//
import Foundation
import CoreLocation
class LocationService:NSNotificationCenter,ServiceProtocol,CLLocationManagerDelegate
{
@objc static var ServiceName:String{return "Location Service"}
static let hereUpdated = "hereUpdated"
private var locationManager:CLLocationManager!
@objc func appStartInit(appName:String) {
locationManager = CLLocationManager()
locationManager.delegate = self
self.locationManager.desiredAccuracy = kCLLocationAccuracyBest
self.locationManager.distanceFilter = 700.0
self.locationManager.startUpdatingLocation()
}
func userLoginInit(userId: String) {
self.setServiceReady()
}
var isLocationServiceEnabled:Bool{
return CLLocationManager.locationServicesEnabled()
}
func refreshHere()
{
self.locationManager.startUpdatingLocation()
}
private(set) var here:CLLocation!
//MARK: CLLocationManagerDelegate
func locationManager(manager: CLLocationManager, didUpdateToLocation newLocation: CLLocation, fromLocation oldLocation: CLLocation) {
here = newLocation
self.postNotificationName(LocationService.hereUpdated, object: self)
self.locationManager.stopUpdatingLocation()
}
func locationManager(manager: CLLocationManager, didFailWithError error: NSError) {
}
} | mit | 6eccc24fc6f0e7583f3171e7dd341be7 | 29.32 | 137 | 0.718152 | 5.509091 | false | false | false | false |
shorlander/firefox-ios | StorageTests/TestSQLiteHistory.swift | 1 | 69855 | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
import Foundation
import Shared
@testable import Storage
import Deferred
import XCTest
let threeMonthsInMillis: UInt64 = 3 * 30 * 24 * 60 * 60 * 1000
let threeMonthsInMicros: UInt64 = UInt64(threeMonthsInMillis) * UInt64(1000)
// Start everything three months ago.
let baseInstantInMillis = Date.now() - threeMonthsInMillis
let baseInstantInMicros = Date.nowMicroseconds() - threeMonthsInMicros
func advanceTimestamp(_ timestamp: Timestamp, by: Int) -> Timestamp {
return timestamp + UInt64(by)
}
func advanceMicrosecondTimestamp(_ timestamp: MicrosecondTimestamp, by: Int) -> MicrosecondTimestamp {
return timestamp + UInt64(by)
}
extension Site {
func asPlace() -> Place {
return Place(guid: self.guid!, url: self.url, title: self.title)
}
}
class BaseHistoricalBrowserTable {
func updateTable(_ db: SQLiteDBConnection, from: Int) -> Bool {
assert(false, "Should never be called.")
}
func exists(_ db: SQLiteDBConnection) -> Bool {
return false
}
func drop(_ db: SQLiteDBConnection) -> Bool {
return false
}
var supportsPartialIndices: Bool {
let v = sqlite3_libversion_number()
return v >= 3008000 // 3.8.0.
}
let oldFaviconsSQL =
"CREATE TABLE IF NOT EXISTS favicons (" +
"id INTEGER PRIMARY KEY AUTOINCREMENT, " +
"url TEXT NOT NULL UNIQUE, " +
"width INTEGER, " +
"height INTEGER, " +
"type INTEGER NOT NULL, " +
"date REAL NOT NULL" +
") "
func run(_ db: SQLiteDBConnection, sql: String?, args: Args? = nil) -> Bool {
if let sql = sql {
let err = db.executeChange(sql, withArgs: args)
return err == nil
}
return true
}
func run(_ db: SQLiteDBConnection, queries: [String?]) -> Bool {
for sql in queries {
if let sql = sql {
if !run(db, sql: sql) {
return false
}
}
}
return true
}
func run(_ db: SQLiteDBConnection, queries: [String]) -> Bool {
for sql in queries {
if !run(db, sql: sql) {
return false
}
}
return true
}
}
// Versions of BrowserTable that we care about:
// v6, prior to 001c73ea1903c238be1340950770879b40c41732, July 2015.
// This is when we first started caring about database versions.
//
// v7, 81e22fa6f7446e27526a5a9e8f4623df159936c3. History tiles.
//
// v8, 02c08ddc6d805d853bbe053884725dc971ef37d7. Favicons.
//
// v10, 4428c7d181ff4779ab1efb39e857e41bdbf4de67. Mirroring. We skipped v9.
//
// These tests snapshot the table creation code at each of these points.
class BrowserTableV6: BaseHistoricalBrowserTable {
var name: String { return "BROWSER" }
var version: Int { return 6 }
func prepopulateRootFolders(_ db: SQLiteDBConnection) -> Bool {
let type = BookmarkNodeType.folder.rawValue
let root = BookmarkRoots.RootID
let titleMobile = NSLocalizedString("Mobile Bookmarks", tableName: "Storage", comment: "The title of the folder that contains mobile bookmarks. This should match bookmarks.folder.mobile.label on Android.")
let titleMenu = NSLocalizedString("Bookmarks Menu", tableName: "Storage", comment: "The name of the folder that contains desktop bookmarks in the menu. This should match bookmarks.folder.menu.label on Android.")
let titleToolbar = NSLocalizedString("Bookmarks Toolbar", tableName: "Storage", comment: "The name of the folder that contains desktop bookmarks in the toolbar. This should match bookmarks.folder.toolbar.label on Android.")
let titleUnsorted = NSLocalizedString("Unsorted Bookmarks", tableName: "Storage", comment: "The name of the folder that contains unsorted desktop bookmarks. This should match bookmarks.folder.unfiled.label on Android.")
let args: Args = [
root, BookmarkRoots.RootGUID, type, "Root", root,
BookmarkRoots.MobileID, BookmarkRoots.MobileFolderGUID, type, titleMobile, root,
BookmarkRoots.MenuID, BookmarkRoots.MenuFolderGUID, type, titleMenu, root,
BookmarkRoots.ToolbarID, BookmarkRoots.ToolbarFolderGUID, type, titleToolbar, root,
BookmarkRoots.UnfiledID, BookmarkRoots.UnfiledFolderGUID, type, titleUnsorted, root,
]
let sql =
"INSERT INTO bookmarks (id, guid, type, url, title, parent) VALUES " +
"(?, ?, ?, NULL, ?, ?), " + // Root
"(?, ?, ?, NULL, ?, ?), " + // Mobile
"(?, ?, ?, NULL, ?, ?), " + // Menu
"(?, ?, ?, NULL, ?, ?), " + // Toolbar
"(?, ?, ?, NULL, ?, ?) " // Unsorted
return self.run(db, sql: sql, args: args)
}
func CreateHistoryTable() -> String {
return "CREATE TABLE IF NOT EXISTS \(TableHistory) (" +
"id INTEGER PRIMARY KEY AUTOINCREMENT, " +
"guid TEXT NOT NULL UNIQUE, " + // Not null, but the value might be replaced by the server's.
"url TEXT UNIQUE, " + // May only be null for deleted records.
"title TEXT NOT NULL, " +
"server_modified INTEGER, " + // Can be null. Integer milliseconds.
"local_modified INTEGER, " + // Can be null. Client clock. In extremis only.
"is_deleted TINYINT NOT NULL, " + // Boolean. Locally deleted.
"should_upload TINYINT NOT NULL, " + // Boolean. Set when changed or visits added.
"domain_id INTEGER REFERENCES \(TableDomains)(id) ON DELETE CASCADE, " +
"CONSTRAINT urlOrDeleted CHECK (url IS NOT NULL OR is_deleted = 1)" +
")"
}
func CreateDomainsTable() -> String {
return "CREATE TABLE IF NOT EXISTS \(TableDomains) (" +
"id INTEGER PRIMARY KEY AUTOINCREMENT, " +
"domain TEXT NOT NULL UNIQUE, " +
"showOnTopSites TINYINT NOT NULL DEFAULT 1" +
")"
}
func CreateQueueTable() -> String {
return "CREATE TABLE IF NOT EXISTS \(TableQueuedTabs) (" +
"url TEXT NOT NULL UNIQUE, " +
"title TEXT" +
") "
}
}
extension BrowserTableV6: Table {
func create(_ db: SQLiteDBConnection) -> Bool {
let visits =
"CREATE TABLE IF NOT EXISTS \(TableVisits) (" +
"id INTEGER PRIMARY KEY AUTOINCREMENT, " +
"siteID INTEGER NOT NULL REFERENCES \(TableHistory)(id) ON DELETE CASCADE, " +
"date REAL NOT NULL, " + // Microseconds since epoch.
"type INTEGER NOT NULL, " +
"is_local TINYINT NOT NULL, " + // Some visits are local. Some are remote ('mirrored'). This boolean flag is the split.
"UNIQUE (siteID, date, type) " +
") "
let indexShouldUpload: String
if self.supportsPartialIndices {
// There's no point tracking rows that are not flagged for upload.
indexShouldUpload =
"CREATE INDEX IF NOT EXISTS \(IndexHistoryShouldUpload) " +
"ON \(TableHistory) (should_upload) WHERE should_upload = 1"
} else {
indexShouldUpload =
"CREATE INDEX IF NOT EXISTS \(IndexHistoryShouldUpload) " +
"ON \(TableHistory) (should_upload)"
}
let indexSiteIDDate =
"CREATE INDEX IF NOT EXISTS \(IndexVisitsSiteIDIsLocalDate) " +
"ON \(TableVisits) (siteID, is_local, date)"
let faviconSites =
"CREATE TABLE IF NOT EXISTS \(TableFaviconSites) (" +
"id INTEGER PRIMARY KEY AUTOINCREMENT, " +
"siteID INTEGER NOT NULL REFERENCES \(TableHistory)(id) ON DELETE CASCADE, " +
"faviconID INTEGER NOT NULL REFERENCES \(TableFavicons)(id) ON DELETE CASCADE, " +
"UNIQUE (siteID, faviconID) " +
") "
let widestFavicons =
"CREATE VIEW IF NOT EXISTS \(ViewWidestFaviconsForSites) AS " +
"SELECT " +
"\(TableFaviconSites).siteID AS siteID, " +
"\(TableFavicons).id AS iconID, " +
"\(TableFavicons).url AS iconURL, " +
"\(TableFavicons).date AS iconDate, " +
"\(TableFavicons).type AS iconType, " +
"MAX(\(TableFavicons).width) AS iconWidth " +
"FROM \(TableFaviconSites), \(TableFavicons) WHERE " +
"\(TableFaviconSites).faviconID = \(TableFavicons).id " +
"GROUP BY siteID "
let historyIDsWithIcon =
"CREATE VIEW IF NOT EXISTS \(ViewHistoryIDsWithWidestFavicons) AS " +
"SELECT \(TableHistory).id AS id, " +
"iconID, iconURL, iconDate, iconType, iconWidth " +
"FROM \(TableHistory) " +
"LEFT OUTER JOIN " +
"\(ViewWidestFaviconsForSites) ON history.id = \(ViewWidestFaviconsForSites).siteID "
let iconForURL =
"CREATE VIEW IF NOT EXISTS \(ViewIconForURL) AS " +
"SELECT history.url AS url, icons.iconID AS iconID FROM " +
"\(TableHistory), \(ViewWidestFaviconsForSites) AS icons WHERE " +
"\(TableHistory).id = icons.siteID "
let bookmarks =
"CREATE TABLE IF NOT EXISTS bookmarks (" +
"id INTEGER PRIMARY KEY AUTOINCREMENT, " +
"guid TEXT NOT NULL UNIQUE, " +
"type TINYINT NOT NULL, " +
"url TEXT, " +
"parent INTEGER REFERENCES bookmarks(id) NOT NULL, " +
"faviconID INTEGER REFERENCES favicons(id) ON DELETE SET NULL, " +
"title TEXT" +
") "
let queries = [
// This used to be done by FaviconsTable.
self.oldFaviconsSQL,
CreateDomainsTable(),
CreateHistoryTable(),
visits, bookmarks, faviconSites,
indexShouldUpload, indexSiteIDDate,
widestFavicons, historyIDsWithIcon, iconForURL,
CreateQueueTable(),
]
return self.run(db, queries: queries) &&
self.prepopulateRootFolders(db)
}
}
class BrowserTableV7: BaseHistoricalBrowserTable {
var name: String { return "BROWSER" }
var version: Int { return 7 }
func prepopulateRootFolders(_ db: SQLiteDBConnection) -> Bool {
let type = BookmarkNodeType.folder.rawValue
let root = BookmarkRoots.RootID
let titleMobile = NSLocalizedString("Mobile Bookmarks", tableName: "Storage", comment: "The title of the folder that contains mobile bookmarks. This should match bookmarks.folder.mobile.label on Android.")
let titleMenu = NSLocalizedString("Bookmarks Menu", tableName: "Storage", comment: "The name of the folder that contains desktop bookmarks in the menu. This should match bookmarks.folder.menu.label on Android.")
let titleToolbar = NSLocalizedString("Bookmarks Toolbar", tableName: "Storage", comment: "The name of the folder that contains desktop bookmarks in the toolbar. This should match bookmarks.folder.toolbar.label on Android.")
let titleUnsorted = NSLocalizedString("Unsorted Bookmarks", tableName: "Storage", comment: "The name of the folder that contains unsorted desktop bookmarks. This should match bookmarks.folder.unfiled.label on Android.")
let args: Args = [
root, BookmarkRoots.RootGUID, type, "Root", root,
BookmarkRoots.MobileID, BookmarkRoots.MobileFolderGUID, type, titleMobile, root,
BookmarkRoots.MenuID, BookmarkRoots.MenuFolderGUID, type, titleMenu, root,
BookmarkRoots.ToolbarID, BookmarkRoots.ToolbarFolderGUID, type, titleToolbar, root,
BookmarkRoots.UnfiledID, BookmarkRoots.UnfiledFolderGUID, type, titleUnsorted, root,
]
let sql =
"INSERT INTO bookmarks (id, guid, type, url, title, parent) VALUES " +
"(?, ?, ?, NULL, ?, ?), " + // Root
"(?, ?, ?, NULL, ?, ?), " + // Mobile
"(?, ?, ?, NULL, ?, ?), " + // Menu
"(?, ?, ?, NULL, ?, ?), " + // Toolbar
"(?, ?, ?, NULL, ?, ?) " // Unsorted
return self.run(db, sql: sql, args: args)
}
func getHistoryTableCreationString() -> String {
return "CREATE TABLE IF NOT EXISTS history (" +
"id INTEGER PRIMARY KEY AUTOINCREMENT, " +
"guid TEXT NOT NULL UNIQUE, " + // Not null, but the value might be replaced by the server's.
"url TEXT UNIQUE, " + // May only be null for deleted records.
"title TEXT NOT NULL, " +
"server_modified INTEGER, " + // Can be null. Integer milliseconds.
"local_modified INTEGER, " + // Can be null. Client clock. In extremis only.
"is_deleted TINYINT NOT NULL, " + // Boolean. Locally deleted.
"should_upload TINYINT NOT NULL, " + // Boolean. Set when changed or visits added.
"domain_id INTEGER REFERENCES \(TableDomains)(id) ON DELETE CASCADE, " +
"CONSTRAINT urlOrDeleted CHECK (url IS NOT NULL OR is_deleted = 1)" +
")"
}
func getDomainsTableCreationString() -> String {
return "CREATE TABLE IF NOT EXISTS \(TableDomains) (" +
"id INTEGER PRIMARY KEY AUTOINCREMENT, " +
"domain TEXT NOT NULL UNIQUE, " +
"showOnTopSites TINYINT NOT NULL DEFAULT 1" +
")"
}
func getQueueTableCreationString() -> String {
return "CREATE TABLE IF NOT EXISTS \(TableQueuedTabs) (" +
"url TEXT NOT NULL UNIQUE, " +
"title TEXT" +
") "
}
}
extension BrowserTableV7: SectionCreator, TableInfo {
func create(_ db: SQLiteDBConnection) -> Bool {
// Right now we don't need to track per-visit deletions: Sync can't
// represent them! See Bug 1157553 Comment 6.
// We flip the should_upload flag on the history item when we add a visit.
// If we ever want to support logic like not bothering to sync if we added
// and then rapidly removed a visit, then we need an 'is_new' flag on each visit.
let visits =
"CREATE TABLE IF NOT EXISTS \(TableVisits) (" +
"id INTEGER PRIMARY KEY AUTOINCREMENT, " +
"siteID INTEGER NOT NULL REFERENCES history(id) ON DELETE CASCADE, " +
"date REAL NOT NULL, " + // Microseconds since epoch.
"type INTEGER NOT NULL, " +
"is_local TINYINT NOT NULL, " + // Some visits are local. Some are remote ('mirrored'). This boolean flag is the split.
"UNIQUE (siteID, date, type) " +
") "
let indexShouldUpload: String
if self.supportsPartialIndices {
// There's no point tracking rows that are not flagged for upload.
indexShouldUpload =
"CREATE INDEX IF NOT EXISTS \(IndexHistoryShouldUpload) " +
"ON history (should_upload) WHERE should_upload = 1"
} else {
indexShouldUpload =
"CREATE INDEX IF NOT EXISTS \(IndexHistoryShouldUpload) " +
"ON history (should_upload)"
}
let indexSiteIDDate =
"CREATE INDEX IF NOT EXISTS \(IndexVisitsSiteIDIsLocalDate) " +
"ON \(TableVisits) (siteID, is_local, date)"
let faviconSites =
"CREATE TABLE IF NOT EXISTS \(TableFaviconSites) (" +
"id INTEGER PRIMARY KEY AUTOINCREMENT, " +
"siteID INTEGER NOT NULL REFERENCES history(id) ON DELETE CASCADE, " +
"faviconID INTEGER NOT NULL REFERENCES favicons(id) ON DELETE CASCADE, " +
"UNIQUE (siteID, faviconID) " +
") "
let widestFavicons =
"CREATE VIEW IF NOT EXISTS \(ViewWidestFaviconsForSites) AS " +
"SELECT " +
"\(TableFaviconSites).siteID AS siteID, " +
"favicons.id AS iconID, " +
"favicons.url AS iconURL, " +
"favicons.date AS iconDate, " +
"favicons.type AS iconType, " +
"MAX(favicons.width) AS iconWidth " +
"FROM \(TableFaviconSites), favicons WHERE " +
"\(TableFaviconSites).faviconID = favicons.id " +
"GROUP BY siteID "
let historyIDsWithIcon =
"CREATE VIEW IF NOT EXISTS \(ViewHistoryIDsWithWidestFavicons) AS " +
"SELECT history.id AS id, " +
"iconID, iconURL, iconDate, iconType, iconWidth " +
"FROM history " +
"LEFT OUTER JOIN " +
"\(ViewWidestFaviconsForSites) ON history.id = \(ViewWidestFaviconsForSites).siteID "
let iconForURL =
"CREATE VIEW IF NOT EXISTS \(ViewIconForURL) AS " +
"SELECT history.url AS url, icons.iconID AS iconID FROM " +
"\(TableHistory), \(ViewWidestFaviconsForSites) AS icons WHERE " +
"\(TableHistory).id = icons.siteID "
let bookmarks =
"CREATE TABLE IF NOT EXISTS bookmarks (" +
"id INTEGER PRIMARY KEY AUTOINCREMENT, " +
"guid TEXT NOT NULL UNIQUE, " +
"type TINYINT NOT NULL, " +
"url TEXT, " +
"parent INTEGER REFERENCES bookmarks(id) NOT NULL, " +
"faviconID INTEGER REFERENCES favicons(id) ON DELETE SET NULL, " +
"title TEXT" +
") "
let queries = [
// This used to be done by FaviconsTable.
self.oldFaviconsSQL,
getDomainsTableCreationString(),
getHistoryTableCreationString(),
visits, bookmarks, faviconSites,
indexShouldUpload, indexSiteIDDate,
widestFavicons, historyIDsWithIcon, iconForURL,
getQueueTableCreationString(),
]
return self.run(db, queries: queries) &&
self.prepopulateRootFolders(db)
}
}
class BrowserTableV8: BaseHistoricalBrowserTable {
var name: String { return "BROWSER" }
var version: Int { return 8 }
func prepopulateRootFolders(_ db: SQLiteDBConnection) -> Bool {
let type = BookmarkNodeType.folder.rawValue
let root = BookmarkRoots.RootID
let titleMobile = NSLocalizedString("Mobile Bookmarks", tableName: "Storage", comment: "The title of the folder that contains mobile bookmarks. This should match bookmarks.folder.mobile.label on Android.")
let titleMenu = NSLocalizedString("Bookmarks Menu", tableName: "Storage", comment: "The name of the folder that contains desktop bookmarks in the menu. This should match bookmarks.folder.menu.label on Android.")
let titleToolbar = NSLocalizedString("Bookmarks Toolbar", tableName: "Storage", comment: "The name of the folder that contains desktop bookmarks in the toolbar. This should match bookmarks.folder.toolbar.label on Android.")
let titleUnsorted = NSLocalizedString("Unsorted Bookmarks", tableName: "Storage", comment: "The name of the folder that contains unsorted desktop bookmarks. This should match bookmarks.folder.unfiled.label on Android.")
let args: Args = [
root, BookmarkRoots.RootGUID, type, "Root", root,
BookmarkRoots.MobileID, BookmarkRoots.MobileFolderGUID, type, titleMobile, root,
BookmarkRoots.MenuID, BookmarkRoots.MenuFolderGUID, type, titleMenu, root,
BookmarkRoots.ToolbarID, BookmarkRoots.ToolbarFolderGUID, type, titleToolbar, root,
BookmarkRoots.UnfiledID, BookmarkRoots.UnfiledFolderGUID, type, titleUnsorted, root,
]
let sql =
"INSERT INTO bookmarks (id, guid, type, url, title, parent) VALUES " +
"(?, ?, ?, NULL, ?, ?), " + // Root
"(?, ?, ?, NULL, ?, ?), " + // Mobile
"(?, ?, ?, NULL, ?, ?), " + // Menu
"(?, ?, ?, NULL, ?, ?), " + // Toolbar
"(?, ?, ?, NULL, ?, ?) " // Unsorted
return self.run(db, sql: sql, args: args)
}
func getHistoryTableCreationString() -> String {
return "CREATE TABLE IF NOT EXISTS \(TableHistory) (" +
"id INTEGER PRIMARY KEY AUTOINCREMENT, " +
"guid TEXT NOT NULL UNIQUE, " + // Not null, but the value might be replaced by the server's.
"url TEXT UNIQUE, " + // May only be null for deleted records.
"title TEXT NOT NULL, " +
"server_modified INTEGER, " + // Can be null. Integer milliseconds.
"local_modified INTEGER, " + // Can be null. Client clock. In extremis only.
"is_deleted TINYINT NOT NULL, " + // Boolean. Locally deleted.
"should_upload TINYINT NOT NULL, " + // Boolean. Set when changed or visits added.
"domain_id INTEGER REFERENCES \(TableDomains)(id) ON DELETE CASCADE, " +
"CONSTRAINT urlOrDeleted CHECK (url IS NOT NULL OR is_deleted = 1)" +
")"
}
func getDomainsTableCreationString() -> String {
return "CREATE TABLE IF NOT EXISTS \(TableDomains) (" +
"id INTEGER PRIMARY KEY AUTOINCREMENT, " +
"domain TEXT NOT NULL UNIQUE, " +
"showOnTopSites TINYINT NOT NULL DEFAULT 1" +
")"
}
func getQueueTableCreationString() -> String {
return "CREATE TABLE IF NOT EXISTS \(TableQueuedTabs) (" +
"url TEXT NOT NULL UNIQUE, " +
"title TEXT" +
") "
}
}
extension BrowserTableV8: SectionCreator, TableInfo {
func create(_ db: SQLiteDBConnection) -> Bool {
let favicons =
"CREATE TABLE IF NOT EXISTS favicons (" +
"id INTEGER PRIMARY KEY AUTOINCREMENT, " +
"url TEXT NOT NULL UNIQUE, " +
"width INTEGER, " +
"height INTEGER, " +
"type INTEGER NOT NULL, " +
"date REAL NOT NULL" +
") "
// Right now we don't need to track per-visit deletions: Sync can't
// represent them! See Bug 1157553 Comment 6.
// We flip the should_upload flag on the history item when we add a visit.
// If we ever want to support logic like not bothering to sync if we added
// and then rapidly removed a visit, then we need an 'is_new' flag on each visit.
let visits =
"CREATE TABLE IF NOT EXISTS visits (" +
"id INTEGER PRIMARY KEY AUTOINCREMENT, " +
"siteID INTEGER NOT NULL REFERENCES history(id) ON DELETE CASCADE, " +
"date REAL NOT NULL, " + // Microseconds since epoch.
"type INTEGER NOT NULL, " +
"is_local TINYINT NOT NULL, " + // Some visits are local. Some are remote ('mirrored'). This boolean flag is the split.
"UNIQUE (siteID, date, type) " +
") "
let indexShouldUpload: String
if self.supportsPartialIndices {
// There's no point tracking rows that are not flagged for upload.
indexShouldUpload =
"CREATE INDEX IF NOT EXISTS \(IndexHistoryShouldUpload) " +
"ON \(TableHistory) (should_upload) WHERE should_upload = 1"
} else {
indexShouldUpload =
"CREATE INDEX IF NOT EXISTS \(IndexHistoryShouldUpload) " +
"ON \(TableHistory) (should_upload)"
}
let indexSiteIDDate =
"CREATE INDEX IF NOT EXISTS \(IndexVisitsSiteIDIsLocalDate) " +
"ON \(TableVisits) (siteID, is_local, date)"
let faviconSites =
"CREATE TABLE IF NOT EXISTS \(TableFaviconSites) (" +
"id INTEGER PRIMARY KEY AUTOINCREMENT, " +
"siteID INTEGER NOT NULL REFERENCES history(id) ON DELETE CASCADE, " +
"faviconID INTEGER NOT NULL REFERENCES favicons(id) ON DELETE CASCADE, " +
"UNIQUE (siteID, faviconID) " +
") "
let widestFavicons =
"CREATE VIEW IF NOT EXISTS \(ViewWidestFaviconsForSites) AS " +
"SELECT " +
"\(TableFaviconSites).siteID AS siteID, " +
"favicons.id AS iconID, " +
"favicons.url AS iconURL, " +
"favicons.date AS iconDate, " +
"favicons.type AS iconType, " +
"MAX(favicons.width) AS iconWidth " +
"FROM \(TableFaviconSites), favicons WHERE " +
"\(TableFaviconSites).faviconID = favicons.id " +
"GROUP BY siteID "
let historyIDsWithIcon =
"CREATE VIEW IF NOT EXISTS \(ViewHistoryIDsWithWidestFavicons) AS " +
"SELECT history.id AS id, " +
"iconID, iconURL, iconDate, iconType, iconWidth " +
"FROM history " +
"LEFT OUTER JOIN " +
"\(ViewWidestFaviconsForSites) ON history.id = \(ViewWidestFaviconsForSites).siteID "
let iconForURL =
"CREATE VIEW IF NOT EXISTS \(ViewIconForURL) AS " +
"SELECT history.url AS url, icons.iconID AS iconID FROM " +
"history, \(ViewWidestFaviconsForSites) AS icons WHERE " +
"history.id = icons.siteID "
let bookmarks =
"CREATE TABLE IF NOT EXISTS bookmarks (" +
"id INTEGER PRIMARY KEY AUTOINCREMENT, " +
"guid TEXT NOT NULL UNIQUE, " +
"type TINYINT NOT NULL, " +
"url TEXT, " +
"parent INTEGER REFERENCES bookmarks(id) NOT NULL, " +
"faviconID INTEGER REFERENCES favicons(id) ON DELETE SET NULL, " +
"title TEXT" +
") "
let queries: [String] = [
getDomainsTableCreationString(),
getHistoryTableCreationString(),
favicons,
visits,
bookmarks,
faviconSites,
indexShouldUpload,
indexSiteIDDate,
widestFavicons,
historyIDsWithIcon,
iconForURL,
getQueueTableCreationString(),
]
return self.run(db, queries: queries) &&
self.prepopulateRootFolders(db)
}
}
class BrowserTableV10: BaseHistoricalBrowserTable {
var name: String { return "BROWSER" }
var version: Int { return 10 }
func prepopulateRootFolders(_ db: SQLiteDBConnection) -> Bool {
let type = BookmarkNodeType.folder.rawValue
let root = BookmarkRoots.RootID
let titleMobile = NSLocalizedString("Mobile Bookmarks", tableName: "Storage", comment: "The title of the folder that contains mobile bookmarks. This should match bookmarks.folder.mobile.label on Android.")
let titleMenu = NSLocalizedString("Bookmarks Menu", tableName: "Storage", comment: "The name of the folder that contains desktop bookmarks in the menu. This should match bookmarks.folder.menu.label on Android.")
let titleToolbar = NSLocalizedString("Bookmarks Toolbar", tableName: "Storage", comment: "The name of the folder that contains desktop bookmarks in the toolbar. This should match bookmarks.folder.toolbar.label on Android.")
let titleUnsorted = NSLocalizedString("Unsorted Bookmarks", tableName: "Storage", comment: "The name of the folder that contains unsorted desktop bookmarks. This should match bookmarks.folder.unfiled.label on Android.")
let args: Args = [
root, BookmarkRoots.RootGUID, type, "Root", root,
BookmarkRoots.MobileID, BookmarkRoots.MobileFolderGUID, type, titleMobile, root,
BookmarkRoots.MenuID, BookmarkRoots.MenuFolderGUID, type, titleMenu, root,
BookmarkRoots.ToolbarID, BookmarkRoots.ToolbarFolderGUID, type, titleToolbar, root,
BookmarkRoots.UnfiledID, BookmarkRoots.UnfiledFolderGUID, type, titleUnsorted, root,
]
let sql =
"INSERT INTO bookmarks (id, guid, type, url, title, parent) VALUES " +
"(?, ?, ?, NULL, ?, ?), " + // Root
"(?, ?, ?, NULL, ?, ?), " + // Mobile
"(?, ?, ?, NULL, ?, ?), " + // Menu
"(?, ?, ?, NULL, ?, ?), " + // Toolbar
"(?, ?, ?, NULL, ?, ?) " // Unsorted
return self.run(db, sql: sql, args: args)
}
func getHistoryTableCreationString(forVersion version: Int = BrowserTable.DefaultVersion) -> String {
return "CREATE TABLE IF NOT EXISTS history (" +
"id INTEGER PRIMARY KEY AUTOINCREMENT, " +
"guid TEXT NOT NULL UNIQUE, " + // Not null, but the value might be replaced by the server's.
"url TEXT UNIQUE, " + // May only be null for deleted records.
"title TEXT NOT NULL, " +
"server_modified INTEGER, " + // Can be null. Integer milliseconds.
"local_modified INTEGER, " + // Can be null. Client clock. In extremis only.
"is_deleted TINYINT NOT NULL, " + // Boolean. Locally deleted.
"should_upload TINYINT NOT NULL, " + // Boolean. Set when changed or visits added.
"domain_id INTEGER REFERENCES \(TableDomains)(id) ON DELETE CASCADE, " +
"CONSTRAINT urlOrDeleted CHECK (url IS NOT NULL OR is_deleted = 1)" +
")"
}
func getDomainsTableCreationString() -> String {
return "CREATE TABLE IF NOT EXISTS \(TableDomains) (" +
"id INTEGER PRIMARY KEY AUTOINCREMENT, " +
"domain TEXT NOT NULL UNIQUE, " +
"showOnTopSites TINYINT NOT NULL DEFAULT 1" +
")"
}
func getQueueTableCreationString() -> String {
return "CREATE TABLE IF NOT EXISTS \(TableQueuedTabs) (" +
"url TEXT NOT NULL UNIQUE, " +
"title TEXT" +
") "
}
func getBookmarksMirrorTableCreationString() -> String {
// The stupid absence of naming conventions here is thanks to pre-Sync Weave. Sorry.
// For now we have the simplest possible schema: everything in one.
let sql =
"CREATE TABLE IF NOT EXISTS \(TableBookmarksMirror) " +
// Shared fields.
"( id INTEGER PRIMARY KEY AUTOINCREMENT" +
", guid TEXT NOT NULL UNIQUE" +
", type TINYINT NOT NULL" + // Type enum. TODO: BookmarkNodeType needs to be extended.
// Record/envelope metadata that'll allow us to do merges.
", server_modified INTEGER NOT NULL" + // Milliseconds.
", is_deleted TINYINT NOT NULL DEFAULT 0" + // Boolean
", hasDupe TINYINT NOT NULL DEFAULT 0" + // Boolean, 0 (false) if deleted.
", parentid TEXT" + // GUID
", parentName TEXT" +
// Type-specific fields. These should be NOT NULL in many cases, but we're going
// for a sparse schema, so this'll do for now. Enforce these in the application code.
", feedUri TEXT, siteUri TEXT" + // LIVEMARKS
", pos INT" + // SEPARATORS
", title TEXT, description TEXT" + // FOLDERS, BOOKMARKS, QUERIES
", bmkUri TEXT, tags TEXT, keyword TEXT" + // BOOKMARKS, QUERIES
", folderName TEXT, queryId TEXT" + // QUERIES
", CONSTRAINT parentidOrDeleted CHECK (parentid IS NOT NULL OR is_deleted = 1)" +
", CONSTRAINT parentNameOrDeleted CHECK (parentName IS NOT NULL OR is_deleted = 1)" +
")"
return sql
}
/**
* We need to explicitly store what's provided by the server, because we can't rely on
* referenced child nodes to exist yet!
*/
func getBookmarksMirrorStructureTableCreationString() -> String {
return "CREATE TABLE IF NOT EXISTS \(TableBookmarksMirrorStructure) " +
"( parent TEXT NOT NULL REFERENCES \(TableBookmarksMirror)(guid) ON DELETE CASCADE" +
", child TEXT NOT NULL" + // Should be the GUID of a child.
", idx INTEGER NOT NULL" + // Should advance from 0.
")"
}
}
extension BrowserTableV10: SectionCreator, TableInfo {
func create(_ db: SQLiteDBConnection) -> Bool {
let favicons =
"CREATE TABLE IF NOT EXISTS favicons (" +
"id INTEGER PRIMARY KEY AUTOINCREMENT, " +
"url TEXT NOT NULL UNIQUE, " +
"width INTEGER, " +
"height INTEGER, " +
"type INTEGER NOT NULL, " +
"date REAL NOT NULL" +
") "
// Right now we don't need to track per-visit deletions: Sync can't
// represent them! See Bug 1157553 Comment 6.
// We flip the should_upload flag on the history item when we add a visit.
// If we ever want to support logic like not bothering to sync if we added
// and then rapidly removed a visit, then we need an 'is_new' flag on each visit.
let visits =
"CREATE TABLE IF NOT EXISTS visits (" +
"id INTEGER PRIMARY KEY AUTOINCREMENT, " +
"siteID INTEGER NOT NULL REFERENCES history(id) ON DELETE CASCADE, " +
"date REAL NOT NULL, " + // Microseconds since epoch.
"type INTEGER NOT NULL, " +
"is_local TINYINT NOT NULL, " + // Some visits are local. Some are remote ('mirrored'). This boolean flag is the split.
"UNIQUE (siteID, date, type) " +
") "
let indexShouldUpload: String
if self.supportsPartialIndices {
// There's no point tracking rows that are not flagged for upload.
indexShouldUpload =
"CREATE INDEX IF NOT EXISTS \(IndexHistoryShouldUpload) " +
"ON history (should_upload) WHERE should_upload = 1"
} else {
indexShouldUpload =
"CREATE INDEX IF NOT EXISTS \(IndexHistoryShouldUpload) " +
"ON history (should_upload)"
}
let indexSiteIDDate =
"CREATE INDEX IF NOT EXISTS \(IndexVisitsSiteIDIsLocalDate) " +
"ON visits (siteID, is_local, date)"
let faviconSites =
"CREATE TABLE IF NOT EXISTS \(TableFaviconSites) (" +
"id INTEGER PRIMARY KEY AUTOINCREMENT, " +
"siteID INTEGER NOT NULL REFERENCES history(id) ON DELETE CASCADE, " +
"faviconID INTEGER NOT NULL REFERENCES favicons(id) ON DELETE CASCADE, " +
"UNIQUE (siteID, faviconID) " +
") "
let widestFavicons =
"CREATE VIEW IF NOT EXISTS \(ViewWidestFaviconsForSites) AS " +
"SELECT " +
"\(TableFaviconSites).siteID AS siteID, " +
"favicons.id AS iconID, " +
"favicons.url AS iconURL, " +
"favicons.date AS iconDate, " +
"favicons.type AS iconType, " +
"MAX(favicons.width) AS iconWidth " +
"FROM \(TableFaviconSites), favicons WHERE " +
"\(TableFaviconSites).faviconID = favicons.id " +
"GROUP BY siteID "
let historyIDsWithIcon =
"CREATE VIEW IF NOT EXISTS \(ViewHistoryIDsWithWidestFavicons) AS " +
"SELECT history.id AS id, " +
"iconID, iconURL, iconDate, iconType, iconWidth " +
"FROM history " +
"LEFT OUTER JOIN " +
"\(ViewWidestFaviconsForSites) ON history.id = \(ViewWidestFaviconsForSites).siteID "
let iconForURL =
"CREATE VIEW IF NOT EXISTS \(ViewIconForURL) AS " +
"SELECT history.url AS url, icons.iconID AS iconID FROM " +
"history, \(ViewWidestFaviconsForSites) AS icons WHERE " +
"history.id = icons.siteID "
let bookmarks =
"CREATE TABLE IF NOT EXISTS bookmarks (" +
"id INTEGER PRIMARY KEY AUTOINCREMENT, " +
"guid TEXT NOT NULL UNIQUE, " +
"type TINYINT NOT NULL, " +
"url TEXT, " +
"parent INTEGER REFERENCES bookmarks(id) NOT NULL, " +
"faviconID INTEGER REFERENCES favicons(id) ON DELETE SET NULL, " +
"title TEXT" +
") "
let bookmarksMirror = getBookmarksMirrorTableCreationString()
let bookmarksMirrorStructure = getBookmarksMirrorStructureTableCreationString()
let indexStructureParentIdx = "CREATE INDEX IF NOT EXISTS \(IndexBookmarksMirrorStructureParentIdx) " +
"ON \(TableBookmarksMirrorStructure) (parent, idx)"
let queries: [String] = [
getDomainsTableCreationString(),
getHistoryTableCreationString(),
favicons,
visits,
bookmarks,
bookmarksMirror,
bookmarksMirrorStructure,
indexStructureParentIdx,
faviconSites,
indexShouldUpload,
indexSiteIDDate,
widestFavicons,
historyIDsWithIcon,
iconForURL,
getQueueTableCreationString(),
]
return self.run(db, queries: queries) &&
self.prepopulateRootFolders(db)
}
}
class TestSQLiteHistory: XCTestCase {
let files = MockFiles()
fileprivate func deleteDatabases() {
for v in ["6", "7", "8", "10", "6-data"] {
do {
try files.remove("browser-v\(v).db")
} catch {}
}
do {
try files.remove("browser.db")
try files.remove("historysynced.db")
} catch {}
}
override func tearDown() {
super.tearDown()
self.deleteDatabases()
}
override func setUp() {
super.setUp()
// Just in case tearDown didn't run or succeed last time!
self.deleteDatabases()
}
// Test that our visit partitioning for frecency is correct.
func testHistoryLocalAndRemoteVisits() {
let db = BrowserDB(filename: "browser.db", files: files)
let prefs = MockProfilePrefs()
let history = SQLiteHistory(db: db, prefs: prefs)
let siteL = Site(url: "http://url1/", title: "title local only")
let siteR = Site(url: "http://url2/", title: "title remote only")
let siteB = Site(url: "http://url3/", title: "title local and remote")
siteL.guid = "locallocal12"
siteR.guid = "remoteremote"
siteB.guid = "bothbothboth"
let siteVisitL1 = SiteVisit(site: siteL, date: baseInstantInMicros + 1000, type: VisitType.link)
let siteVisitL2 = SiteVisit(site: siteL, date: baseInstantInMicros + 2000, type: VisitType.link)
let siteVisitR1 = SiteVisit(site: siteR, date: baseInstantInMicros + 1000, type: VisitType.link)
let siteVisitR2 = SiteVisit(site: siteR, date: baseInstantInMicros + 2000, type: VisitType.link)
let siteVisitR3 = SiteVisit(site: siteR, date: baseInstantInMicros + 3000, type: VisitType.link)
let siteVisitBL1 = SiteVisit(site: siteB, date: baseInstantInMicros + 4000, type: VisitType.link)
let siteVisitBR1 = SiteVisit(site: siteB, date: baseInstantInMicros + 5000, type: VisitType.link)
let deferred =
history.clearHistory()
>>> { history.addLocalVisit(siteVisitL1) }
>>> { history.addLocalVisit(siteVisitL2) }
>>> { history.addLocalVisit(siteVisitBL1) }
>>> { history.insertOrUpdatePlace(siteL.asPlace(), modified: baseInstantInMillis + 2) }
>>> { history.insertOrUpdatePlace(siteR.asPlace(), modified: baseInstantInMillis + 3) }
>>> { history.insertOrUpdatePlace(siteB.asPlace(), modified: baseInstantInMillis + 5) }
// Do this step twice, so we exercise the dupe-visit handling.
>>> { history.storeRemoteVisits([siteVisitR1, siteVisitR2, siteVisitR3], forGUID: siteR.guid!) }
>>> { history.storeRemoteVisits([siteVisitR1, siteVisitR2, siteVisitR3], forGUID: siteR.guid!) }
>>> { history.storeRemoteVisits([siteVisitBR1], forGUID: siteB.guid!) }
>>> { history.getSitesByFrecencyWithHistoryLimit(3)
>>== { (sites: Cursor) -> Success in
XCTAssertEqual(3, sites.count)
// Two local visits beat a single later remote visit and one later local visit.
// Two local visits beat three remote visits.
XCTAssertEqual(siteL.guid!, sites[0]!.guid!)
XCTAssertEqual(siteB.guid!, sites[1]!.guid!)
XCTAssertEqual(siteR.guid!, sites[2]!.guid!)
return succeed()
}
// This marks everything as modified so we can fetch it.
>>> history.onRemovedAccount
// Now check that we have no duplicate visits.
>>> { history.getModifiedHistoryToUpload()
>>== { (places) -> Success in
if let (_, visits) = places.find({$0.0.guid == siteR.guid!}) {
XCTAssertEqual(3, visits.count)
} else {
XCTFail("Couldn't find site R.")
}
return succeed()
}
}
}
XCTAssertTrue(deferred.value.isSuccess)
}
func testUpgrades() {
let sources: [(Int, SectionCreator)] = [
(6, BrowserTableV6()),
(7, BrowserTableV7()),
(8, BrowserTableV8()),
(10, BrowserTableV10()),
]
let destination = BrowserTable()
for (version, table) in sources {
let db = BrowserDB(filename: "browser-v\(version).db", files: files)
XCTAssertTrue(
db.runWithConnection { (conn, err) in
XCTAssertTrue(table.create(conn), "Creating browser table version \(version)")
// And we can upgrade to the current version.
XCTAssertTrue(destination.updateTable(conn, from: table.version), "Upgrading browser table from version \(version)")
}.value.isSuccess
)
db.forceClose()
}
}
func testUpgradesWithData() {
let db = BrowserDB(filename: "browser-v6-data.db", files: files)
XCTAssertTrue(db.createOrUpdate(BrowserTableV6()) == .success, "Creating browser table version 6")
// Insert some data.
let queries = [
"INSERT INTO domains (id, domain) VALUES (1, 'example.com')",
"INSERT INTO history (id, guid, url, title, server_modified, local_modified, is_deleted, should_upload, domain_id) VALUES (5, 'guid', 'http://www.example.com', 'title', 5, 10, 0, 1, 1)",
"INSERT INTO visits (siteID, date, type, is_local) VALUES (5, 15, 1, 1)",
"INSERT INTO favicons (url, width, height, type, date) VALUES ('http://www.example.com/favicon.ico', 10, 10, 1, 20)",
"INSERT INTO favicon_sites (siteID, faviconID) VALUES (5, 1)",
"INSERT INTO bookmarks (guid, type, url, parent, faviconID, title) VALUES ('guid', 1, 'http://www.example.com', 0, 1, 'title')"
]
XCTAssertTrue(db.run(queries).value.isSuccess)
// And we can upgrade to the current version.
XCTAssertTrue(db.createOrUpdate(BrowserTable()) == .success, "Upgrading browser table from version 6")
let prefs = MockProfilePrefs()
let history = SQLiteHistory(db: db, prefs: prefs)
let results = history.getSitesByLastVisit(10).value.successValue
XCTAssertNotNil(results)
XCTAssertEqual(results![0]?.url, "http://www.example.com")
db.forceClose()
}
func testDomainUpgrade() {
let db = BrowserDB(filename: "browser.db", files: files)
let prefs = MockProfilePrefs()
let history = SQLiteHistory(db: db, prefs: prefs)
let site = Site(url: "http://www.example.com/test1.1", title: "title one")
var err: NSError? = nil
// Insert something with an invalid domain ID. We have to manually do this since domains are usually hidden.
let _ = db.withConnection(&err, callback: { (connection, err) -> Int in
let insert = "INSERT INTO \(TableHistory) (guid, url, title, local_modified, is_deleted, should_upload, domain_id) " +
"?, ?, ?, ?, ?, ?, ?"
let args: Args = [Bytes.generateGUID(), site.url, site.title, Date.now(), 0, 0, -1]
err = connection.executeChange(insert, withArgs: args)
return 0
})
// Now insert it again. This should update the domain
history.addLocalVisit(SiteVisit(site: site, date: Date.nowMicroseconds(), type: VisitType.link)).succeeded()
// DomainID isn't normally exposed, so we manually query to get it
let results = db.withConnection(&err, callback: { (connection, err) -> Cursor<Int> in
let sql = "SELECT domain_id FROM \(TableHistory) WHERE url = ?"
let args: Args = [site.url]
return connection.executeQuery(sql, factory: IntFactory, withArgs: args)
})
XCTAssertNotEqual(results[0]!, -1, "Domain id was updated")
}
func testDomains() {
let db = BrowserDB(filename: "browser.db", files: files)
let prefs = MockProfilePrefs()
let history = SQLiteHistory(db: db, prefs: prefs)
let initialGuid = Bytes.generateGUID()
let site11 = Site(url: "http://www.example.com/test1.1", title: "title one")
let site12 = Site(url: "http://www.example.com/test1.2", title: "title two")
let site13 = Place(guid: initialGuid, url: "http://www.example.com/test1.3", title: "title three")
let site3 = Site(url: "http://www.example2.com/test1", title: "title three")
let expectation = self.expectation(description: "First.")
history.clearHistory().bind({ success in
return all([history.addLocalVisit(SiteVisit(site: site11, date: Date.nowMicroseconds(), type: VisitType.link)),
history.addLocalVisit(SiteVisit(site: site12, date: Date.nowMicroseconds(), type: VisitType.link)),
history.addLocalVisit(SiteVisit(site: site3, date: Date.nowMicroseconds(), type: VisitType.link))])
}).bind({ (results: [Maybe<()>]) in
return history.insertOrUpdatePlace(site13, modified: Date.nowMicroseconds())
}).bind({ guid in
XCTAssertEqual(guid.successValue!, initialGuid, "Guid is correct")
return history.getSitesByFrecencyWithHistoryLimit(10)
}).bind({ (sites: Maybe<Cursor<Site>>) -> Success in
XCTAssert(sites.successValue!.count == 2, "2 sites returned")
return history.removeSiteFromTopSites(site11)
}).bind({ success in
XCTAssertTrue(success.isSuccess, "Remove was successful")
return history.getSitesByFrecencyWithHistoryLimit(10)
}).upon({ (sites: Maybe<Cursor<Site>>) in
XCTAssert(sites.successValue!.count == 1, "1 site returned")
expectation.fulfill()
})
waitForExpectations(timeout: 10.0) { error in
return
}
}
func testHistoryIsSynced() {
let db = BrowserDB(filename: "historysynced.db", files: files)
let prefs = MockProfilePrefs()
let history = SQLiteHistory(db: db, prefs: prefs)
let initialGUID = Bytes.generateGUID()
let site = Place(guid: initialGUID, url: "http://www.example.com/test1.3", title: "title")
XCTAssertFalse(history.hasSyncedHistory().value.successValue ?? true)
XCTAssertTrue(history.insertOrUpdatePlace(site, modified: Date.now()).value.isSuccess)
XCTAssertTrue(history.hasSyncedHistory().value.successValue ?? false)
}
// This is a very basic test. Adds an entry, retrieves it, updates it,
// and then clears the database.
func testHistoryTable() {
let db = BrowserDB(filename: "browser.db", files: files)
let prefs = MockProfilePrefs()
let history = SQLiteHistory(db: db, prefs: prefs)
let bookmarks = SQLiteBookmarks(db: db)
let site1 = Site(url: "http://url1/", title: "title one")
let site1Changed = Site(url: "http://url1/", title: "title one alt")
let siteVisit1 = SiteVisit(site: site1, date: Date.nowMicroseconds(), type: VisitType.link)
let siteVisit2 = SiteVisit(site: site1Changed, date: Date.nowMicroseconds() + 1000, type: VisitType.bookmark)
let site2 = Site(url: "http://url2/", title: "title two")
let siteVisit3 = SiteVisit(site: site2, date: Date.nowMicroseconds() + 2000, type: VisitType.link)
let expectation = self.expectation(description: "First.")
func done() -> Success {
expectation.fulfill()
return succeed()
}
func checkSitesByFrecency(_ f: @escaping (Cursor<Site>) -> Success) -> () -> Success {
return {
history.getSitesByFrecencyWithHistoryLimit(10)
>>== f
}
}
func checkSitesByDate(_ f: @escaping (Cursor<Site>) -> Success) -> () -> Success {
return {
history.getSitesByLastVisit(10)
>>== f
}
}
func checkSitesWithFilter(_ filter: String, f: @escaping (Cursor<Site>) -> Success) -> () -> Success {
return {
history.getSitesByFrecencyWithHistoryLimit(10, whereURLContains: filter)
>>== f
}
}
func checkDeletedCount(_ expected: Int) -> () -> Success {
return {
history.getDeletedHistoryToUpload()
>>== { guids in
XCTAssertEqual(expected, guids.count)
return succeed()
}
}
}
history.clearHistory()
>>> { history.addLocalVisit(siteVisit1) }
>>> checkSitesByFrecency { (sites: Cursor) -> Success in
XCTAssertEqual(1, sites.count)
XCTAssertEqual(site1.title, sites[0]!.title)
XCTAssertEqual(site1.url, sites[0]!.url)
sites.close()
return succeed()
}
>>> { history.addLocalVisit(siteVisit2) }
>>> checkSitesByFrecency { (sites: Cursor) -> Success in
XCTAssertEqual(1, sites.count)
XCTAssertEqual(site1Changed.title, sites[0]!.title)
XCTAssertEqual(site1Changed.url, sites[0]!.url)
sites.close()
return succeed()
}
>>> { history.addLocalVisit(siteVisit3) }
>>> checkSitesByFrecency { (sites: Cursor) -> Success in
XCTAssertEqual(2, sites.count)
// They're in order of frecency.
XCTAssertEqual(site1Changed.title, sites[0]!.title)
XCTAssertEqual(site2.title, sites[1]!.title)
return succeed()
}
>>> checkSitesByDate { (sites: Cursor<Site>) -> Success in
XCTAssertEqual(2, sites.count)
// They're in order of date last visited.
let first = sites[0]!
let second = sites[1]!
XCTAssertEqual(site2.title, first.title)
XCTAssertEqual(site1Changed.title, second.title)
XCTAssertTrue(siteVisit3.date == first.latestVisit!.date)
return succeed()
}
>>> checkSitesWithFilter("two") { (sites: Cursor<Site>) -> Success in
XCTAssertEqual(1, sites.count)
let first = sites[0]!
XCTAssertEqual(site2.title, first.title)
return succeed()
}
>>>
checkDeletedCount(0)
>>> { history.removeHistoryForURL("http://url2/") }
>>>
checkDeletedCount(1)
>>> checkSitesByFrecency { (sites: Cursor) -> Success in
XCTAssertEqual(1, sites.count)
// They're in order of frecency.
XCTAssertEqual(site1Changed.title, sites[0]!.title)
return succeed()
}
>>> { history.clearHistory() }
>>>
checkDeletedCount(0)
>>> checkSitesByDate { (sites: Cursor<Site>) -> Success in
XCTAssertEqual(0, sites.count)
return succeed()
}
>>> checkSitesByFrecency { (sites: Cursor<Site>) -> Success in
XCTAssertEqual(0, sites.count)
return succeed()
}
>>> done
waitForExpectations(timeout: 10.0) { error in
return
}
}
func testFaviconTable() {
let db = BrowserDB(filename: "browser.db", files: files)
let prefs = MockProfilePrefs()
let history = SQLiteHistory(db: db, prefs: prefs)
let bookmarks = SQLiteBookmarks(db: db)
let expectation = self.expectation(description: "First.")
func done() -> Success {
expectation.fulfill()
return succeed()
}
func updateFavicon() -> Success {
let fav = Favicon(url: "http://url2/", date: Date(), type: .icon)
fav.id = 1
let site = Site(url: "http://bookmarkedurl/", title: "My Bookmark")
return history.addFavicon(fav, forSite: site) >>> succeed
}
func checkFaviconForBookmarkIsNil() -> Success {
return bookmarks.bookmarksByURL("http://bookmarkedurl/".asURL!) >>== { results in
XCTAssertEqual(1, results.count)
XCTAssertNil(results[0]?.favicon)
return succeed()
}
}
func checkFaviconWasSetForBookmark() -> Success {
return history.getFaviconsForBookmarkedURL("http://bookmarkedurl/") >>== { results in
XCTAssertEqual(1, results.count)
if let actualFaviconURL = results[0]??.url {
XCTAssertEqual("http://url2/", actualFaviconURL)
}
return succeed()
}
}
func removeBookmark() -> Success {
return bookmarks.testFactory.removeByURL("http://bookmarkedurl/")
}
func checkFaviconWasRemovedForBookmark() -> Success {
return history.getFaviconsForBookmarkedURL("http://bookmarkedurl/") >>== { results in
XCTAssertEqual(0, results.count)
return succeed()
}
}
history.clearAllFavicons()
>>> bookmarks.clearBookmarks
>>> { bookmarks.addToMobileBookmarks("http://bookmarkedurl/".asURL!, title: "Title", favicon: nil) }
>>> checkFaviconForBookmarkIsNil
>>> updateFavicon
>>> checkFaviconWasSetForBookmark
>>> removeBookmark
>>> checkFaviconWasRemovedForBookmark
>>> done
waitForExpectations(timeout: 10.0) { error in
return
}
}
func testTopSitesFrecencyOrder() {
let db = BrowserDB(filename: "browser.db", files: files)
let prefs = MockProfilePrefs()
let history = SQLiteHistory(db: db, prefs: prefs)
history.setTopSitesCacheSize(20)
history.clearTopSitesCache().value
history.clearHistory().value
// Lets create some history. This will create 100 sites that will have 21 local and 21 remote visits
populateHistoryForFrecencyCalculations(history, siteCount: 100)
// Create a new site thats for an existing domain but a different URL.
let site = Site(url: "http://s\(5)ite\(5).com/foo-different-url", title: "A \(5) different url")
site.guid = "abc\(5)defhi"
history.insertOrUpdatePlace(site.asPlace(), modified: baseInstantInMillis - 20000).value
// Don't give it any remote visits. But give it 100 local visits. This should be the new Topsite!
for i in 0...100 {
addVisitForSite(site, intoHistory: history, from: .local, atTime: advanceTimestamp(baseInstantInMicros, by: 1000000 * i))
}
let expectation = self.expectation(description: "First.")
func done() -> Success {
expectation.fulfill()
return succeed()
}
func loadCache() -> Success {
return history.updateTopSitesCacheIfInvalidated() >>> succeed
}
func checkTopSitesReturnsResults() -> Success {
return history.getTopSitesWithLimit(20) >>== { topSites in
XCTAssertEqual(topSites.count, 20)
XCTAssertEqual(topSites[0]!.guid, "abc\(5)defhi")
return succeed()
}
}
loadCache()
>>> checkTopSitesReturnsResults
>>> done
waitForExpectations(timeout: 10.0) { error in
return
}
}
func testTopSitesFiltersGoogle() {
let db = BrowserDB(filename: "browser.db", files: files)
let prefs = MockProfilePrefs()
let history = SQLiteHistory(db: db, prefs: prefs)
history.setTopSitesCacheSize(20)
history.clearTopSitesCache().value
history.clearHistory().value
// Lets create some history. This will create 100 sites that will have 21 local and 21 remote visits
populateHistoryForFrecencyCalculations(history, siteCount: 100)
func createTopSite(url: String, guid: String) {
let site = Site(url: url, title: "Hi")
site.guid = guid
history.insertOrUpdatePlace(site.asPlace(), modified: baseInstantInMillis - 20000).value
// Don't give it any remote visits. But give it 100 local visits. This should be the new Topsite!
for i in 0...100 {
addVisitForSite(site, intoHistory: history, from: .local, atTime: advanceTimestamp(baseInstantInMicros, by: 1000000 * i))
}
}
createTopSite(url: "http://google.com", guid: "abcgoogle") // should not be a topsite
createTopSite(url: "http://www.google.com", guid: "abcgoogle1") // should not be a topsite
createTopSite(url: "http://google.co.za", guid: "abcgoogleza") // should not be a topsite
createTopSite(url: "http://docs.google.com", guid: "docsgoogle") // should be a topsite
let expectation = self.expectation(description: "First.")
func done() -> Success {
expectation.fulfill()
return succeed()
}
func loadCache() -> Success {
return history.updateTopSitesCacheIfInvalidated() >>> succeed
}
func checkTopSitesReturnsResults() -> Success {
return history.getTopSitesWithLimit(20) >>== { topSites in
XCTAssertEqual(topSites[0]?.guid, "docsgoogle") // google docs should be the first topsite
// make sure all other google guids are not in the topsites array
topSites.forEach {
let guid: String = $0!.guid! // type checking is hard
XCTAssertNil(["abcgoogle", "abcgoogle1", "abcgoogleza"].index(of: guid))
}
XCTAssertEqual(topSites.count, 20)
return succeed()
}
}
loadCache()
>>> checkTopSitesReturnsResults
>>> done
waitForExpectations(timeout: 10.0) { error in
return
}
}
func testTopSitesCache() {
let db = BrowserDB(filename: "browser.db", files: files)
let prefs = MockProfilePrefs()
let history = SQLiteHistory(db: db, prefs: prefs)
history.setTopSitesCacheSize(20)
history.clearTopSitesCache().succeeded()
history.clearHistory().succeeded()
// Make sure that we get back the top sites
populateHistoryForFrecencyCalculations(history, siteCount: 100)
// Add extra visits to the 5th site to bubble it to the top of the top sites cache
let site = Site(url: "http://s\(5)ite\(5).com/foo", title: "A \(5)")
site.guid = "abc\(5)def"
for i in 0...20 {
addVisitForSite(site, intoHistory: history, from: .local, atTime: advanceTimestamp(baseInstantInMicros, by: 1000000 * i))
}
let expectation = self.expectation(description: "First.")
func done() -> Success {
expectation.fulfill()
return succeed()
}
func loadCache() -> Success {
return history.updateTopSitesCacheIfInvalidated() >>> succeed
}
func checkTopSitesReturnsResults() -> Success {
return history.getTopSitesWithLimit(20) >>== { topSites in
XCTAssertEqual(topSites.count, 20)
XCTAssertEqual(topSites[0]!.guid, "abc\(5)def")
return succeed()
}
}
func invalidateIfNeededDoesntChangeResults() -> Success {
return history.updateTopSitesCacheIfInvalidated() >>> {
return history.getTopSitesWithLimit(20) >>== { topSites in
XCTAssertEqual(topSites.count, 20)
XCTAssertEqual(topSites[0]!.guid, "abc\(5)def")
return succeed()
}
}
}
func addVisitsToZerothSite() -> Success {
let site = Site(url: "http://s\(0)ite\(0).com/foo", title: "A \(0)")
site.guid = "abc\(0)def"
for i in 0...20 {
addVisitForSite(site, intoHistory: history, from: .local, atTime: advanceTimestamp(baseInstantInMicros, by: 1000000 * i))
}
return succeed()
}
func markInvalidation() -> Success {
history.setTopSitesNeedsInvalidation()
return succeed()
}
func checkSitesInvalidate() -> Success {
history.updateTopSitesCacheIfInvalidated().succeeded()
return history.getTopSitesWithLimit(20) >>== { topSites in
XCTAssertEqual(topSites.count, 20)
XCTAssertEqual(topSites[0]!.guid, "abc\(5)def")
XCTAssertEqual(topSites[1]!.guid, "abc\(0)def")
return succeed()
}
}
loadCache()
>>> checkTopSitesReturnsResults
>>> invalidateIfNeededDoesntChangeResults
>>> markInvalidation
>>> addVisitsToZerothSite
>>> checkSitesInvalidate
>>> done
waitForExpectations(timeout: 10.0) { error in
return
}
}
func testPinnedTopSites() {
let db = BrowserDB(filename: "browser.db", files: files)
let prefs = MockProfilePrefs()
let history = SQLiteHistory(db: db, prefs: prefs)
history.setTopSitesCacheSize(20)
history.clearTopSitesCache().succeeded()
history.clearHistory().succeeded()
// add 2 sites to pinned topsite
// get pinned site and make sure it exists in the right order
// remove pinned sites
// make sure pinned sites dont exist
// create pinned sites.
let site1 = Site(url: "http://s\(1)ite\(1).com/foo", title: "A \(1)")
site1.id = 1
site1.guid = "abc\(1)def"
addVisitForSite(site1, intoHistory: history, from: .local, atTime: Date.now())
let site2 = Site(url: "http://s\(2)ite\(2).com/foo", title: "A \(2)")
site2.id = 2
site2.guid = "abc\(2)def"
addVisitForSite(site2, intoHistory: history, from: .local, atTime: Date.now())
let expectation = self.expectation(description: "First.")
func done() -> Success {
expectation.fulfill()
return succeed()
}
func addPinnedSites() -> Success {
return history.addPinnedTopSite(site1) >>== {
return history.addPinnedTopSite(site2)
}
}
func checkPinnedSites() -> Success {
return history.getPinnedTopSites() >>== { pinnedSites in
XCTAssertEqual(pinnedSites.count, 2)
XCTAssertEqual(pinnedSites[0]!.url, site2.url)
XCTAssertEqual(pinnedSites[1]!.url, site1.url, "The older pinned site should be last")
return succeed()
}
}
func removePinnedSites() -> Success {
return history.removeFromPinnedTopSites(site2) >>== {
return history.getPinnedTopSites() >>== { pinnedSites in
XCTAssertEqual(pinnedSites.count, 1, "There should only be one pinned site")
XCTAssertEqual(pinnedSites[0]!.url, site1.url, "Site2 should be the only pin left")
return succeed()
}
}
}
func dupePinnedSite() -> Success {
return history.addPinnedTopSite(site1) >>== {
return history.getPinnedTopSites() >>== { pinnedSites in
XCTAssertEqual(pinnedSites.count, 1, "There should not be a dupe")
XCTAssertEqual(pinnedSites[0]!.url, site1.url, "Site2 should be the only pin left")
return succeed()
}
}
}
func removeHistory() -> Success {
return history.clearHistory() >>== {
return history.getPinnedTopSites() >>== { pinnedSites in
XCTAssertEqual(pinnedSites.count, 1, "Pinned sites should exist after a history clear")
return succeed()
}
}
}
addPinnedSites()
>>> checkPinnedSites
>>> removePinnedSites
>>> dupePinnedSite
>>> removeHistory
>>> done
waitForExpectations(timeout: 10.0) { error in
return
}
}
}
class TestSQLiteHistoryTransactionUpdate: XCTestCase {
func testUpdateInTransaction() {
let files = MockFiles()
let db = BrowserDB(filename: "browser.db", files: files)
let prefs = MockProfilePrefs()
let history = SQLiteHistory(db: db, prefs: prefs)
history.clearHistory().succeeded()
let site = Site(url: "http://site/foo", title: "AA")
site.guid = "abcdefghiabc"
history.insertOrUpdatePlace(site.asPlace(), modified: 1234567890).succeeded()
let ts: MicrosecondTimestamp = baseInstantInMicros
let local = SiteVisit(site: site, date: ts, type: VisitType.link)
XCTAssertTrue(history.addLocalVisit(local).value.isSuccess)
}
}
class TestSQLiteHistoryFilterSplitting: XCTestCase {
let history: SQLiteHistory = {
let files = MockFiles()
let db = BrowserDB(filename: "browser.db", files: files)
let prefs = MockProfilePrefs()
return SQLiteHistory(db: db, prefs: prefs)
}()
func testWithSingleWord() {
let (fragment, args) = history.computeWhereFragmentWithFilter("foo", perWordFragment: "?", perWordArgs: { [$0] })
XCTAssertEqual(fragment, "?")
XCTAssert(stringArgsEqual(args, ["foo"]))
}
func testWithIdenticalWords() {
let (fragment, args) = history.computeWhereFragmentWithFilter("foo fo foo", perWordFragment: "?", perWordArgs: { [$0] })
XCTAssertEqual(fragment, "?")
XCTAssert(stringArgsEqual(args, ["foo"]))
}
func testWithDistinctWords() {
let (fragment, args) = history.computeWhereFragmentWithFilter("foo bar", perWordFragment: "?", perWordArgs: { [$0] })
XCTAssertEqual(fragment, "? AND ?")
XCTAssert(stringArgsEqual(args, ["foo", "bar"]))
}
func testWithDistinctWordsAndWhitespace() {
let (fragment, args) = history.computeWhereFragmentWithFilter(" foo bar ", perWordFragment: "?", perWordArgs: { [$0] })
XCTAssertEqual(fragment, "? AND ?")
XCTAssert(stringArgsEqual(args, ["foo", "bar"]))
}
func testWithSubstrings() {
let (fragment, args) = history.computeWhereFragmentWithFilter("foo bar foobar", perWordFragment: "?", perWordArgs: { [$0] })
XCTAssertEqual(fragment, "?")
XCTAssert(stringArgsEqual(args, ["foobar"]))
}
func testWithSubstringsAndIdenticalWords() {
let (fragment, args) = history.computeWhereFragmentWithFilter("foo bar foobar foobar", perWordFragment: "?", perWordArgs: { [$0] })
XCTAssertEqual(fragment, "?")
XCTAssert(stringArgsEqual(args, ["foobar"]))
}
fileprivate func stringArgsEqual(_ one: Args, _ other: Args) -> Bool {
return one.elementsEqual(other, by: { (oneElement: Any?, otherElement: Any?) -> Bool in
return (oneElement as! String) == (otherElement as! String)
})
}
}
// MARK - Private Test Helper Methods
enum VisitOrigin {
case local
case remote
}
private func populateHistoryForFrecencyCalculations(_ history: SQLiteHistory, siteCount count: Int) {
for i in 0...count {
let site = Site(url: "http://s\(i)ite\(i).com/foo", title: "A \(i)")
site.guid = "abc\(i)def"
let baseMillis: UInt64 = baseInstantInMillis - 20000
history.insertOrUpdatePlace(site.asPlace(), modified: baseMillis).succeeded()
for j in 0...20 {
let visitTime = advanceMicrosecondTimestamp(baseInstantInMicros, by: (1000000 * i) + (1000 * j))
addVisitForSite(site, intoHistory: history, from: .local, atTime: visitTime)
addVisitForSite(site, intoHistory: history, from: .remote, atTime: visitTime - 100)
}
}
}
func addVisitForSite(_ site: Site, intoHistory history: SQLiteHistory, from: VisitOrigin, atTime: MicrosecondTimestamp) {
let visit = SiteVisit(site: site, date: atTime, type: VisitType.link)
switch from {
case .local:
history.addLocalVisit(visit).succeeded()
case .remote:
history.storeRemoteVisits([visit], forGUID: site.guid!).succeeded()
}
}
| mpl-2.0 | 7afec5b1e039e0ecac57dfbbd2f96edc | 42.388199 | 231 | 0.588004 | 4.86591 | false | false | false | false |
EZ-NET/CodePiece | ESTwitter/API/Error/PostError.swift | 1 | 2006 | //
// Error.swift
// ESTwitter
//
// Created by Tomohiro Kumagai on 2020/01/27.
// Copyright © 2020 Tomohiro Kumagai. All rights reserved.
//
import Swifter
public enum PostError : Error {
public enum State {
case beforePosted
case afterPosted
// case withNoPostProcess
}
case apiError(APIError, state: State)
case tweetError(String)
case parseError(String, state: State)
case internalError(String, state: State)
case unexpectedError(Error, state: State)
}
extension PostError {
init(tweetError error: SwifterError) {
switch error.kind {
case .urlResponseError:
switch SwifterError.Response(fromMessage: error.message) {
case .some(let response):
self = .tweetError(response.message)
case .none:
self = .tweetError(error.message)
}
default:
self = .tweetError(error.message)
}
}
}
// MARK: - Swifter
internal extension SwifterError {
struct Response: Decodable {
var code: Int
var message: String
}
}
internal extension SwifterError.Response {
init?(fromMessage message: String) {
let components = message.split(separator: ",", maxSplits: 1, omittingEmptySubsequences: true)
guard let rawBody = components.last else {
return nil
}
typealias ResponseJson = [String : [SwifterError.Response]]
// let body = "{\(rawBody.trimmingCharacters(in: .whitespaces))}"
let body = rawBody
.replacingOccurrences(of: "Response:", with: "")
.trimmingCharacters(in: .whitespaces)
// let body = """
// {
// "code": 220,
// "message": "DUMMY"
// }
// """
guard
let bodyData = body.data(using: .utf8),
let jsonObject = try? JSONDecoder().decode(ResponseJson.self, from: bodyData),
let responses = jsonObject["errors"],
let response = responses.first
else {
return nil
}
self = response
}
init?(error: SwifterError) {
guard case .urlResponseError = error.kind else {
return nil
}
self.init(fromMessage: error.message)
}
}
| gpl-3.0 | 00785e43e06268d75e61ebf307bfd220 | 17.738318 | 95 | 0.665337 | 3.486957 | false | false | false | false |
nheagy/WordPress-iOS | WordPress/Classes/Models/Product.swift | 1 | 1042 | import Foundation
import StoreKit
@objc
protocol Product {
var localizedDescription: String { get }
var localizedTitle: String { get }
var price: NSDecimalNumber { get }
var priceLocale: NSLocale { get }
var productIdentifier: String { get }
}
extension SKProduct: Product {}
extension SKProduct {
public override var description: String {
return "<SKProduct: \(productIdentifier), title: \(localizedTitle)>"
}
}
class MockProduct: NSObject, Product {
let localizedDescription: String
let localizedTitle: String
let price: NSDecimalNumber
var priceLocale: NSLocale
let productIdentifier: String
init(localizedDescription: String, localizedTitle: String, price: NSDecimalNumber, priceLocale: NSLocale, productIdentifier: String) {
self.localizedDescription = localizedDescription
self.localizedTitle = localizedTitle
self.price = price
self.priceLocale = priceLocale
self.productIdentifier = productIdentifier
}
}
| gpl-2.0 | cd506172042bc90fbc36248078ec8903 | 25.717949 | 138 | 0.705374 | 5.484211 | false | false | false | false |
the-blue-alliance/the-blue-alliance-ios | the-blue-alliance-ios/Operations/App Setup/PersistentContainerOperation.swift | 1 | 1587 | import CoreData
import Foundation
import Search
import TBAOperation
class PersistentContainerOperation: TBAOperation {
let indexDelegate: TBACoreDataCoreSpotlightDelegate
let persistentContainer: NSPersistentContainer
init(indexDelegate: TBACoreDataCoreSpotlightDelegate, persistentContainer: NSPersistentContainer) {
self.indexDelegate = indexDelegate
self.persistentContainer = persistentContainer
super.init()
}
override func execute() {
// Setup our Core Data + Spotlight export
persistentContainer.persistentStoreDescriptions.forEach {
$0.setOption(indexDelegate, forKey: NSCoreDataCoreSpotlightExporter)
}
persistentContainer.loadPersistentStores(completionHandler: { (_, error) in
/*
Typical reasons for an error here include:
* The parent directory does not exist, cannot be created, or disallows writing.
* The persistent store is not accessible, due to permissions or data protection when the device is locked.
* The device is out of space.
* The store could not be migrated to the current model version.
Check the error message to determine what the actual problem was.
*/
self.persistentContainer.viewContext.automaticallyMergesChangesFromParent = true
self.persistentContainer.viewContext.mergePolicy = NSMergePolicy(merge: .mergeByPropertyStoreTrumpMergePolicyType)
self.completionError = error
self.finish()
})
}
}
| mit | 3cafd05f4c4a3e9ddce9ca310e2f3e39 | 39.692308 | 126 | 0.700693 | 5.988679 | false | false | false | false |
dche/FlatUtil | Sources/ParsingState.swift | 1 | 1546 | //
// FlatUtil - ParsingState.swift
//
// Structure for storing parsing result and position.
//
// Copyright (c) 2016 The FlatUtil authors.
// Licensed under MIT License.
struct ParsingError: Error {
let line: Int
let column: Int
let reason: String
}
struct ParsingPosition {
let string: String.UTF8View
let index: String.UTF8View.Index
let line: Int
let column: Int
var character: UInt8 {
return string[index]
}
func error<T>(message: String) -> Result<T> {
let err =
ParsingError(line: line, column: column, reason: message)
return .error(err)
}
func newline() -> Result<ParsingPosition> {
let idx = string.index(index, offsetBy: 1)
guard idx < string.endIndex else {
return self.error(message: "Unexpected end of input.")
}
let pos =
ParsingPosition(string: string, index: idx, line: line + 1, column: 0)
return .value(pos)
}
func advance() -> Result<ParsingPosition> {
let idx = string.index(index, offsetBy: 1)
guard idx < string.endIndex else {
return self.error(message: "Unexpected end of input.")
}
let pos =
ParsingPosition(string: string, index: idx, line: line, column: column + 1)
return .value(pos)
}
}
struct ParsingState<T> {
let value: T
let position: ParsingPosition
init (_ value: T, _ position: ParsingPosition) {
self.value = value
self.position = position
}
}
| mit | 237fbcb8c06a71480e7917bf5295fc84 | 24.766667 | 87 | 0.604787 | 4.015584 | false | false | false | false |
nicolafiorillo/BarcodeReader | BarcodeReader/CameraViewControllerOld.swift | 1 | 11517 | //
// ViewController.swift
// BarcodeReader
//
// Created by Nicola Fiorillo on 23/06/15.
// Copyright (c) 2015 White Peaks Mobile Software Sagl. All rights reserved.
//
import UIKit
import AVFoundation
import AssetsLibrary
class CameraViewControllerOld: UIViewController {
private var camera: AVCaptureDevice! = AVCaptureDevice.defaultDeviceWithMediaType(AVMediaTypeVideo)
private var videoInput: AVCaptureDeviceInput? = nil
private var imageOutput: AVCaptureStillImageOutput? = nil
private var captureSession: AVCaptureSession? = nil
private var videoPreview: VideoPreviewView? = nil
@IBOutlet weak var toolbar: UIView!
@IBOutlet weak var torchButton: UIButton!
@IBOutlet weak var snapButton: UIButton!
@IBOutlet weak var switchButton: UIButton!
var captureConnection: AVCaptureConnection? {
get {
if imageOutput == nil {
return nil
}
if let connections = imageOutput?.connections {
for connection in connections {
if let ports = connection.inputPorts {
for port in ports {
if port.mediaType == AVMediaTypeVideo {
return connection as? AVCaptureConnection
}
}
}
}
}
return nil
}
}
override func viewDidLoad() {
super.viewDidLoad()
assert(self.view.isKindOfClass(VideoPreviewView), "Wrong view class")
videoPreview = self.view as? VideoPreviewView
let effectView = UIVisualEffectView(effect: UIBlurEffect(style: UIBlurEffectStyle.Light))
effectView.frame = self.toolbar.bounds
toolbar.insertSubview(effectView, atIndex: 0)
authorizeAndSetupCamera()
let tapRecognizer = UITapGestureRecognizer(target: self, action: "handleTap:")
self.view.addGestureRecognizer(tapRecognizer)
let notificationCenter = NSNotificationCenter.defaultCenter()
notificationCenter.addObserver(self, selector: "subjetChanged:", name: AVCaptureDeviceSubjectAreaDidChangeNotification, object: nil)
}
deinit {
NSNotificationCenter.defaultCenter().removeObserver(self)
}
func subjetChanged(notification: NSNotification) {
if camera.focusMode == AVCaptureFocusMode.Locked {
if camera.lockForConfiguration(nil) {
if camera.focusPointOfInterestSupported {
camera.focusPointOfInterest = CGPoint(x: 0.5, y: 0.5)
}
if camera.isFocusModeSupported(AVCaptureFocusMode.ContinuousAutoFocus) {
camera.focusMode = AVCaptureFocusMode.ContinuousAutoFocus
}
camera.unlockForConfiguration()
println("BarcodeReader: continuous focus mode")
}
}
}
func handleTap(gesture: UITapGestureRecognizer) {
if gesture.state == UIGestureRecognizerState.Ended {
if !camera.focusPointOfInterestSupported || !camera.isFocusModeSupported(AVCaptureFocusMode.AutoFocus) {
println("BarcodeReader: focus point not supported by current camera")
return
}
let locationInPreview = gesture.locationInView(videoPreview)
let locationInCapture = videoPreview?.previewLayer?.captureDevicePointOfInterestForPoint(locationInPreview)
if camera.lockForConfiguration(nil) {
camera.focusPointOfInterest = locationInCapture!
camera.focusMode = AVCaptureFocusMode.AutoFocus
println("BarcodeReader: focus mode - locked to focus point")
camera.unlockForConfiguration()
}
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func torch(sender: UIButton) {
if camera.hasTorch {
println("BarcodeReader: trying set torch")
var error: NSError? = nil
if !camera.lockForConfiguration(&error) {
println("BarcodeReader: error locking camera configuration \(error?.localizedDescription)")
return
}
toggleTorch()
camera.unlockForConfiguration()
}
}
func toggleTorch() {
let torchMode = camera.torchActive ? AVCaptureTorchMode.Off : AVCaptureTorchMode.On
if camera.isTorchModeSupported(torchMode) {
camera.torchMode = torchMode
println(String(format: "BarcodeReader: torch is %@", torchMode.rawValue == 0 ? "off" : "on"))
}
}
@IBAction func switchCam(sender: UIButton) {
captureSession?.beginConfiguration()
let newCamera = alternativeCameraToCurrent
captureSession?.removeInput(videoInput)
if let newVideoInput = CameraViewControllerOld.addVideoInputToCaptureSession(newCamera, captureSession: captureSession) {
camera = newCamera
videoInput = newVideoInput
CameraViewControllerOld.configureCamera(camera)
}
else {
captureSession?.addInput(videoInput)
}
updateConnectionToInterfaceOrientation(UIApplication.sharedApplication().statusBarOrientation)
captureSession?.commitConfiguration()
}
static func configureCamera(camera: AVCaptureDevice?) {
if (camera?.isFocusModeSupported(AVCaptureFocusMode.Locked) != nil) {
if (camera?.lockForConfiguration(nil) != nil) {
camera?.subjectAreaChangeMonitoringEnabled = true
camera?.unlockForConfiguration()
}
}
}
static func addVideoInputToCaptureSession(camera: AVCaptureDevice?, captureSession: AVCaptureSession?) -> AVCaptureDeviceInput? {
var error: NSError? = nil
let videoInput = AVCaptureDeviceInput(device:camera, error: &error)
if videoInput == nil {
println("BarcodeReader: \(error?.localizedDescription)")
return nil
}
if captureSession?.canAddInput(videoInput) == false {
println("BarcodeReader: unable to add video input to capture session")
return nil
}
captureSession?.addInput(videoInput)
return videoInput
}
@IBAction func snap(sender: UIButton) {
if let videoConnection = captureConnection {
imageOutput?.captureStillImageAsynchronouslyFromConnection(videoConnection, completionHandler: { (buffer, error) -> Void in
if error != nil {
println("BarcodeReader: \(error?.localizedDescription)")
return
}
self.authorizeAndWriteImage(buffer)
})
}
else {
println("BarcodeReader: no video connection for still image output")
return
}
}
func authorizeAndWriteImage(buffer: CMSampleBuffer!) {
let status = ALAssetsLibrary.authorizationStatus()
switch(status) {
case ALAuthorizationStatus.Authorized:
println("BarcodeReader: authorized to save image in camera roll")
writeImage(buffer)
break
case ALAuthorizationStatus.NotDetermined:
if let lib = ALAssetsLibrary() as ALAssetsLibrary? {
lib.enumerateGroupsWithTypes(ALAssetsGroupAll, usingBlock: { (group, stop: UnsafeMutablePointer<ObjCBool>) -> Void in
println("BarcodeReader: just authorized to save image in camera roll")
stop.memory = true
self.writeImage(buffer)
}, failureBlock: { (error) -> Void in
println("BarcodeReader: just unauthorized to save image in camera roll")
})
}
break
case ALAuthorizationStatus.Restricted:
println("BarcodeReader: unauthorized to save image in camera roll (Restricted)")
break;
case ALAuthorizationStatus.Denied:
println("BarcodeReader: unauthorized to save image in camera roll (Denied)")
break
default:
break
}
}
func writeImage(buffer: CMSampleBuffer!) {
let imageData = AVCaptureStillImageOutput.jpegStillImageNSDataRepresentation(buffer)
let image = UIImage(data: imageData)
UIImageWriteToSavedPhotosAlbum(image, nil, nil, nil)
}
func authorizeAndSetupCamera() {
let status = AVCaptureDevice.authorizationStatusForMediaType(AVMediaTypeVideo)
switch (status) {
case AVAuthorizationStatus.Authorized:
println("BarcodeReader: authorized to use camera")
setupCamera()
break;
case AVAuthorizationStatus.NotDetermined:
AVCaptureDevice.requestAccessForMediaType(AVMediaTypeVideo, completionHandler: { granted in
dispatch_async(dispatch_get_main_queue(), {
if granted {
self.setupCamera()
self.captureSession?.startRunning()
}
else {
println("BarcodeReader: unauthorized to use camera")
}
})
})
break;
case AVAuthorizationStatus.Restricted:
println("BarcodeReader: unauthorized to use camera (Restricted)")
break;
case AVAuthorizationStatus.Denied:
println("BarcodeReader: unauthorized to use camera (Denied)")
break;
default:
break;
}
}
func setupCamera() {
snapButton.enabled = false
switchButton.enabled = false
if (camera == nil) {
println("BarcodeReader: camera not found")
return
}
captureSession = AVCaptureSession()
videoInput = CameraViewControllerOld.addVideoInputToCaptureSession(camera, captureSession: captureSession)
imageOutput = AVCaptureStillImageOutput()
if captureSession?.canAddOutput(imageOutput) == false {
println("BarcodeReader: unable to add still image output to capture session")
return
}
captureSession?.addOutput(imageOutput)
videoPreview?.previewLayer?.session = captureSession
torchButton.enabled = camera.hasTorch;
snapButton.enabled = true
switchButton.enabled = alternativeCameraToCurrent != nil
CameraViewControllerOld.configureCamera(camera)
println("BarcodeReader: ok")
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
if captureSession == nil {
return;
}
println("startRunning")
self.captureSession?.startRunning()
}
override func viewDidDisappear(animated: Bool) {
super.viewDidDisappear(animated)
if captureSession == nil {
return;
}
println("stopRunning")
self.captureSession?.stopRunning()
}
override func viewWillTransitionToSize(size: CGSize, withTransitionCoordinator coordinator: UIViewControllerTransitionCoordinator) {
coordinator.animateAlongsideTransition({ context in
let interfaceOrientation = UIApplication.sharedApplication().statusBarOrientation
self.updateConnectionToInterfaceOrientation(interfaceOrientation)
}, completion: nil)
super.viewWillTransitionToSize(size, withTransitionCoordinator: coordinator)
}
func getVideoOrientationForUIInterfaceOrientation(interfaceOrientation: UIInterfaceOrientation) -> AVCaptureVideoOrientation {
switch (interfaceOrientation) {
case UIInterfaceOrientation.LandscapeLeft:
return AVCaptureVideoOrientation.LandscapeLeft
case UIInterfaceOrientation.LandscapeRight:
return AVCaptureVideoOrientation.LandscapeRight
case UIInterfaceOrientation.Portrait:
return AVCaptureVideoOrientation.Portrait
case UIInterfaceOrientation.PortraitUpsideDown:
return AVCaptureVideoOrientation.PortraitUpsideDown
default:
return AVCaptureVideoOrientation.Portrait
}
}
func updateConnectionToInterfaceOrientation(toInterfaceOrientation: UIInterfaceOrientation) {
if captureSession == nil {
return;
}
let capturedOrientation = getVideoOrientationForUIInterfaceOrientation(toInterfaceOrientation)
if let connections = imageOutput?.connections {
for connection in connections as! [AVCaptureConnection] {
if connection.supportsVideoOrientation {
connection.videoOrientation = capturedOrientation
}
}
}
if let layer = videoPreview?.previewLayer {
if layer.connection.supportsVideoOrientation {
videoPreview?.previewLayer?.connection.videoOrientation = capturedOrientation
}
}
}
var alternativeCameraToCurrent: AVCaptureDevice? {
get {
if captureSession == nil {
return nil
}
if let cameras = AVCaptureDevice.devicesWithMediaType(AVMediaTypeVideo) {
for cam in cameras as! [AVCaptureDevice] {
if cam != camera {
return cam
}
}
}
return nil
}
}
} | mit | 62b91e0bc49b0ea5004db1e6ce0b8712 | 27.509901 | 134 | 0.744552 | 4.636473 | false | false | false | false |
codeOfRobin/Components-Personal | Sources/ImageFromFramework.swift | 1 | 1529 | //
// ImageFromFramework.swift
// BuildingBlocks-iOS
//
// Created by Robin Malhotra on 05/09/17.
// Copyright © 2017 BuildingBlocks. All rights reserved.
//
import UIKit
class FrameworkImageLoader {
static func imageFromCurrentBundle(named name: String) -> UIImage {
if let image = UIImage.init(named: name, in: Bundle.init(for: FrameworkImageLoader.self), compatibleWith: nil) {
return image
} else {
#if DEBUG
fatalError()
#else
return UIImage()
#endif
}
}
}
public enum FrameworkImage {
public static let close = FrameworkImageLoader.imageFromCurrentBundle(named: "Close Button")
public static let chevron = FrameworkImageLoader.imageFromCurrentBundle(named: "Chevron")
public static let tick = FrameworkImageLoader.imageFromCurrentBundle(named: "Tick Button")
public static let add = FrameworkImageLoader.imageFromCurrentBundle(named: "Add Button")
public static let delete = FrameworkImageLoader.imageFromCurrentBundle(named: "Delete")
public static let empty = FrameworkImageLoader.imageFromCurrentBundle(named: "Empty")
public static let organization = FrameworkImageLoader.imageFromCurrentBundle(named: "Organization")
public static let twitter = FrameworkImageLoader.imageFromCurrentBundle(named: "Twitter")
public static let mail = FrameworkImageLoader.imageFromCurrentBundle(named: "Mail")
public static let facebook = FrameworkImageLoader.imageFromCurrentBundle(named: "Facebook")
public static let phone = FrameworkImageLoader.imageFromCurrentBundle(named: "Phone")
}
| mit | 7f0a1c9a8bac45b758ae0fefe3cc6164 | 40.297297 | 114 | 0.78534 | 4.152174 | false | false | false | false |
awsdocs/aws-doc-sdk-examples | swift/example_code/iam/CreateUser/Sources/ServiceHandler/ServiceHandler.swift | 1 | 2431 | /*
A class containing functions that interact with AWS services.
Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
SPDX-License-Identifier: Apache-2.0
*/
// snippet-start:[iam.swift.createuser.handler]
// snippet-start:[iam.swift.createuser.handler.imports]
import Foundation
import AWSIAM
import ClientRuntime
import AWSClientRuntime
// snippet-end:[iam.swift.createuser.handler.imports]
// snippet-start:[iam.swift.createuser.enum.service-error]
/// Errors returned by `ServiceHandler` functions.
enum ServiceHandlerError: Error {
case noSuchUser /// No matching user found, or unable to create the user.
}
// snippet-end:[iam.swift.createuser.enum.service-error]
/// A class containing all the code that interacts with the AWS SDK for Swift.
public class ServiceHandler {
public let client: IamClient
/// Initialize and return a new ``ServiceHandler`` object, which is used
/// to drive the AWS calls used for the example. The Region string
/// `AWS_GLOBAL` is used because users are shared across all Regions.
///
/// - Returns: A new ``ServiceHandler`` object, ready to be called to
/// execute AWS operations.
// snippet-start:[iam.swift.createuser.handler.init]
public init() async {
do {
client = try IamClient(region: "AWS_GLOBAL")
} catch {
print("ERROR: ", dump(error, name: "Initializing Amazon IAM client"))
exit(1)
}
}
// snippet-end:[iam.swift.createuser.handler.init]
/// Create a new AWS Identity and Access Management (IAM) user.
///
/// - Parameter name: The user's name.
///
/// - Returns: The ID of the newly created user.
// snippet-start:[iam.swift.createuser.handler.createuser]
public func createUser(name: String) async throws -> String {
let input = CreateUserInput(
userName: name
)
do {
let output = try await client.createUser(input: input)
guard let user = output.user else {
throw ServiceHandlerError.noSuchUser
}
guard let id = user.userId else {
throw ServiceHandlerError.noSuchUser
}
return id
} catch {
throw error
}
}
// snippet-end:[iam.swift.createuser.handler.createuser]
}
// snippet-end:[iam.swift.createuser.handler]
| apache-2.0 | d62a0e7f72abd483dfad53fdc4fd2770 | 33.728571 | 89 | 0.642534 | 4.242583 | false | false | false | false |
Neft-io/neft | packages/neft-runtime-macos/io.neft.mac/Renderer.swift | 1 | 833 | import Cocoa
class Renderer {
var app: ViewController!
var items: [Item] = []
var navigator: Navigator!
var device: Device!
var screen: Screen!
func getItemFromReader(_ reader: Reader) -> Item? {
let id = reader.getInteger()
return id == -1 ? nil : self.items[id]
}
func load() {
self.navigator = Navigator()
self.device = Device()
self.screen = Screen()
Device.register()
Screen.register()
Navigator.register()
Item.register()
Image.register()
Text.register()
NativeItem.register()
Rectangle.register()
}
func pxToDp(_ px: CGFloat) -> CGFloat {
return px / device.pixelRatio
}
func dpToPx(_ dp: CGFloat) -> CGFloat {
return dp * device.pixelRatio
}
}
| apache-2.0 | f7adc3286c226dfe8e4970a378fb4f3d | 19.825 | 55 | 0.560624 | 4.207071 | false | false | false | false |
sovereignshare/fly-smuthe | Fly Smuthe/Fly Smuthe/IntensityColorConstants.swift | 1 | 672 | //
// IntensityColors.swift
// Fly Smuthe
//
// Created by Adam M Rivera on 9/19/15.
// Copyright (c) 2015 Adam M Rivera. All rights reserved.
//
import Foundation
import UIKit
struct IntensityColorConstants{
static let Inaccurate = UIColor(white: 0.667, alpha: 0.3);
static let Smooth = UIColor(red: 0.0, green: 1.0, blue: 0.0, alpha: 0.3);
static let Light = UIColor(red: 0.5, green: 1.0, blue: 0.0, alpha: 0.3);
static let Moderate = UIColor(red: 1.0, green: 1.0, blue: 0.0, alpha: 0.3);
static let Severe = UIColor(red: 1.0, green: 0.0, blue: 0.0, alpha: 0.3);
static let Extreme = UIColor(red: 1.0, green: 0.0, blue: 0.0, alpha: 0.5);
}
| gpl-3.0 | 0e5a04b12578840e5bf32d003e64bacc | 34.368421 | 79 | 0.644345 | 2.731707 | false | false | false | false |
sovereignshare/fly-smuthe | Fly Smuthe/Fly Smuthe/IJReachability.swift | 1 | 4601 | //
// IJReachability.swift
// IJReachability
//
// Created by Isuru Nanayakkara on 1/14/15.
// Copyright (c) 2015 Appex. All rights reserved.
//
import Foundation
import SystemConfiguration
public enum IJReachabilityType {
case WWAN,
WiFi,
NotConnected
}
struct NetworkStatusConstants {
static let kNetworkAvailabilityStatusChangeNotification = "kNetworkAvailabilityStatusChangeNotification"
static let Status = "Status"
static let Offline = "Offline"
static let Online = "Online"
static let Unknown = "Unknown"
}
/// With thanks to http://stackoverflow.com/questions/25623272/how-to-use-scnetworkreachability-in-swift/25623647#25623647
public class IJReachability {
/**
:see: Original post - http://www.chrisdanielson.com/2009/07/22/iphone-network-connectivity-test-example/
*/
public class func isConnectedToNetwork() -> Bool {
var zeroAddress = sockaddr_in()
zeroAddress.sin_len = UInt8(sizeofValue(zeroAddress))
zeroAddress.sin_family = sa_family_t(AF_INET)
guard let defaultRouteReachability = withUnsafePointer(&zeroAddress, {
SCNetworkReachabilityCreateWithAddress(nil, UnsafePointer($0))
}) else {
return false
}
var flags : SCNetworkReachabilityFlags = []
if SCNetworkReachabilityGetFlags(defaultRouteReachability, &flags) == false {
return false
}
let isReachable = flags.contains(.Reachable)
let needsConnection = flags.contains(.ConnectionRequired)
return isReachable && !needsConnection
}
public class func isConnectedToNetworkOfType() -> IJReachabilityType {
//MARK: - TODO Check this when I have an actual iOS 9 device.
if !self.isConnectedToNetwork() {
return .NotConnected
}
var zeroAddress = sockaddr_in()
zeroAddress.sin_len = UInt8(sizeofValue(zeroAddress))
zeroAddress.sin_family = sa_family_t(AF_INET)
guard let defaultRouteReachability = withUnsafePointer(&zeroAddress, {
SCNetworkReachabilityCreateWithAddress(nil, UnsafePointer($0))
}) else {
return .NotConnected
}
var flags : SCNetworkReachabilityFlags = []
if SCNetworkReachabilityGetFlags(defaultRouteReachability, &flags) == false {
return .NotConnected
}
let isReachable = flags.contains(.Reachable)
let isWWAN = flags.contains(.IsWWAN)
if isReachable && isWWAN {
return .WWAN
}
if isReachable && !isWWAN {
return .WiFi
}
return .NotConnected
}
///
/// Usage:
///
/// Setup
///
///
/// NSNotificationCenter.defaultCenter().addObserver(self,
/// selector: "networkStatusDidChange:",
/// name: NetworkStatusConstants.kNetworkAvailabilityStatusChangeNotification,
/// object: nil)
///
///
/// IJReachability.monitorNetworkChanges()
///
/// Callback
///
/// func networkStatusDidChange(notification: NSNotification) {
/// let networkStatus = notification.userInfo?[ NetworkStatusConstants.Status]
/// print("\(networkStatus)")
/// }
///
///
class func monitorNetworkChanges() {
let host = "google.com"
var context = SCNetworkReachabilityContext(version: 0, info: nil, retain: nil, release: nil, copyDescription: nil)
let reachability = SCNetworkReachabilityCreateWithName(nil, host)!
SCNetworkReachabilitySetCallback(reachability, { (_, flags, _) in
let status:String?
if !flags.contains(SCNetworkReachabilityFlags.ConnectionRequired) && flags.contains(SCNetworkReachabilityFlags.Reachable) {
status = NetworkStatusConstants.Online
} else {
status = NetworkStatusConstants.Offline
}
NSNotificationCenter.defaultCenter().postNotificationName(NetworkStatusConstants.kNetworkAvailabilityStatusChangeNotification,
object: nil,
userInfo: [NetworkStatusConstants.Status: status!])
}, &context)
SCNetworkReachabilityScheduleWithRunLoop(reachability, CFRunLoopGetMain(), kCFRunLoopCommonModes)
}
} | gpl-3.0 | ae6343f9560882cd1fd28974d7e59a33 | 30.520548 | 138 | 0.610302 | 5.617827 | false | false | false | false |
acevest/acecode | learn/AcePlay/AcePlay.playground/Pages/Extensions.xcplaygroundpage/Contents.swift | 1 | 4555 | //: [Previous](@previous)
import Foundation
var str = "Hello, Extensions"
//: [Next](@next)
// 扩展 就是为一个已有的类、结构体、枚举类型或者协议类型添加新功能。这包括在没有权限获取原始源代码的情况下扩展类型的能力
// Swift 中的扩展可以:
// 1. 添加计算型属性和计算型类型属性
// 2. 定义实例方法和类型方法
// 3. 提供新的构造器
// 4. 定义下标
// 5. 定义和使用新的嵌套类型
// 6. 使一个已有类型符合某个协议
// 在 Swift 中,甚至可以对协议进行扩展,提供协议要求的实现,或者添加额外的功能,从而可以让符合协议的类型拥有这些功能
// 注意:扩展可以为一个类型添加新的功能,但是不能重写已有的功能。
// 语法
//
//extension SomeType {
// somecode
//}
//
//可以通过扩展来扩展一个已有类型,使其采纳一个或多个协议。在这种情况下,无论是类还是结构体,协议名字的书写方式完全一样:
//
//extension SomeType: SomeProtocol, AnotherProctocol {
// // 协议实现写到这里
//}
// 注意: 如果通过扩展为一个已有类型添加新功能,那么新功能对该类型的所有已有实例都是可用的,即使它们是在这个扩展定义之前创建的
// 扩展计算型属性
// 转换成米
extension Double {
var km: Double { return self*1000 }
var m: Double { return self }
var cm: Double { return self/100 }
var ft: Double { return self/3.28084 }
}
var tenThousandFeet = 10_000.ft
print("Ten thousand feets is \(tenThousandFeet) meters")
let aMarathon = 42.km + 195.m
print("a marathon is \(aMarathon) meters long")
// 注意: 扩展可以添加新的计算型属性,但是不可以添加存储型属性,也不可以为已有属性添加属性观察器
// 扩展构造器
// 扩展能为类添加新的便利构造器,但是它们不能为类添加新的指定构造器或析构器。指定构造器和析构器必须总是由原始的类实现来提供
// 如果使用扩展为一个值类型添加构造器,同时该值类型的原始实现中未定义任何定制的构造器且所有存储属性提供了默认值,那么就可以在扩展中的构造器里调用默认构造器和逐一成员构造器。
struct Size {
var width: Double = 0.0
var height: Double = 0.0
}
struct Point {
var x: Double = 0.0
var y: Double = 0.0
}
struct Rect {
var origin = Point()
var size = Size()
}
var defaultRect = Rect()
var originRect = Rect(origin: Point(x: 2.0, y:2.0), size: Size(width: 5.0, height: 5.0))
// 可以为Rect扩展一个指定中心点和Size的构造器
extension Rect {
init(center: Point, size: Size) {
let originX = center.x - size.width / 2
let originY = center.y - size.height / 2
self.init(origin: Point(x: originX, y: originY), size: size)
}
}
var centerRect = Rect(center: Point(x: 0.0, y: 0.0), size: Size(width: 5.0, height: 5.0))
// 扩展方法
extension Int {
func repeatTask(task: (Int) -> Void) {
for i in 0..<self {
task(i)
}
}
}
func testTask(index: Int) {
print("it's task[\(index)]'s turn")
}
5.repeatTask(task: testTask)
// 闭包方法
3.repeatTask { index in print("IT'S TASK[\(index)]'s TURN") }
// 扩展可变实例方法
extension Int {
mutating func square() -> Int {
self = self * self
return self
}
}
var someInt = 3
print(someInt.square())
print(someInt)
// 扩展下标
extension Int {
subscript(index: Int) -> Int {
var base = 1
for _ in 1..<index {
base *= 10
}
return (self / base) % 10
}
}
print(123456[5])
print(31415926[1])
// 扩展嵌套类型
extension Int {
enum Kind: String {
case Negative
case Zero
case Positive
}
var kind: Kind {
switch self {
case let x where x > 0:
return .Positive
case Int.min..<0 :
return .Negative
default:
return .Zero
}
}
}
func printIntegerKinds(_ numbers: [Int]) {
for n in numbers {
var s: String = ""
switch n.kind {
case .Negative:
s += "-"
case .Zero:
s += " "
case .Positive:
s += "+"
}
s += "\(n.kind)"
print(s)
}
}
var numbers: [Int] = [1, 2, 3, -1, 0, -8]
printIntegerKinds(numbers)
| gpl-2.0 | 7b8d89eb83a7e96c0f5abbeef2d26ee4 | 16.994681 | 89 | 0.588235 | 2.835708 | false | false | false | false |
lieven/fietsknelpunten-ios | App/AppDelegate.swift | 1 | 805 | //
// AppDelegate.swift
// Fietsknelpunten
//
// Created by Lieven Dekeyser on 11/11/16.
// Copyright © 2016 Fietsknelpunten. All rights reserved.
//
import UIKit
@UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey : Any]? = nil) -> Bool {
let navigationController = EditingNavigationController(rootViewController: MainViewController())
navigationController.isToolbarHidden = false
let window = UIWindow()
window.tintColor = UIColor(red: 0.732, green: 0.23, blue: 0.23, alpha: 1.0)
window.rootViewController = navigationController
self.window = window
window.makeKeyAndVisible()
return true
}
}
| mit | 7756257879415da664fca9245fbb8dcc | 25.8 | 149 | 0.754975 | 4.466667 | false | false | false | false |
KevinChouRafael/Shrimp | Shrimp/Classes/ShrimpRequest+Codable.swift | 1 | 2926 | //
// ShrimpRequest+Codeable.swift
// Shrimp
//
// Created by kai zhou on 27/01/2018.
// Copyright © 2018 kai zhou. All rights reserved.
//
import Foundation
public extension ShrimpRequest{
@discardableResult
func responseCodable<T:Codable>(_ responseHandler:@escaping (_ result:T,_ response:URLResponse?)->Void,
errorHandler:((_ error:Error?)->Void)?)->ShrimpRequest{
return responseString({ (resultString, urlResponse) in
let decoder = JSONDecoder()
decoder.dateDecodingStrategy = ShrimpConfigure.shared.dateDecodingStrategy
do{
let responseResult = try decoder.decode(T.self, from: Data(resultString.utf8))
responseHandler(responseResult,urlResponse)
}catch {
debugPrint("\(error)")
errorHandler?(ShrimpError.createError(ShrimpError.Code.responseDecodingFailed.rawValue, localizedDescription: "响应解析错误。\(error.localizedDescription)"))
}
}, errorHandler:{(error) in
errorHandler?(error)
})
}
@discardableResult
func responseCodable<T:Codable>(_ responseHandler:@escaping (_ result:T, _ data:Data?,_ response:URLResponse?)->Void,
errorHandler:((_ error:Error?)->Void)?)->ShrimpRequest{
return responseData({ (resultData, urlResponse) in
guard resultData != nil, resultData.count > 0 else{
if let httpResponse = urlResponse as? HTTPURLResponse{
let code = httpResponse.statusCode
debugPrint("\(code)")
errorHandler?(ShrimpError.createError(code))
}
return
}
let decoder = JSONDecoder()
decoder.dateDecodingStrategy = ShrimpConfigure.shared.dateDecodingStrategy
do{
let resultString = String(data: resultData, encoding: String.Encoding.utf8)!
let responseResult = try decoder.decode(T.self, from: Data(resultString.utf8))
responseHandler(responseResult,resultData,urlResponse)
}catch {
debugPrint("\(error)")
errorHandler?(ShrimpError.createError(ShrimpError.Code.responseDecodingFailed.rawValue, localizedDescription: "响应解析错误。\(error.localizedDescription)"))
}
}, errorHandler:{(error) in
errorHandler?(error)
})
}
}
| mit | c21460462c6baf9b5c64fbef54429456 | 37.118421 | 170 | 0.519158 | 6.257019 | false | false | false | false |
ijovi23/JvPunchIO | JvPunchIO-Recorder/Pods/FileKit/Sources/DispatchWatcher.swift | 3 | 12379 | //
// GCDFSWatcher.swift
// FileKit
//
// Created by ijump on 5/2/16.
// Copyright © 2016 Nikolai Vazquez. All rights reserved.
//
import Foundation
/// Delegate for `DispatchFileSystemWatcher`
public protocol DispatchFileSystemWatcherDelegate: class {
// MARK: - Protocol
/// Call when the file-system object was deleted from the namespace.
func fsWatcherDidObserveDelete(_ watch: DispatchFileSystemWatcher)
/// Call when the file-system object data changed.
func fsWatcherDidObserveWrite(_ watch: DispatchFileSystemWatcher)
/// Call when the file-system object changed in size.
func fsWatcherDidObserveExtend(_ watch: DispatchFileSystemWatcher)
/// Call when the file-system object metadata changed.
func fsWatcherDidObserveAttrib(_ watch: DispatchFileSystemWatcher)
/// Call when the file-system object link count changed.
func fsWatcherDidObserveLink(_ watch: DispatchFileSystemWatcher)
/// Call when the file-system object was renamed in the namespace.
func fsWatcherDidObserveRename(_ watch: DispatchFileSystemWatcher)
/// Call when the file-system object was revoked.
func fsWatcherDidObserveRevoke(_ watch: DispatchFileSystemWatcher)
/// Call when the file-system object was created.
func fsWatcherDidObserveCreate(_ watch: DispatchFileSystemWatcher)
/// Call when the directory changed (additions, deletions, and renamings).
///
/// Calls `fsWatcherDidObserveWrite` by default.
func fsWatcherDidObserveDirectoryChange(_ watch: DispatchFileSystemWatcher)
}
// Optional func and default func for `GCDFSWatcherDelegate`
// Empty func treated as Optional func
public extension DispatchFileSystemWatcherDelegate {
// MARK: - Extension
/// Call when the file-system object was deleted from the namespace.
public func fsWatcherDidObserveDelete(_ watch: DispatchFileSystemWatcher) {
}
/// Call when the file-system object data changed.
public func fsWatcherDidObserveWrite(_ watch: DispatchFileSystemWatcher) {
}
/// Call when the file-system object changed in size.
public func fsWatcherDidObserveExtend(_ watch: DispatchFileSystemWatcher) {
}
/// Call when the file-system object metadata changed.
public func fsWatcherDidObserveAttrib(_ watch: DispatchFileSystemWatcher) {
}
/// Call when the file-system object link count changed.
public func fsWatcherDidObserveLink(_ watch: DispatchFileSystemWatcher) {
}
/// Call when the file-system object was renamed in the namespace.
public func fsWatcherDidObserveRename(_ watch: DispatchFileSystemWatcher) {
}
/// Call when the file-system object was revoked.
public func fsWatcherDidObserveRevoke(_ watch: DispatchFileSystemWatcher) {
}
/// Call when the file-system object was created.
public func fsWatcherDidObserveCreate(_ watch: DispatchFileSystemWatcher) {
}
/// Call when the directory changed (additions, deletions, and renamings).
///
/// Calls `fsWatcherDidObserveWrite` by default.
public func fsWatcherDidObserveDirectoryChange(_ watch: DispatchFileSystemWatcher) {
fsWatcherDidObserveWrite(watch)
}
}
/// Watcher for Vnode events
open class DispatchFileSystemWatcher {
// MARK: - Properties
/// The paths being watched.
open let path: Path
/// The events used to create the watcher.
open let events: DispatchFileSystemEvents
/// The delegate to call when events happen
weak var delegate: DispatchFileSystemWatcherDelegate?
/// The watcher for watching creation event
weak var createWatcher: DispatchFileSystemWatcher?
/// The callback for file system events.
fileprivate let callback: ((DispatchFileSystemWatcher) -> Void)?
/// The queue for the watcher.
fileprivate let queue: DispatchQueue?
/// A file descriptor for the path.
fileprivate var fileDescriptor: CInt = -1
/// A dispatch source to monitor a file descriptor created from the path.
fileprivate var source: DispatchSourceProtocol?
/// Current events
open var currentEvent: DispatchFileSystemEvents? {
if let source = source {
return DispatchFileSystemEvents(rawValue: source.data)
}
if createWatcher != nil {
return .Create
}
return nil
}
// MARK: - Initialization
/// Creates a watcher for the given paths.
///
/// - Parameter paths: The paths.
/// - Parameter events: The create events.
/// - Parameter queue: The queue to be run within.
/// - Parameter callback: The callback to be called on changes.
///
/// This method does follow links.
init(path: Path,
events: DispatchFileSystemEvents,
queue: DispatchQueue,
callback: ((DispatchFileSystemWatcher) -> Void)?
) {
self.path = path.absolute
self.events = events
self.queue = queue
self.callback = callback
}
// MARK: - Deinitialization
deinit {
//print("\(path): Deinit")
close()
}
// MARK: - Private Methods
/// Dispatch the event.
///
/// If `callback` is set, call the `callback`. Else if `delegate` is set, call the `delegate`
///
/// - Parameter eventType: The current event to be watched.
fileprivate func dispatchDelegate(_ eventType: DispatchFileSystemEvents) {
if let callback = self.callback {
callback(self)
} else if let delegate = self.delegate {
if eventType.contains(.Delete) {
delegate.fsWatcherDidObserveDelete(self)
}
if eventType.contains(.Write) {
if path.isDirectoryFile {
delegate.fsWatcherDidObserveDirectoryChange(self)
} else {
delegate.fsWatcherDidObserveWrite(self)
}
}
if eventType.contains(.Extend) {
delegate.fsWatcherDidObserveExtend(self)
}
if eventType.contains(.Attribute) {
delegate.fsWatcherDidObserveAttrib(self)
}
if eventType.contains(.Link) {
delegate.fsWatcherDidObserveLink(self)
}
if eventType.contains(.Rename) {
delegate.fsWatcherDidObserveRename(self)
}
if eventType.contains(.Revoke) {
delegate.fsWatcherDidObserveRevoke(self)
}
if eventType.contains(.Create) {
delegate.fsWatcherDidObserveCreate(self)
}
}
}
// MARK: - Methods
/// Start watching.
///
/// This method does follow links.
@discardableResult
open func startWatching() -> Bool {
// create a watcher for CREATE event if path not exists and events contains CREATE
if !path.exists {
if events.contains(.Create) {
let parent = path.parent.absolute
var _events = events
_events.remove(.Create)
// only watch a CREATE event if parent exists and is a directory
if parent.isDirectoryFile {
#if os(OSX)
let watch = { parent.watch2($0, callback: $1) }
#else
let watch = { parent.watch($0, callback: $1) }
#endif
createWatcher = watch(.Write) { [weak self] watch in
// stop watching when path created
if self?.path.isRegular == true || self?.path.isDirectoryFile == true {
self?.dispatchDelegate(.Create)
//self.delegate?.fsWatcherDidObserveCreate(self)
self?.createWatcher = nil
self?.startWatching()
watch.stopWatching()
}
}
return true
}
}
return false
}
// Only watching for regular file and directory
else if path.isRegular || path.isDirectoryFile {
if source == nil && fileDescriptor == -1 {
fileDescriptor = open(path._safeRawValue, O_EVTONLY)
if fileDescriptor == -1 { return false }
var _events = events
_events.remove(.Create)
source = DispatchSource.makeFileSystemObjectSource(fileDescriptor: fileDescriptor, eventMask: DispatchSource.FileSystemEvent(rawValue: _events.rawValue), queue: queue)
// Recheck if open success and source create success
if source != nil && fileDescriptor != -1 {
guard callback != nil || delegate != nil else {
return false
}
// Define the block to call when a file change is detected.
source!.setEventHandler { //[unowned self] () in
let eventType = DispatchFileSystemEvents(rawValue: self.source!.data)
self.dispatchDelegate(eventType)
}
// Define a cancel handler to ensure the path is closed when the source is cancelled.
source!.setCancelHandler { //[unowned self] () in
_ = Darwin.close(self.fileDescriptor)
self.fileDescriptor = -1
self.source = nil
}
// Start monitoring the path via the source.
source!.resume()
return true
}
}
return false
} else {
return false
}
}
/// Stop watching.
///
/// **Note:** make sure call this func, or `self` will not release
open func stopWatching() {
if source != nil {
source!.cancel()
}
}
/// Closes the watcher.
open func close() {
createWatcher?.stopWatching()
_ = Darwin.close(self.fileDescriptor)
self.fileDescriptor = -1
self.source = nil
}
}
extension Path {
#if os(OSX)
// MARK: - Watching
/// Watches a path for filesystem events and handles them in the callback or delegate.
///
/// - Parameter events: The create events.
/// - Parameter queue: The queue to be run within.
/// - Parameter delegate: The delegate to call when events happen.
/// - Parameter callback: The callback to be called on changes.
public func watch2(_ events: DispatchFileSystemEvents = .All,
queue: DispatchQueue? = nil,
delegate: DispatchFileSystemWatcherDelegate? = nil,
callback: ((DispatchFileSystemWatcher) -> Void)? = nil
) -> DispatchFileSystemWatcher {
let dispathQueue: DispatchQueue
if #available(OSX 10.10, *) {
dispathQueue = queue ?? DispatchQueue.global(qos: .default)
} else {
dispathQueue = queue ?? DispatchQueue.global(priority: .default)
}
let watcher = DispatchFileSystemWatcher(path: self, events: events, queue: dispathQueue, callback: callback)
watcher.delegate = delegate
watcher.startWatching()
return watcher
}
#else
// MARK: - Watching
/// Watches a path for filesystem events and handles them in the callback or delegate.
///
/// - Parameter events: The create events.
/// - Parameter queue: The queue to be run within.
/// - Parameter delegate: The delegate to call when events happen.
/// - Parameter callback: The callback to be called on changes.
public func watch(_ events: DispatchFileSystemEvents = .All,
queue: DispatchQueue = DispatchQueue.global(qos: .default),
delegate: DispatchFileSystemWatcherDelegate? = nil,
callback: ((DispatchFileSystemWatcher) -> Void)? = nil
) -> DispatchFileSystemWatcher {
let watcher = DispatchFileSystemWatcher(path: self, events: events, queue: queue, callback: callback)
watcher.delegate = delegate
watcher.startWatching()
return watcher
}
#endif
}
| mit | 602a234d8aea673947c5cd01eba3708e | 33.383333 | 183 | 0.604056 | 5.098023 | false | false | false | false |
bkmunar/firefox-ios | Client/Frontend/Reader/ReaderModeStyleViewController.swift | 1 | 15685 | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
import Foundation
import UIKit
private struct ReaderModeStyleViewControllerUX {
static let RowHeight = 50
static let Width = 270
static let Height = 4 * RowHeight
static let FontTypeRowBackground = UIColor(rgb: 0xfbfbfb)
static let FontTypeTitleFontSansSerif = UIFont(name: "FiraSans", size: 16)
static let FontTypeTitleFontSerif = UIFont(name: "Charis SIL", size: 16)
static let FontTypeTitleSelectedColor = UIColor(rgb: 0x333333)
static let FontTypeTitleNormalColor = UIColor.lightGrayColor() // TODO THis needs to be 44% of 0x333333
static let FontSizeRowBackground = UIColor(rgb: 0xf4f4f4)
static let FontSizeLabelFontSansSerif = UIFont(name: "FiraSans-Book", size: 22)
static let FontSizeLabelFontSerif = UIFont(name: "Charis SIL", size: 22)
static let FontSizeLabelColor = UIColor(rgb: 0x333333)
static let FontSizeButtonTextColorEnabled = UIColor(rgb: 0x333333)
static let FontSizeButtonTextColorDisabled = UIColor.lightGrayColor() // TODO THis needs to be 44% of 0x333333
static let FontSizeButtonTextFont = UIFont(name: "FiraSans-Book", size: 22)
static let ThemeRowBackgroundColor = UIColor.whiteColor()
static let ThemeTitleFontSansSerif = UIFont(name: "FiraSans-Light", size: 15)
static let ThemeTitleFontSerif = UIFont(name: "Charis SIL", size: 15)
static let ThemeTitleColorLight = UIColor(rgb: 0x333333)
static let ThemeTitleColorDark = UIColor.whiteColor()
static let ThemeTitleColorSepia = UIColor(rgb: 0x333333)
static let ThemeBackgroundColorLight = UIColor.whiteColor()
static let ThemeBackgroundColorDark = UIColor.blackColor()
static let ThemeBackgroundColorSepia = UIColor(rgb: 0xf0ece7)
static let BrightnessRowBackground = UIColor(rgb: 0xf4f4f4)
static let BrightnessSliderTintColor = UIColor(rgb: 0xe66000)
static let BrightnessSliderWidth = 140
static let BrightnessIconOffset = 10
}
// MARK: -
protocol ReaderModeStyleViewControllerDelegate {
func readerModeStyleViewController(readerModeStyleViewController: ReaderModeStyleViewController, didConfigureStyle style: ReaderModeStyle)
}
// MARK: -
class ReaderModeStyleViewController: UIViewController {
var delegate: ReaderModeStyleViewControllerDelegate?
var readerModeStyle: ReaderModeStyle = DefaultReaderModeStyle
private var fontTypeButtons: [FontTypeButton]!
private var fontSizeLabel: FontSizeLabel!
private var fontSizeButtons: [FontSizeButton]!
private var themeButtons: [ThemeButton]!
override func viewDidLoad() {
// Our preferred content size has a fixed width and height based on the rows + padding
preferredContentSize = CGSize(width: ReaderModeStyleViewControllerUX.Width, height: ReaderModeStyleViewControllerUX.Height)
popoverPresentationController?.backgroundColor = ReaderModeStyleViewControllerUX.FontTypeRowBackground
// Font type row
let fontTypeRow = UIView()
view.addSubview(fontTypeRow)
fontTypeRow.backgroundColor = ReaderModeStyleViewControllerUX.FontTypeRowBackground
fontTypeRow.snp_makeConstraints { (make) -> () in
make.top.equalTo(self.view)
make.left.right.equalTo(self.view)
make.height.equalTo(ReaderModeStyleViewControllerUX.RowHeight)
}
fontTypeButtons = [
FontTypeButton(fontType: ReaderModeFontType.SansSerif),
FontTypeButton(fontType: ReaderModeFontType.Serif)
]
setupButtons(fontTypeButtons, inRow: fontTypeRow, action: "SELchangeFontType:")
// Font size row
let fontSizeRow = UIView()
view.addSubview(fontSizeRow)
fontSizeRow.backgroundColor = ReaderModeStyleViewControllerUX.FontSizeRowBackground
fontSizeRow.snp_makeConstraints { (make) -> () in
make.top.equalTo(fontTypeRow.snp_bottom)
make.left.right.equalTo(self.view)
make.height.equalTo(ReaderModeStyleViewControllerUX.RowHeight)
}
fontSizeLabel = FontSizeLabel()
fontSizeRow.addSubview(fontSizeLabel)
fontSizeLabel.snp_makeConstraints { (make) -> () in
make.center.equalTo(fontSizeRow)
return
}
fontSizeButtons = [
FontSizeButton(fontSizeAction: FontSizeAction.Smaller),
FontSizeButton(fontSizeAction: FontSizeAction.Bigger)
]
setupButtons(fontSizeButtons, inRow: fontSizeRow, action: "SELchangeFontSize:")
// Theme row
let themeRow = UIView()
view.addSubview(themeRow)
themeRow.snp_makeConstraints { (make) -> () in
make.top.equalTo(fontSizeRow.snp_bottom)
make.left.right.equalTo(self.view)
make.height.equalTo(ReaderModeStyleViewControllerUX.RowHeight)
}
themeButtons = [
ThemeButton(theme: ReaderModeTheme.Light),
ThemeButton(theme: ReaderModeTheme.Dark),
ThemeButton(theme: ReaderModeTheme.Sepia)
]
setupButtons(themeButtons, inRow: themeRow, action: "SELchangeTheme:")
// Brightness row
let brightnessRow = UIView()
view.addSubview(brightnessRow)
brightnessRow.backgroundColor = ReaderModeStyleViewControllerUX.BrightnessRowBackground
brightnessRow.snp_makeConstraints { (make) -> () in
make.top.equalTo(themeRow.snp_bottom)
make.left.right.equalTo(self.view)
make.height.equalTo(ReaderModeStyleViewControllerUX.RowHeight)
}
let slider = UISlider()
brightnessRow.addSubview(slider)
slider.accessibilityLabel = NSLocalizedString("Brightness", comment: "Accessibility label for brightness adjustment slider in Reader Mode display settings")
slider.tintColor = ReaderModeStyleViewControllerUX.BrightnessSliderTintColor
slider.addTarget(self, action: "SELchangeBrightness:", forControlEvents: UIControlEvents.ValueChanged)
slider.snp_makeConstraints { make in
make.center.equalTo(brightnessRow.center)
make.width.equalTo(ReaderModeStyleViewControllerUX.BrightnessSliderWidth)
}
let brightnessMinImageView = UIImageView(image: UIImage(named: "brightnessMin"))
brightnessRow.addSubview(brightnessMinImageView)
brightnessMinImageView.snp_makeConstraints { (make) -> () in
make.centerY.equalTo(slider)
make.right.equalTo(slider.snp_left).offset(-ReaderModeStyleViewControllerUX.BrightnessIconOffset)
}
let brightnessMaxImageView = UIImageView(image: UIImage(named: "brightnessMax"))
brightnessRow.addSubview(brightnessMaxImageView)
brightnessMaxImageView.snp_makeConstraints { (make) -> () in
make.centerY.equalTo(slider)
make.left.equalTo(slider.snp_right).offset(ReaderModeStyleViewControllerUX.BrightnessIconOffset)
}
selectFontType(readerModeStyle.fontType)
updateFontSizeButtons()
selectTheme(readerModeStyle.theme)
slider.value = Float(UIScreen.mainScreen().brightness)
}
/// Setup constraints for a row of buttons. Left to right. They are all given the same width.
private func setupButtons(buttons: [UIButton], inRow row: UIView, action: Selector) {
for (idx, button) in enumerate(buttons) {
row.addSubview(button)
button.addTarget(self, action: action, forControlEvents: UIControlEvents.TouchUpInside)
button.snp_makeConstraints { make in
make.top.equalTo(row.snp_top)
if idx == 0 {
make.left.equalTo(row.snp_left)
} else {
make.left.equalTo(buttons[idx - 1].snp_right)
}
make.bottom.equalTo(row.snp_bottom)
make.width.equalTo(self.preferredContentSize.width / CGFloat(buttons.count))
}
}
}
func SELchangeFontType(button: FontTypeButton) {
selectFontType(button.fontType)
delegate?.readerModeStyleViewController(self, didConfigureStyle: readerModeStyle)
}
private func selectFontType(fontType: ReaderModeFontType) {
readerModeStyle.fontType = fontType
for button in fontTypeButtons {
button.selected = (button.fontType == fontType)
}
for button in themeButtons {
button.fontType = fontType
}
fontSizeLabel.fontType = fontType
}
func SELchangeFontSize(button: FontSizeButton) {
switch button.fontSizeAction {
case .Smaller:
readerModeStyle.fontSize = readerModeStyle.fontSize.smaller()
case .Bigger:
readerModeStyle.fontSize = readerModeStyle.fontSize.bigger()
}
updateFontSizeButtons()
delegate?.readerModeStyleViewController(self, didConfigureStyle: readerModeStyle)
}
private func updateFontSizeButtons() {
for button in fontSizeButtons {
switch button.fontSizeAction {
case .Bigger:
button.enabled = !readerModeStyle.fontSize.isLargest()
break
case .Smaller:
button.enabled = !readerModeStyle.fontSize.isSmallest()
break
}
}
}
func SELchangeTheme(button: ThemeButton) {
selectTheme(button.theme)
delegate?.readerModeStyleViewController(self, didConfigureStyle: readerModeStyle)
}
private func selectTheme(theme: ReaderModeTheme) {
readerModeStyle.theme = theme
}
func SELchangeBrightness(slider: UISlider) {
UIScreen.mainScreen().brightness = CGFloat(slider.value)
}
}
// MARK: -
class FontTypeButton: UIButton {
var fontType: ReaderModeFontType = .SansSerif
convenience init(fontType: ReaderModeFontType) {
self.init(frame: CGRectZero)
self.fontType = fontType
setTitleColor(ReaderModeStyleViewControllerUX.FontTypeTitleSelectedColor, forState: UIControlState.Selected)
setTitleColor(ReaderModeStyleViewControllerUX.FontTypeTitleNormalColor, forState: UIControlState.Normal)
backgroundColor = ReaderModeStyleViewControllerUX.FontTypeRowBackground
accessibilityHint = NSLocalizedString("Changes font type.", comment: "Accessibility hint for the font type buttons in reader mode display settings")
switch fontType {
case .SansSerif:
setTitle(NSLocalizedString("Sans-serif", comment: "Font type setting in the reading view settings"), forState: UIControlState.Normal)
let f = ReaderModeStyleViewControllerUX.ThemeTitleFontSansSerif
titleLabel?.font = f
case .Serif:
setTitle(NSLocalizedString("Serif", comment: "Font type setting in the reading view settings"), forState: UIControlState.Normal)
let f = ReaderModeStyleViewControllerUX.ThemeTitleFontSerif
titleLabel?.font = f
}
}
}
// MARK: -
enum FontSizeAction {
case Smaller
case Bigger
}
class FontSizeButton: UIButton {
var fontSizeAction: FontSizeAction = .Bigger
convenience init(fontSizeAction: FontSizeAction) {
self.init(frame: CGRectZero)
self.fontSizeAction = fontSizeAction
setTitleColor(ReaderModeStyleViewControllerUX.FontSizeButtonTextColorEnabled, forState: UIControlState.Normal)
setTitleColor(ReaderModeStyleViewControllerUX.FontSizeButtonTextColorDisabled, forState: UIControlState.Disabled)
switch fontSizeAction {
case .Smaller:
let smallerFontLabel = NSLocalizedString("-", comment: "Button for smaller reader font size. Keep this extremely short! This is shown in the reader mode toolbar.")
let smallerFontAccessibilityLabel = NSLocalizedString("Decrease text size", comment: "Accessibility label for button decreasing font size in display settings of reader mode")
setTitle(smallerFontLabel, forState: .Normal)
accessibilityLabel = smallerFontAccessibilityLabel
case .Bigger:
let largerFontLabel = NSLocalizedString("+", comment: "Button for larger reader font size. Keep this extremely short! This is shown in the reader mode toolbar.")
let largerFontAccessibilityLabel = NSLocalizedString("Increase text size", comment: "Accessibility label for button increasing font size in display settings of reader mode")
setTitle(largerFontLabel, forState: .Normal)
accessibilityLabel = largerFontAccessibilityLabel
}
// TODO Does this need to change with the selected font type? Not sure if makes sense for just +/-
titleLabel?.font = ReaderModeStyleViewControllerUX.FontSizeButtonTextFont
}
}
// MARK: -
class FontSizeLabel: UILabel {
override init(frame: CGRect) {
super.init(frame: frame)
let fontSizeLabel = NSLocalizedString("Aa", comment: "Button for reader mode font size. Keep this extremely short! This is shown in the reader mode toolbar.")
text = fontSizeLabel
isAccessibilityElement = false
}
required init(coder aDecoder: NSCoder) {
// TODO
fatalError("init(coder:) has not been implemented")
}
var fontType: ReaderModeFontType = .SansSerif {
didSet {
switch fontType {
case .SansSerif:
font = ReaderModeStyleViewControllerUX.FontSizeLabelFontSansSerif
case .Serif:
font = ReaderModeStyleViewControllerUX.FontSizeLabelFontSerif
}
}
}
}
// MARK: -
class ThemeButton: UIButton {
var theme: ReaderModeTheme!
convenience init(theme: ReaderModeTheme) {
self.init(frame: CGRectZero)
self.theme = theme
setTitle(theme.rawValue, forState: UIControlState.Normal)
accessibilityHint = NSLocalizedString("Changes color theme.", comment: "Accessibility hint for the color theme setting buttons in reader mode display settings")
switch theme {
case .Light:
setTitle(NSLocalizedString("Light", comment: "Light theme setting in Reading View settings"), forState: .Normal)
setTitleColor(ReaderModeStyleViewControllerUX.ThemeTitleColorLight, forState: UIControlState.Normal)
backgroundColor = ReaderModeStyleViewControllerUX.ThemeBackgroundColorLight
case .Dark:
setTitle(NSLocalizedString("Dark", comment: "Dark theme setting in Reading View settings"), forState: .Normal)
setTitleColor(ReaderModeStyleViewControllerUX.ThemeTitleColorDark, forState: UIControlState.Normal)
backgroundColor = ReaderModeStyleViewControllerUX.ThemeBackgroundColorDark
case .Sepia:
setTitle(NSLocalizedString("Sepia", comment: "Sepia theme setting in Reading View settings"), forState: .Normal)
setTitleColor(ReaderModeStyleViewControllerUX.ThemeTitleColorSepia, forState: UIControlState.Normal)
backgroundColor = ReaderModeStyleViewControllerUX.ThemeBackgroundColorSepia
}
}
var fontType: ReaderModeFontType = .SansSerif {
didSet {
switch fontType {
case .SansSerif:
titleLabel?.font = ReaderModeStyleViewControllerUX.ThemeTitleFontSansSerif
case .Serif:
titleLabel?.font = ReaderModeStyleViewControllerUX.ThemeTitleFontSerif
}
}
}
} | mpl-2.0 | a6c0117291b70f35ccc361a56a8d8ce2 | 40.607427 | 186 | 0.695442 | 5.544362 | false | false | false | false |
biohazardlover/ROer | Roer/MapTextureLoader.swift | 1 | 2708 |
class MapTextureLoader {
static let TEXTURE_MAX_ANISOTROPY_EXT = -1
static let MAX_TEXTURE_MAX_ANISOTROPY_EXT = -1
class func textureWithMapName(_ mapName: String, textureName: String, isWater: Bool = false) -> GLuint {
var texture: GLuint = 0
glGenTextures(1, &texture)
glBindTexture(GLenum(GL_TEXTURE_2D), texture)
glTexParameteri(GLenum(GL_TEXTURE_2D), GLenum(GL_TEXTURE_MAG_FILTER), GLint(GL_LINEAR))
glTexParameteri(GLenum(GL_TEXTURE_2D), GLenum(GL_TEXTURE_MIN_FILTER), GLint(GL_LINEAR_MIPMAP_NEAREST))
if TEXTURE_MAX_ANISOTROPY_EXT > 0 {
glTexParameterf(GLenum(GL_TEXTURE_2D), GLenum(TEXTURE_MAX_ANISOTROPY_EXT), GLfloat(MAX_TEXTURE_MAX_ANISOTROPY_EXT))
}
if (isWater) {
glTexParameteri(GLenum(GL_TEXTURE_2D), GLenum(GL_TEXTURE_WRAP_S), GL_REPEAT)
glTexParameteri(GLenum(GL_TEXTURE_2D), GLenum(GL_TEXTURE_WRAP_T), GL_REPEAT)
}
let url = documentDirectoryURL.appendingPathComponent("\(mapName)/\(textureName)")
let image: CGImage?
if url.pathExtension == "png" {
guard let dataProvider = CGDataProvider(url: url as CFURL) else { return texture }
image = CGImage(pngDataProviderSource: dataProvider, decode: nil, shouldInterpolate: false, intent: .defaultIntent)
} else {
guard let dataProvider = CGDataProvider(url: url as CFURL) else { return texture }
image = CGImage(jpegDataProviderSource: dataProvider, decode: nil, shouldInterpolate: false, intent: .defaultIntent)
}
let width = image?.width ?? 0
let height = image?.height ?? 0
let spriteData = calloc(width * height * 4, MemoryLayout<GLubyte>.size)
let colorSpace = CGColorSpaceCreateDeviceRGB()
let spriteContext = CGContext(data: spriteData, width: width, height: height, bitsPerComponent: 8, bytesPerRow: width * 4, space: colorSpace, bitmapInfo: CGImageAlphaInfo.premultipliedLast.rawValue)
let rect = CGRect(x: 0, y: 0, width: CGFloat(width), height: CGFloat(height))
spriteContext?.draw(image!, in: rect)
glTexImage2D(GLenum(GL_TEXTURE_2D), 0, GL_RGBA, GLsizei(width), GLsizei(height), 0, GLenum(GL_RGBA), GLenum(GL_UNSIGNED_BYTE), spriteData)
glGenerateMipmap(GLenum(GL_TEXTURE_2D))
return texture;
}
class func texturesWithMapName(_ mapName: String, textureNames: [String], isWater: Bool = false) -> [GLuint] {
return textureNames.map { (textureName) -> GLuint in
textureWithMapName(mapName, textureName: textureName, isWater: isWater)
}
}
}
| mit | 288b199adc28e38b02dc11b00d475f44 | 51.076923 | 206 | 0.656204 | 3.941776 | false | false | false | false |
kysonyangs/ysbilibili | Pods/SwiftDate/Sources/SwiftDate/ISO8601Parser.swift | 4 | 26401 | //
// SwiftDate, Full featured Swift date library for parsing, validating, manipulating, and formatting dates and timezones.
// Created by: Daniele Margutti
// Main contributors: Jeroen Houtzager
//
//
// 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
/// This defines all possible errors you can encounter parsing ISO8601 string
///
/// - eof: end of file
/// - notDigit: expected digit, value cannot be parsed as int
/// - notDouble: expected double digit, value cannot be parsed as double
/// - invalid: invalid state reached. Something in the format is not correct
public enum ISO8601ParserError: Error {
case eof
case notDigit
case notDouble
case invalid
}
// MARK: - Internal Extension for UnicodeScalar type
internal extension UnicodeScalar {
/// return `true` if current character is a digit (arabic), `false` otherwise
var isDigit: Bool {
return "0"..."9" ~= self
}
/// return `true` if current character is a space
var isSpace: Bool {
return CharacterSet.whitespaces.contains(self)
}
}
// MARK: - Internal Extension for Int type
internal extension Int {
/// Return `true` if current year is a leap year, `false` otherwise
var isLeapYear: Bool {
return ((self % 4) == 0) && (((self % 100) != 0) || ((self % 400) == 0))
}
}
/// Parser configuration
/// This configuration can be used to define custom behaviour of the parser itself.
public struct ISO8601Configuration {
/// Time separator character. By default is `:`.
var time_separator: ISO8601Parser.ISOChar = ":"
/// Strict parsing. By default is `false`.
var strict: Bool = false
/// Calendar used to generate the date. By default is the current system calendar
var calendar: Calendar = Calendar.current
init(strict: Bool = false, calendar: Calendar? = nil) {
self.strict = strict
self.calendar = calendar ?? Calendar.current
}
}
/// Internal structure
internal enum Weekday: Int {
case monday = 0
case tuesday = 1
case wednesday = 2
case thursday = 3
}
/// This is the ISO8601 Parser class: it evaluates automatically the format of the ISO8601 date
/// and attempt to parse it in a valid `Date` object.
/// Resulting date also includes Time Zone settings and a property which allows you to inspect
/// single date components.
///
/// This work is inspired to the original ISO8601DateFormatter class written in ObjC by
/// Peter Hosey (available here https://bitbucket.org/boredzo/iso-8601-parser-unparser).
/// I've made a Swift porting and fixed some issues when parsing several ISO8601 date variants.
public class ISO8601Parser {
/// Some typealias to make the code cleaner
public typealias ISOString = String.UnicodeScalarView
public typealias ISOIndex = String.UnicodeScalarView.Index
public typealias ISOChar = UnicodeScalar
public typealias ISOParsedDate = (date: Date?, timezone: TimeZone?)
/// This represent the internal parser status representation
public struct ParsedDate {
/// Type of date parsed
///
/// - monthAndDate: month and date style
/// - week: date with week number
/// - dateOnly: date only
public enum DateStyle {
case monthAndDate
case week
case dateOnly
}
/// Parsed year value
var year: Int = 0
/// Parsed month or week number
var month_or_week: Int = 0
/// Parsed day value
var day: Int = 0
/// Parsed hour value
var hour: Int = 0
/// Parsed minutes value
var minute: TimeInterval = 0.0
/// Parsed seconds value
var seconds: TimeInterval = 0.0
/// Parsed nanoseconds value
var nanoseconds: TimeInterval = 0.0
/// Parsed weekday number (1=monday, 7=sunday)
/// If `nil` source string has not specs about weekday.
var weekday: Int? = nil
/// Timezone parsed hour value
var tz_hour: Int = 0
/// Timezone parsed minute value
var tz_minute: Int = 0
/// Type of parsed date
var type: DateStyle = .monthAndDate
/// Parsed timezone object
var timezone: TimeZone?
}
/// Source raw parsed values
private var date: ParsedDate = ParsedDate()
/// Source string represented as unicode scalars
private let string: ISOString
/// Current position of the parser in source string.
/// Initially is equal to `string.startIndex`
private var cIdx: ISOIndex
/// Just a shortcut to the last index in source string
private var eIdx: ISOIndex
/// Lenght of the string
private var length: Int
/// Number of hyphens characters found before any value
/// Consequential "-" are used to define implicit values in dates.
private var hyphens: Int = 0
/// Private date components used for default values
private var now_cmps: DateComponents
/// Configuration used for parser
private var cfg: ISO8601Configuration
/// Date components parsed
private(set) var date_components: DateComponents?
/// Parsed date
private(set) var parsedDate: Date?
/// Parsed timezone
private(set) var parsedTimeZone: TimeZone?
/// Date adjusted at parsed timezone
private var dateInTimezone: Date? {
get {
self.cfg.calendar.timeZone = date.timezone ?? TimeZone(identifier: "UTC")!
return self.cfg.calendar.date(from: self.date_components!)
}
}
/// Formatter used to transform a date to a valid ISO8601 string
private(set) var formatter: DateFormatter = DateFormatter()
/// Initialize a new parser with a source ISO8601 string to parse
/// Parsing is done during initialization; any exception is reported
/// before allocating.
///
/// - Parameters:
/// - src: source ISO8601 string
/// - config: configuration used for parsing
/// - Throws: throw an `ISO8601Error` if parsing operation fails
public init?(_ src: String, config: ISO8601Configuration = ISO8601Configuration()) {
let src_trimmed = src.trimmingCharacters(in: CharacterSet.whitespacesAndNewlines)
guard src_trimmed.characters.count > 0 else {
return nil
}
self.string = src_trimmed.unicodeScalars
self.length = src_trimmed.characters.count
self.cIdx = string.startIndex
self.eIdx = string.endIndex
self.cfg = config
self.now_cmps = cfg.calendar.dateComponents([.year,.month,.day], from: Date())
var idx = self.cIdx
while idx < self.eIdx {
if string[idx] == "-" { hyphens += 1 }
else { break }
idx = string.index(after: idx)
}
do {
try self.parse()
} catch {
return nil
}
}
/// Return a date parsed from a valid ISO8601 string
///
/// - Parameter string: source string
/// - Returns: a valid `Date` object or `nil` if date cannot be parsed
public static func date(from string: String) -> ISOParsedDate? {
guard let parser = ISO8601Parser(string) else {
return nil
}
return (parser.parsedDate,parser.parsedTimeZone)
}
//MARK: - Internal Parser
/// Private parsing function
///
/// - Throws: throw an `ISO8601Error` if parsing operation fails
@discardableResult
private func parse() throws -> ISOParsedDate {
// PARSE DATE
if current() == "T" {
// There is no date here, only a time.
// Set the date to now; then we'll parse the time.
next()
guard current().isDigit else {
throw ISO8601ParserError.invalid
}
date.year = now_cmps.year!
date.month_or_week = now_cmps.month!
date.day = now_cmps.day!
} else {
moveUntil(is: "-")
let is_time_only = (string.contains("T") == false && string.contains(":") && !string.contains("-"))
if is_time_only == false {
var (num_digits,segment) = try read_int()
switch num_digits {
case 0: try parse_digits_0(num_digits, &segment)
case 8: try parse_digits_8(num_digits, &segment)
case 6: try parse_digits_6(num_digits, &segment)
case 4: try parse_digits_4(num_digits, &segment)
case 1: try parse_digits_1(num_digits, &segment)
case 2: try parse_digits_2(num_digits, &segment)
case 7: try parse_digits_7(num_digits, &segment) //YYYY DDD (ordinal date)
case 3: try parse_digits_3(num_digits, &segment) //--DDD (ordinal date, implicit year)
default: throw ISO8601ParserError.invalid
}
} else {
date.year = now_cmps.year!
date.month_or_week = now_cmps.month!
date.day = now_cmps.day!
}
}
var hasTime = false
if current().isSpace || current() == "T" {
hasTime = true
next()
}
// PARSE TIME
if current().isDigit == true {
let time_sep = cfg.time_separator
let hasTimeSeparator = string.contains(time_sep)
date.hour = try read_int(2).value
if hasTimeSeparator == false && hasTime{
date.minute = TimeInterval(try read_int(2).value)
}
else if current() == time_sep {
next()
if time_sep == "," || time_sep == "." {
//We can't do fractional minutes when '.' is the segment separator.
//Only allow whole minutes and whole seconds.
date.minute = TimeInterval(try read_int(2).value)
if current() == time_sep {
next()
date.seconds = TimeInterval(try read_int(2).value)
}
} else {
//Allow a fractional minute.
//If we don't get a fraction, look for a seconds segment.
//Otherwise, the fraction of a minute is the seconds.
date.minute = try read_double().value
if current() != ":" {
var int_part: Double = 0.0
var frac_part: Double = 0.0
frac_part = modf(date.minute, &int_part)
date.minute = int_part
date.seconds = frac_part
if date.seconds > Double.ulpOfOne {
// Convert fraction (e.g. .5) into seconds (e.g. 30).
date.seconds = date.seconds * 60
} else if current() == time_sep {
next()
// date.seconds = try read_double().value
let value = try modf(read_double().value)
date.nanoseconds = TimeInterval(round(value.1 * 1000) * 1000000)
date.seconds = TimeInterval(value.0)
}
} else {
// fractional minutes
next()
let value = try modf(read_double().value)
date.nanoseconds = TimeInterval(round(value.1 * 1000) * 1000000)
date.seconds = TimeInterval(value.0)
}
}
}
if cfg.strict == false {
if current().isSpace == true {
next()
}
}
switch current() {
case "Z":
date.timezone = TimeZone(abbreviation: "UTC")
case "+","-":
let is_negative = current() == "-"
next()
if current().isDigit == true {
//Read hour offset.
date.tz_hour = try read_int(2).value
if is_negative == true { date.tz_hour = -date.tz_hour }
// Optional separator
if current() == time_sep {
next()
}
if current().isDigit {
// Read minute offset
date.tz_minute = try read_int(2).value
if is_negative == true { date.tz_minute = -date.tz_minute }
}
let timezone_offset = (date.tz_hour * 3600) + (date.tz_minute * 60)
date.timezone = TimeZone(secondsFromGMT: timezone_offset)
}
default:
break
}
}
self.date_components = DateComponents()
self.date_components!.year = date.year
self.date_components!.day = date.day
self.date_components!.hour = date.hour
self.date_components!.minute = Int(date.minute)
self.date_components!.second = Int(date.seconds)
self.date_components!.nanosecond = Int(date.nanoseconds)
switch date.type {
case .monthAndDate:
self.date_components!.month = date.month_or_week
case .week:
//Adapted from <http://personal.ecu.edu/mccartyr/ISOwdALG.txt>.
//This works by converting the week date into an ordinal date, then letting the next case handle it.
let prevYear = date.year - 1
let YY = prevYear % 100
let C = prevYear - YY
let G = YY + YY / 4
let isLeapYear = (((C / 100) % 4) * 5)
let Jan1Weekday = ((isLeapYear + G) % 7)
var day = ((8 - Jan1Weekday) + (7 * (Jan1Weekday > Weekday.thursday.rawValue ? 1 : 0)))
day += (date.day - 1) + (7 * (date.month_or_week - 2))
if let weekday = date.weekday {
//self.date_components!.weekday = weekday
self.date_components!.day = day + weekday
} else {
self.date_components!.day = day
}
case .dateOnly: //An "ordinal date".
break
}
//self.cfg.calendar.timeZone = date.timezone ?? TimeZone(identifier: "UTC")!
//self.parsedDate = self.cfg.calendar.date(from: self.date_components!)
let tz = date.timezone ?? TimeZone(identifier: "UTC")!
self.parsedTimeZone = tz
self.cfg.calendar.timeZone = tz
self.parsedDate = self.cfg.calendar.date(from: self.date_components!)
return (self.parsedDate,self.parsedTimeZone)
}
private func parse_digits_3(_ num_digits: Int, _ segment: inout Int) throws {
//Technically, the standard only allows one hyphen. But it says that two hyphens is the logical implementation, and one was dropped for brevity. So I have chosen to allow the missing hyphen.
if hyphens < 1 || (hyphens > 2 && cfg.strict == false) {
throw ISO8601ParserError.invalid
}
date.day = segment
date.year = now_cmps.year!
date.type = .dateOnly
if cfg.strict == true && (date.day > (365 + (date.year.isLeapYear ? 1 : 0))) {
throw ISO8601ParserError.invalid
}
}
private func parse_digits_7(_ num_digits: Int, _ segment: inout Int) throws {
guard hyphens == 0 else { throw ISO8601ParserError.invalid }
date.day = segment % 1000
date.year = segment / 1000
date.type = .dateOnly
if cfg.strict == true && (date.day > (365 + (date.year.isLeapYear ? 1 : 0))) {
throw ISO8601ParserError.invalid
}
}
private func parse_digits_2(_ num_digits: Int, _ segment: inout Int) throws {
func parse_hyphens_3(_ num_digits: Int, _ segment: inout Int) throws {
date.year = now_cmps.year!
date.month_or_week = now_cmps.month!
date.day = segment
}
func parse_hyphens_2(_ num_digits: Int, _ segment: inout Int) throws {
date.year = now_cmps.year!
date.month_or_week = segment
if current() == "-" {
next()
date.day = try read_int(2).value
} else {
date.day = 1
}
}
func parse_hyphens_1(_ num_digits: Int, _ segment: inout Int) throws {
let current_year = now_cmps.year!
let current_century = (current_year % 100)
date.year = segment + (current_year - current_century)
if num_digits == 1 { // implied decade
date.year += current_century - (current_year % 10)
}
if current() == "-" {
next()
if current() == "W" {
next()
date.type = .week
}
date.month_or_week = try read_int(2).value
if current() == "-" {
next()
if date.type == .week {
// weekday number
let weekday = try read_int().value
if weekday > 7 {
throw ISO8601ParserError.invalid
}
date.weekday = weekday
} else {
date.day = try read_int().value
if date.day == 0 {
date.day = 1
}
if date.month_or_week == 0 {
date.month_or_week = 1
}
}
} else {
date.day = 1
}
} else {
date.month_or_week = 1
date.day = 1
}
}
func parse_hyphens_0(_ num_digits: Int, _ segment: inout Int) throws {
if current() == "-" {
// Implicit century
date.year = now_cmps.year!
date.year -= (date.year % 100)
date.year += segment
next()
if current() == "W" {
try parseWeekAndDay()
} else if current().isDigit == false {
try centuryOnly(&segment)
} else {
// Get month and/or date.
let (v_count,v_seg) = try read_int()
switch v_count {
case 4: // YY-MMDD
date.day = v_seg % 100
date.month_or_week = v_seg / 100
case 1: // YY-M; YY-M-DD (extension)
if cfg.strict == true {
throw ISO8601ParserError.invalid
}
case 2: // YY-MM; YY-MM-DD
date.month_or_week = v_seg
if current() == "-" {
next()
if current().isDigit == true {
date.day = try read_int(2).value
} else {
date.day = 1
}
} else {
date.day = 1
}
case 3: // Ordinal date
date.day = v_seg
date.type = .dateOnly
default:
break
}
}
} else if current() == "W" {
date.year = now_cmps.year!
date.year -= (date.year % 100)
date.year += segment
try parseWeekAndDay()
} else {
try centuryOnly(&segment)
}
}
switch hyphens {
case 0: try parse_hyphens_0(num_digits, &segment)
case 1: try parse_hyphens_1(num_digits, &segment) //-YY; -YY-MM (implicit century)
case 2: try parse_hyphens_2(num_digits, &segment) //--MM; --MM-DD
case 3: try parse_hyphens_3(num_digits, &segment) //---DD
default: throw ISO8601ParserError.invalid
}
}
private func parse_digits_1(_ num_digits: Int, _ segment: inout Int) throws {
if cfg.strict == true {
// Two digits only - never just one.
guard hyphens == 1 else { throw ISO8601ParserError.invalid }
if current() == "-" {
next()
}
next()
guard current() == "W" else { throw ISO8601ParserError.invalid }
date.year = now_cmps.year!
date.year -= (date.year % 10)
date.year += segment
} else {
try parse_digits_2(num_digits, &segment)
}
}
private func parse_digits_4(_ num_digits: Int, _ segment: inout Int) throws {
func parse_hyphens_0(_ num_digits: Int, _ segment: inout Int) throws {
date.year = segment
if current() == "-" {
next()
}
if current().isDigit == false {
if current() == "W" {
try parseWeekAndDay()
} else {
date.month_or_week = 1
date.day = 1
}
} else {
let (v_num,v_seg) = try read_int()
switch v_num {
case 4: // MMDD
date.day = v_seg % 100
date.month_or_week = v_seg / 100
case 2: // MM
date.month_or_week = v_seg
if current() == "-" {
next()
}
if current().isDigit == false {
date.day = 1
} else {
date.day = try read_int().value
}
case 3: // DDD
date.day = v_seg % 1000
date.type = .dateOnly
if cfg.strict == true && (date.day > 365 + (date.year.isLeapYear ? 1 : 0)) {
throw ISO8601ParserError.invalid
}
default:
throw ISO8601ParserError.invalid
}
}
}
func parse_hyphens_1(_ num_digits: Int, _ segment: inout Int) throws {
date.month_or_week = segment % 100
date.year = segment / 100
if current() == "-" {
next()
}
if current().isDigit == false {
date.day = 1
} else {
date.day = try read_int().value
}
}
func parse_hyphens_2(_ num_digits: Int, _ segment: inout Int) throws {
date.day = segment % 100
date.month_or_week = segment / 100
date.year = now_cmps.year!
}
switch hyphens {
case 0: try parse_hyphens_0(num_digits, &segment) // YYYY
case 1: try parse_hyphens_1(num_digits, &segment) // YYMM
case 2: try parse_hyphens_2(num_digits, &segment) // MMDD
default: throw ISO8601ParserError.invalid
}
}
private func parse_digits_6(_ num_digits: Int, _ segment: inout Int) throws {
// YYMMDD (implicit century)
guard hyphens == 0 else { throw ISO8601ParserError.invalid }
date.day = segment % 100
segment /= 100
date.month_or_week = segment % 100
date.year = now_cmps.year!
date.year -= (date.year % 100)
date.year += (segment / 100)
}
private func parse_digits_8(_ num_digits: Int, _ segment: inout Int) throws {
// YYYY MM DD
guard hyphens == 0 else {
throw ISO8601ParserError.invalid
}
date.day = segment % 100
segment /= 100
date.month_or_week = segment % 100
date.year = segment / 100
}
private func parse_digits_0(_ num_digits: Int, _ segment: inout Int) throws {
guard current() == "W" else {
throw ISO8601ParserError.invalid
}
if seek(1) == "-" && isDigit(seek(2)) &&
((hyphens == 1 || hyphens == 2) && cfg.strict == false) {
date.year = now_cmps.year!
date.month_or_week = 1
next(2)
try parseDayAfterWeek()
} else if hyphens == 1 {
date.year = now_cmps.year!
if current() == "W" {
next()
date.month_or_week = try read_int(2).value
date.type = .week
try parseWeekday()
} else {
try parseDayAfterWeek()
}
} else {
throw ISO8601ParserError.invalid
}
}
private func parseWeekday() throws {
if current() == "-" {
next()
}
let weekday = try read_int().value
if weekday > 7 {
throw ISO8601ParserError.invalid
}
date.type = .week
date.weekday = weekday
}
private func parseWeekAndDay() throws {
next()
if current().isDigit == false {
//Not really a week-based date; just a year followed by '-W'.
guard cfg.strict == false else {
throw ISO8601ParserError.invalid
}
date.month_or_week = 1
date.day = 1
} else {
date.month_or_week = try read_int(2).value
try parseWeekday()
}
}
private func parseDayAfterWeek() throws {
date.day = current().isDigit == true ? try read_int(2).value : 1
date.type = .week
}
private func centuryOnly(_ segment: inout Int) throws {
date.year = segment * 100 + now_cmps.year! % 100
date.month_or_week = 1
date.day = 1
}
/// Return `true` if given character is a char
///
/// - Parameter char: char to evaluate
/// - Returns: `true` if char is a digit, `false` otherwise
private func isDigit(_ char: UnicodeScalar?) -> Bool {
guard let char = char else { return false }
return char.isDigit
}
/// MARK: - Scanner internal functions
/// Get the value at specified offset from current scanner position without
/// moving the current scanner's index.
///
/// - Parameter offset: offset to move
/// - Returns: char at given position, `nil` if not found
@discardableResult
public func seek(_ offset: Int = 1) -> ISOChar? {
let move_idx = string.index(cIdx, offsetBy: offset)
guard move_idx < eIdx else {
return nil
}
return string[move_idx]
}
/// Return the char at the current position of the scanner
///
/// - Parameter next: if `true` return the current char and move to the next position
/// - Returns: the char sat the current position of the scanner
@discardableResult
public func current(_ next: Bool = false) -> ISOChar {
let current = string[cIdx]
if next == true { cIdx = string.index(after: cIdx) }
return current
}
/// Move by `offset` characters the index of the scanner and return the char at the current
/// position. If EOF is reached `nil` is returned.
///
/// - Parameter offset: offset value (use negative number to move backwards)
/// - Returns: character at the current position.
@discardableResult
private func next(_ offset: Int = 1) -> ISOChar? {
let next = string.index(cIdx, offsetBy: offset)
guard next < eIdx else {
return nil
}
cIdx = next
return string[cIdx]
}
/// Read from the current scanner index and parse the value as Int.
///
/// - Parameter max_count: number of characters to move. If nil scanners continues until a non
/// digit value is encountered.
/// - Returns: parsed value
/// - Throws: throw an exception if parser fails
@discardableResult
private func read_int(_ max_count: Int? = nil) throws -> (count: Int, value: Int) {
var move_idx = cIdx
var count = 0
while move_idx < eIdx {
if let max = max_count, count >= max { break }
if string[move_idx].isDigit == false { break }
count += 1
move_idx = string.index(after: move_idx)
}
let raw_value = String(string[cIdx..<move_idx])
if raw_value == "" {
return (count,0)
}
guard let value = Int(raw_value) else {
throw ISO8601ParserError.notDigit
}
cIdx = move_idx
return (count, value)
}
/// Read from the current scanner index and parse the value as Double.
/// If parser fails an exception is throw.
/// Unit separator can be `-` or `,`.
///
/// - Returns: double value
/// - Throws: throw an exception if parser fails
@discardableResult
private func read_double() throws -> (count: Int, value: Double) {
var move_idx = cIdx
var count = 0
var fractional_start = false
while move_idx < eIdx {
let char = string[move_idx]
if char == "." || char == "," {
if fractional_start == true { throw ISO8601ParserError.notDouble }
else { fractional_start = true }
} else {
if char.isDigit == false { break }
}
count += 1
move_idx = string.index(after: move_idx)
}
let raw_value = String(string[cIdx..<move_idx]).replacingOccurrences(of: ",", with: ".")
if raw_value == "" {
return (count,0.0)
}
guard let value = Double(raw_value) else {
throw ISO8601ParserError.notDouble
}
cIdx = move_idx
return (count,value)
}
/// Move the current scanner index to the next position until the current char of the scanner
/// is the given `char` value.
///
/// - Parameter char: char
/// - Returns: the number of characters passed
@discardableResult
private func moveUntil(is char: UnicodeScalar) -> Int {
var move_idx = cIdx
var count = 0
while move_idx < eIdx {
guard string[move_idx] == char else { break }
move_idx = string.index(after: move_idx)
count += 1
}
cIdx = move_idx
return count
}
/// Move the current scanner index to the next position until passed `char` value is
/// encountered or `eof` is reached.
///
/// - Parameter char: char
/// - Returns: the number of characters passed
@discardableResult
private func moveUntil(isNot char: UnicodeScalar) -> Int {
var move_idx = cIdx
var count = 0
while move_idx < eIdx {
guard string[move_idx] != char else { break }
move_idx = string.index(after: move_idx)
count += 1
}
cIdx = move_idx
return count
}
}
| mit | 87d7fadd244c3c8741de3f3594388e0e | 27.206197 | 192 | 0.640695 | 3.311301 | false | false | false | false |
chatappcodepath/ChatAppSwift | LZChat/Plugins/TicTacToeMessageCollectionViewCell.swift | 1 | 3020 | //
// TicTacToeMessageCollectionViewCell.swift
// LZChat
//
// Created by Kevin Balvantkumar Patel on 12/4/16.
//
// License
// Copyright (c) 2017 chatappcodepath
// Released under an MIT license: http://opensource.org/licenses/MIT
//
//
import UIKit
class TicTacToeMessageCollectionViewCell: MessageCollectionViewCell {
public static let cellReuseIdentifier = "TicTacToeMessageCollectionViewCell"
public static let xibFileName = "TicTacToeMessageCollectionViewCell"
public static let rawHeight:CGFloat = 210
@IBOutlet weak var tile0: UILabel!
@IBOutlet weak var tile1: UILabel!
@IBOutlet weak var tile2: UILabel!
@IBOutlet weak var tile3: UILabel!
@IBOutlet weak var tile4: UILabel!
@IBOutlet weak var tile5: UILabel!
@IBOutlet weak var tile6: UILabel!
@IBOutlet weak var tile7: UILabel!
@IBOutlet weak var tile8: UILabel!
@IBOutlet weak var gridView: UIView!
@IBOutlet weak var resultLabel: UILabel!
var tiles:[UILabel]?
var tictactoeModel: TicTacToePayload?
override var message: Message? {
didSet {
tictactoeModel = message?.parsedPayload as? TicTacToePayload
if let tictactoeModel = tictactoeModel,
let sid = FirebaseUtils.sharedInstance.authUser?.uid {
for i in 0..<tictactoeModel.currentTileStates.count {
tiles?[i].text = tictactoeModel.currentTileStates[i].symbol()
}
if let resultString = tictactoeModel.getGameResult(sid: sid).description {
resultLabel.text = resultString
resultLabel.isHidden = false
} else {
resultLabel.isHidden = true
}
}
}
}
private func positionOfTile(tile: UILabel?) -> Int? {
for i in 0..<tiles!.count {
if (tile == tiles?[i]) { return i }
}
return nil
}
func handleTap(recognizer: UITapGestureRecognizer) {
let tile = recognizer.view as? UILabel
if let position = positionOfTile(tile: tile),
let message = message,
let currentUser = FirebaseUtils.sharedInstance.authUser {
if let payload = tictactoeModel?.payloadAfterTouchingTile(atPosition: position, sid: currentUser.uid) {
let updatedMessage = Message.updatedMessageWith(payload: payload, currentMessage: message)
messageSendingDelegate?.updateMessage(updatedMessage)
}
}
}
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
tiles = [tile0, tile1, tile2, tile3, tile4, tile5, tile6, tile7, tile8]
for tile in tiles! {
gridView.layer.cornerRadius = 15.0
gridView.clipsToBounds = true
let tapGr = UITapGestureRecognizer(target: self, action: #selector(handleTap(recognizer:)))
tile.addGestureRecognizer(tapGr)
}
}
}
| mit | 6867e68a4dba1857a78eea8c43693040 | 34.952381 | 115 | 0.62947 | 4.631902 | false | false | false | false |
GianniCarlo/Audiobook-Player | BookPlayer/Extensions/UIImage+BookPlayer.swift | 1 | 2845 | //
// UIImage+BookPlayer.swift
// BookPlayer
//
// Created by Florian Pichler on 28.04.18.
// Copyright © 2018 Tortuga Power. All rights reserved.
//
import UIKit
extension UIImage {
func averageColor() -> UIColor? {
var bitmap = [UInt8](repeating: 0, count: 4)
var inputImage: CIImage
if let ciImage = self.ciImage {
inputImage = ciImage
} else if let cgImage = self.cgImage {
inputImage = CoreImage.CIImage(cgImage: cgImage)
} else {
return nil
}
// Get average color.
let context = CIContext()
let extent = inputImage.extent
let inputExtent = CIVector(x: extent.origin.x, y: extent.origin.y, z: extent.size.width, w: extent.size.height)
guard
let filter = CIFilter(name: "CIAreaAverage", parameters: [kCIInputImageKey: inputImage, kCIInputExtentKey: inputExtent]),
let outputImage = filter.outputImage
else {
return nil
}
let outputExtent = outputImage.extent
assert(outputExtent.size.width == 1 && outputExtent.size.height == 1)
// Render to bitmap.
context.render(outputImage, toBitmap: &bitmap, rowBytes: 4, bounds: CGRect(x: 0, y: 0, width: 1, height: 1), format: CIFormat.RGBA8, colorSpace: CGColorSpaceCreateDeviceRGB())
// Compute result.
let result = UIColor(red: CGFloat(bitmap[0]) / 255.0, green: CGFloat(bitmap[1]) / 255.0, blue: CGFloat(bitmap[2]) / 255.0, alpha: CGFloat(bitmap[3]) / 255.0)
return result
}
func imageWith(newSize: CGSize) -> UIImage {
let renderer = UIGraphicsImageRenderer(size: newSize)
let image = renderer.image { _ in
self.draw(in: CGRect(origin: CGPoint.zero, size: newSize))
}
return image
}
func addLayerMask(_ name: String) -> UIImage {
guard
let image = UIImage(named: name),
let currentImage = self.cgImage,
let maskImageReference = image.cgImage,
let provider = maskImageReference.dataProvider,
let imageMask = CGImage(maskWidth: maskImageReference.width,
height: maskImageReference.height,
bitsPerComponent: maskImageReference.bitsPerComponent,
bitsPerPixel: maskImageReference.bitsPerPixel,
bytesPerRow: maskImageReference.bytesPerRow,
provider: provider,
decode: nil,
shouldInterpolate: false)
else { return self }
guard let maskedImage = currentImage.masking(imageMask) else { return self }
return UIImage(cgImage: maskedImage)
}
}
| gpl-3.0 | 8a0bd1bca258a661d8e6b483b6cc2c0e | 35.461538 | 183 | 0.58263 | 4.787879 | false | false | false | false |
srosskopf/Geschmacksbildung | Geschmacksbildung/Geschmacksbildung/Ex2Controller.swift | 1 | 10282 | //
// Ex2Controller.swift
// Geschmacksbildung
//
// Created by Sebastian Roßkopf on 18.06.16.
// Copyright © 2016 sebastian rosskopf. All rights reserved.
//
import UIKit
class Ex2Controller: UIViewController {
//MARK: - Variables
@IBOutlet var contentView: UIView!
@IBOutlet var scrollView: UIScrollView!
@IBOutlet var letsStartButton: UIButton!
@IBOutlet var nextButton: UIButton!
@IBOutlet var introTextView: UITextView!
@IBOutlet var textView: UITextView!
@IBOutlet var personImageView: UIImageView!
@IBOutlet var font1ImageView: UIImageView!
@IBOutlet var font2ImageView: UIImageView!
@IBOutlet var font3ImageView: UIImageView!
@IBOutlet var font4ImageView: UIImageView!
@IBOutlet var font5ImageView: UIImageView!
@IBOutlet var infoLabel: UILabel!
var firstExerciseCorrect: Bool = false
var secondExerciseCorrect: Bool = false
var senderFrame: CGRect?
let correctTagPerson1: Int = 2
let correctTagPerson2: Int = 4
var imageViews: [UIImageView] = []
//MARK: - View methods
override func viewDidLoad() {
super.viewDidLoad()
let path = NSBundle.mainBundle().pathForResource("03_Style", ofType: "rtf")
let textURL = NSURL.fileURLWithPath(path!)
let options = [NSDocumentTypeDocumentAttribute: NSRTFTextDocumentType]
let attribText = try! NSAttributedString(URL: textURL, options: options, documentAttributes: nil)
introTextView.attributedText = attribText
let _path = NSBundle.mainBundle().pathForResource("03_Style_Explanation", ofType: "rtf")
let _textURL = NSURL.fileURLWithPath(_path!)
let _attribText = try! NSAttributedString(URL: _textURL, options: options, documentAttributes: nil)
textView.attributedText = _attribText
self.textView.scrollRangeToVisible(NSMakeRange(0, 0))
self.introTextView.scrollRangeToVisible(NSMakeRange(0, 0))
imageViews = [font1ImageView, font2ImageView, font3ImageView, font4ImageView, font5ImageView]
var tag = 0
for imageView in imageViews {
imageView.tag = tag
tag += 1
}
nextButton.alpha = 0
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
//MARK: - Methods
func resetStuff(toFirstExercise toFirstExercise: Bool) {
print("will reset stuff")
infoLabel.hidden = true
nextButton.alpha = 0
for imageView in imageViews {
imageView.hidden = false
imageView.userInteractionEnabled = true
}
setupPerson1()
if toFirstExercise {
firstExerciseCorrect = false
secondExerciseCorrect = false
}
self.view.layoutIfNeeded()
}
@IBAction func startButtonTapped(sender: UIButton) {
scrollView.setContentOffset(CGPoint(x: self.scrollView.frame.size.width, y: 0), animated: true)
}
@IBAction func handlePan(sender: UIPanGestureRecognizer) {
print("panning :O \(sender.view!.tag)")
let senderX = sender.view!.center.x
let senderY = sender.view!.center.y
switch sender.state {
case .Began:
print("toches began")
senderFrame = sender.view!.frame
if firstExerciseCorrect {
personImageView.image = UIImage(named: "Business 1")
}
else {
personImageView.image = UIImage(named: "Heavy Metal 1")
}
case .Changed:
let translation = sender.translationInView(self.view)
sender.view?.center = CGPointMake(senderX + translation.x, senderY + translation.y)
sender.setTranslation(CGPointZero, inView: self.view)
case .Ended:
if sender.view!.center.x > personImageView.center.x + personImageView.frame.size.width/2 ||
sender.view!.center.x < personImageView.center.x - personImageView.frame.size.width/2 {
//touch is ended outside of the person, will go back to original frame
if let frame = senderFrame {
sender.view?.frame = frame
}
}
else {
sender.view!.hidden = true
//touch ended with font being dropped on person
if firstExerciseCorrect == false {
if sender.view!.tag == correctTagPerson1 {
infoLabel.text = "Well done!"
infoLabel.hidden = false
infoLabel.alpha = 1
personImageView.image = UIImage(named: "Heavy Metal 3")
UIView.animateWithDuration(0.5, animations: {
self.nextButton.alpha = 1
})
firstExerciseCorrect = true
for imageView in imageViews {
imageView.userInteractionEnabled = false
}
}
else {
infoLabel.text = "Try again"
infoLabel.hidden = false
infoLabel.alpha = 1
personImageView.image = UIImage(named: "Heavy Metal 2")
}
}
else {
if sender.view!.tag == correctTagPerson2 {
infoLabel.text = "Well done!"
infoLabel.hidden = false
infoLabel.alpha = 1
personImageView.image = UIImage(named: "Business 3")
UIView.animateWithDuration(0.5, animations: {
self.nextButton.alpha = 1
})
secondExerciseCorrect = true
}
else {
infoLabel.text = "Try again"
infoLabel.hidden = false
infoLabel.alpha = 1
personImageView.image = UIImage(named: "Business 2")
}
}
}
if let frame = senderFrame {
sender.view?.frame = frame
}
print("touches ended")
default: break
}
}
func setupPerson2() {
personImageView.image = UIImage(named: "Business 1")
var counter = 1
for imageView in imageViews {
imageView.image = UIImage(named: "BusinessFont\(counter)")
print("assgining new image: BusinessFont\(counter)")
counter += 1
}
}
func setupPerson1() {
personImageView.image = UIImage(named: "Heavy Metal 1")
var counter = 1
for imageView in imageViews {
imageView.image = UIImage(named: "Metalfont\(counter)")
print("assgining new image: Metalfont\(counter)")
counter += 1
}
}
@IBAction func nextButtonTapped(sender: UIButton) {
if secondExerciseCorrect {
NSUserDefaults.standardUserDefaults().setBool(true, forKey: "exercise2Finished")
scrollView.setContentOffset(CGPoint(x: 2 * self.scrollView.frame.size.width, y: 0), animated: true)
}
else if firstExerciseCorrect == true {
UIView.animateWithDuration(0.5, delay: 0, options: .CurveEaseIn, animations: {
self.infoLabel.alpha = 0
self.personImageView.alpha = 0
self.nextButton.alpha = 0
for imageView in self.imageViews {
imageView.alpha = 0
}
}, completion: { (finished) in
self.resetStuff(toFirstExercise: false)
self.setupPerson2()
for imageView in self.imageViews {
imageView.userInteractionEnabled = true
}
UIView.animateWithDuration(0.5, animations: {
self.personImageView.alpha = 1
for imageView in self.imageViews {
imageView.alpha = 1
}
})
})
}
}
@IBAction func mainButtonTapped(sender: UIButton) {
NSNotificationCenter.defaultCenter().postNotificationName("menuButtonTapped", object: sender)
}
/*
// 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 | 3cd9298cd8cf60dbdf9094f3abc10470 | 31.738854 | 111 | 0.488132 | 6.029326 | false | false | false | false |
stripe/stripe-ios | StripePaymentSheet/StripePaymentSheet/Internal/Link/Controllers/PayWithLinkViewController-BaseViewController.swift | 1 | 4543 | //
// PayWithLinkViewController-BaseViewController.swift
// StripePaymentSheet
//
// Created by Ramon Torres on 11/2/21.
// Copyright © 2021 Stripe, Inc. All rights reserved.
//
import UIKit
@_spi(STP) import StripeCore
@_spi(STP) import StripeUICore
extension PayWithLinkViewController {
/// For internal SDK use only
@objc(STP_Internal_PayWithLinkBaseViewController)
class BaseViewController: UIViewController {
weak var coordinator: PayWithLinkCoordinating?
let context: Context
var preferredContentMargins: NSDirectionalEdgeInsets {
return customNavigationBar.isLarge
? LinkUI.contentMarginsWithLargeNav
: LinkUI.contentMargins
}
private(set) lazy var customNavigationBar: LinkNavigationBar = {
let navigationBar = LinkNavigationBar()
navigationBar.backButton.addTarget(
self,
action: #selector(onBackButtonTapped(_:)),
for: .touchUpInside
)
navigationBar.closeButton.addTarget(
self,
action: #selector(onCloseButtonTapped(_:)),
for: .touchUpInside
)
navigationBar.menuButton.addTarget(
self,
action: #selector(onMenuButtonTapped(_:)),
for: .touchUpInside
)
return navigationBar
}()
private(set) lazy var contentView = UIView()
init(context: Context) {
self.context = context
super.init(nibName: nil, bundle: nil)
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = .linkBackground
customNavigationBar.translatesAutoresizingMaskIntoConstraints = false
view.addSubview(customNavigationBar)
contentView.translatesAutoresizingMaskIntoConstraints = false
view.addSubview(contentView)
NSLayoutConstraint.activate([
// Navigation bar
customNavigationBar.topAnchor.constraint(equalTo: view.topAnchor),
customNavigationBar.leadingAnchor.constraint(equalTo: view.leadingAnchor),
customNavigationBar.trailingAnchor.constraint(equalTo: view.trailingAnchor),
// Content view
contentView.topAnchor.constraint(equalTo: customNavigationBar.bottomAnchor),
contentView.leadingAnchor.constraint(equalTo: view.leadingAnchor),
contentView.trailingAnchor.constraint(equalTo: view.trailingAnchor),
contentView.bottomAnchor.constraint(equalTo: view.bottomAnchor)
])
}
override func present(
_ viewControllerToPresent: UIViewController,
animated flag: Bool,
completion: (() -> Void)? = nil
) {
// Any view controller presented by this controller should also be customized.
context.configuration.style.configure(viewControllerToPresent)
super.present(viewControllerToPresent, animated: flag, completion: completion)
}
@objc
func onBackButtonTapped(_ sender: UIButton) {
navigationController?.popViewController(animated: true)
}
@objc
func onCloseButtonTapped(_ sender: UIButton) {
if context.shouldFinishOnClose {
coordinator?.finish(withResult: .canceled)
} else {
coordinator?.cancel()
}
}
@objc
func onMenuButtonTapped(_ sender: UIButton) {
let actionSheet = UIAlertController(title: nil, message: nil, preferredStyle: .actionSheet)
actionSheet.addAction(UIAlertAction(
title: STPLocalizedString("Log out of Link", "Title of the logout action."),
style: .destructive,
handler: { [weak self] _ in
self?.coordinator?.logout(cancel: true)
}
))
actionSheet.addAction(UIAlertAction(title: String.Localized.cancel, style: .cancel))
// iPad support
actionSheet.popoverPresentationController?.sourceView = sender
actionSheet.popoverPresentationController?.sourceRect = sender.bounds
present(actionSheet, animated: true)
}
}
}
| mit | 3a685730aeae2353a21370621526c607 | 35.047619 | 103 | 0.608763 | 5.992084 | false | false | false | false |
CatchChat/Yep | Yep/Views/Cells/Feed/SearchedFeed/SearchedFeedURLCell.swift | 1 | 1680 | //
// SearchedFeedURLCell.swift
// Yep
//
// Created by NIX on 16/4/19.
// Copyright © 2016年 Catch Inc. All rights reserved.
//
import UIKit
import YepKit
final class SearchedFeedURLCell: SearchedFeedBasicCell {
override class func heightOfFeed(feed: DiscoveredFeed) -> CGFloat {
let height = super.heightOfFeed(feed) + (10 + 20)
return ceil(height)
}
var tapURLInfoAction: ((URL: NSURL) -> Void)?
lazy var feedURLContainerView: IconTitleContainerView = {
let view = IconTitleContainerView(frame: CGRect(x: 0, y: 0, width: 200, height: 150))
return view
}()
override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
contentView.addSubview(feedURLContainerView)
feedURLContainerView.iconImageView.image = UIImage.yep_iconLink
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func configureWithFeed(feed: DiscoveredFeed, layout: SearchedFeedCellLayout, keyword: String?) {
super.configureWithFeed(feed, layout: layout, keyword: keyword)
if let attachment = feed.attachment {
if case let .URL(openGraphInfo) = attachment {
feedURLContainerView.titleLabel.text = openGraphInfo.title
feedURLContainerView.tapAction = { [weak self] in
self?.tapURLInfoAction?(URL: openGraphInfo.URL)
}
}
}
let _URLLayout = layout._URLLayout!
feedURLContainerView.frame = _URLLayout.URLContainerViewFrame
}
}
| mit | 719dc61039eae814e1f2da4039c78997 | 27.423729 | 109 | 0.658915 | 4.495979 | false | false | false | false |
newtonstudio/cordova-plugin-device | imgly-sdk-ios-master/imglyKit/Frontend/IMGLYFixedFilterStack.swift | 1 | 2447 | //
// FixedFilterStack.swift
// imglyKit
//
// Created by Sascha Schwabbauer on 08/04/15.
// Copyright (c) 2015 9elements GmbH. All rights reserved.
//
import UIKit
import CoreImage
/**
* This class represents the filterstack that is used when using the UI.
* It represents a chain of filters that will be applied to the taken image.
* That way we make sure the order of filters stays the same, and we don't need to take
* care about creating the single filters.
*/
public class IMGLYFixedFilterStack: NSObject {
// MARK: - Properties
public var enhancementFilter: IMGLYEnhancementFilter = {
let filter = IMGLYInstanceFactory.enhancementFilter()
filter.enabled = false
filter.storeEnhancedImage = true
return filter
}()
public var orientationCropFilter = IMGLYInstanceFactory.orientationCropFilter()
public var effectFilter = IMGLYInstanceFactory.effectFilterWithType(IMGLYFilterType.None)
public var brightnessFilter = IMGLYInstanceFactory.colorAdjustmentFilter()
public var tiltShiftFilter = IMGLYInstanceFactory.tiltShiftFilter()
public var textFilter = IMGLYInstanceFactory.textFilter()
public var stickerFilters = [CIFilter]()
public var activeFilters: [CIFilter] {
var activeFilters: [CIFilter] = [enhancementFilter, orientationCropFilter, tiltShiftFilter, effectFilter, brightnessFilter, textFilter]
activeFilters += stickerFilters
return activeFilters
}
// MARK: - Initializers
required override public init () {
super.init()
}
}
extension IMGLYFixedFilterStack: NSCopying {
public func copyWithZone(zone: NSZone) -> AnyObject {
let copy = self.dynamicType()
copy.enhancementFilter = enhancementFilter.copyWithZone(zone) as! IMGLYEnhancementFilter
copy.orientationCropFilter = orientationCropFilter.copyWithZone(zone) as! IMGLYOrientationCropFilter
copy.effectFilter = effectFilter.copyWithZone(zone) as! IMGLYResponseFilter
copy.brightnessFilter = brightnessFilter.copyWithZone(zone) as! IMGLYContrastBrightnessSaturationFilter
copy.tiltShiftFilter = tiltShiftFilter.copyWithZone(zone) as! IMGLYTiltshiftFilter
copy.textFilter = textFilter.copyWithZone(zone) as! IMGLYTextFilter
copy.stickerFilters = NSArray(array: stickerFilters, copyItems: true) as! [CIFilter]
return copy
}
}
| apache-2.0 | 1143f10338474661aaf30f17d03dd872 | 38.467742 | 143 | 0.729465 | 4.652091 | false | false | false | false |
byu-oit-appdev/ios-byuSuite | byuSuite/Apps/SafeWalk/controller/SafeWalkMapViewController.swift | 1 | 4306 | //
// SafeWalkMapViewController.swift
// byuSuite
//
// Created by Erik Brady on 8/9/17.
// Copyright © 2017 Brigham Young University. All rights reserved.
//
import MapKit
private let DESTINATION_IDENTIFIER = "destinationPin"
private let SEGUE_IDENTIFIER = "beginSession"
class SafeWalkMapViewController: ByuMapViewController2 {
//MARK: Outlets
@IBOutlet private weak var confirmButton: UIButton!
@IBOutlet private weak var spinner: UIActivityIndicatorView!
//MARK: Public Properties
var phoneNumber: String!
//MARK: Private Properties
private var destination: SafeWalkCoordinateInfo?
override func viewDidLoad() {
super.viewDidLoad()
//Add this recognizer to allow user to add Destination Pin to map
let lpgr = UILongPressGestureRecognizer(target: self, action: #selector(handleLongPress))
lpgr.minimumPressDuration = 0.10
mapView.addGestureRecognizer(lpgr)
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
zoomToFitMapAnnotations(includeUserLocation: true, keepByuInFrame: true)
}
deinit {
mapView.delegate = nil
}
//MARK: Navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == SEGUE_IDENTIFIER,
let vc = segue.destination as? SafeWalkSessionViewController,
let destination = destination {
vc.destination = destination
}
}
//MARK: MKMapViewDelegate Methods
func mapView(_ mapView: MKMapView, viewFor annotation: MKAnnotation) -> MKAnnotationView? {
if annotation.isKind(of: SafeWalkCoordinateInfo.self) {
var pinView = mapView.dequeueReusableAnnotationView(withIdentifier: DESTINATION_IDENTIFIER) as? MKPinAnnotationView
if pinView == nil {
//No annotation view exists in the reuse queue (i.e. none are available to reuse); create one
pinView = MKPinAnnotationView(annotation: annotation, reuseIdentifier: DESTINATION_IDENTIFIER)
pinView?.animatesDrop = true
pinView?.tintColor = UIColor.byuTint
pinView?.pinTintColor = UIColor.byuTint
}
return pinView
} else {
return nil
}
}
//MARK: Listeners
@IBAction func confirmDestination(_ sender: Any) {
if let destination = destination {
if !destination.isWithinByuPoliceDispatchRange() {
super.displayAlert(title: "Out of Range", message: "Your selected destination is out of the area BYU Police Dispatch is able to monitor.", alertHandler: nil)
} else {
super.displayActionSheet(from: sender, actions: [
UIAlertAction(title: "Begin SafeWalk Session", style: .default, handler: { (action) in
super.displayAlert(error: nil, title: "Warning", message: "\nYou will receive a confirmation text to inform you that your SafeWalk session has begun, and your location is being monitored. Until you have received this confirmation, you are NOT being tracked. Once your session has begun, DO NOT terminate the app until you have confirmed that you are safe.", alertHandler: { (_) in
self.performSegue(withIdentifier: SEGUE_IDENTIFIER, sender: nil)
})
})
])
}
} else {
super.displayAlert(error: nil, title: "Please tap your approximate destination.", message: nil, alertHandler: nil)
}
}
@IBAction func cancelButtonTapped(_ sender: Any) {
popBack()
}
@objc func handleLongPress(gestureRecognizer: UIGestureRecognizer) {
if gestureRecognizer.state == .began {
let touchPoint = gestureRecognizer.location(in: mapView)
//Remove old annotations since there will only be one destination
mapView.removeAnnotations(mapView.annotations)
let coordinate = mapView.convert(touchPoint, toCoordinateFrom: mapView)
destination = SafeWalkCoordinateInfo(coordinate: coordinate, phoneNumber: phoneNumber)
if let destination = destination {
mapView.addAnnotation(destination)
}
}
}
}
| apache-2.0 | 22c1a5f294ca50062aa8d485e88ce597 | 35.794872 | 386 | 0.659233 | 5.106762 | false | false | false | false |
Jnosh/SwiftBinaryHeapExperiments | BinaryHeap/NonGenericHeaps.swift | 1 | 5443 | //
// NonGenericHeap.swift
// BinaryHeap
//
// Created by Janosch Hildebrand on 22/11/15.
// Copyright © 2015 Janosch Hildebrand. All rights reserved.
//
public struct SmallValueElementHeap : BinaryHeapType, CustomDebugStringConvertible, CustomStringConvertible {
private var heap: UnsafePointerHeap<ValueElementSmall>
public init() {
heap = UnsafePointerHeap()
}
public var count: Int {
return heap.count
}
public var first: ValueElementSmall? {
return heap.first
}
public mutating func insert(value: ValueElementSmall) {
heap.insert(value)
}
public mutating func removeFirst() -> ValueElementSmall {
return heap.removeFirst()
}
public mutating func removeAll(keepCapacity keepCapacity: Bool = false) {
heap.removeAll(keepCapacity: keepCapacity)
}
}
public struct MediumValueElementHeap : BinaryHeapType, CustomDebugStringConvertible, CustomStringConvertible {
private var heap: UnsafePointerHeap<ValueElementMedium>
public init() {
heap = UnsafePointerHeap()
}
public var count: Int {
return heap.count
}
public var first: ValueElementMedium? {
return heap.first
}
public mutating func insert(value: ValueElementMedium) {
heap.insert(value)
}
public mutating func removeFirst() -> ValueElementMedium {
return heap.removeFirst()
}
public mutating func removeAll(keepCapacity keepCapacity: Bool = false) {
heap.removeAll(keepCapacity: keepCapacity)
}
}
public struct LargeValueElementHeap : BinaryHeapType, CustomDebugStringConvertible, CustomStringConvertible {
private var heap: UnsafePointerHeap<ValueElementLarge>
public init() {
heap = UnsafePointerHeap()
}
public var count: Int {
return heap.count
}
public var first: ValueElementLarge? {
return heap.first
}
public mutating func insert(value: ValueElementLarge) {
heap.insert(value)
}
public mutating func removeFirst() -> ValueElementLarge {
return heap.removeFirst()
}
public mutating func removeAll(keepCapacity keepCapacity: Bool = false) {
heap.removeAll(keepCapacity: keepCapacity)
}
}
public struct ReferenceElementHeap : BinaryHeapType, CustomDebugStringConvertible, CustomStringConvertible {
private var heap: UnsafePointerHeap<ReferenceElement>
public init() {
heap = UnsafePointerHeap()
}
public var count: Int {
return heap.count
}
public var first: ReferenceElement? {
return heap.first
}
public mutating func insert(value: ReferenceElement) {
heap.insert(value)
}
public mutating func removeFirst() -> ReferenceElement {
return heap.removeFirst()
}
public mutating func removeAll(keepCapacity keepCapacity: Bool = false) {
heap.removeAll(keepCapacity: keepCapacity)
}
}
public struct PointerReferenceElementHeap : BinaryHeapType, CustomDebugStringConvertible, CustomStringConvertible {
private var heap: UnsafePointerHeap<PointerElement<ReferenceElement>>
public init() {
heap = UnsafePointerHeap()
}
public var count: Int {
return heap.count
}
public var first: PointerElement<ReferenceElement>? {
return heap.first
}
public mutating func insert(value: PointerElement<ReferenceElement>) {
heap.insert(value)
}
public mutating func removeFirst() -> PointerElement<ReferenceElement> {
return heap.removeFirst()
}
public mutating func removeAll(keepCapacity keepCapacity: Bool = false) {
heap.removeAll(keepCapacity: keepCapacity)
}
}
public struct PointerValueElementHeap : BinaryHeapType, CustomDebugStringConvertible, CustomStringConvertible {
private var heap: UnsafePointerHeap<PointerElement<ValueElementLarge>>
public init() {
heap = UnsafePointerHeap()
}
public var count: Int {
return heap.count
}
public var first: PointerElement<ValueElementLarge>? {
return heap.first
}
public mutating func insert(value: PointerElement<ValueElementLarge>) {
heap.insert(value)
}
public mutating func removeFirst() -> PointerElement<ValueElementLarge> {
return heap.removeFirst()
}
public mutating func removeAll(keepCapacity keepCapacity: Bool = false) {
heap.removeAll(keepCapacity: keepCapacity)
}
}
public struct UnmanagedElementHeap : BinaryHeapType, CustomDebugStringConvertible, CustomStringConvertible {
private var heap: UnsafePointerHeap<UnmanagedElement<ReferenceElement>>
public init() {
heap = UnsafePointerHeap()
}
public var count: Int {
return heap.count
}
public var first: UnmanagedElement<ReferenceElement>? {
return heap.first
}
public mutating func insert(value: UnmanagedElement<ReferenceElement>) {
heap.insert(value)
}
public mutating func removeFirst() -> UnmanagedElement<ReferenceElement> {
return heap.removeFirst()
}
public mutating func removeAll(keepCapacity keepCapacity: Bool = false) {
heap.removeAll(keepCapacity: keepCapacity)
}
}
| mit | 6c1133b90726f147d0643c9a9e2443b6 | 25.676471 | 115 | 0.669791 | 5.105066 | false | false | false | false |
Marshal89/SlideOutMenu | SlideOutMenu.swift | 1 | 7657 | /*
SlideOutMenu.swift
version : beta
MIT License
Copyright (c) 2017 Hani Althubaiti on 6/22/17.
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
@IBDesignable class SideOutMenu: UIViewController {
//represents menu status
enum Status{
case Opened
case Closed
}
/* Controllers defintions */
var main:UIViewController?
var menu:UIViewController?
var menuStatus:Status = .Closed
/* General Settings */
var _shadow:Bool = false
var _shadowColor:UIColor = UIColor.black
var _shadowOpacity:Float = 1
var _shadowRadius:CGFloat = 3
var byPercentage = true;
var menuWidth:CGFloat = 90;
var menuShift:CGFloat?
var mainShift:CGFloat?
var _menuImage = UIImage(named: "menu")
/* Storyboard IDs */
var _mainID = "main"
var _menuID = "menu"
override func viewDidLoad(){
super.viewDidLoad()
//get main & menu VCL
main = storyboard!.instantiateViewController(withIdentifier: mainID)
menu = storyboard!.instantiateViewController(withIdentifier: menuID)
//Add BarButton
self.navigationItem.leftBarButtonItem = UIBarButtonItem(image: _menuImage, style: UIBarButtonItemStyle.plain, target: self, action: #selector(handelMenu))
//create left & right gesture
createGesture()
if menu != nil && main != nil{
//width calculation
if(byPercentage){
menuShift = view.frame.width * menuWidth / 100.0
mainShift = menuShift! + 1
}else{
menuShift = menuWidth
mainShift = menuWidth
}
/* Add menu to container & configurations */
self.addChildViewController(menu!)
menu!.view.frame.size.width = menuShift!
self.view.addSubview(menu!.view)
// menu!.didMove(toParentViewController: self)
menuStatus = .Closed
/* Add main to container & configurations */
self.addChildViewController(main!)
self.view.addSubview(main!.view)
//shadow settings
if(_shadow){
main!.view.layer.masksToBounds = false
main!.view.layer.shadowColor = _shadowColor.cgColor
main!.view.layer.shadowOffset = CGSize.zero
main!.view.layer.shadowOpacity = _shadowOpacity
main!.view.layer.shadowRadius = _shadowRadius
}
// main!.didMove(toParentViewController: self)
}
// Do any additional setup after loading the view.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
/* Handling the menu */
@IBAction func handelMenu(){
UIView.animate(withDuration: 0.5, animations: {
if(self.menuStatus == .Closed){
if self.menu != nil && self.main != nil{
/* put the menu first */
let y = self.view.frame.origin.y
let w = self.view.frame.size.width
let h = self.view.frame.size.height
self.main!.view.frame = CGRect(x: self.mainShift!, y: y, width: w, height: h)
self.menuStatus = .Opened
}
}else{
if self.menu != nil && self.main != nil{
let x = self.view.frame.origin.y
let y = self.view.frame.origin.y
let w = self.view.frame.size.width
let h = self.view.frame.size.height
self.main!.view.frame = CGRect(x: x, y: y, width: w, height: h)
self.menuStatus = .Closed
}
}
})
}
/* Handling Gesture */
func createGesture(){
//left side
let leftScreenEdgeRecognizer = UIScreenEdgePanGestureRecognizer(target: self,action: #selector(self.leftGesture))
leftScreenEdgeRecognizer.edges = .left
//right side
let rightScreenEdgeRecognizer = UIScreenEdgePanGestureRecognizer(target: self,action: #selector(self.rightGesture))
rightScreenEdgeRecognizer.edges = .right
//add to the view
view.addGestureRecognizer(leftScreenEdgeRecognizer)
view.addGestureRecognizer(rightScreenEdgeRecognizer)
}
func leftGesture(_ recognizer: UIScreenEdgePanGestureRecognizer){
if(recognizer.state == .recognized && menuStatus == .Closed){
handelMenu()
}
}
func rightGesture(_ recognizer: UIScreenEdgePanGestureRecognizer){
if(recognizer.state == .recognized && menuStatus == .Opened){
handelMenu()
}
}
/* End of handling gesture */
override func viewWillDisappear(_ animated: Bool) {
//in case of the menu is opend
if(menuStatus == .Opened){
handelMenu()
}
}
/* General Settings */
@IBInspectable public var enableShadow: Bool = false {
didSet {
_shadow = enableShadow
}
}
@IBInspectable public var shadowColor: UIColor = UIColor.black {
didSet {
_shadowColor = shadowColor
}
}
@IBInspectable public var shadowOpacity: Float = 1.0 {
didSet {
if(shadowOpacity > 1){
shadowOpacity = 1
}else if(shadowOpacity < 0){
shadowOpacity = 0
}
_shadowOpacity = shadowOpacity
}
}
@IBInspectable public var shadowRadius: CGFloat = 3.0 {
didSet {
_shadowRadius = shadowRadius
}
}
@IBInspectable public var mainID: String = "main" {
didSet {
_mainID = mainID
}
}
@IBInspectable public var menuID: String = "menu" {
didSet {
_menuID = menuID
}
}
@IBInspectable public var shiftMenuByPercentage: Bool = true {
didSet {
byPercentage = shiftMenuByPercentage
}
}
@IBInspectable public var shiftValue: CGFloat = 90 {
didSet {
if(byPercentage){
if(shiftValue > 100){
shiftValue = 100
}else if(shiftValue < 0){
shiftValue = 0
}
}
menuWidth = shiftValue
}
}
@IBInspectable public var menuImage: UIImage = UIImage(named:"menu")! {
didSet {
_menuImage = menuImage
}
}
}
| mit | bce1212a0c940c32b3c6b4da9e5fc5d2 | 32.880531 | 162 | 0.587828 | 4.933634 | false | false | false | false |
rnystrom/GitHawk | Local Pods/GitHubAPI/GitHubAPI/Client.swift | 1 | 2915 | //
// Client.swift
// GitHubAPI
//
// Created by Ryan Nystrom on 3/3/18.
// Copyright © 2018 Ryan Nystrom. All rights reserved.
//
import Foundation
import Apollo
public protocol HTTPPerformer {
func send(
url: String,
method: HTTPMethod,
parameters: [String: Any]?,
headers: [String: String]?,
completion: @escaping (HTTPURLResponse?, Any?, Error?) -> Void
)
}
public protocol ClientDelegate: class {
func didUnauthorize(client: Client)
}
public class Client {
weak var delegate: ClientDelegate?
private let httpPerformer: HTTPPerformer
private let apollo: ApolloClient
private let token: String?
public init(
httpPerformer: HTTPPerformer,
apollo: ApolloClient,
token: String? = nil
) {
self.httpPerformer = httpPerformer
self.apollo = apollo
self.token = token
}
public func send<T: HTTPRequest>(_ request: T, completion: @escaping (Result<T.ResponseType>) -> Void) {
var parameters = request.parameters ?? [:]
parameters["access_token"] = token
httpPerformer.send(
url: request.url,
method: request.method,
parameters: parameters,
headers: request.headers) { [weak self] (response, json, error) in
guard let strongSelf = self else { return }
if request.logoutOnAuthFailure,
let statusCode = response?.statusCode,
statusCode == 401 {
completion(.failure(ClientError.unauthorized))
strongSelf.delegate?.didUnauthorize(client: strongSelf)
} else {
asyncProcessResponse(request: request, input: json, response: response, error: error, completion: completion)
}
}
}
@discardableResult
public func query<T: GraphQLQuery, Q>(
_ query: T,
result: @escaping (T.Data) -> Q?,
completion: @escaping (Result<Q>) -> Void
) -> Cancellable {
return apollo.fetch(query: query, cachePolicy: .fetchIgnoringCacheData) { (response, error) in
if let data = response?.data, let q = result(data) {
completion(.success(q))
} else {
completion(.failure(error ?? response?.errors?.first))
}
}
}
@discardableResult
public func mutate<T: GraphQLMutation, Q>(
_ mutation: T,
result: @escaping (T.Data) -> Q?,
completion: @escaping (Result<Q>) -> Void
) -> Cancellable {
return apollo.perform(mutation: mutation) { (response, error) in
if let data = response?.data, let q = result(data) {
completion(.success(q))
} else {
completion(.failure(error ?? response?.errors?.first))
}
}
}
}
| mit | fad40ad0ccc4fe42feda2c26b3ce1c60 | 29.354167 | 129 | 0.57138 | 4.603476 | false | false | false | false |
mcxiaoke/learning-ios | cocoa_programming_for_osx/20_DrawingTextWithAttributes/Dice/Dice/DieView.swift | 1 | 7185 | //
// DieView.swift
// Dice
//
// Created by mcxiaoke on 16/5/5.
// Copyright © 2016年 mcxiaoke. All rights reserved.
//
import Cocoa
@IBDesignable class DieView: NSView {
var highlighted: Bool = false {
didSet {
needsDisplay = true
}
}
var intValue : Int? = 5 {
didSet {
needsDisplay = true
}
}
var pressed: Bool = false {
didSet {
needsDisplay = true
}
}
override var intrinsicContentSize: NSSize {
return NSSize(width: 40, height: 40)
}
override var focusRingMaskBounds: NSRect {
return bounds
}
override func drawFocusRingMask() {
NSBezierPath.fillRect(bounds)
}
override var acceptsFirstResponder: Bool {
return true
}
override func becomeFirstResponder() -> Bool {
return true
}
override func resignFirstResponder() -> Bool {
return true
}
override func keyDown(theEvent: NSEvent) {
interpretKeyEvents([theEvent])
}
override func insertTab(sender: AnyObject?) {
window?.selectNextKeyView(sender)
}
override func insertBacktab(sender: AnyObject?) {
window?.selectPreviousKeyView(sender)
}
override func insertText(insertString: AnyObject) {
let text = insertString as! String
if let number = Int(text) {
intValue = number
}
}
override func mouseEntered(theEvent: NSEvent) {
highlighted = true
window?.makeFirstResponder(self)
}
override func mouseExited(theEvent: NSEvent) {
highlighted = false
}
override func viewDidMoveToWindow() {
window?.acceptsMouseMovedEvents = true
// let options: NSTrackingAreaOptions = .MouseEnteredAndExited | .ActiveAlways | .InVisibleRect
// Swift 2 fix
// http://stackoverflow.com/questions/36560189/no-candidates-produce-the-expected-contextual-result-type-nstextstorageedit
let options: NSTrackingAreaOptions = [.MouseEnteredAndExited, .ActiveAlways, .InVisibleRect ]
let trackingArea = NSTrackingArea(rect: NSRect(), options: options, owner: self, userInfo: nil)
addTrackingArea(trackingArea)
}
func randomize() {
intValue = Int(arc4random_uniform(5)+1)
}
override func mouseDown(theEvent: NSEvent) {
Swift.print("mouse down")
let pointInView = convertPoint(theEvent.locationInWindow, fromView: nil)
// let dieFrame = metricsForSize(bounds.size).dieFrame
// pressed = dieFrame.contains(pointInView)
pressed = diePathWithSize(bounds.size).containsPoint(pointInView)
}
override func mouseDragged(theEvent: NSEvent) {
Swift.print("mouse dragged, location: \(theEvent.locationInWindow)")
}
override func mouseUp(theEvent: NSEvent) {
Swift.print("mouse up click count: \(theEvent.clickCount)")
if theEvent.clickCount == 2 {
randomize()
}
pressed = false
}
override func drawRect(dirtyRect: NSRect) {
let bgColor = NSColor.lightGrayColor()
bgColor.set()
NSBezierPath.fillRect(bounds)
// NSColor.greenColor().set()
// let path = NSBezierPath()
// path.moveToPoint(NSPoint(x: 0, y: 0))
// path.lineToPoint(NSPoint(x: bounds.width, y: bounds.height))
// path.stroke()
if highlighted {
NSColor.redColor().set()
let rect = CGRect(x: 5, y: bounds.height - 15, width: 10, height: 10)
NSBezierPath(ovalInRect:rect).fill()
}
drawDieWithSize(bounds.size)
}
func metricsForSize(size:CGSize) -> (edgeLength: CGFloat, dieFrame: CGRect, drawingBounds:CGRect) {
let edgeLength = min(size.width, size.height)
let padding = edgeLength / 10.0
// at center
let ox = (size.width - edgeLength )/2
let oy = (size.height - edgeLength)/2
let drawingBounds = CGRect(x: ox, y: oy, width: edgeLength, height: edgeLength)
var dieFrame = drawingBounds.insetBy(dx: padding, dy: padding)
if pressed {
dieFrame = dieFrame.offsetBy(dx: 0, dy: -edgeLength/40)
}
return (edgeLength, dieFrame, drawingBounds)
}
func diePathWithSize(size:CGSize) -> NSBezierPath {
let (edgeLength, dieFrame, _) = metricsForSize(size)
let cornerRadius:CGFloat = edgeLength / 5.0
return NSBezierPath(roundedRect: dieFrame, xRadius: cornerRadius, yRadius: cornerRadius)
}
func drawDieWithSize(size:CGSize) {
if let intValue = intValue {
let (edgeLength, dieFrame, drawingBounds) = metricsForSize(size)
let cornerRadius:CGFloat = edgeLength / 5.0
let dotRadius = edgeLength / 12.0
let dotFrame = dieFrame.insetBy(dx: dotRadius * 2.5, dy: dotRadius * 2.5)
NSGraphicsContext.saveGraphicsState()
let shadow = NSShadow()
shadow.shadowOffset = NSSize(width: 0, height: -1)
shadow.shadowBlurRadius = ( pressed ? edgeLength/100 : edgeLength / 20)
shadow.set()
NSColor.whiteColor().set()
NSBezierPath(roundedRect: dieFrame, xRadius: cornerRadius, yRadius: cornerRadius).fill()
NSGraphicsContext.restoreGraphicsState()
// NSColor.redColor().set()
NSColor.blackColor().set()
let gradient = NSGradient(startingColor: NSColor.redColor(), endingColor: NSColor.greenColor())
// gradient?.drawInRect(drawingBounds, angle: 180.0)
func drawDot(u: CGFloat, v:CGFloat) {
let dotOrigin = CGPoint(x: dotFrame.minX + dotFrame.width * u,
y: dotFrame.minY + dotFrame.height * v)
let dotRect = CGRect(origin: dotOrigin, size: CGSizeZero).insetBy(dx: -dotRadius, dy: -dotRadius)
let path = NSBezierPath(ovalInRect: dotRect)
path.fill()
}
if (1...6).indexOf(intValue) != nil {
if [1,3,5].indexOf(intValue) != nil {
drawDot(0.5, v: 0.5)
}
if (2...6).indexOf(intValue) != nil {
drawDot(0, v: 1)
drawDot(1, v: 0)
}
if (4...6).indexOf(intValue) != nil {
drawDot(1, v: 1)
drawDot(0, v: 0)
}
if intValue == 6 {
drawDot(0, v: 0.5)
drawDot(1, v: 0.5)
}
}else{
let paraStyle = NSParagraphStyle.defaultParagraphStyle().mutableCopy() as! NSMutableParagraphStyle
paraStyle.alignment = .Center
let font = NSFont.systemFontOfSize(edgeLength * 0.5)
let attrs = [
NSForegroundColorAttributeName: NSColor.blackColor(),
NSFontAttributeName: font,
NSParagraphStyleAttributeName: paraStyle
]
let string = "\(intValue)" as NSString
string.drawCenteredInRect(dieFrame, withAttributes: attrs)
}
}
}
@IBAction func saveAsPDF(sender: AnyObject!) {
let sp = NSSavePanel()
sp.allowedFileTypes = ["pdf"]
sp.beginSheetModalForWindow(window!) { [unowned sp] (result) in
if result == NSModalResponseOK {
//
let data = self.dataWithPDFInsideRect(self.bounds)
do {
try data.writeToURL(sp.URL!, options: NSDataWritingOptions.DataWritingAtomic)
}catch {
let alert = NSAlert()
alert.messageText = "Save Error"
alert.informativeText = "Can not save as PDF!"
alert.runModal()
}
}
}
}
}
| apache-2.0 | baee5d8fc8693fe3c2be61e323aaea64 | 28.80083 | 126 | 0.639655 | 4.23467 | false | false | false | false |
leyamcir/StarWars | StarWars/ForceSensitive.swift | 1 | 2256 | //
// ForceSensitive.swift
// StarWars
//
// Created by Alicia Daza on 23/06/16.
// Copyright © 2016 Alicia Daza. All rights reserved.
//
import Foundation
import UIKit
class ForceSensitive : StarWarsCharacter {
//MARK: - Stored Properties
let midichlorians : Int
//MARK: - Inicialization
init(firstName : String?, lastName : String?, alias: String?,
soundData : NSData, photo: UIImage, url: NSURL, affiliation: StarWarsAffiliation, midichlorians: Int){
// Always self attributes first
self.midichlorians = midichlorians
// After all is setted, super can be called
super.init(firstName: firstName, lastName: lastName,
alias: alias, soundData: soundData, photo: photo,
url: url, affiliation: affiliation)
}
convenience init(jediWithFirstName: String?,
lastName: String?,
alias: String?,
soundData: NSData,
photo: UIImage,
url: NSURL,
midichlorians: Int) {
self.init(firstName: jediWithFirstName,
lastName: lastName,
alias: alias, soundData: soundData,
photo: photo,
url: url,
affiliation: .rebelAlliance,
midichlorians: midichlorians)
}
convenience init(sithWithFirstName: String?,
lastName: String?,
alias: String?,
soundData: NSData,
photo: UIImage,
url: NSURL,
midichlorians: Int) {
self.init(firstName: sithWithFirstName,
lastName: lastName,
alias: alias, soundData: soundData,
photo: photo,
url: url,
affiliation: .galacticEmpire,
midichlorians: midichlorians)
}
// MARK: - Proxies
override var proxyForComparison: String {
get {
return "\(super.proxyForComparison)\(midichlorians)"
}
}
override var proxyForSorting: String {
get {
let isSith = ((affiliation == .galacticEmpire) ||
(affiliation == .firstOrder)) ? "S" : "J"
return "\(isSith)\(midichlorians)\(super.proxyForSorting)"
}
}
}
| gpl-3.0 | b14a94d1ba14139ef6acf2667a934d57 | 26.168675 | 110 | 0.567627 | 4.430255 | false | false | false | false |
RoseEr/HealthyLifestyleTracker | HealthyLifestyleTracker/CalendarViewController.swift | 1 | 3902 | //
// CalendarViewController.swift
// HealthyLifestyleTracker
//
// Created by Eric Rose on 1/28/17.
// Copyright © 2017 Eric Rose. All rights reserved.
//
import UIKit
class CalendarViewController: UIViewController, FSCalendarDelegate, FSCalendarDataSource {
private weak var calendar : FSCalendar!
private weak var eventsTableController : EventsTableViewController!
override func viewDidLoad() {
super.viewDidLoad()
self.view.backgroundColor = UIColor.white
self.calendar = FSCalendar(frame: CGRect(x: 0, y: 0, width: 0, height: 0))
self.calendar.dataSource = self
self.calendar.delegate = self
self.calendar.clipsToBounds = true
self.view.addSubview(self.calendar)
let cEvent = CalendarEvent(text: "2000/2000", isCalorieEvent: true)
var cEvents = [CalendarEvent]()
cEvents.append(cEvent)
let eventsTableController = EventsTableViewController(events: cEvents, nibName: nil, bundle: nil)
self.eventsTableController = eventsTableController
self.addChildViewController(self.eventsTableController)
self.view.addSubview(self.eventsTableController.tableView)
self.setupConstraints()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
private func updateEvents() {
let cEvent = CalendarEvent(text: "1000/2000", isCalorieEvent: true)
var cEvents = [CalendarEvent]()
cEvents.append(cEvent)
self.eventsTableController.events = cEvents
self.eventsTableController.tableView.reloadData()
}
private func setupConstraints() {
self.calendar.translatesAutoresizingMaskIntoConstraints = false
self.eventsTableController.tableView.translatesAutoresizingMaskIntoConstraints = false
let calendarWidthConstraint = NSLayoutConstraint(item: self.calendar, attribute: .width, relatedBy: .equal, toItem: self.view, attribute: .width, multiplier: 1.0, constant: 0)
let calendarHeightConstraint = NSLayoutConstraint(item: self.calendar, attribute: .height, relatedBy: .equal, toItem: self.view, attribute: .height, multiplier: 0.5, constant: 0)
let calendarXConstraint = NSLayoutConstraint(item: self.calendar, attribute: .centerX, relatedBy: .equal, toItem: self.view, attribute: .centerX, multiplier: 1, constant: 0)
let calendarYConstraint = NSLayoutConstraint(item: self.calendar, attribute: .top, relatedBy: .equal, toItem: self.view, attribute: .top, multiplier: 1, constant: 48)
let eventsTableViewWidthConstraint = NSLayoutConstraint(item: self.eventsTableController.tableView, attribute: .width, relatedBy: .equal, toItem: self.view, attribute: .width, multiplier: 1.0, constant: 0)
let eventsTableViewHeightConstraint = NSLayoutConstraint(item: self.eventsTableController.tableView, attribute: .height, relatedBy: .equal, toItem: self.view, attribute: .height, multiplier: 0.5, constant: 0)
let eventsTableViewXConstraint = NSLayoutConstraint(item: self.eventsTableController.tableView, attribute: .centerX, relatedBy: .equal, toItem: self.view, attribute: .centerX, multiplier: 1, constant: 0)
let eventsTableViewYConstraint = NSLayoutConstraint(item: self.eventsTableController.tableView, attribute: .top, relatedBy: .equal, toItem: self.calendar, attribute: .bottom, multiplier: 1, constant: 0)
NSLayoutConstraint.activate([calendarWidthConstraint, calendarHeightConstraint, calendarXConstraint, calendarYConstraint, eventsTableViewWidthConstraint, eventsTableViewHeightConstraint, eventsTableViewXConstraint, eventsTableViewYConstraint])
}
//MARK: - FSCalendar Delegate
func calendar(_ calendar: FSCalendar, didSelect date: Date) {
self.updateEvents()
}
}
| mit | f854146d38a6400aa4cb349b7bfbf62d | 51.716216 | 251 | 0.72161 | 4.82797 | false | false | false | false |
fgulan/letter-ml | project/LetterML/Frameworks/framework/Source/Timestamp.swift | 9 | 2766 | import Foundation
// This reimplements CMTime such that it can reach across to Linux
public struct TimestampFlags: OptionSet {
public let rawValue:UInt32
public init(rawValue:UInt32) { self.rawValue = rawValue }
public static let valid = TimestampFlags(rawValue: 1 << 0)
public static let hasBeenRounded = TimestampFlags(rawValue: 1 << 1)
public static let positiveInfinity = TimestampFlags(rawValue: 1 << 2)
public static let negativeInfinity = TimestampFlags(rawValue: 1 << 3)
public static let indefinite = TimestampFlags(rawValue: 1 << 4)
}
public struct Timestamp: Comparable {
let value:Int64
let timescale:Int32
let flags:TimestampFlags
let epoch:Int64
public init(value:Int64, timescale:Int32, flags:TimestampFlags, epoch:Int64) {
self.value = value
self.timescale = timescale
self.flags = flags
self.epoch = epoch
}
func seconds() -> Double {
return Double(value) / Double(timescale)
}
}
public func ==(x:Timestamp, y:Timestamp) -> Bool {
// TODO: Fix this
// if (x.flags.contains(TimestampFlags.PositiveInfinity) && y.flags.contains(TimestampFlags.PositiveInfinity)) {
// return true
// } else if (x.flags.contains(TimestampFlags.NegativeInfinity) && y.flags.contains(TimestampFlags.NegativeInfinity)) {
// return true
// } else if (x.flags.contains(TimestampFlags.Indefinite) || y.flags.contains(TimestampFlags.Indefinite) || x.flags.contains(TimestampFlags.NegativeInfinity) || y.flags.contains(TimestampFlags.NegativeInfinity) || x.flags.contains(TimestampFlags.PositiveInfinity) && y.flags.contains(TimestampFlags.PositiveInfinity)) {
// return false
// }
let correctedYValue:Int64
if (x.timescale != y.timescale) {
correctedYValue = Int64(round(Double(y.value) * Double(x.timescale) / Double(y.timescale)))
} else {
correctedYValue = y.value
}
return ((x.value == correctedYValue) && (x.epoch == y.epoch))
}
public func <(x:Timestamp, y:Timestamp) -> Bool {
// TODO: Fix this
// if (x.flags.contains(TimestampFlags.PositiveInfinity) || y.flags.contains(TimestampFlags.NegativeInfinity)) {
// return false
// } else if (x.flags.contains(TimestampFlags.NegativeInfinity) || y.flags.contains(TimestampFlags.PositiveInfinity)) {
// return true
// }
if (x.epoch < y.epoch) {
return true
} else if (x.epoch > y.epoch) {
return false
}
let correctedYValue:Int64
if (x.timescale != y.timescale) {
correctedYValue = Int64(round(Double(y.value) * Double(x.timescale) / Double(y.timescale)))
} else {
correctedYValue = y.value
}
return (x.value < correctedYValue)
}
| mit | 8d371308cfd2175775e4776e1a991e5e | 35.88 | 322 | 0.673897 | 3.923404 | false | false | false | false |
tkremenek/swift | benchmark/utils/main.swift | 1 | 11287 | //===--- main.swift -------------------------------------------*- 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
//
//===----------------------------------------------------------------------===//
// This is just a driver for performance overview tests.
import TestsUtils
import DriverUtils
import Ackermann
import AngryPhonebook
import AnyHashableWithAClass
import Array2D
import ArrayAppend
import ArrayInClass
import ArrayLiteral
import ArrayOfGenericPOD
import ArrayOfGenericRef
import ArrayOfPOD
import ArrayOfRef
import ArraySetElement
import ArraySubscript
import BinaryFloatingPointConversionFromBinaryInteger
import BinaryFloatingPointProperties
import BitCount
import Breadcrumbs
import BucketSort
import ByteSwap
import COWTree
import COWArrayGuaranteedParameterOverhead
import CString
import CSVParsing
import Calculator
import CaptureProp
import ChaCha
import ChainedFilterMap
import CharacterLiteralsLarge
import CharacterLiteralsSmall
import CharacterProperties
import Chars
import ClassArrayGetter
import Codable
import Combos
import CreateObjects
import DataBenchmarks
import DeadArray
import DevirtualizeProtocolComposition
import DictOfArraysToArrayOfDicts
import DictTest
import DictTest2
import DictTest3
import DictTest4
import DictTest4Legacy
import DictionaryBridge
import DictionaryBridgeToObjC
import DictionaryCompactMapValues
import DictionaryCopy
import DictionaryGroup
import DictionaryKeysContains
import DictionaryLiteral
import DictionaryOfAnyHashableStrings
import DictionaryRemove
import DictionarySubscriptDefault
import DictionarySwap
#if canImport(_Differentiation)
import Differentiation
#endif
import Diffing
import DiffingMyers
import DropFirst
import DropLast
import DropWhile
import ErrorHandling
import Exclusivity
import ExistentialPerformance
import Fibonacci
import FindStringNaive
import FlattenList
import FloatingPointConversion
import FloatingPointParsing
import FloatingPointPrinting
import Hanoi
import Hash
import Histogram
import HTTP2StateMachine
import IndexPathTest
import InsertCharacter
import IntegerParsing
import Integrate
import IterateData
import Join
import LazyFilter
import LinkedList
import LuhnAlgoEager
import LuhnAlgoLazy
import MapReduce
import Memset
import Mirror
import MonteCarloE
import MonteCarloPi
import NibbleSort
import NIOChannelPipeline
import NSDictionaryCastToSwift
import NSError
#if canImport(Darwin)
import NSStringConversion
#endif
import NopDeinit
import ObjectAllocation
#if canImport(Darwin)
import ObjectiveCBridging
import ObjectiveCBridgingStubs
#if !(SWIFT_PACKAGE || Xcode)
import ObjectiveCNoBridgingStubs
#endif
#endif
import ObserverClosure
import ObserverForwarderStruct
import ObserverPartiallyAppliedMethod
import ObserverUnappliedMethod
import OpaqueConsumingUsers
import OpenClose
import Phonebook
import PointerArithmetics
import PolymorphicCalls
import PopFront
import PopFrontGeneric
import Prefix
import PrefixWhile
import Prims
import PrimsNonStrongRef
import PrimsSplit
import ProtocolConformance
import ProtocolDispatch
import ProtocolDispatch2
import Queue
import RC4
import RGBHistogram
import Radix2CooleyTukey
import RandomShuffle
import RandomTree
import RandomValues
import RangeAssignment
import RangeIteration
import RangeOverlaps
import RangeReplaceableCollectionPlusDefault
import RecursiveOwnedParameter
import ReduceInto
import RemoveWhere
import ReversedCollections
import RomanNumbers
import SIMDRandomMask
import SIMDReduceInteger
import SequenceAlgos
import SetTests
import SevenBoom
import Sim2DArray
import SortArrayInClass
import SortIntPyramids
import SortLargeExistentials
import SortLettersInPlace
import SortStrings
import StackPromo
import StaticArray
import StrComplexWalk
import StrToInt
import StringBuilder
import StringComparison
import StringEdits
import StringEnum
import StringInterpolation
import StringMatch
import StringRemoveDupes
import StringReplaceSubrange
import StringSplitting
import StringSwitch
import StringTests
import StringWalk
import Substring
import Suffix
import SuperChars
import TwoSum
import TypeFlood
import UTF8Decode
import Walsh
import WordCount
import XorLoop
@inline(__always)
private func registerBenchmark(_ bench: BenchmarkInfo) {
registeredBenchmarks.append(bench)
}
@inline(__always)
private func registerBenchmark<
S : Sequence
>(_ infos: S) where S.Element == BenchmarkInfo {
registeredBenchmarks.append(contentsOf: infos)
}
registerBenchmark(Ackermann)
registerBenchmark(AngryPhonebook)
registerBenchmark(AnyHashableWithAClass)
registerBenchmark(Array2D)
registerBenchmark(ArrayAppend)
registerBenchmark(ArrayInClass)
registerBenchmark(ArrayLiteral)
registerBenchmark(ArrayOfGenericPOD)
registerBenchmark(ArrayOfGenericRef)
registerBenchmark(ArrayOfPOD)
registerBenchmark(ArrayOfRef)
registerBenchmark(ArraySetElement)
registerBenchmark(ArraySubscript)
registerBenchmark(BinaryFloatingPointConversionFromBinaryInteger)
registerBenchmark(BinaryFloatingPointPropertiesBinade)
registerBenchmark(BinaryFloatingPointPropertiesNextUp)
registerBenchmark(BinaryFloatingPointPropertiesUlp)
registerBenchmark(BitCount)
registerBenchmark(Breadcrumbs)
registerBenchmark(BucketSort)
registerBenchmark(ByteSwap)
registerBenchmark(COWTree)
registerBenchmark(COWArrayGuaranteedParameterOverhead)
registerBenchmark(CString)
registerBenchmark(CSVParsing)
registerBenchmark(Calculator)
registerBenchmark(CaptureProp)
registerBenchmark(ChaCha)
registerBenchmark(ChainedFilterMap)
registerBenchmark(CharacterLiteralsLarge)
registerBenchmark(CharacterLiteralsSmall)
registerBenchmark(CharacterPropertiesFetch)
registerBenchmark(CharacterPropertiesStashed)
registerBenchmark(CharacterPropertiesStashedMemo)
registerBenchmark(CharacterPropertiesPrecomputed)
registerBenchmark(Chars)
registerBenchmark(Codable)
registerBenchmark(Combos)
registerBenchmark(ClassArrayGetter)
registerBenchmark(CreateObjects)
registerBenchmark(DataBenchmarks)
registerBenchmark(DeadArray)
registerBenchmark(DevirtualizeProtocolComposition)
registerBenchmark(DictOfArraysToArrayOfDicts)
registerBenchmark(Dictionary)
registerBenchmark(Dictionary2)
registerBenchmark(Dictionary3)
registerBenchmark(Dictionary4)
registerBenchmark(Dictionary4Legacy)
registerBenchmark(DictionaryBridge)
registerBenchmark(DictionaryBridgeToObjC)
registerBenchmark(DictionaryCompactMapValues)
registerBenchmark(DictionaryCopy)
registerBenchmark(DictionaryGroup)
registerBenchmark(DictionaryKeysContains)
registerBenchmark(DictionaryLiteral)
registerBenchmark(DictionaryOfAnyHashableStrings)
registerBenchmark(DictionaryRemove)
registerBenchmark(DictionarySubscriptDefault)
registerBenchmark(DictionarySwap)
#if canImport(_Differentiation)
registerBenchmark(Differentiation)
#endif
registerBenchmark(Diffing)
registerBenchmark(DiffingMyers)
registerBenchmark(DropFirst)
registerBenchmark(DropLast)
registerBenchmark(DropWhile)
registerBenchmark(ErrorHandling)
registerBenchmark(Exclusivity)
registerBenchmark(ExistentialPerformance)
registerBenchmark(Fibonacci)
registerBenchmark(FindStringNaive)
registerBenchmark(FlattenListLoop)
registerBenchmark(FlattenListFlatMap)
registerBenchmark(FloatingPointConversion)
registerBenchmark(FloatingPointParsing)
registerBenchmark(FloatingPointPrinting)
registerBenchmark(Hanoi)
registerBenchmark(HashTest)
registerBenchmark(Histogram)
registerBenchmark(HTTP2StateMachine)
registerBenchmark(IndexPathTest)
registerBenchmark(InsertCharacter)
registerBenchmark(IntegerParsing)
registerBenchmark(IntegrateTest)
registerBenchmark(IterateData)
registerBenchmark(Join)
registerBenchmark(LazyFilter)
registerBenchmark(LinkedList)
registerBenchmark(LuhnAlgoEager)
registerBenchmark(LuhnAlgoLazy)
registerBenchmark(MapReduce)
registerBenchmark(Memset)
registerBenchmark(MirrorDefault)
registerBenchmark(MonteCarloE)
registerBenchmark(MonteCarloPi)
registerBenchmark(NSDictionaryCastToSwift)
registerBenchmark(NSErrorTest)
#if canImport(Darwin)
registerBenchmark(NSStringConversion)
#endif
registerBenchmark(NibbleSort)
registerBenchmark(NIOChannelPipeline)
registerBenchmark(NopDeinit)
registerBenchmark(ObjectAllocation)
#if canImport(Darwin)
registerBenchmark(ObjectiveCBridging)
registerBenchmark(ObjectiveCBridgingStubs)
#if !(SWIFT_PACKAGE || Xcode)
registerBenchmark(ObjectiveCNoBridgingStubs)
#endif
#endif
registerBenchmark(ObserverClosure)
registerBenchmark(ObserverForwarderStruct)
registerBenchmark(ObserverPartiallyAppliedMethod)
registerBenchmark(ObserverUnappliedMethod)
registerBenchmark(OpaqueConsumingUsers)
registerBenchmark(OpenClose)
registerBenchmark(Phonebook)
registerBenchmark(PointerArithmetics)
registerBenchmark(PolymorphicCalls)
registerBenchmark(PopFront)
registerBenchmark(PopFrontArrayGeneric)
registerBenchmark(Prefix)
registerBenchmark(PrefixWhile)
registerBenchmark(Prims)
registerBenchmark(PrimsNonStrongRef)
registerBenchmark(PrimsSplit)
registerBenchmark(ProtocolConformance)
registerBenchmark(ProtocolDispatch)
registerBenchmark(ProtocolDispatch2)
registerBenchmark(QueueGeneric)
registerBenchmark(QueueConcrete)
registerBenchmark(RC4Test)
registerBenchmark(RGBHistogram)
registerBenchmark(Radix2CooleyTukey)
registerBenchmark(RandomShuffle)
registerBenchmark(RandomTree)
registerBenchmark(RandomValues)
registerBenchmark(RangeAssignment)
registerBenchmark(RangeIteration)
registerBenchmark(RangeOverlaps)
registerBenchmark(RangeReplaceableCollectionPlusDefault)
registerBenchmark(RecursiveOwnedParameter)
registerBenchmark(ReduceInto)
registerBenchmark(RemoveWhere)
registerBenchmark(ReversedCollections)
registerBenchmark(RomanNumbers)
registerBenchmark(SIMDRandomMask)
registerBenchmark(SIMDReduceInteger)
registerBenchmark(SequenceAlgos)
registerBenchmark(SetTests)
registerBenchmark(SevenBoom)
registerBenchmark(Sim2DArray)
registerBenchmark(SortArrayInClass)
registerBenchmark(SortIntPyramids)
registerBenchmark(SortLargeExistentials)
registerBenchmark(SortLettersInPlace)
registerBenchmark(SortStrings)
registerBenchmark(StackPromo)
registerBenchmark(StaticArrayTest)
registerBenchmark(StrComplexWalk)
registerBenchmark(StrToInt)
registerBenchmark(StringBuilder)
registerBenchmark(StringComparison)
registerBenchmark(StringEdits)
registerBenchmark(StringEnum)
registerBenchmark(StringHashing)
registerBenchmark(StringInterpolation)
registerBenchmark(StringInterpolationSmall)
registerBenchmark(StringInterpolationManySmallSegments)
registerBenchmark(StringMatch)
registerBenchmark(StringNormalization)
registerBenchmark(StringRemoveDupes)
registerBenchmark(StringReplaceSubrange)
if #available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *) {
registerBenchmark(StringSplitting)
}
registerBenchmark(StringSwitch)
registerBenchmark(StringTests)
registerBenchmark(StringWalk)
registerBenchmark(SubstringTest)
registerBenchmark(Suffix)
registerBenchmark(SuperChars)
registerBenchmark(TwoSum)
registerBenchmark(TypeFlood)
registerBenchmark(TypeName)
registerBenchmark(UTF8Decode)
registerBenchmark(Walsh)
registerBenchmark(WordCount)
registerBenchmark(XorLoop)
main()
| apache-2.0 | cf763cabcfd9721cb6bbcaead6030ea6 | 27.007444 | 80 | 0.883406 | 5.476468 | false | false | false | false |
Basadev/MakeSchoolNotes | MakeSchoolNotes/ViewControllers/NewNoteVC.swift | 1 | 1146 | //
// NewNoteVC.swift
// MakeSchoolNotes
//
// Created by Professional on 2015-06-22.
// Copyright (c) 2015 MakeSchool. All rights reserved.
//
import UIKit
class NewNoteVC: UIViewController {
var currentNote:Note?
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.
}
// MARK: - 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.
if (segue.identifier == "ShowNewNote") {
// create a new Note and hold onto it, to be able to save it later
currentNote = Note()
let noteViewController = segue.destinationViewController as! NoteDisplayVC
noteViewController.note = currentNote
noteViewController.edit = true
}
}
}
| mit | e03c43f80ef537784c5e741b9068cfec | 25.651163 | 86 | 0.641361 | 4.939655 | false | false | false | false |
honghaoz/2048-Solver-AI | 2048 AI/AI/TDLearning/RectSize.swift | 1 | 671 | // Copyright © 2019 ChouTi. All rights reserved.
import Foundation
struct RectSize: Equatable {
let columns: Int
let rows: Int
var width: Int {
return columns
}
var height: Int {
return rows
}
init(rows: Int, cols: Int) {
self.rows = rows
self.columns = cols
}
init(size: Int) {
self.init(rows: size, cols: size)
}
func contains(position: BoardPos) -> Bool {
return position.row() >= 0 && position.row() < height && position.column() >= 0 && position.column() < width
}
}
func == (lhs: RectSize, rhs: RectSize) -> Bool {
if lhs.columns == rhs.columns, lhs.rows == rhs.rows {
return true
}
return false
}
| gpl-2.0 | 70a45f39a0b7eb3294b842ba622e4ec2 | 17.611111 | 112 | 0.614925 | 3.401015 | false | false | false | false |
HongliYu/firefox-ios | Shared/TimeConstants.swift | 1 | 6633 | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
import Foundation
public typealias Timestamp = UInt64
public typealias MicrosecondTimestamp = UInt64
public let ThreeWeeksInSeconds = 3 * 7 * 24 * 60 * 60
public let OneYearInMilliseconds = 12 * OneMonthInMilliseconds
public let OneMonthInMilliseconds = 30 * OneDayInMilliseconds
public let OneWeekInMilliseconds = 7 * OneDayInMilliseconds
public let OneDayInMilliseconds = 24 * OneHourInMilliseconds
public let OneHourInMilliseconds = 60 * OneMinuteInMilliseconds
public let OneMinuteInMilliseconds = 60 * OneSecondInMilliseconds
public let OneSecondInMilliseconds: UInt64 = 1000
fileprivate let rfc822DateFormatter: DateFormatter = {
let dateFormatter = DateFormatter()
dateFormatter.timeZone = TimeZone(abbreviation: "GMT")
dateFormatter.dateFormat = "EEE',' dd MMM yyyy HH':'mm':'ss 'GMT'"
dateFormatter.locale = Locale(identifier: "en_US")
return dateFormatter
}()
extension TimeInterval {
public static func fromMicrosecondTimestamp(_ microsecondTimestamp: MicrosecondTimestamp) -> TimeInterval {
return Double(microsecondTimestamp) / 1000000
}
}
extension Timestamp {
public static func uptimeInMilliseconds() -> Timestamp {
return Timestamp(DispatchTime.now().uptimeNanoseconds) / 1000000
}
}
extension Date {
public static func now() -> Timestamp {
return UInt64(1000 * Date().timeIntervalSince1970)
}
public func toMicrosecondTimestamp() -> MicrosecondTimestamp {
return UInt64(1_000_000 * timeIntervalSince1970)
}
public static func nowNumber() -> NSNumber {
return NSNumber(value: now() as UInt64)
}
public static func nowMicroseconds() -> MicrosecondTimestamp {
return UInt64(1000000 * Date().timeIntervalSince1970)
}
public static func fromTimestamp(_ timestamp: Timestamp) -> Date {
return Date(timeIntervalSince1970: Double(timestamp) / 1000)
}
public static func fromMicrosecondTimestamp(_ microsecondTimestamp: MicrosecondTimestamp) -> Date {
return Date(timeIntervalSince1970: Double(microsecondTimestamp) / 1000000)
}
public func toRelativeTimeString(dateStyle: DateFormatter.Style = .short, timeStyle: DateFormatter.Style = .short) -> String {
let now = Date()
let units: Set<Calendar.Component> = [.second, .minute, .day, .weekOfYear, .month, .year, .hour]
let components = Calendar.current.dateComponents(units, from: self, to: now)
if components.year ?? 0 > 0 {
return String(format: DateFormatter.localizedString(from: self, dateStyle: dateStyle, timeStyle: timeStyle))
}
if components.month == 1 {
return String(format: NSLocalizedString("more than a month ago", comment: "Relative date for dates older than a month and less than two months."))
}
if components.month ?? 0 > 1 {
return String(format: DateFormatter.localizedString(from: self, dateStyle: dateStyle, timeStyle: timeStyle))
}
if components.weekOfYear ?? 0 > 0 {
return String(format: NSLocalizedString("more than a week ago", comment: "Description for a date more than a week ago, but less than a month ago."))
}
if components.day == 1 {
return String(format: NSLocalizedString("yesterday", comment: "Relative date for yesterday."))
}
if components.day ?? 0 > 1 {
return String(format: NSLocalizedString("this week", comment: "Relative date for date in past week."), String(describing: components.day))
}
if components.hour ?? 0 > 0 || components.minute ?? 0 > 0 {
// Can't have no time specified for this formatting case.
let timeStyle = timeStyle != .none ? timeStyle : .short
let absoluteTime = DateFormatter.localizedString(from: self, dateStyle: .none, timeStyle: timeStyle)
let format = NSLocalizedString("today at %@", comment: "Relative date for date older than a minute.")
return String(format: format, absoluteTime)
}
return String(format: NSLocalizedString("just now", comment: "Relative time for a tab that was visited within the last few moments."))
}
public func toRFC822String() -> String {
return rfc822DateFormatter.string(from: self)
}
}
let MaxTimestampAsDouble: Double = Double(UInt64.max)
/** This is just like decimalSecondsStringToTimestamp, but it looks for values that seem to be
* milliseconds and fixes them. That's necessary because Firefox for iOS <= 7.3 uploaded millis
* when seconds were expected.
*/
public func someKindOfTimestampStringToTimestamp(_ input: String) -> Timestamp? {
var double = 0.0
if Scanner(string: input).scanDouble(&double) {
// This should never happen. Hah!
if double.isNaN || double.isInfinite {
return nil
}
// `double` will be either huge or negatively huge on overflow, and 0 on underflow.
// We clamp to reasonable ranges.
if double < 0 {
return nil
}
if double >= MaxTimestampAsDouble {
// Definitely not representable as a timestamp if the seconds are this large!
return nil
}
if double > 1000000000000 {
// Oh, this was in milliseconds.
return Timestamp(double)
}
let millis = double * 1000
if millis >= MaxTimestampAsDouble {
// Not representable as a timestamp.
return nil
}
return Timestamp(millis)
}
return nil
}
public func decimalSecondsStringToTimestamp(_ input: String) -> Timestamp? {
var double = 0.0
if Scanner(string: input).scanDouble(&double) {
// This should never happen. Hah!
if double.isNaN || double.isInfinite {
return nil
}
// `double` will be either huge or negatively huge on overflow, and 0 on underflow.
// We clamp to reasonable ranges.
if double < 0 {
return nil
}
let millis = double * 1000
if millis >= MaxTimestampAsDouble {
// Not representable as a timestamp.
return nil
}
return Timestamp(millis)
}
return nil
}
public func millisecondsToDecimalSeconds(_ input: Timestamp) -> String {
let val: Double = Double(input) / 1000
return String(format: "%.2F", val)
}
| mpl-2.0 | efda61b09f7b522bd9a5b3c552cd8629 | 35.85 | 160 | 0.663501 | 4.827511 | false | false | false | false |
Mazy-ma/XMCustomUIViewControllerTransitions_Swift | XMCustomUIViewControllerTransitions/XMCustomUIViewControllerTransitions/Classes/AnimateTranstion/SwipeInteractionController.swift | 1 | 1987 | //
// SwipeInteractionController.swift
// XMCustomUIViewControllerTransitions
//
// Created by TwtMac on 17/1/22.
// Copyright © 2017年 Mazy. All rights reserved.
//
import UIKit
class SwipeInteractionController: UIPercentDrivenInteractiveTransition {
var interactionInProgress: Bool = false
var shouldCompleteTransition: Bool = false
var viewController: UIViewController?
func wireToViewController(vc: UIViewController) {
viewController = vc
prepareGestureRecognizerInView(view: vc.view)
}
private func prepareGestureRecognizerInView(view: UIView) {
// 添加边缘手势
let edgePanGesture = UIScreenEdgePanGestureRecognizer.init(target: self, action: #selector(handleGesture))
// 设置手势位置为左边
edgePanGesture.edges = .left
view.addGestureRecognizer(edgePanGesture)
}
/**
处理左划手势
@param gestureRecognizer 手势
*/
@objc func handleGesture(gesture: UIScreenEdgePanGestureRecognizer) {
let translation = gesture.translation(in: gesture.view?.superview)
var progress = translation.x/200
progress = CGFloat(fminf(fmaxf(Float(progress), 0), 1.0))
switch gesture.state {
case .began:
interactionInProgress = true
viewController?.dismiss(animated: true, completion: nil)
case .changed:
shouldCompleteTransition = progress > 0.5
update(progress)
case .cancelled:
interactionInProgress = false
cancel()
case .ended:
interactionInProgress = false
if !self.shouldCompleteTransition {
cancel()
} else {
finish()
}
default:
break
}
}
}
| apache-2.0 | 0feeeaee11bc5a9c16ea2581be19f82f | 27.925373 | 114 | 0.579979 | 5.785075 | false | false | false | false |
guyht/vimari | Vimari/ViewController.swift | 1 | 3325 | import Cocoa
import SafariServices.SFSafariApplication
import OSLog
class ViewController: NSViewController {
@IBOutlet var extensionStatus: NSTextField!
@IBOutlet var spinner: NSProgressIndicator!
private enum Constant {
static let extensionIdentifier = "net.televator.Vimari.SafariExtension"
static let openSettings = "openSettings"
static let resetSettings = "resetSettings"
}
func refreshExtensionStatus() {
NSLog("Refreshing extension status")
spinner.startAnimation(self)
extensionStatus.stringValue = "Checking extension status"
if SFSafariServicesAvailable() {
SFSafariExtensionManager.getStateOfSafariExtension(
withIdentifier: Constant.extensionIdentifier) {
state, error in
print("State", state as Any, "Error", error as Any, state?.isEnabled as Any)
DispatchQueue.main.async {
// TODO: handle this getting updated in the Safari preferences too.
if let state = state {
if state.isEnabled {
self.extensionStatus.stringValue = "Enabled"
} else {
self.extensionStatus.stringValue = "Disabled"
}
}
if let error = error {
NSLog("Error", error.localizedDescription)
self.extensionStatus.stringValue = error.localizedDescription
}
self.spinner.stopAnimation(self)
}
}
} else {
NSLog("SFSafariServices not available")
extensionStatus.stringValue = "Unavailable, Vimari requires Safari 10 or greater."
spinner.stopAnimation(self)
}
}
@IBAction func refreshButton(_: NSButton) {
refreshExtensionStatus()
}
override func viewDidLoad() {
super.viewDidLoad()
refreshExtensionStatus()
}
@IBAction func openSafariExtensionPreferences(_: AnyObject?) {
SFSafariApplication.showPreferencesForExtension(
withIdentifier: Constant.extensionIdentifier) { error in
if let _ = error {
// Insert code to inform the user that something went wrong.
}
}
}
@IBAction func openSettingsAction(_ sender: Any) {
dispatchOpenSettings()
}
@IBAction func resetSettingsAction(_ sender: Any) {
dispatchResetSettings()
}
func dispatchOpenSettings() {
SFSafariApplication.dispatchMessage(
withName: Constant.openSettings,
toExtensionWithIdentifier: Constant.extensionIdentifier,
userInfo: nil) { (error) in
if let error = error {
print(error.localizedDescription)
}
}
}
func dispatchResetSettings() {
SFSafariApplication.dispatchMessage(
withName: Constant.resetSettings,
toExtensionWithIdentifier: Constant.extensionIdentifier,
userInfo: nil) { (error) in
if let error = error {
print(error.localizedDescription)
}
}
}
}
| mit | 6c241aa135449a329428f168b20c3b58 | 33.278351 | 94 | 0.577444 | 5.853873 | false | false | false | false |
openHPI/xikolo-ios | Common/Data/Model/CourseSection.swift | 1 | 1747 | //
// Created for xikolo-ios under GPL-3.0 license.
// Copyright © HPI. All rights reserved.
//
import CoreData
import Foundation
import Stockpile
public final class CourseSection: NSManagedObject {
@NSManaged public var id: String
@NSManaged public var abstract: String?
@NSManaged public var title: String?
@NSManaged public var position: Int32
@NSManaged public var accessible: Bool
@NSManaged public var startsAt: Date?
@NSManaged public var endsAt: Date?
@NSManaged public var course: Course?
@NSManaged public var items: Set<CourseItem>
@nonobjc public class func fetchRequest() -> NSFetchRequest<CourseSection> {
return NSFetchRequest<CourseSection>(entityName: "CourseSection")
}
var itemsSorted: [CourseItem] {
return self.items.sorted {
return $0.position < $1.position
}
}
}
extension CourseSection: JSONAPIPullable {
public static var type: String {
return "course-sections"
}
public func update(from object: ResourceData, with context: SynchronizationContext) throws {
let attributes = try object.value(for: "attributes") as JSON
self.title = try attributes.value(for: "title")
self.position = try attributes.value(for: "position")
self.abstract = try attributes.value(for: "description")
self.accessible = try attributes.value(for: "accessible")
self.startsAt = try attributes.value(for: "start_at")
self.endsAt = try attributes.value(for: "end_at")
let relationships = try object.value(for: "relationships") as JSON
try self.updateRelationship(forKeyPath: \Self.course, forKey: "course", fromObject: relationships, with: context)
}
}
| gpl-3.0 | 2dc4265e7ec6dd8132005529b7d14c25 | 31.943396 | 121 | 0.689003 | 4.311111 | false | false | false | false |
lorentey/swift | validation-test/compiler_crashers_2_fixed/0004-rdar20564605.swift | 66 | 4452 | // RUN: not %target-swift-frontend %s -typecheck
public protocol Q_SequenceDefaults {
typealias Element
typealias Iterator : IteratorProtocol
func makeIterator() -> Iterator
}
extension Q_SequenceDefaults {
public final var underestimatedCount: Int { return 0 }
public final func preprocessingPass<R>(body: (Self)->R) -> R? {
return nil
}
/// Create a ContiguousArray containing the elements of `self`,
/// in the same order.
public final func copyToContiguousArray() -> ContiguousArray<Iterator.Element> {
let initialCapacity = underestimatedCount
var result = _ContiguousArrayBuffer<Iterator.Element>(
count: initialCapacity, minimumCapacity: 0)
var iter = self.makeIterator()
while let x = iter.next() {
result += CollectionOfOne(x)
}
return ContiguousArray(result)
}
/// Initialize the storage at baseAddress with the contents of this
/// sequence.
public final func initializeRawMemory(
baseAddress: UnsafeMutablePointer<Iterator.Element>
) {
var p = baseAddress
var iter = self.makeIterator()
while let element = iter.next() {
p.initialize(to: element)
p += 1
}
}
public final static func _constrainElement(Iterator.Element) {}
}
/// A type that can be iterated with a `for`\ ...\ `in` loop.
///
/// `Sequence` makes no requirement on conforming types regarding
/// whether they will be destructively "consumed" by iteration. To
/// ensure non-destructive iteration, constrain your *sequence* to
/// `Collection`.
public protocol Q_Sequence : Q_SequenceDefaults {
/// A type that provides the *sequence*\ 's iteration interface and
/// encapsulates its iteration state.
typealias Iterator : IteratorProtocol
func makeIterator() -> Iterator
/// Return a value less than or equal to the number of elements in
/// self, **nondestructively**.
///
/// Complexity: O(N)
var underestimatedCount: Int
/// If `self` is multi-pass (i.e., a `Collection`), invoke the function
/// on `self` and return its result. Otherwise, return `nil`.
func preprocessingPass<R>(body: (Self)->R) -> R?
/// Create a ContiguousArray containing the elements of `self`,
/// in the same order.
func copyToContiguousArray() -> ContiguousArray<Element>
/// Initialize the storage at baseAddress with the contents of this
/// sequence.
func initializeRawMemory(
baseAddress: UnsafeMutablePointer<Element>
)
static func _constrainElement(Element)
}
public extension IteratorProtocol {
typealias Iterator = Self
public final func makeIterator() -> Iterator {
return self
}
}
public protocol Q_CollectionDefaults : Q_Sequence {
typealias Index : ForwardIndex
var startIndex: Index {get}
var endIndex: Index {get}
}
public protocol Q_Indexable {
typealias Index : ForwardIndex
typealias Element
var startIndex: Index {get}
var endIndex: Index {get}
subscript(i: Index) -> Element {get}
}
extension Q_Indexable {
typealias Iterator = Q_IndexingIterator<Self>
public final func makeIterator() -> Q_IndexingIterator<Self> {
return Q_IndexingIterator(pos: self.startIndex, elements: self)
}
}
extension Q_CollectionDefaults {
public final func count() -> Index.Distance {
return distance(startIndex, endIndex)
}
public final var underestimatedCount: Int {
let n = count().toIntMax()
return n > IntMax(Int.max) ? Int.max : Int(n)
}
public final func preprocessingPass<R>(body: (Self)->R) -> R? {
return body(self)
}
}
public struct Q_IndexingIterator<C: Q_Indexable> : IteratorProtocol {
public typealias Element = C.Element
var pos: C.Index
let elements: C
public mutating func next() -> Element? {
if pos == elements.endIndex {
return nil
}
let ret = elements[pos]
pos += 1
return ret
}
}
public protocol Q_Collection : Q_Indexable, Q_CollectionDefaults {
func count() -> Index.Distance
subscript(position: Index) -> Element {get}
}
extension Array : Q_Collection {
public func copyToContiguousArray() -> ContiguousArray<Element> {
return ContiguousArray(self~>_copyToNativeArrayBuffer())
}
}
struct Boo : Q_Collection {
let startIndex: Int = 0
let endIndex: Int = 10
func makeIterator() -> Q_IndexingIterator<Boo> {
return Q_IndexingIterator(pos: self.startIndex, elements: self)
}
typealias Element = String
subscript(i: Int) -> String {
return "Boo"
}
}
| apache-2.0 | 2ebee69e81ea9f2eee2395d79c9f8052 | 25.658683 | 82 | 0.694744 | 4.289017 | false | false | false | false |
geekaurora/ReactiveListViewKit | ReactiveListViewKit/ReactiveListViewKit/TemplateViews/CZFeedListSupplementaryLineView.swift | 1 | 3499 | //
// CZFeedListSupplementaryLineView.swift
// ReactiveListViewKit
//
// Created by Cheng Zhang on 2/7/17.
// Copyright © 2017 Cheng Zhang. All rights reserved.
//
import UIKit
/**
Line SupplementaryView for SectionHeaderView/SectionFooterView
*/
open class CZFeedListSupplementaryLineFeedModel: CZFeedModel {
public init(inset: UIEdgeInsets = ReactiveListViewKit.feedListSupplementaryLineFooterViewInset) {
super.init(viewClass: CZFeedListSupplementaryLineView.self,
viewModel: CZFeedListSupplementaryLineViewModel(inset: inset))
}
public required init(viewClass: CZFeedCellViewSizeCalculatable.Type, viewModel: CZFeedViewModelable) {
super.init(viewClass: viewClass, viewModel: viewModel)
}
}
open class CZFeedListSupplementaryLineViewModel: NSObject, CZFeedViewModelable {
public let isHorizontal: Bool
public lazy var diffId: String = self.currentClassName
public let inset: UIEdgeInsets
public required init(inset: UIEdgeInsets, isHorizontal: Bool = false) {
self.inset = inset
self.isHorizontal = isHorizontal
super.init()
diffId = currentClassName
}
public func isEqual(toDiffableObj object: AnyObject) -> Bool {
guard let object = object as? CZFeedListSupplementaryLineViewModel else {return false}
return diffId == object.diffId
}
public func copy(with zone: NSZone? = nil) -> Any {
let copy = type(of: self).init(inset: inset,
isHorizontal: isHorizontal)
return copy
}
}
open class CZFeedListSupplementaryLineView: UIView, CZFeedCellViewSizeCalculatable {
public var onAction: OnAction?
public var lineView: UIView!
private lazy var hasSetup: Bool = false
public var viewModel: CZFeedViewModelable?
public var diffId: String {
return viewModel?.diffId ?? ""
}
public required init(viewModel: CZFeedViewModelable?, onAction: OnAction?) {
self.viewModel = viewModel
self.onAction = onAction
super.init(frame: .zero)
setup()
config(with: viewModel)
}
public required init?(coder: NSCoder) {
super.init(coder: coder)
setup()
}
public func setup() {
guard let viewModel = viewModel as? CZFeedListSupplementaryLineViewModel, !hasSetup else {return}
hasSetup = true
translatesAutoresizingMaskIntoConstraints = false
lineView = CZDividerView()
addSubview(lineView)
NSLayoutConstraint.activate([
lineView.leadingAnchor.constraint(equalTo: leadingAnchor, constant: viewModel.inset.left),
lineView.trailingAnchor.constraint(equalTo: trailingAnchor, constant: -viewModel.inset.right),
lineView.topAnchor.constraint(equalTo: topAnchor, constant: viewModel.inset.top),
lineView.bottomAnchor.constraint(equalTo: bottomAnchor, constant: -viewModel.inset.bottom)
])
}
public func config(with viewModel: CZFeedViewModelable?) {
setup()
}
public static func sizeThatFits(_ containerSize: CGSize, viewModel: CZFeedViewModelable) -> CGSize {
return CZFacadeViewHelper.sizeThatFits(containerSize,
viewModel: viewModel,
viewClass: CZFeedListSupplementaryLineView.self,
isHorizontal: false)
}
}
| mit | 7088686583fd694cdef47f306f82c6b2 | 35.061856 | 106 | 0.666953 | 4.990014 | false | false | false | false |
Codility-BMSTU/Codility | Codility/Codility/OBCard.swift | 1 | 501 | //
// Card.swift
// Codility
//
// Created by Кирилл Володин on 15.09.17.
// Copyright © 2017 Кирилл Володин. All rights reserved.
//
import Foundation
class OBCard {
var name: String = "" //Название карты
var type: String = "" //Тип карты = ['debit', 'credit'],
var paymentSystem: String = "" //Тип платежной системы = ['visa', 'mastercard', 'mir'],
var description: String = "" //Описание карты
}
| apache-2.0 | 43176e0686b52c45b72c660eba0789ea | 25.3125 | 91 | 0.631829 | 2.883562 | false | false | false | false |
wireapp/wire-ios-sync-engine | Source/Synchronization/ZMOperatonLoop+Background.swift | 1 | 3668 | //
// Wire
// Copyright (C) 2018 Wire Swiss GmbH
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see http://www.gnu.org/licenses/.
//
import Foundation
private enum PushChannelKeys: String {
case data = "data"
case identifier = "id"
case notificationType = "type"
}
private enum PushNotificationType: String {
case plain
case cipher
case notice
}
@objc
public extension ZMOperationLoop {
@objc(fetchEventsFromPushChannelPayload:completionHandler:)
func fetchEvents(fromPushChannelPayload payload: [AnyHashable: Any], completionHandler: @escaping () -> Void) {
guard let nonce = messageNonce(fromPushChannelData: payload) else {
return completionHandler()
}
pushNotificationStatus.fetch(eventId: nonce, completionHandler: {
self.callEventStatus.waitForCallEventProcessingToComplete { [weak self] in
guard let strongSelf = self else { return }
strongSelf.syncMOC.performGroupedBlock {
completionHandler()
}
}
})
}
func messageNonce(fromPushChannelData payload: [AnyHashable: Any]) -> UUID? {
guard let notificationData = payload[PushChannelKeys.data.rawValue] as? [AnyHashable: Any],
let rawNotificationType = notificationData[PushChannelKeys.notificationType.rawValue] as? String,
let notificationType = PushNotificationType(rawValue: rawNotificationType) else {
return nil
}
switch notificationType {
case .plain, .notice:
if let data = notificationData[PushChannelKeys.data.rawValue] as? [AnyHashable: Any], let rawUUID = data[PushChannelKeys.identifier.rawValue] as? String {
return UUID(uuidString: rawUUID)
}
case .cipher:
return messageNonce(fromEncryptedPushChannelData: notificationData)
}
return nil
}
func messageNonce(fromEncryptedPushChannelData encryptedPayload: [AnyHashable: Any]) -> UUID? {
// @"aps" : @{ @"alert": @{@"loc-args": @[],
// @"loc-key" : @"push.notification.new_message"}
// },
// @"data": @{ @"data" : @"SomeEncryptedBase64EncodedString",
// @"mac" : @"someMacHashToVerifyTheIntegrityOfTheEncodedPayload",
// @"type" : @"cipher"
//
guard let apsSignalKeyStore = apsSignalKeyStore else {
Logging.network.debug("Could not initiate APSSignalingKeystore")
return nil
}
guard let decryptedPayload = apsSignalKeyStore.decryptDataDictionary(encryptedPayload) else {
Logging.network.debug("Failed to decrypt data dictionary from push payload: \(encryptedPayload)")
return nil
}
if let data = decryptedPayload[PushChannelKeys.data.rawValue] as? [AnyHashable: Any], let rawUUID = data[PushChannelKeys.identifier.rawValue] as? String {
return UUID(uuidString: rawUUID)
}
return nil
}
}
| gpl-3.0 | 41b02a3dceafcc33caf144e4ec49a982 | 36.814433 | 166 | 0.647492 | 4.788512 | false | false | false | false |
elpassion/el-space-ios | ELSpace/Models/DTO/ReportDTO.swift | 1 | 790 | import Mapper
struct ReportDTO {
let id: Int
let userId: Int
let projectId: Int?
let value: String
let performedAt: String
let comment: String?
let createdAt: String
let updatedAt: String
let billable: Bool
let reportType: Int
}
extension ReportDTO: Mappable {
init(map: Mapper) throws {
id = try map.from("id")
userId = try map.from("user_id")
projectId = map.optionalFrom("project_id")
value = try map.from("value")
performedAt = try map.from("performed_at")
comment = map.optionalFrom("comment")
createdAt = try map.from("created_at")
updatedAt = try map.from("updated_at")
billable = try map.from("billable")
reportType = try map.from("report_type")
}
}
| gpl-3.0 | 382686e6ee6b6e23a8ee9ee25062685e | 24.483871 | 50 | 0.61519 | 3.910891 | false | false | false | false |
xwu/swift | test/SILGen/lazy_globals.swift | 8 | 4233 | // RUN: %target-swift-emit-silgen -parse-as-library %s | %FileCheck %s
// CHECK: sil private [global_init_once_fn] [ossa] @[[T:.*]]WZ : $@convention(c) () -> () {
// CHECK: alloc_global @$s12lazy_globals1xSiv
// CHECK: [[XADDR:%.*]] = global_addr @$s12lazy_globals1xSivp : $*Int
// CHECK: store {{%.*}} to [trivial] [[XADDR]] : $*Int
// CHECK: sil hidden [global_init] [ossa] @$s12lazy_globals1xSivau : $@convention(thin) () -> Builtin.RawPointer {
// CHECK: [[TOKEN_ADDR:%.*]] = global_addr @[[T]]Wz : $*Builtin.Word
// CHECK: [[TOKEN_PTR:%.*]] = address_to_pointer [[TOKEN_ADDR]] : $*Builtin.Word to $Builtin.RawPointer
// CHECK: [[INIT_FUNC:%.*]] = function_ref @[[T]]WZ : $@convention(c) () -> ()
// CHECK: builtin "once"([[TOKEN_PTR]] : $Builtin.RawPointer, [[INIT_FUNC]] : $@convention(c) () -> ()) : $()
// CHECK: [[GLOBAL_ADDR:%.*]] = global_addr @$s12lazy_globals1xSivp : $*Int
// CHECK: [[GLOBAL_PTR:%.*]] = address_to_pointer [[GLOBAL_ADDR]] : $*Int to $Builtin.RawPointer
// CHECK: return [[GLOBAL_PTR]] : $Builtin.RawPointer
// CHECK: }
var x: Int = 0
// CHECK: sil private [global_init_once_fn] [ossa] @[[T:.*]]WZ : $@convention(c) () -> () {
// CHECK: alloc_global @$s12lazy_globals3FooV3fooSivpZ
// CHECK: [[XADDR:%.*]] = global_addr @$s12lazy_globals3FooV3fooSivpZ : $*Int
// CHECK: store {{.*}} to [trivial] [[XADDR]] : $*Int
// CHECK: return
struct Foo {
// CHECK: sil hidden [global_init] [ossa] @$s12lazy_globals3FooV3fooSivau : $@convention(thin) () -> Builtin.RawPointer {
// CHECK: [[TOKEN_ADDR:%.*]] = global_addr @[[T]]Wz : $*Builtin.Word
// CHECK: [[TOKEN_PTR:%.*]] = address_to_pointer [[TOKEN_ADDR]] : $*Builtin.Word to $Builtin.RawPointer
// CHECK: [[INIT_FUNC:%.*]] = function_ref @[[T]]WZ : $@convention(c) () -> ()
// CHECK: builtin "once"([[TOKEN_PTR]] : $Builtin.RawPointer, [[INIT_FUNC]] : $@convention(c) () -> ()) : $()
// CHECK: [[GLOBAL_ADDR:%.*]] = global_addr @$s12lazy_globals3FooV3fooSivpZ : $*Int
// CHECK: [[GLOBAL_PTR:%.*]] = address_to_pointer [[GLOBAL_ADDR]] : $*Int to $Builtin.RawPointer
// CHECK: return [[GLOBAL_PTR]] : $Builtin.RawPointer
static var foo: Int = 22
static var computed: Int {
return 33
}
static var initialized: Int = 57
}
// CHECK: sil private [global_init_once_fn] [ossa] @[[T:.*3bar.*]]WZ : $@convention(c) () -> () {
// CHECK: alloc_global @$s12lazy_globals3BarO3barSivpZ
// CHECK: [[XADDR:%.*]] = global_addr @$s12lazy_globals3BarO3barSivpZ : $*Int
// CHECK: store {{.*}} to [trivial] [[XADDR]] : $*Int
// CHECK: return
enum Bar {
// CHECK: sil hidden [global_init] [ossa] @$s12lazy_globals3BarO3barSivau : $@convention(thin) () -> Builtin.RawPointer {
// CHECK: [[TOKEN_ADDR:%.*]] = global_addr @[[T]]Wz : $*Builtin.Word
// CHECK: [[TOKEN_PTR:%.*]] = address_to_pointer [[TOKEN_ADDR]] : $*Builtin.Word to $Builtin.RawPointer
// CHECK: [[INIT_FUNC:%.*]] = function_ref @[[T]]WZ : $@convention(c) () -> ()
// CHECK: builtin "once"([[TOKEN_PTR]] : $Builtin.RawPointer, [[INIT_FUNC]] : $@convention(c) () -> ()) : $()
// CHECK: [[GLOBAL_ADDR:%.*]] = global_addr @$s12lazy_globals3BarO3barSivpZ : $*Int
// CHECK: [[GLOBAL_PTR:%.*]] = address_to_pointer [[GLOBAL_ADDR]] : $*Int to $Builtin.RawPointer
// CHECK: return [[GLOBAL_PTR]] : $Builtin.RawPointer
static var bar: Int = 33
}
// We only emit one initializer function per pattern binding, which initializes
// all of the bound variables.
func f() -> (Int, Int) { return (1, 2) }
// CHECK: sil private [global_init_once_fn] [ossa] @[[T:.*2a1.*2b1.*]]WZ : $@convention(c) () -> () {
// CHECK: function_ref @$s12lazy_globals1fSi_SityF : $@convention(thin) () -> (Int, Int)
// CHECK: sil hidden [global_init] [ossa] @$s12lazy_globals2a1Sivau : $@convention(thin) () -> Builtin.RawPointer
// CHECK: function_ref @[[T]]WZ : $@convention(c) () -> ()
// CHECK: global_addr @$s12lazy_globals2a1Sivp : $*Int
// CHECK: sil hidden [global_init] [ossa] @$s12lazy_globals2b1Sivau : $@convention(thin) () -> Builtin.RawPointer {
// CHECK: function_ref @[[T]]WZ : $@convention(c) () -> ()
// CHECK: global_addr @$s12lazy_globals2b1Sivp : $*Int
var (a1, b1) = f()
var computed: Int {
return 44
}
var initialized: Int = 57
| apache-2.0 | 2d1562b3d090351f88e18db8b88f019c | 51.259259 | 121 | 0.609261 | 3.076308 | false | false | false | false |
TwoRingSoft/shared-utils | Examples/Pippin/Pods/PinpointKit/PinpointKit/PinpointKit/Sources/Core/Editing/EditImageViewController.swift | 1 | 32549 | //
// EditImageViewController.swift
// PinpointKit
//
// Created by Matthew Bischoff on 2/19/16.
// Copyright © 2016 Lickability. All rights reserved.
//
import UIKit
import CoreImage
/// The default view controller responsible for editing an image.
open class EditImageViewController: UIViewController, UIGestureRecognizerDelegate {
private static let TextViewEditingBarAnimationDuration = 0.25
// MARK: - Editor
public weak var delegate: EditorDelegate?
// MARK: - InterfaceCustomizable
public var interfaceCustomization: InterfaceCustomization? {
didSet {
guard isViewLoaded else { return }
updateInterfaceCustomization()
}
}
// MARK: - Properties
/// The bar button item provider that specifies the left and right bar button items.
public var barButtonItemProvider: EditImageViewControllerBarButtonItemProviding? {
get {
return barButtonItemProviderBackingStore ?? defaultBarButtonItemProvider
}
set {
barButtonItemProviderBackingStore = newValue
}
}
private lazy var defaultBarButtonItemProvider: EditImageViewControllerBarButtonItemProviding? = {
guard let interfaceCustomization = self.interfaceCustomization else { assertionFailure(); return nil }
return DefaultBarButtonItemProvider(interfaceCustomization: interfaceCustomization, rightBarButtonItemTarget: self, rightBarButtonItemSelector: #selector(EditImageViewController.doneButtonTapped(_:)))
}()
private var barButtonItemProviderBackingStore: EditImageViewControllerBarButtonItemProviding?
private lazy var segmentedControl: UISegmentedControl = { [unowned self] in
let segmentArray = [Tool.arrow, Tool.box, Tool.text, Tool.blur]
let view = UISegmentedControl(items: segmentArray.map { $0.segmentedControlItem })
view.selectedSegmentIndex = 0
let textToolIndex = segmentArray.firstIndex(of: Tool.text)
if let index = textToolIndex {
let segment = view.subviews[index]
segment.accessibilityLabel = "Text Tool"
}
for i in 0..<view.numberOfSegments {
view.setWidth(54, forSegmentAt: i)
}
view.addTarget(self, action: #selector(EditImageViewController.toolChanged(_:)), for: .valueChanged)
return view
}()
fileprivate let imageView: UIImageView = {
let imageView = UIImageView()
imageView.translatesAutoresizingMaskIntoConstraints = false
imageView.contentMode = .scaleAspectFit
return imageView
}()
fileprivate let annotationsView: AnnotationsView = {
let view = AnnotationsView()
view.translatesAutoresizingMaskIntoConstraints = false
return view
}()
private var createAnnotationPanGestureRecognizer: UIPanGestureRecognizer! = nil
private var updateAnnotationPanGestureRecognizer: UIPanGestureRecognizer! = nil
private var createOrUpdateAnnotationTapGestureRecognizer: UITapGestureRecognizer! = nil
private var updateAnnotationPinchGestureRecognizer: UIPinchGestureRecognizer! = nil
private var touchDownGestureRecognizer: UILongPressGestureRecognizer! = nil
private var previousUpdateAnnotationPinchScale: CGFloat = 1
private var previousUpdateAnnotationPanGestureRecognizerLocation: CGPoint!
private lazy var keyboardAvoider: KeyboardAvoider? = {
guard let window = UIApplication.shared.keyWindow else { assertionFailure("PinpointKit did not find a keyWindow."); return nil }
return KeyboardAvoider(window: window)
}()
private var currentTool: Tool? {
return Tool(rawValue: segmentedControl.selectedSegmentIndex)
}
private var currentAnnotationView: AnnotationView? {
didSet {
if let oldTextAnnotationView = oldValue as? TextAnnotationView {
NotificationCenter.default.removeObserver(self, name: UITextView.textDidChangeNotification, object: oldTextAnnotationView.textView)
NotificationCenter.default.removeObserver(self, name: UITextView.textDidEndEditingNotification, object: oldTextAnnotationView.textView)
}
if let currentTextAnnotationView = currentTextAnnotationView {
keyboardAvoider?.triggerViews = [currentTextAnnotationView.textView]
NotificationCenter.default.addObserver(self, selector: #selector(EditImageViewController.textViewTextDidChange), name: UITextView.textDidChangeNotification, object: currentTextAnnotationView.textView)
NotificationCenter.default.addObserver(self, selector: #selector(EditImageViewController.forceEndEditingTextView), name: UITextView.textDidEndEditingNotification, object: currentTextAnnotationView.textView)
}
}
}
private var currentTextAnnotationView: TextAnnotationView? {
return currentAnnotationView as? TextAnnotationView
}
private var currentBlurAnnotationView: BlurAnnotationView? {
return currentAnnotationView as? BlurAnnotationView
}
private var selectedAnnotationView: AnnotationView?
private var fixedSpaceBarButtonItem: UIBarButtonItem {
let fixedSpace = UIBarButtonItem(barButtonSystemItem: .fixedSpace, target: nil, action: nil)
fixedSpace.width = 10
return fixedSpace
}
public init() {
super.init(nibName: nil, bundle: nil)
navigationItem.titleView = segmentedControl
touchDownGestureRecognizer = UILongPressGestureRecognizer(target: self, action: #selector(EditImageViewController.handleTouchDownGestureRecognizer(_:)))
touchDownGestureRecognizer.minimumPressDuration = 0.0
touchDownGestureRecognizer.delegate = self
createAnnotationPanGestureRecognizer = UIPanGestureRecognizer(target: self, action: #selector(EditImageViewController.handleCreateAnnotationGestureRecognizer(_:)))
createAnnotationPanGestureRecognizer.maximumNumberOfTouches = 1
createAnnotationPanGestureRecognizer.delegate = self
updateAnnotationPanGestureRecognizer = UIPanGestureRecognizer(target: self, action: #selector(EditImageViewController.handleUpdateAnnotationGestureRecognizer(_:)))
updateAnnotationPanGestureRecognizer.maximumNumberOfTouches = 1
updateAnnotationPanGestureRecognizer.delegate = self
createOrUpdateAnnotationTapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(EditImageViewController.handleUpdateAnnotationTapGestureRecognizer(_:)))
createOrUpdateAnnotationTapGestureRecognizer.delegate = self
updateAnnotationPinchGestureRecognizer = UIPinchGestureRecognizer(target: self, action: #selector(EditImageViewController.handleUpdateAnnotationPinchGestureRecognizer(_:)))
updateAnnotationPinchGestureRecognizer.delegate = self
annotationsView.isAccessibilityElement = true
annotationsView.accessibilityTraits.insert(.allowsDirectInteraction)
}
@available(*, unavailable)
public required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
deinit {
NotificationCenter.default.removeObserver(self)
createAnnotationPanGestureRecognizer.delegate = nil
updateAnnotationPanGestureRecognizer.delegate = nil
createOrUpdateAnnotationTapGestureRecognizer.delegate = nil
updateAnnotationPinchGestureRecognizer.delegate = nil
touchDownGestureRecognizer.delegate = nil
}
// MARK: - UIResponder
open override var canBecomeFirstResponder: Bool {
return true
}
open override func canPerformAction(_ action: Selector, withSender sender: Any?) -> Bool {
let textViewIsEditing = currentTextAnnotationView?.textView.isFirstResponder ?? false
return action == #selector(EditImageViewController.deleteSelectedAnnotationView) && !textViewIsEditing
}
// MARK: - UIViewController
open override func viewDidLoad() {
super.viewDidLoad()
assert(imageView.image != nil, "A screenshot must be set using `setScreenshot(_:)` before loading the view.")
navigationItem.leftBarButtonItem = barButtonItemProvider?.leftBarButtonItem
if let rightBarButtonItem = barButtonItemProvider?.rightBarButtonItem {
navigationItem.rightBarButtonItems = [rightBarButtonItem, fixedSpaceBarButtonItem]
}
view.backgroundColor = .white
view.addSubview(imageView)
view.addSubview(annotationsView)
keyboardAvoider?.viewsToAvoidKeyboard = [imageView, annotationsView]
let doubleTapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(EditImageViewController.handleDoubleTapGestureRecognizer(_:)))
doubleTapGestureRecognizer.numberOfTapsRequired = 2
doubleTapGestureRecognizer.delegate = self
createOrUpdateAnnotationTapGestureRecognizer.require(toFail: doubleTapGestureRecognizer)
view.addGestureRecognizer(touchDownGestureRecognizer)
view.addGestureRecognizer(doubleTapGestureRecognizer)
view.addGestureRecognizer(createOrUpdateAnnotationTapGestureRecognizer)
view.addGestureRecognizer(updateAnnotationPinchGestureRecognizer)
let longPressGestureRecognizer = UILongPressGestureRecognizer(target: self, action: #selector(EditImageViewController.handleLongPressGestureRecognizer(_:)))
longPressGestureRecognizer.minimumPressDuration = 1
longPressGestureRecognizer.delegate = self
view.addGestureRecognizer(longPressGestureRecognizer)
if let gestureRecognizer = createAnnotationPanGestureRecognizer {
view.addGestureRecognizer(gestureRecognizer)
}
if let gestureRecognizer = updateAnnotationPanGestureRecognizer {
view.addGestureRecognizer(gestureRecognizer)
}
updateInterfaceCustomization()
setupConstraints()
}
open override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
navigationController?.hidesBarsOnTap = true
navigationController?.setNavigationBarHidden(true, animated: false)
}
open override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
navigationController?.setNavigationBarHidden(false, animated: true)
}
open override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
navigationController?.hidesBarsOnTap = true
}
open override func viewDidLayoutSubviews() {
if let height = navigationController?.navigationBar.frame.height {
var rect = annotationsView.frame
rect.origin.y += height
rect.size.height -= height
annotationsView.accessibilityFrame = rect
}
}
open override var prefersStatusBarHidden: Bool {
return true
}
open override func traitCollectionDidChange(_ previousTraitCollection: UITraitCollection?) {
setNeedsStatusBarAppearanceUpdate()
}
open override var shouldAutorotate: Bool {
return false
}
open override var supportedInterfaceOrientations: UIInterfaceOrientationMask {
return imageIsLandscape() ? .landscape : [.portrait, .portraitUpsideDown]
}
open override var preferredInterfaceOrientationForPresentation: UIInterfaceOrientation {
var landscapeOrientation = UIInterfaceOrientation.landscapeRight
var portraitOrientation = UIInterfaceOrientation.portrait
if traitCollection.userInterfaceIdiom == .pad {
let deviceOrientation = UIDevice.current.orientation
landscapeOrientation = (deviceOrientation == .landscapeRight ? .landscapeLeft : .landscapeRight)
portraitOrientation = (deviceOrientation == .portraitUpsideDown ? .portraitUpsideDown : .portrait)
}
return imageIsLandscape() ? landscapeOrientation : portraitOrientation
}
// MARK: - EditImageViewController
/**
Dismisses the receiver if `delegate` is `nil` or returns `true` for `editorShouldDismiss(_:with:)`. If `delegate` returns `true`, `editorWillDismiss(_:with:)` and `editorDidDismiss(_:with:)` will be called before and after, respectively.
- parameter animated: Whether dismissal is animated.
*/
public func attemptToDismiss(animated: Bool) {
guard let delegate = delegate else {
dismiss(animated: animated, completion: nil)
return
}
let screenshot = self.view.pinpoint_screenshot
if delegate.editorShouldDismiss(self, with: screenshot) {
delegate.editorWillDismiss(self, with: screenshot)
dismiss(animated: animated) { [weak self] in
guard let strongSelf = self else { return }
delegate.editorDidDismiss(strongSelf, with: screenshot)
}
}
}
// MARK: - Private
private func setupConstraints() {
let views = [
"imageView": imageView,
"annotationsView": annotationsView
]
view.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "|[imageView]|", options: [], metrics: nil, views: views))
view.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "|[annotationsView]|", options: [], metrics: nil, views: views))
view.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "V:|[imageView]|", options: [], metrics: nil, views: views))
view.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "V:|[annotationsView]|", options: [], metrics: nil, views: views))
}
@objc private func doneButtonTapped(_ button: UIBarButtonItem) {
attemptToDismiss(animated: true)
}
@objc private func handleTouchDownGestureRecognizer(_ gestureRecognizer: UILongPressGestureRecognizer) {
if gestureRecognizer.state == .began {
let possibleAnnotationView = annotationView(with: gestureRecognizer)
let annotationViewIsNotBlurView = !(possibleAnnotationView is BlurAnnotationView)
if let annotationView = possibleAnnotationView {
let wasTopmostAnnotationView = (annotationsView.subviews.last == annotationView)
annotationsView.bringSubviewToFront(annotationView)
if annotationViewIsNotBlurView {
if !wasTopmostAnnotationView {
informDelegate(of: .broughtToFront)
}
navigationController?.barHideOnTapGestureRecognizer.failRecognizing()
}
}
if possibleAnnotationView != currentTextAnnotationView {
endEditingTextView()
if !(possibleAnnotationView is TextAnnotationView) {
createOrUpdateAnnotationTapGestureRecognizer.failRecognizing()
}
// Prevents creating a new text view when swiping away from the current one.
createAnnotationPanGestureRecognizer.failRecognizing()
if annotationViewIsNotBlurView {
navigationController?.barHideOnTapGestureRecognizer.failRecognizing()
}
}
}
}
private func annotationView(with gestureRecognizer: UIGestureRecognizer) -> AnnotationView? {
let view = annotationsView
if gestureRecognizer is UIPinchGestureRecognizer {
var annotationViews: [AnnotationView] = []
let numberOfTouches = gestureRecognizer.numberOfTouches
for index in 0..<numberOfTouches {
if let annotationView = self.annotationView(in: view, with: gestureRecognizer.location(ofTouch: index, in: view)) {
annotationViews.append(annotationView)
}
}
let annotationView = annotationViews.first
let annotationViewsFiltered = annotationViews.filter { $0 == annotationViews.first }
return annotationViewsFiltered.count == numberOfTouches ? annotationView : nil
}
return annotationView(in: view, with: gestureRecognizer.location(in: view))
}
private func annotationView(in view: UIView, with location: CGPoint) -> AnnotationView? {
let hitView = view.hitTest(location, with: nil)
let hitTextView = hitView as? UITextView
let hitTextViewSuperview = hitTextView?.superview as? AnnotationView
let hitAnnotationView = hitView as? AnnotationView
return hitAnnotationView ?? hitTextViewSuperview
}
private func imageIsLandscape() -> Bool {
guard let imageSize = imageView.image?.size else { return false }
guard let imageScale = imageView.image?.scale else { return false }
let imagePixelSize = CGSize(width: imageSize.width * imageScale, height: imageSize.height * imageScale)
let portraitPixelSize = UIScreen.main.portraitPixelSize
return CGFloat(imagePixelSize.width) == portraitPixelSize.height && CGFloat(imagePixelSize.height) == portraitPixelSize.width
}
private func beginEditingTextView() {
guard let currentTextAnnotationView = currentTextAnnotationView else { return }
currentTextAnnotationView.beginEditing()
guard barButtonItemProvider?.hidesBarButtonItemsWhileEditingTextAnnotations == true else { return }
guard let buttonFont = interfaceCustomization?.appearance.editorTextAnnotationDismissButtonFont else { assertionFailure(); return }
let dismissButton = UIBarButtonItem(title: interfaceCustomization?.interfaceText.textEditingDismissButtonTitle, style: .done, target: self, action: #selector(EditImageViewController.endEditingTextViewIfFirstResponder))
dismissButton.setTitleTextAttributesForAllStates([.font: buttonFont])
navigationItem.setRightBarButtonItems([dismissButton, fixedSpaceBarButtonItem], animated: true)
navigationItem.setLeftBarButton(nil, animated: true)
}
@objc private func textViewTextDidChange() {
informDelegate(of: .textEdited)
}
@objc private func forceEndEditingTextView() {
endEditingTextView(false)
}
@objc private func endEditingTextViewIfFirstResponder() {
endEditingTextView(true)
}
private func endEditingTextView(_ checksFirstResponder: Bool = true) {
if let textView = currentTextAnnotationView?.textView, !checksFirstResponder || textView.isFirstResponder {
textView.resignFirstResponder()
if !textView.hasText && currentTextAnnotationView?.superview != nil {
currentTextAnnotationView?.removeFromSuperview()
informDelegate(of: .deleted(animated: false))
}
navigationItem.setLeftBarButton(barButtonItemProvider?.leftBarButtonItem, animated: true)
navigationItem.setRightBarButton(barButtonItemProvider?.rightBarButtonItem, animated: true)
currentAnnotationView = nil
}
}
private func handleGestureRecognizerFinished() {
currentBlurAnnotationView?.drawsBorder = false
let isEditingTextView = currentTextAnnotationView?.textView.isFirstResponder ?? false
currentAnnotationView = isEditingTextView ? currentAnnotationView : nil
}
@objc private func toolChanged(_ segmentedControl: UISegmentedControl) {
if let tool = currentTool {
delegate?.editor(_editor: self, didSelect: tool)
}
endEditingTextView()
// Disable the bar hiding behavior when selecting the text tool. Enable for all others.
navigationController?.barHideOnTapGestureRecognizer.isEnabled = currentTool != .text
}
private func updateInterfaceCustomization() {
guard let appearance = interfaceCustomization?.appearance else { assertionFailure(); return }
segmentedControl.setTitleTextAttributes([.font: appearance.editorTextAnnotationSegmentFont], for: .normal)
guard let annotationFont = appearance.annotationTextAttributes[.font] as? UIFont else { assertionFailure(); return }
UITextView.appearance(whenContainedInInstancesOf: [TextAnnotationView.self]).font = annotationFont
if let annotationFillColor = appearance.annotationFillColor {
annotationsView.tintColor = annotationFillColor
}
}
// MARK: - Create annotations
@objc private func handleCreateAnnotationGestureRecognizer(_ gestureRecognizer: UIPanGestureRecognizer) {
switch gestureRecognizer.state {
case .began:
handleCreateAnnotationGestureRecognizerBegan(gestureRecognizer)
case .changed:
handleCreateAnnotationGestureRecognizerChanged(gestureRecognizer)
case .ended:
handleGestureRecognizerFinished()
// We inform the delegate of text annotation view creation on initial creation.
if !(currentAnnotationView is TextAnnotationView) {
informDelegate(of: .added)
}
case .cancelled, .failed:
handleGestureRecognizerFinished()
default:
break
}
}
private func handleCreateAnnotationGestureRecognizerBegan(_ gestureRecognizer: UIGestureRecognizer) {
guard let currentTool = currentTool else { return }
guard let annotationStrokeColor = interfaceCustomization?.appearance.annotationStrokeColor else { return }
guard let annotationTextAttributes = interfaceCustomization?.appearance.annotationTextAttributes else { return }
let currentLocation = gestureRecognizer.location(in: annotationsView)
let factory = AnnotationViewFactory(image: imageView.image?.cgImage, currentLocation: currentLocation, tool: currentTool, strokeColor: annotationStrokeColor, textAttributes: annotationTextAttributes)
let view: AnnotationView = factory.annotationView()
view.frame = annotationsView.bounds
view.autoresizingMask = [.flexibleWidth, .flexibleHeight]
annotationsView.addSubview(view)
currentAnnotationView = view
if currentAnnotationView is TextAnnotationView {
beginEditingTextView()
informDelegate(of: .added)
}
}
private func handleCreateAnnotationGestureRecognizerChanged(_ gestureRecognizer: UIPanGestureRecognizer) {
let currentLocation = gestureRecognizer.location(in: annotationsView)
currentAnnotationView?.setSecondControlPoint(currentLocation)
}
// MARK: - Update annotations
@objc private func handleUpdateAnnotationGestureRecognizer(_ gestureRecognizer: UIPanGestureRecognizer) {
switch gestureRecognizer.state {
case .began:
handleUpdateAnnotationGestureRecognizerBegan(gestureRecognizer)
case .changed:
handleUpdateAnnotationGestureRecognizerChanged(gestureRecognizer)
case .ended:
handleGestureRecognizerFinished()
informDelegate(of: .moved)
case .cancelled, .failed:
handleGestureRecognizerFinished()
default:
break
}
}
private func handleUpdateAnnotationGestureRecognizerBegan(_ gestureRecognizer: UIPanGestureRecognizer) {
currentAnnotationView = annotationView(with: gestureRecognizer)
previousUpdateAnnotationPanGestureRecognizerLocation = gestureRecognizer.location(in: gestureRecognizer.view)
currentBlurAnnotationView?.drawsBorder = true
UIMenuController.shared.setMenuVisible(false, animated: true)
currentTextAnnotationView?.textView.selectedRange = NSRange()
}
private func handleUpdateAnnotationGestureRecognizerChanged(_ gestureRecognizer: UIPanGestureRecognizer) {
let currentLocation = gestureRecognizer.location(in: gestureRecognizer.view)
let previousLocation: CGPoint = previousUpdateAnnotationPanGestureRecognizerLocation
let offset = CGPoint(x: currentLocation.x - previousLocation.x, y: currentLocation.y - previousLocation.y)
currentAnnotationView?.move(controlPointsBy: offset)
previousUpdateAnnotationPanGestureRecognizerLocation = gestureRecognizer.location(in: gestureRecognizer.view)
}
@objc private func handleUpdateAnnotationTapGestureRecognizer(_ gestureRecognizer: UITapGestureRecognizer) {
switch gestureRecognizer.state {
case .ended:
if let annotationView = annotationView(with: gestureRecognizer) {
currentAnnotationView = annotationView as? TextAnnotationView
beginEditingTextView()
} else if currentTool == .text {
handleCreateAnnotationGestureRecognizerBegan(gestureRecognizer)
}
default:
break
}
}
@objc private func handleUpdateAnnotationPinchGestureRecognizer(_ gestureRecognizer: UIPinchGestureRecognizer) {
switch gestureRecognizer.state {
case .began:
handleUpdateAnnotationPinchGestureRecognizerBegan(gestureRecognizer)
case .changed:
handleUpdateAnnotationPinchGestureRecognizerChanged(gestureRecognizer)
case .ended:
// Ensure we’re actually editing an annotation before notifying the delegate.
// Also, text annotations are not resizable.
if currentTextAnnotationView == nil && currentAnnotationView != nil {
informDelegate(of: .resized)
}
handleGestureRecognizerFinished()
case .cancelled, .failed:
handleGestureRecognizerFinished()
default:
break
}
}
private func handleUpdateAnnotationPinchGestureRecognizerBegan(_ gestureRecognizer: UIPinchGestureRecognizer) {
currentAnnotationView = annotationView(with: gestureRecognizer)
previousUpdateAnnotationPinchScale = 1
currentBlurAnnotationView?.drawsBorder = true
}
private func handleUpdateAnnotationPinchGestureRecognizerChanged(_ gestureRecognizer: UIPinchGestureRecognizer) {
if previousUpdateAnnotationPinchScale != 0 {
currentAnnotationView?.scale(controlPointsBy: (gestureRecognizer.scale / previousUpdateAnnotationPinchScale))
}
previousUpdateAnnotationPinchScale = gestureRecognizer.scale
}
// MARK: - Delete annotations
@objc private func handleDoubleTapGestureRecognizer(_ gestureRecognizer: UITapGestureRecognizer) {
if let view = annotationView(with: gestureRecognizer) {
deleteAnnotationView(view, animated: true)
}
}
@objc private func handleLongPressGestureRecognizer(_ gestureRecognizer: UILongPressGestureRecognizer) {
if gestureRecognizer.state != .began {
return
}
guard let view = annotationView(with: gestureRecognizer) else { return }
selectedAnnotationView = view
becomeFirstResponder()
let point = gestureRecognizer.location(in: gestureRecognizer.view)
let targetRect = CGRect(origin: point, size: CGSize())
let controller = UIMenuController.shared
controller.setTargetRect(targetRect, in: view)
controller.menuItems = [
UIMenuItem(title: "Delete", action: #selector(EditImageViewController.deleteSelectedAnnotationView))
]
controller.update()
controller.setMenuVisible(true, animated: true)
}
private func deleteAnnotationView(_ annotationView: UIView, animated: Bool) {
let removeAnnotationView = {
self.endEditingTextView()
annotationView.removeFromSuperview()
}
if animated {
informDelegate(of: .deleted(animated: true))
UIView.perform(.delete, on: [annotationView], options: [], animations: nil) { _ in
removeAnnotationView()
}
} else {
removeAnnotationView()
informDelegate(of: .deleted(animated: false))
}
}
@objc private func deleteSelectedAnnotationView() {
if let selectedAnnotationView = selectedAnnotationView {
deleteAnnotationView(selectedAnnotationView, animated: true)
}
}
private func informDelegate(of change: AnnotationChange) {
guard let delegate = delegate else { return }
guard let image = imageView.image else { assertionFailure(); return }
delegate.editor(self, didMake: change, to: image)
}
// MARK: - UIGestureRecognizerDelegate
public func gestureRecognizerShouldBegin(_ gestureRecognizer: UIGestureRecognizer) -> Bool {
if gestureRecognizer == createAnnotationPanGestureRecognizer {
return annotationView(with: gestureRecognizer) == nil
}
if gestureRecognizer == updateAnnotationPanGestureRecognizer {
return annotationView(with: gestureRecognizer) != nil
}
if gestureRecognizer == createOrUpdateAnnotationTapGestureRecognizer {
let annotationViewExists = annotationView(with: gestureRecognizer) != nil
return currentTool == .text ? true : annotationViewExists
}
if gestureRecognizer == touchDownGestureRecognizer {
return true
}
let isEditingText = currentTextAnnotationView?.textView.isFirstResponder ?? false
return !isEditingText
}
public func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldRecognizeSimultaneouslyWith otherGestureRecognizer: UIGestureRecognizer) -> Bool {
let isTouchDown = gestureRecognizer == touchDownGestureRecognizer || otherGestureRecognizer == touchDownGestureRecognizer
let isPinch = gestureRecognizer == updateAnnotationPinchGestureRecognizer || otherGestureRecognizer == updateAnnotationPinchGestureRecognizer
return isTouchDown || isPinch
}
}
extension EditImageViewController: Editor {
/// The screenshot, without annotations. Note that setting a new image will clear all annotations in the editor.
public var screenshot: UIImage? {
get {
return imageView.image
}
set {
let oldScreenshot = imageView.image
imageView.image = newValue
if newValue != oldScreenshot {
clearAllAnnotations()
}
}
}
public var numberOfAnnotations: Int {
return annotationsView.subviews.count
}
public func clearAllAnnotations() {
for annotationView in annotationsView.subviews where annotationView is AnnotationView {
annotationView.removeFromSuperview()
}
}
}
private class DefaultBarButtonItemProvider: EditImageViewControllerBarButtonItemProviding {
public let leftBarButtonItem: UIBarButtonItem? = nil
public let rightBarButtonItem: UIBarButtonItem?
public let hidesBarButtonItemsWhileEditingTextAnnotations = true
public init(interfaceCustomization: InterfaceCustomization, rightBarButtonItemTarget: AnyObject?, rightBarButtonItemSelector: Selector) {
rightBarButtonItem = UIBarButtonItem(doneButtonWithTarget: rightBarButtonItemTarget, title: interfaceCustomization.interfaceText.editorDoneButtonTitle, font: interfaceCustomization.appearance.editorDoneButtonFont, action: rightBarButtonItemSelector)
}
}
| mit | 94e52985111a49881a6096e07b183c3a | 42.627346 | 257 | 0.687058 | 6.518326 | false | false | false | false |
antonmes/MessagePack | Tests/MessagePack/ExtendedTests.swift | 1 | 4699 | @testable import MessagePack
@testable import C7
import XCTest
class ExtendedTests: XCTestCase {
func testPackFixext1() {
let value = MessagePackValue.Extended(5, [0x00])
let packed: Data = [0xd4, 0x05, 0x00]
XCTAssertEqual(pack(value), packed)
}
func testUnpackFixext1() {
let packed: Data = [0xd4, 0x05, 0x00]
let value = MessagePackValue.Extended(5, [0x00])
let unpacked = try? unpack(packed)
XCTAssertEqual(unpacked, value)
}
func testPackFixext2() {
let value = MessagePackValue.Extended(5, [0x00, 0x01])
let packed: Data = [0xd5, 0x05, 0x00, 0x01]
XCTAssertEqual(pack(value), packed)
}
func testUnpackFixext2() {
let packed: Data = [0xd5, 0x05, 0x00, 0x01]
let value = MessagePackValue.Extended(5, [0x00, 0x01])
let unpacked = try? unpack(packed)
XCTAssertEqual(unpacked, value)
}
func testPackFixext4() {
let value = MessagePackValue.Extended(5, [0x00, 0x01, 0x02, 0x03])
let packed: Data = [0xd6, 0x05, 0x00, 0x01, 0x02, 0x03]
XCTAssertEqual(pack(value), packed)
}
func testUnpackFixext4() {
let packed: Data = [0xd6, 0x05, 0x00, 0x01, 0x02, 0x03]
let value = MessagePackValue.Extended(5, [0x00, 0x01, 0x02, 0x03])
let unpacked = try? unpack(packed)
XCTAssertEqual(unpacked, value)
}
func testPackFixext8() {
let value = MessagePackValue.Extended(5, [0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07])
let packed: Data = [0xd7, 0x05, 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07]
XCTAssertEqual(pack(value), packed)
}
func testUnpackFixext8() {
let packed: Data = [0xd7, 0x05, 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07]
let value = MessagePackValue.Extended(5, [0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07])
let unpacked = try? unpack(packed)
XCTAssertEqual(unpacked, value)
}
func testPackFixext16() {
let value = MessagePackValue.Extended(5, [0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f])
let packed: Data = [0xd8, 0x05, 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f]
XCTAssertEqual(pack(value), packed)
}
func testUnpackFixext16() {
let value = MessagePackValue.Extended(5, [0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f])
let packed: Data = [0xd8, 0x05, 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f]
let unpacked = try? unpack(packed)
XCTAssertEqual(unpacked, value)
}
func testPackExt8() {
let payload = Data(repeating: 0, count: 7)
let value = MessagePackValue.Extended(5, payload)
XCTAssertEqual(pack(value), [0xc7, 0x07, 0x05] + payload)
}
func testUnpackExt8() {
let payload = Data(repeating: 0, count: 7)
let value = MessagePackValue.Extended(5, payload)
let unpacked = try? unpack([0xc7, 0x07, 0x05] + payload)
XCTAssertEqual(unpacked, value)
}
func testPackExt16() {
let payload = Data(repeating: 0, count: 0x100)
let value = MessagePackValue.Extended(5, payload)
XCTAssertEqual(pack(value), [0xc8, 0x01, 0x00, 0x05] + payload)
}
func testUnpackExt16() {
let payload = Data(repeating: 0, count: 0x100)
let value = MessagePackValue.Extended(5, payload)
let unpacked = try? unpack([0xc8, 0x01, 0x00, 0x05] + payload)
XCTAssertEqual(unpacked, value)
}
func testPackExt32() {
let payload = Data(repeating: 0, count: 0x10000)
let value = MessagePackValue.Extended(5, payload)
XCTAssertEqual(pack(value), [0xc9, 0x00, 0x01, 0x00, 0x00, 0x05] + payload)
}
func testUnpackExt32() {
let payload = Data(repeating: 0, count: 0x10000)
let value = MessagePackValue.Extended(5, payload)
let unpacked = try? unpack([0xc9, 0x00, 0x01, 0x00, 0x00, 0x05] + payload)
XCTAssertEqual(unpacked, value)
}
func testUnpackInsufficientData() {
let dataArray: [Data] = [
// fixent
[0xd4], [0xd5], [0xd6], [0xd7], [0xd8],
// ext 8, 16, 32
[0xc7], [0xc8], [0xc9]
]
for data in dataArray {
do {
try unpack(data)
XCTFail("Expected unpack to throw")
} catch {
XCTAssertEqual(error as? MessagePackError, .InsufficientData)
}
}
}
}
| apache-2.0 | 6c6a6c52c6b7a1eaf3a320e8551c2c8a | 33.807407 | 146 | 0.60481 | 2.97782 | false | true | false | false |
mattiaberretti/MBDesign | MBDesign/Classes/Dialog/DialogViewController.swift | 1 | 3610 | //
// DialogViewController.swift
// Design
//
// Created by Mattia on 30/06/18.
// Copyright © 2018 Mattia. All rights reserved.
//
import UIKit
public class DialogViewController: UIViewController {
@IBOutlet weak var labelTesto: UILabel!
@IBOutlet weak var areaBottoni: UIView!
@IBOutlet weak var labelTitolo: UILabel!
@IBOutlet weak var popUp: UIView!
private let paddingElementi : CGFloat = 48
var titolo : String
var messaggio : String
public var azioni : Array<DialogAction>
private var controllerHeight : CGFloat{
return self.labelTitolo.frame.height + self.areaBottoni.frame.height + self.labelTesto.frame.height + paddingElementi
}
public init(titolo : String, messaggio : String){
self.messaggio = messaggio
self.titolo = titolo
self.azioni = []
super.init(nibName: "DialogViewController", bundle: Bundle(for: DialogViewController.self))
self.modalPresentationStyle = .overCurrentContext
self.modalTransitionStyle = .crossDissolve
}
required public init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override public func viewDidLoad() {
super.viewDidLoad()
self.labelTitolo.text = self.titolo
self.labelTesto.text = self.messaggio
self.popUp.layer.shadowOffset = CGSize(width: 5, height: 5)
self.popUp.layer.shadowColor = UIColor.lightGray.cgColor
self.popUp.layer.shadowOpacity = 1
self.popUp.layer.borderColor = UIColor.lightGray.cgColor
self.popUp.layer.cornerRadius = 5
self.popUp.layer.borderWidth = 1
self.labelTesto.sizeToFit()
self.inserisciBottoni()
}
override public func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
public func addAction(_ action : DialogAction){
self.azioni.append(action)
}
func inserisciBottoni(){
var xPosition = self.areaBottoni.frame.size.width
let altezzaArea = self.areaBottoni.frame.size.height
for i in 0..<self.azioni.count {
let bottone = UIButton(type: UIButton.ButtonType.roundedRect)
bottone.setTitle(self.azioni[i].titolo, for: UIControl.State.normal)
bottone.setTitleColor(UIColor.black, for: UIControl.State.normal)
bottone.addTarget(self, action: #selector(self.btnClick(_:)), for: UIControl.Event.touchUpInside)
bottone.tag = i
bottone.sizeToFit()
xPosition -= bottone.frame.size.width
let y = altezzaArea - (bottone.frame.size.height)
bottone.frame = CGRect(x: xPosition, y: y, width: bottone.frame.size.width, height: bottone.frame.size.height)
self.areaBottoni.insertSubview(bottone, at: i)
xPosition -= 8
}
}
@objc
func btnClick(_ sender : UIButton){
if let azione = self.azioni[sender.tag].action {
azione(self.azioni[sender.tag])
}
self.dismiss(animated: true, completion: nil)
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
| mit | 0133f3b6ada0891717b5764dbb46f4ad | 33.371429 | 125 | 0.644223 | 4.29132 | false | false | false | false |
looseyi/RefreshController | Source/RefreshView.swift | 1 | 1795 | //
// RefreshView.swift
// RefreshController
//
// Created by Edmond on 5/6/2559 BE.
// Copyright © 2559 BE Edmond. All rights reserved.
//
import UIKit
public protocol RefreshViewProtocol: class {
func pullToUpdate(_ controller: PullToRefreshController, didChangeState state: RefreshState)
func pullToUpdate(_ controller: PullToRefreshController, didChangePercentage percentate: CGFloat)
func pullToUpdate(_ controller: PullToRefreshController, didSetEnable enable: Bool)
}
open class RefreshView: UIView {
var state: RefreshState? {
willSet {
if newValue == .stop {
indicator.stopAnimating()
} else if newValue == .loading {
indicator.startAnimating()
}
}
}
public let indicator = RefreshIndicator(color: .lightGray)
public override init(frame: CGRect) {
super.init(frame: frame)
addSubview(indicator)
}
required public init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
open override func layoutSubviews() {
super.layoutSubviews()
let boundsCenter = CGPoint(x: bounds.midX, y: bounds.midY)
indicator.center = boundsCenter
}
}
extension RefreshView: RefreshViewProtocol {
public func pullToUpdate(_ controller: PullToRefreshController, didChangeState state: RefreshState) {
self.state = state
setNeedsLayout()
}
public func pullToUpdate(_ controller: PullToRefreshController, didChangePercentage percentage: CGFloat) {
indicator.setPercentage(percentage)
}
public func pullToUpdate(_ controller: PullToRefreshController, didSetEnable enable: Bool) {
if !enable {
state = .stop
}
}
}
| mit | 025d83d644e5519e758aa942ed056b15 | 27.03125 | 110 | 0.667224 | 4.955801 | false | false | false | false |
space-app-challenge-london/iOS-client | SpaceApps001/ProductOverviewViewController.swift | 1 | 4526 | //
// ProductOverviewViewController.swift
// SpaceApps001
//
// Created by Bratt Neumayer on 4/30/17.
// Copyright © 2017 Bratt Neumayer. All rights reserved.
//
import UIKit
import RxSwift
import RxCocoa
import RxSegue
import Cartography
class ProductOverviewViewController: UIViewController {
@IBOutlet weak var wastageBarController: UIView!
@IBOutlet weak var waterBarContainer: UIView!
@IBOutlet weak var emissionBarContainer: UIView!
@IBOutlet weak var stagesButton: UIButton!
@IBOutlet weak var headerImageView: UIImageView!
@IBOutlet weak var emissionBarWidthConstraint: NSLayoutConstraint!
@IBOutlet weak var waterBarWidthConstraint: NSLayoutConstraint!
@IBOutlet weak var wastageBarWidthConstraint: NSLayoutConstraint!
private let bag = DisposeBag()
var headerImage: UIImage?
var dataForFood = [DataStages]()
var foodForOverview: DataFood?// = DataFood.Cheese
private var showStagesSegue: AnyObserver<Void> {
return NavigationSegue(fromViewController: self.navigationController!,
toViewControllerFactory: { (sender, context) -> ProductStagesViewController in
guard let productSelection = UIStoryboard.instanciate(storyboard: Storyboard.productStages,
identifier: ProductStagesViewController.identifier) as? ProductStagesViewController else {
return ProductStagesViewController()
}
productSelection.dataStages = DataStages.all()
return productSelection
}).asObserver()
}
override func viewDidLoad() {
super.viewDidLoad()
self.stagesButton.setCorners()
self.emissionBarContainer.setCorners()
self.wastageBarController.setCorners()
self.waterBarContainer.setCorners()
let totalBarWidth:CGFloat = self.waterBarContainer.bounds.width
let emissionValue: CGFloat = CGFloat(foodForOverview!.carbonFootprint)
let waterValue: CGFloat = CGFloat(foodForOverview!.waterUsage)
let wastageValue: CGFloat = CGFloat(foodForOverview!.foodWastage)
var emissionRelativity: CGFloat = 0
var waterRelativity: CGFloat = 0
var wastageRelativity: CGFloat = 0
if emissionValue != CGFloat(0){
emissionRelativity = 40 / emissionValue
}
if waterValue != CGFloat(0){
waterRelativity = 17196 / waterValue
}
if wastageValue != CGFloat(0){
wastageRelativity = 100 / wastageValue
}
if emissionValue != CGFloat(0){
emissionBarWidthConstraint.constant = totalBarWidth / emissionRelativity
}else{
emissionBarWidthConstraint.constant = 0.0
}
if waterValue != CGFloat(0){
waterBarWidthConstraint.constant = totalBarWidth / waterRelativity
}else{
waterBarWidthConstraint.constant = 0.0
}
if wastageValue != CGFloat(0){
wastageBarWidthConstraint.constant = totalBarWidth / wastageRelativity
}else{
wastageBarWidthConstraint.constant = 0.0
}
self.headerImageView.image = UIImage(named: foodForOverview!.rawValue)
// if self.headerImage != nil{
//
// self.headerImageView.image = UIImage(named: foodForOverview!.rawValue)//self.headerImage!
// }
stagesButton.rx.tap.bindTo(showStagesSegue).addDisposableTo(bag)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
| mit | a31285ad041089990e38a75d745268a4 | 32.768657 | 176 | 0.597348 | 5.491505 | false | false | false | false |
ralcr/Localizabler | LocalizablerTests/IOSLocalizationFileTests.swift | 1 | 3416 | //
// IOSLocalizationFileTests.swift
// Localizabler
//
// Created by Baluta Cristian on 02/10/15.
// Copyright © 2015 Cristian Baluta. All rights reserved.
//
import XCTest
@testable import Localizable_strings
class IOSLocalizationFileTests: XCTestCase {
func testKeyValueSeparation() {
let url = Bundle(for: type(of: self)).url(forResource: "test", withExtension: "strings")
let file = try! IOSLocalizationFile(url: url!)
let comps = file.splitLine("\"key1\" = \"value 1\";")
XCTAssert(comps.term == "key1", "Key is wrong")
XCTAssert(comps.translation == "value 1", "Translation is wrong")
}
func testKeysExtraction() {
let url = Bundle(for: type(of: self)).url(forResource: "test", withExtension: "strings")
let file = try! IOSLocalizationFile(url: url!)
let lines = file.allLines()
XCTAssert(lines.count == 9, "Wrong number of lines, check parsing")
XCTAssertTrue(lines[5].term == "key3")
XCTAssertTrue(lines[5].translation == "value 3")
XCTAssertTrue(lines[5].comment == " // Inline comment 2")
XCTAssert(file.allTerms().count == 4, "Wrong number of keys, check parsing")
XCTAssert(file.translationForTerm("key1") == "value 1", "Wrong dictionary")
XCTAssert(file.translationForTerm("key2") == "value 2", "Wrong dictionary")
XCTAssert(file.translationForTerm("key3") == "value 3", "Wrong dictionary")
XCTAssert(file.translationForTerm("key4").hasPrefix("<html><head>"), "Splitting of line failed")
XCTAssert(file.translationForTerm("key4").hasSuffix("</body></html>"), "Splitting of html line failed")
}
func testValidLines() {
let url = Bundle(for: type(of: self)).url(forResource: "test", withExtension: "strings")
let file = try! IOSLocalizationFile(url: url!)
XCTAssertFalse(file.isValidLine(""), "")
XCTAssertFalse(file.isValidLine("// Comment"), "")
XCTAssertFalse(file.isValidLine("\"\"=\"\""), "Missing termination character ;")
XCTAssertFalse(file.isValidLine("\";"), "Missing equal is not allowed")
XCTAssertFalse(file.isValidLine("\"\"=\"\";"), "Missing keys are not allowed")
XCTAssertTrue(file.isValidLine("\"key\"=\"ใช้คีย์ลัดเดิม\";"), "Thai chars not matched, probably the string range is using string.characters.length instead string.utf16.length")
XCTAssertTrue(file.isValidLine("\"key\"=\"\";"), "Missing spaces are allowed")
XCTAssertTrue(file.isValidLine(" \"key\"=\"\";"), "Spaces at the beginning are allowed")
XCTAssertTrue(file.isValidLine(" \"key\"=\"\"; "), "Spaces at the beginning and end are allowed")
XCTAssertTrue(file.isValidLine("\"key\" = \"value\";"), "Spaces around = sign are allowed")
XCTAssertTrue(file.isValidLine("\"key key\" = \"value value value value \";"), "")
XCTAssertTrue(file.isValidLine("\"The key \"%@\" can't.\" = \"The key \"%@\" can't be used <html> \"; %@.\";"),
"Html in the right side allowed. This includes termination character ;")
}
func testLineWithComment() {
let url = Bundle(for: type(of: self)).url(forResource: "test", withExtension: "strings")
let file = try! IOSLocalizationFile(url: url!)
XCTAssertTrue(file.isValidLine("\"The key\" = \"The translation\"; /* The comment */"),
"Line with comment should be valid")
}
}
| mit | 869026874fb47948c956a9109e53b0af | 48.808824 | 185 | 0.649247 | 3.929234 | false | true | false | false |
ScoutHarris/WordPress-iOS | WordPressKit/WordPressKitTests/UsersServiceRemoteXMLRPCTests.swift | 2 | 3772 | import WordPressKit
import wpxmlrpc
import XCTest
class UsersServiceRemoteXMLRPCTests: RemoteTestCase, XMLRPCTestable {
// MARK: - Constants
let fetchProfileSuccessMockFilename = "xmlrpc-response-getprofile.xml"
let fetchProfileMissingDataMockFilename = "xmlrpc-response-valid-but-unexpected-dictionary.xml"
// MARK: - Properties
var remote: Any?
// MARK: - Overridden Methods
override func setUp() {
super.setUp()
remote = UsersServiceRemoteXMLRPC(api: getXmlRpcApi(), username: XMLRPCTestableConstants.xmlRpcUserName, password: XMLRPCTestableConstants.xmlRpcPassword)
}
override func tearDown() {
super.tearDown()
remote = nil
}
// MARK: - Tests
func testFetchProfileSucceeds() {
let expect = expectation(description: "Get user profile")
stubRemoteResponse(XMLRPCTestableConstants.xmlRpcUrl, filename: fetchProfileSuccessMockFilename, contentType: .XML)
if let remoteInstance = remote as? UsersServiceRemoteXMLRPC {
remoteInstance.fetchProfile({ (remoteProfile) in
XCTAssertEqual(remoteProfile.bio, "", "Bios should be equal.")
XCTAssertEqual(remoteProfile.displayName, "Test", "Display name should be equal.")
XCTAssertEqual(remoteProfile.email, "[email protected]", "Email should be equal.")
XCTAssertEqual(remoteProfile.firstName, "", "First nameshould be equal.")
XCTAssertEqual(remoteProfile.lastName, "", "Last name should be equal.")
XCTAssertEqual(remoteProfile.nicename, "tester", "Nicename should be equal.")
XCTAssertEqual(remoteProfile.nickname, "tester", "Nickname should be equal.")
XCTAssertEqual(remoteProfile.url, "", "URL should be equal.")
XCTAssertEqual(remoteProfile.userID, 1, "User ID should be equal.")
XCTAssertEqual(remoteProfile.username, "test", "Username should be equal.")
expect.fulfill()
}, failure: { (error) in
XCTFail("This callback shouldn't get called")
expect.fulfill()
})
}
waitForExpectations(timeout: timeout, handler: nil)
}
func testFetchProfileDoesNotCrashWhenReceivingMissingData() {
let expect = expectation(description: "Get user profile")
stubRemoteResponse(XMLRPCTestableConstants.xmlRpcUrl, filename: fetchProfileMissingDataMockFilename, contentType: .XML)
if let remoteInstance = remote as? UsersServiceRemoteXMLRPC {
remoteInstance.fetchProfile({ (remoteProfile) in
XCTAssertEqual(remoteProfile.bio, "", "Bios should be equal.")
XCTAssertEqual(remoteProfile.displayName, "", "Display name should be equal.")
XCTAssertEqual(remoteProfile.email, "", "Email should be equal.")
XCTAssertEqual(remoteProfile.firstName, "", "First nameshould be equal.")
XCTAssertEqual(remoteProfile.lastName, "", "Last name should be equal.")
XCTAssertEqual(remoteProfile.nicename, "", "Nicename should be equal.")
XCTAssertEqual(remoteProfile.nickname, "", "Nickname should be equal.")
XCTAssertEqual(remoteProfile.url, "", "URL should be equal.")
XCTAssertEqual(remoteProfile.userID, 0, "User ID should be equal.")
XCTAssertEqual(remoteProfile.username, "", "Username should be equal.")
expect.fulfill()
}, failure: { (error) in
XCTFail("This callback shouldn't get called")
expect.fulfill()
})
}
waitForExpectations(timeout: timeout, handler: nil)
}
}
| gpl-2.0 | dcdd319948dee83af995d064d395f763 | 40 | 162 | 0.647667 | 5.090418 | false | true | false | false |
vnu/vTweetz | Pods/SwiftDate/SwiftDate_src/DateInRegion+Comparisons.swift | 2 | 9982 | //
// SwiftDate, an handy tool to manage date and timezones in swift
// Created by: Daniele Margutti
// Main contributors: Jeroen Houtzager
//
//
// 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
// MARK: - Comparators
public extension DateInRegion {
/// Returns an NSComparisonResult value that indicates the ordering of two given dates based on their components down to a given unit granularity.
///
/// - Parameters:
/// - date: date to compare.
/// - toUnitGranularity: The smallest unit that must, along with all larger units, be equal for the given dates to be considered the same.
/// For possible values, see “[Calendar Units](xcdoc://?url=developer.apple.com/library/prerelease/ios/documentation/Cocoa/Reference/Foundation/Classes/NSCalendar_Class/index.html#//apple_ref/c/tdef/NSCalendarUnit)”
///
/// - Returns: NSOrderedSame if the dates are the same down to the given granularity, otherwise NSOrderedAscending or NSOrderedDescending.
///
/// - seealso: [compareDate:toDate:toUnitGranularity:](xcdoc://?url=developer.apple.com/library/prerelease/ios/documentation/Cocoa/Reference/Foundation/Classes/NSCalendar_Class/index.html#//apple_ref/occ/instm/NSCalendar/compareDate:toDate:toUnitGranularity:)
///
public func compareDate(date: DateInRegion, toUnitGranularity unit: NSCalendarUnit) -> NSComparisonResult {
return calendar.compareDate(self.absoluteTime, toDate: date.absoluteTime, toUnitGranularity: unit)
}
/// Compares equality of two given dates based on their components down to a given unit granularity.
///
/// - Parameters:
/// - unit: The smallest unit that must, along with all larger units, be equal for the given dates to be considered the same.
/// - date: date to compare.
///
/// - Returns: `true` if the dates are the same down to the given granularity, otherwise `false`
///
/// - seealso: [compareDate:toDate:toUnitGranularity:](xcdoc://?url=developer.apple.com/library/prerelease/ios/documentation/Cocoa/Reference/Foundation/Classes/NSCalendar_Class/index.html#//apple_ref/occ/instm/NSCalendar/compareDate:toDate:toUnitGranularity:)
///
public func isIn(unit: NSCalendarUnit, ofDate date: DateInRegion) -> Bool {
return self.compareDate(date, toUnitGranularity: unit) == .OrderedSame
}
/// Compares whether the receiver is before `date` based on their components down to a given unit granularity.
///
/// - Parameters:
/// - unit: The smallest unit that must, along with all larger units, be less for the given dates.
/// - date: date to compare.
///
/// - Returns: `true` if the unit of the receiver is less than the unit of `date`, otherwise `false`
///
/// - seealso: [compareDate:toDate:toUnitGranularity:](xcdoc://?url=developer.apple.com/library/prerelease/ios/documentation/Cocoa/Reference/Foundation/Classes/NSCalendar_Class/index.html#//apple_ref/occ/instm/NSCalendar/compareDate:toDate:toUnitGranularity:)
///
public func isBefore(unit: NSCalendarUnit, ofDate date: DateInRegion) -> Bool {
return self.compareDate(date, toUnitGranularity: unit) == .OrderedAscending
}
/// Compares whether the receiver is after `date` based on their components down to a given unit granularity.
///
/// - Parameters:
/// - unit: The smallest unit that must, along with all larger units, be greater
/// - date: date to compare.
///
/// - Returns: `true` if the unit of the receiver is greater than the unit of `date`, otherwise `false`
///
/// - seealso: [compareDate:toDate:toUnitGranularity:](xcdoc://?url=developer.apple.com/library/prerelease/ios/documentation/Cocoa/Reference/Foundation/Classes/NSCalendar_Class/index.html#//apple_ref/occ/instm/NSCalendar/compareDate:toDate:toUnitGranularity:)
///
public func isAfter(unit: NSCalendarUnit, ofDate date: DateInRegion) -> Bool {
return self.compareDate(date, toUnitGranularity: unit) == .OrderedDescending
}
/// Returns whether the given date is in today.
///
/// - Returns: a boolean indicating whether the receiver is in today
///
/// - note: This value is interpreted in the context of the calendar of the receiver
///
/// - seealso: [isDateInToday:](xcdoc://?url=developer.apple.com/library/prerelease/ios/documentation/Cocoa/Reference/Foundation/Classes/NSCalendar_Class/index.html#//apple_ref/occ/instm/NSCalendar/isDateInToday:)
///
public func isInToday( ) -> Bool {
return calendar.isDateInToday(absoluteTime)
}
/// Returns whether the given date is in yesterday.
///
/// - Returns: a boolean indicating whether the receiver is in yesterday
///
/// - note: This value is interpreted in the context of the calendar of the receiver
///
/// - seealso: [isDateInYesterday:](xcdoc://?url=developer.apple.com/library/prerelease/ios/documentation/Cocoa/Reference/Foundation/Classes/NSCalendar_Class/index.html#//apple_ref/occ/instm/NSCalendar/isDateInYesterday:)
///
public func isInYesterday() -> Bool {
return calendar.isDateInYesterday(absoluteTime)
}
/// Returns whether the given date is in tomorrow.
///
/// - Returns: a boolean indicating whether the receiver is in tomorrow
///
/// - note: This value is interpreted in the context of the calendar of the receiver
///
/// - seealso: [isDateInTomorrow:](xcdoc://?url=developer.apple.com/library/prerelease/ios/documentation/Cocoa/Reference/Foundation/Classes/NSCalendar_Class/index.html#//apple_ref/occ/instm/NSCalendar/isDateInTomorrow:)
///
public func isInTomorrow() -> Bool {
return calendar.isDateInTomorrow(absoluteTime)
}
/// Returns whether the given date is in the weekend.
///
/// - Returns: a boolean indicating whether the receiver is in the weekend
///
/// - note: This value is interpreted in the context of the calendar of the receiver
///
/// - seealso: [isDateInWeekend:](xcdoc://?url=developer.apple.com/library/prerelease/ios/documentation/Cocoa/Reference/Foundation/Classes/NSCalendar_Class/index.html#//apple_ref/occ/instm/NSCalendar/isDateInWeekend:)
///
public func isInWeekend() -> Bool {
return calendar.isDateInWeekend(absoluteTime)
}
/// Returns whether the given date is on the same day as the receiver in the time zone and calendar of the receiver.
///
/// - Parameters:
/// - date: a date to compare against
///
/// - Returns: a boolean indicating whether the receiver is on the same day as the given date in the time zone and calendar of the receiver.
///
/// - seealso: [isDate:inSameDayAsDate:](xcdoc://?url=developer.apple.com/library/prerelease/ios/documentation/Cocoa/Reference/Foundation/Classes/NSCalendar_Class/index.html#//apple_ref/occ/instm/NSCalendar/isDate:inSameDayAsDate:)
///
public func isInSameDayAsDate(date: DateInRegion) -> Bool {
return calendar.isDate(self.absoluteTime, inSameDayAsDate: date.absoluteTime)
}
/// Returns whether the given date is equal to the receiver.
///
/// - Parameters:
/// - date: a date to compare against
///
/// - Returns: a boolean indicating whether the receiver is equal to the given date
///
/// - seealso: [isEqualToDate:](xcdoc://?url=developer.apple.com/library/prerelease/ios/documentation/Cocoa/Reference/Foundation/Classes/NSDate_Class/index.html#//apple_ref/occ/instm/NSDate/isEqualToDate:)
///
public func isEqualToDate(right: DateInRegion) -> Bool {
return absoluteTime.isEqualToDate(right.absoluteTime)
}
}
// MARK: - Comparable delegate
/// Instances of conforming types can be compared using relational operators, which define a strict total order.
///
/// A type conforming to Comparable need only supply the < and == operators; default implementations of <=, >, >=, and != are supplied by the standard library:
///
extension DateInRegion: Comparable {}
/// Returns whether the given date is later than the receiver.
/// Just the dates are compared. Calendars, time zones are irrelevant.
///
/// - Parameters:
/// - date: a date to compare against
///
/// - Returns: a boolean indicating whether the receiver is earlier than the given date
///
public func <(ldate: DateInRegion, rdate: DateInRegion) -> Bool {
return ldate.absoluteTime.compare(rdate.absoluteTime) == .OrderedAscending
}
/// Returns whether the given date is earlier than the receiver.
/// Just the dates are compared. Calendars, time zones are irrelevant.
///
/// - Parameters:
/// - date: a date to compare against
///
/// - Returns: a boolean indicating whether the receiver is later than the given date
///
public func >(ldate: DateInRegion, rdate: DateInRegion) -> Bool {
return ldate.absoluteTime.compare(rdate.absoluteTime) == .OrderedDescending
}
| apache-2.0 | 42dc04c9299bd772e213b6cccaae1125 | 49.649746 | 263 | 0.71377 | 4.359109 | false | false | false | false |
HeMet/MVVMKit | MVVMKit/DataBindings/Adapters/TableViewAdapter.swift | 1 | 7721 | //
// TableViewMultiDataAdapter.swift
// MVVMKit
//
// Created by Евгений Губин on 21.06.15.
// Copyright (c) 2015 GitHub. All rights reserved.
//
import UIKit
public class TableViewAdapter: TableViewBaseAdapter, ObservableArrayListener {
var items: ObservableOrderedDictionary<Int, TableViewSectionDataModel> = [:]
var headers: ObservableOrderedDictionary<Int, TableViewSectionModel> = [:]
var footers: ObservableOrderedDictionary<Int, TableViewSectionModel> = [:]
override public init(tableView: UITableView) {
super.init(tableView: tableView)
items.onDidInsertRange.register(tag) { [unowned self] in
let set = self.indexSetOf($1.1)
self.tableView.insertSections(set, withRowAnimation: .Right)
}
items.onDidRemoveRange.register(tag) { [unowned self] in
let set = self.indexSetOf($1.1)
self.tableView.deleteSections(set, withRowAnimation: .Left)
}
items.onDidChangeRange.register(tag) { [unowned self] in
let set = self.indexSetOf($1.1)
self.tableView.reloadSections(set, withRowAnimation: .Middle)
}
items.onBatchUpdate.register(tag) { [unowned self] in
self.batchUpdate($1)
}
}
deinit {
disposeItems()
}
func disposeItems() {
// Workaround: Enumeration on items itself cause compiler to crash.
for key in items.keys {
items[key]!.dispose()
}
}
/// One-to-One
public func setData<T: AnyObject>(data: T, forSectionAtIndex sIndex: Int) {
items[sIndex]?.dispose()
items[sIndex] = SimpleItem(data: data)
}
/// One-to-Many
public func setData<T: AnyObject>(data: ObservableArray<T>, forSectionAtIndex sIndex: Int) {
items[sIndex]?.dispose()
data.bindToSection(sIndex, listener: self)
items[sIndex] = data
}
/// One-to-Any
public func hasDataForSection(sIndex: Int) -> Bool {
return items[sIndex] != nil
}
public func removeDataForSection(sIndex: Int) {
items[sIndex]!.dispose()
items[sIndex] = nil
}
/// Section header & footers
public func setTitle(title: String, forSection: TableViewSectionView, atIndex: Int) {
var models = getModelsForSectionView(forSection)
models[atIndex] = TableViewSimpleSection(title: title)
}
public func setData(data: AnyObject, forSection: TableViewSectionView, atIndex: Int) {
var models = getModelsForSectionView(forSection)
models[atIndex] = TableViewCustomViewSection(viewModel: data)
}
public func removeSectionView(sectionView: TableViewSectionView, atIndex: Int) {
var models = getModelsForSectionView(sectionView)
models[atIndex] = nil
}
/// Implementation details
func getModelsForSectionView(sv: TableViewSectionView) -> ObservableOrderedDictionary<Int, TableViewSectionModel> {
return sv == .Header ? headers : footers
}
override func numberOfSections(tableView: UITableView) -> Int {
let idx = reduce(items.keys, -1, max)
return items.count > 0 ? idx + 1 : 0
}
override func numberOfRowsInSection(tableView: UITableView, section: Int) -> Int {
return items[section]?.count ?? 0
}
override func viewModelForIndexPath(indexPath: NSIndexPath) -> AnyObject {
return items[indexPath.section]!.getDataAtIndex(indexPath.row)
}
override func viewModelForSectionHeaderAtIndex(index: Int) -> AnyObject? {
return headers[index]?.viewModel
}
override func viewModelForSectionFooterAtIndex(index: Int) -> AnyObject? {
return footers[index]?.viewModel
}
override func titleForHeader(tableView: UITableView, section: Int) -> String? {
return headers[section]?.title
}
override func titleForFooter(tableView: UITableView, section: Int) -> String? {
return footers[section]?.title
}
func indexSetOf(range: Range<Int>) -> NSIndexSet {
return reduce(range, NSMutableIndexSet()) { set, index in
set.addIndex(index)
return set
}
}
func indexPathsOf(section: Int, idxs: [Int]) -> [NSIndexPath] {
return idxs.map { NSIndexPath(forRow: $0, inSection: section) }
}
func handleDidInsertItems(section: Int, idxs: [Int]) {
let paths = indexPathsOf(section, idxs: idxs)
tableView.insertRowsAtIndexPaths(paths, withRowAnimation: .Right)
onCellsInserted?(self, paths)
}
func handleDidRemoveItems(section: Int, idxs: [Int]) {
let paths = indexPathsOf(section, idxs: idxs)
tableView.deleteRowsAtIndexPaths(paths, withRowAnimation: .Right)
onCellsRemoved?(self, paths)
}
func handleDidChangeItems(section: Int, idxs: [Int]) {
let paths = indexPathsOf(section, idxs: idxs)
tableView.reloadRowsAtIndexPaths(paths, withRowAnimation: .Right)
onCellsReloaded?(self, paths)
}
func handleItemsBatchUpdate(section: Int, phase: UpdatePhase) {
batchUpdate(phase)
}
func batchUpdate(phase: UpdatePhase) {
switch phase {
case .Begin:
beginUpdate()
case .End:
endUpdate()
}
}
}
protocol TableViewSectionDataModel {
var count: Int { get }
func getDataAtIndex(index: Int) -> AnyObject
func dispose()
}
protocol ObservableArrayListener: class {
func handleDidInsertItems(section: Int, idxs: [Int])
func handleDidRemoveItems(section: Int, idxs: [Int])
func handleDidChangeItems(section: Int, idxs: [Int])
func handleItemsBatchUpdate(section: Int, phase: UpdatePhase)
}
// AnyObject is a protocol hence we cann't extend it to support TableViewMultiDataAdapterItem
struct SimpleItem<T: AnyObject>: TableViewSectionDataModel {
let data: T
let count = 1
func getDataAtIndex(index: Int) -> AnyObject {
return data
}
func dispose() {
}
}
extension ObservableArray: TableViewSectionDataModel {
var tag: String {
return "CollectionItem<T: AnyObject>"
}
func getDataAtIndex(index: Int) -> AnyObject {
// there is no way in Swift 1.2 to specify extenstion for array of objects only
return self[index] as! AnyObject
}
func bindToSection(section: Int, listener: ObservableArrayListener) {
onDidChangeRange.register(tag) { [unowned listener] in
listener.handleDidChangeItems(section, idxs: Array($1.1))
}
onDidInsertRange.register(tag) { [unowned listener] in
listener.handleDidInsertItems(section, idxs: Array($1.1))
}
onDidRemoveRange.register(tag) { [unowned listener] in
listener.handleDidRemoveItems(section, idxs: Array($1.1))
}
onBatchUpdate.register(tag) { [unowned listener] in
listener.handleItemsBatchUpdate(section, phase: $1)
}
}
func dispose() {
onDidChangeRange.unregister(tag)
onDidInsertRange.unregister(tag)
onDidRemoveRange.unregister(tag)
onBatchUpdate.unregister(tag)
}
}
protocol TableViewSectionModel {
var title: String? { get }
var viewModel: AnyObject? { get }
}
struct TableViewSimpleSection : TableViewSectionModel {
var title: String?
let viewModel: AnyObject? = nil
}
struct TableViewCustomViewSection : TableViewSectionModel {
let title: String? = nil
var viewModel: AnyObject?
}
| mit | 9c17d54cff1559e74d3c96d4229b0589 | 30.337398 | 119 | 0.642496 | 4.479372 | false | false | false | false |
brentsimmons/Evergreen | Mac/MainWindow/Timeline/TimelineViewController.swift | 1 | 38446 | //
// TimelineViewController.swift
// NetNewsWire
//
// Created by Brent Simmons on 7/26/15.
// Copyright © 2015 Ranchero Software, LLC. All rights reserved.
//
import Foundation
import RSCore
import Articles
import Account
import os.log
protocol TimelineDelegate: AnyObject {
func timelineSelectionDidChange(_: TimelineViewController, selectedArticles: [Article]?)
func timelineRequestedWebFeedSelection(_: TimelineViewController, webFeed: WebFeed)
func timelineInvalidatedRestorationState(_: TimelineViewController)
}
enum TimelineShowFeedName {
case none
case byline
case feed
}
final class TimelineViewController: NSViewController, UndoableCommandRunner, UnreadCountProvider {
@IBOutlet var tableView: TimelineTableView!
private var readFilterEnabledTable = [FeedIdentifier: Bool]()
var isReadFiltered: Bool? {
guard representedObjects?.count == 1, let timelineFeed = representedObjects?.first as? Feed else {
return nil
}
guard timelineFeed.defaultReadFilterType != .alwaysRead else {
return nil
}
if let feedID = timelineFeed.feedID, let readFilterEnabled = readFilterEnabledTable[feedID] {
return readFilterEnabled
} else {
return timelineFeed.defaultReadFilterType == .read
}
}
var isCleanUpAvailable: Bool {
let isEligibleForCleanUp: Bool?
if representedObjects?.count == 1, let timelineFeed = representedObjects?.first as? Feed, timelineFeed.defaultReadFilterType == .alwaysRead {
isEligibleForCleanUp = true
} else {
isEligibleForCleanUp = isReadFiltered
}
guard isEligibleForCleanUp ?? false else { return false }
let readSelectedCount = selectedArticles.filter({ $0.status.read }).count
let readArticleCount = articles.count - unreadCount
let availableToCleanCount = readArticleCount - readSelectedCount
return availableToCleanCount > 0
}
var representedObjects: [AnyObject]? {
didSet {
if !representedObjectArraysAreEqual(oldValue, representedObjects) {
unreadCount = 0
selectionDidChange(nil)
if showsSearchResults {
fetchAndReplaceArticlesAsync()
} else {
fetchAndReplaceArticlesSync()
if articles.count > 0 {
tableView.scrollRowToVisible(0)
}
updateUnreadCount()
}
}
}
}
weak var delegate: TimelineDelegate?
var sharingServiceDelegate: NSSharingServiceDelegate?
var showsSearchResults = false
var selectedArticles: [Article] {
return Array(articles.articlesForIndexes(tableView.selectedRowIndexes))
}
var hasAtLeastOneSelectedArticle: Bool {
return tableView.selectedRow != -1
}
var articles = ArticleArray() {
didSet {
defer {
updateUnreadCount()
}
if articles == oldValue {
return
}
if articles.representSameArticlesInSameOrder(as: oldValue) {
// When the array is the same — same articles, same order —
// but some data in some of the articles may have changed.
// Just reload visible cells in this case: don’t call reloadData.
articleRowMap = [String: [Int]]()
reloadVisibleCells()
return
}
if let representedObjects = representedObjects, representedObjects.count == 1 && representedObjects.first is WebFeed {
showFeedNames = {
for article in articles {
if !article.byline().isEmpty {
return .byline
}
}
return .none
}()
} else {
showFeedNames = .feed
}
articleRowMap = [String: [Int]]()
tableView.reloadData()
}
}
var unreadCount: Int = 0 {
didSet {
if unreadCount != oldValue {
postUnreadCountDidChangeNotification()
}
}
}
var undoableCommands = [UndoableCommand]()
private var fetchSerialNumber = 0
private let fetchRequestQueue = FetchRequestQueue()
private var exceptionArticleFetcher: ArticleFetcher?
private var articleRowMap = [String: [Int]]() // articleID: rowIndex
private var cellAppearance: TimelineCellAppearance!
private var cellAppearanceWithIcon: TimelineCellAppearance!
private var showFeedNames: TimelineShowFeedName = .none {
didSet {
if showFeedNames != oldValue {
updateShowIcons()
updateTableViewRowHeight()
reloadVisibleCells()
}
}
}
private var showIcons = false
private var currentRowHeight: CGFloat = 0.0
private var didRegisterForNotifications = false
static let fetchAndMergeArticlesQueue = CoalescingQueue(name: "Fetch and Merge Articles", interval: 0.5, maxInterval: 2.0)
private var sortDirection = AppDefaults.shared.timelineSortDirection {
didSet {
if sortDirection != oldValue {
sortParametersDidChange()
}
}
}
private var groupByFeed = AppDefaults.shared.timelineGroupByFeed {
didSet {
if groupByFeed != oldValue {
sortParametersDidChange()
}
}
}
private var fontSize: FontSize = AppDefaults.shared.timelineFontSize {
didSet {
if fontSize != oldValue {
fontSizeDidChange()
}
}
}
private var previouslySelectedArticles: ArticleArray?
private var oneSelectedArticle: Article? {
return selectedArticles.count == 1 ? selectedArticles.first : nil
}
private let keyboardDelegate = TimelineKeyboardDelegate()
private var timelineShowsSeparatorsObserver: NSKeyValueObservation?
convenience init(delegate: TimelineDelegate) {
self.init(nibName: "TimelineTableView", bundle: nil)
self.delegate = delegate
}
override func viewDidLoad() {
cellAppearance = TimelineCellAppearance(showIcon: false, fontSize: fontSize)
cellAppearanceWithIcon = TimelineCellAppearance(showIcon: true, fontSize: fontSize)
updateRowHeights()
tableView.rowHeight = currentRowHeight
tableView.target = self
tableView.doubleAction = #selector(openArticleInBrowser(_:))
tableView.setDraggingSourceOperationMask(.copy, forLocal: false)
tableView.keyboardDelegate = keyboardDelegate
if #available(macOS 11.0, *) {
tableView.style = .inset
}
if !didRegisterForNotifications {
NotificationCenter.default.addObserver(self, selector: #selector(statusesDidChange(_:)), name: .StatusesDidChange, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(webFeedIconDidBecomeAvailable(_:)), name: .WebFeedIconDidBecomeAvailable, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(avatarDidBecomeAvailable(_:)), name: .AvatarDidBecomeAvailable, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(faviconDidBecomeAvailable(_:)), name: .FaviconDidBecomeAvailable, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(accountDidDownloadArticles(_:)), name: .AccountDidDownloadArticles, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(accountStateDidChange(_:)), name: .AccountStateDidChange, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(accountsDidChange(_:)), name: .UserDidAddAccount, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(accountsDidChange(_:)), name: .UserDidDeleteAccount, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(containerChildrenDidChange(_:)), name: .ChildrenDidChange, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(userDefaultsDidChange(_:)), name: UserDefaults.didChangeNotification, object: nil)
didRegisterForNotifications = true
}
}
override func viewDidAppear() {
sharingServiceDelegate = SharingServiceDelegate(self.view.window)
}
// MARK: - API
func markAllAsRead(completion: (() -> Void)? = nil) {
guard let undoManager = undoManager, let markReadCommand = MarkStatusCommand(initialArticles: articles, markingRead: true, undoManager: undoManager, completion: completion) else {
return
}
runCommand(markReadCommand)
}
func canMarkAllAsRead() -> Bool {
return articles.canMarkAllAsRead()
}
func canMarkSelectedArticlesAsRead() -> Bool {
return selectedArticles.canMarkAllAsRead()
}
func representsThisObjectOnly(_ object: AnyObject) -> Bool {
guard let representedObjects = representedObjects else {
return false
}
if representedObjects.count != 1 {
return false
}
return representedObjects.first! === object
}
func cleanUp() {
fetchAndReplacePreservingSelection()
}
func toggleReadFilter() {
guard let filter = isReadFiltered, let feedID = (representedObjects?.first as? Feed)?.feedID else { return }
readFilterEnabledTable[feedID] = !filter
delegate?.timelineInvalidatedRestorationState(self)
fetchAndReplacePreservingSelection()
}
// MARK: State Restoration
func saveState(to state: inout [AnyHashable : Any]) {
state[UserInfoKey.readArticlesFilterStateKeys] = readFilterEnabledTable.keys.compactMap { $0.userInfo }
state[UserInfoKey.readArticlesFilterStateValues] = readFilterEnabledTable.values.compactMap( { $0 })
if selectedArticles.count == 1 {
state[UserInfoKey.articlePath] = selectedArticles.first!.pathUserInfo
}
}
func restoreState(from state: [AnyHashable : Any]) {
guard let readArticlesFilterStateKeys = state[UserInfoKey.readArticlesFilterStateKeys] as? [[AnyHashable: AnyHashable]],
let readArticlesFilterStateValues = state[UserInfoKey.readArticlesFilterStateValues] as? [Bool] else {
return
}
for i in 0..<readArticlesFilterStateKeys.count {
if let feedIdentifier = FeedIdentifier(userInfo: readArticlesFilterStateKeys[i]) {
readFilterEnabledTable[feedIdentifier] = readArticlesFilterStateValues[i]
}
}
if let articlePathUserInfo = state[UserInfoKey.articlePath] as? [AnyHashable : Any],
let accountID = articlePathUserInfo[ArticlePathKey.accountID] as? String,
let account = AccountManager.shared.existingAccount(with: accountID),
let articleID = articlePathUserInfo[ArticlePathKey.articleID] as? String {
exceptionArticleFetcher = SingleArticleFetcher(account: account, articleID: articleID)
fetchAndReplaceArticlesSync()
if let selectedIndex = articles.firstIndex(where: { $0.articleID == articleID }) {
tableView.selectRow(selectedIndex)
DispatchQueue.main.async {
self.tableView.scrollTo(row: selectedIndex)
}
focus()
}
} else {
fetchAndReplaceArticlesSync()
}
}
// MARK: - Actions
@objc func openArticleInBrowser(_ sender: Any?) {
if let link = oneSelectedArticle?.preferredLink {
Browser.open(link, invertPreference: NSApp.currentEvent?.modifierFlags.contains(.shift) ?? false)
}
}
@IBAction func toggleStatusOfSelectedArticles(_ sender: Any?) {
guard !selectedArticles.isEmpty else {
return
}
let articles = selectedArticles
let status = articles.first!.status
let markAsRead = !status.read
if markAsRead {
markSelectedArticlesAsRead(sender)
}
else {
markSelectedArticlesAsUnread(sender)
}
}
@IBAction func markSelectedArticlesAsRead(_ sender: Any?) {
guard let undoManager = undoManager, let markReadCommand = MarkStatusCommand(initialArticles: selectedArticles, markingRead: true, undoManager: undoManager) else {
return
}
runCommand(markReadCommand)
}
@IBAction func markSelectedArticlesAsUnread(_ sender: Any?) {
guard let undoManager = undoManager, let markUnreadCommand = MarkStatusCommand(initialArticles: selectedArticles, markingRead: false, undoManager: undoManager) else {
return
}
runCommand(markUnreadCommand)
}
@IBAction func copy(_ sender: Any?) {
NSPasteboard.general.copyObjects(selectedArticles)
}
@IBAction func selectNextUp(_ sender: Any?) {
guard let lastSelectedRow = tableView.selectedRowIndexes.last else {
return
}
let nextRowIndex = lastSelectedRow - 1
if nextRowIndex <= 0 {
tableView.scrollTo(row: 0, extraHeight: 0)
}
tableView.selectRow(nextRowIndex)
let followingRowIndex = nextRowIndex - 1
if followingRowIndex < 0 {
return
}
tableView.scrollToRowIfNotVisible(followingRowIndex)
}
@IBAction func selectNextDown(_ sender: Any?) {
guard let firstSelectedRow = tableView.selectedRowIndexes.first else {
return
}
let tableMaxIndex = tableView.numberOfRows - 1
let nextRowIndex = firstSelectedRow + 1
if nextRowIndex >= tableMaxIndex {
tableView.scrollTo(row: tableMaxIndex, extraHeight: 0)
}
tableView.selectRow(nextRowIndex)
let followingRowIndex = nextRowIndex + 1
if followingRowIndex > tableMaxIndex {
return
}
tableView.scrollToRowIfNotVisible(followingRowIndex)
}
func toggleReadStatusForSelectedArticles() {
// If any one of the selected articles is unread, then mark them as read.
// If all articles are read, then mark them as unread them.
let commandStatus = markReadCommandStatus()
let markingRead: Bool
switch commandStatus {
case .canMark:
markingRead = true
case .canUnmark:
markingRead = false
case .canDoNothing:
return
}
guard let undoManager = undoManager, let markStarredCommand = MarkStatusCommand(initialArticles: selectedArticles, markingRead: markingRead, undoManager: undoManager) else {
return
}
runCommand(markStarredCommand)
}
func toggleStarredStatusForSelectedArticles() {
// If any one of the selected articles is not starred, then star them.
// If all articles are starred, then unstar them.
let commandStatus = markStarredCommandStatus()
let starring: Bool
switch commandStatus {
case .canMark:
starring = true
case .canUnmark:
starring = false
case .canDoNothing:
return
}
guard let undoManager = undoManager, let markStarredCommand = MarkStatusCommand(initialArticles: selectedArticles, markingStarred: starring, undoManager: undoManager) else {
return
}
runCommand(markStarredCommand)
}
func markStarredCommandStatus() -> MarkCommandValidationStatus {
return MarkCommandValidationStatus.statusFor(selectedArticles) { $0.anyArticleIsUnstarred() }
}
func markReadCommandStatus() -> MarkCommandValidationStatus {
let articles = selectedArticles
if articles.anyArticleIsUnread() {
return .canMark
}
if articles.anyArticleIsReadAndCanMarkUnread() {
return .canUnmark
}
return .canDoNothing
}
func markOlderArticlesRead() {
markOlderArticlesRead(selectedArticles)
}
func markAboveArticlesRead() {
markAboveArticlesRead(selectedArticles)
}
func markBelowArticlesRead() {
markBelowArticlesRead(selectedArticles)
}
func canMarkAboveArticlesAsRead() -> Bool {
guard let first = selectedArticles.first else { return false }
return articles.articlesAbove(article: first).canMarkAllAsRead()
}
func canMarkBelowArticlesAsRead() -> Bool {
guard let last = selectedArticles.last else { return false }
return articles.articlesBelow(article: last).canMarkAllAsRead()
}
func markOlderArticlesRead(_ selectedArticles: [Article]) {
// Mark articles older than the selectedArticles(s) as read.
var cutoffDate: Date? = nil
for article in selectedArticles {
if cutoffDate == nil {
cutoffDate = article.logicalDatePublished
}
else if cutoffDate! > article.logicalDatePublished {
cutoffDate = article.logicalDatePublished
}
}
if cutoffDate == nil {
return
}
let articlesToMark = articles.filter { $0.logicalDatePublished < cutoffDate! }
if articlesToMark.isEmpty {
return
}
guard let undoManager = undoManager, let markReadCommand = MarkStatusCommand(initialArticles: articlesToMark, markingRead: true, undoManager: undoManager) else {
return
}
runCommand(markReadCommand)
}
func markAboveArticlesRead(_ selectedArticles: [Article]) {
guard let first = selectedArticles.first else { return }
let articlesToMark = articles.articlesAbove(article: first)
guard !articlesToMark.isEmpty else { return }
guard let undoManager = undoManager, let markReadCommand = MarkStatusCommand(initialArticles: articlesToMark, markingRead: true, undoManager: undoManager) else {
return
}
runCommand(markReadCommand)
}
func markBelowArticlesRead(_ selectedArticles: [Article]) {
guard let last = selectedArticles.last else { return }
let articlesToMark = articles.articlesBelow(article: last)
guard !articlesToMark.isEmpty else { return }
guard let undoManager = undoManager, let markReadCommand = MarkStatusCommand(initialArticles: articlesToMark, markingRead: true, undoManager: undoManager) else {
return
}
runCommand(markReadCommand)
}
// MARK: - Navigation
func goToDeepLink(for userInfo: [AnyHashable : Any]) {
guard let articleID = userInfo[ArticlePathKey.articleID] as? String else { return }
if isReadFiltered ?? false {
if let accountName = userInfo[ArticlePathKey.accountName] as? String,
let account = AccountManager.shared.existingActiveAccount(forDisplayName: accountName) {
exceptionArticleFetcher = SingleArticleFetcher(account: account, articleID: articleID)
fetchAndReplaceArticlesSync()
}
}
guard let ix = articles.firstIndex(where: { $0.articleID == articleID }) else { return }
NSCursor.setHiddenUntilMouseMoves(true)
tableView.selectRow(ix)
tableView.scrollTo(row: ix)
}
func goToNextUnread(wrappingToTop wrapping: Bool = false) {
guard let ix = indexOfNextUnreadArticle() else {
return
}
NSCursor.setHiddenUntilMouseMoves(true)
tableView.selectRow(ix)
tableView.scrollTo(row: ix)
}
func canGoToNextUnread(wrappingToTop wrapping: Bool = false) -> Bool {
guard let _ = indexOfNextUnreadArticle(wrappingToTop: wrapping) else {
return false
}
return true
}
func indexOfNextUnreadArticle(wrappingToTop wrapping: Bool = false) -> Int? {
return articles.rowOfNextUnreadArticle(tableView.selectedRow, wrappingToTop: wrapping)
}
func focus() {
guard let window = tableView.window else {
return
}
window.makeFirstResponderUnlessDescendantIsFirstResponder(tableView)
if !hasAtLeastOneSelectedArticle && articles.count > 0 {
tableView.selectRowAndScrollToVisible(0)
}
}
// MARK: - Notifications
@objc func statusesDidChange(_ note: Notification) {
guard let articleIDs = note.userInfo?[Account.UserInfoKey.articleIDs] as? Set<String> else {
return
}
reloadVisibleCells(for: articleIDs)
updateUnreadCount()
}
@objc func webFeedIconDidBecomeAvailable(_ note: Notification) {
guard showIcons, let feed = note.userInfo?[UserInfoKey.webFeed] as? WebFeed else {
return
}
let indexesToReload = tableView.indexesOfAvailableRowsPassingTest { (row) -> Bool in
guard let article = articles.articleAtRow(row) else {
return false
}
return feed == article.webFeed
}
if let indexesToReload = indexesToReload {
reloadCells(for: indexesToReload)
}
}
@objc func avatarDidBecomeAvailable(_ note: Notification) {
guard showIcons, let avatarURL = note.userInfo?[UserInfoKey.url] as? String else {
return
}
let indexesToReload = tableView.indexesOfAvailableRowsPassingTest { (row) -> Bool in
guard let article = articles.articleAtRow(row), let authors = article.authors, !authors.isEmpty else {
return false
}
for author in authors {
if author.avatarURL == avatarURL {
return true
}
}
return false
}
if let indexesToReload = indexesToReload {
reloadCells(for: indexesToReload)
}
}
@objc func faviconDidBecomeAvailable(_ note: Notification) {
if showIcons {
queueReloadAvailableCells()
}
}
@objc func accountDidDownloadArticles(_ note: Notification) {
guard let feeds = note.userInfo?[Account.UserInfoKey.webFeeds] as? Set<WebFeed> else {
return
}
let shouldFetchAndMergeArticles = representedObjectsContainsAnyWebFeed(feeds) || representedObjectsContainsAnyPseudoFeed()
if shouldFetchAndMergeArticles {
queueFetchAndMergeArticles()
}
}
@objc func accountStateDidChange(_ note: Notification) {
if representedObjectsContainsAnyPseudoFeed() {
fetchAndReplaceArticlesAsync()
}
}
@objc func accountsDidChange(_ note: Notification) {
if representedObjectsContainsAnyPseudoFeed() {
fetchAndReplaceArticlesAsync()
}
}
@objc func containerChildrenDidChange(_ note: Notification) {
if representedObjectsContainsAnyPseudoFeed() || representedObjectsContainAnyFolder() {
fetchAndReplaceArticlesAsync()
}
}
@objc func userDefaultsDidChange(_ note: Notification) {
self.fontSize = AppDefaults.shared.timelineFontSize
self.sortDirection = AppDefaults.shared.timelineSortDirection
self.groupByFeed = AppDefaults.shared.timelineGroupByFeed
}
// MARK: - Reloading Data
private func cellForRowView(_ rowView: NSView) -> NSView? {
for oneView in rowView.subviews where oneView is TimelineTableCellView {
return oneView
}
return nil
}
private func reloadVisibleCells() {
guard let indexes = tableView.indexesOfAvailableRows() else {
return
}
reloadVisibleCells(for: indexes)
}
private func reloadVisibleCells(for articles: [Article]) {
reloadVisibleCells(for: Set(articles.articleIDs()))
}
private func reloadVisibleCells(for articles: Set<Article>) {
reloadVisibleCells(for: articles.articleIDs())
}
private func reloadVisibleCells(for articleIDs: Set<String>) {
if articleIDs.isEmpty {
return
}
let indexes = indexesForArticleIDs(articleIDs)
reloadVisibleCells(for: indexes)
}
private func reloadVisibleCells(for indexes: IndexSet) {
let indexesToReload = tableView.indexesOfAvailableRowsPassingTest { (row) -> Bool in
return indexes.contains(row)
}
if let indexesToReload = indexesToReload {
reloadCells(for: indexesToReload)
}
}
private func reloadCells(for indexes: IndexSet) {
if indexes.isEmpty {
return
}
tableView.reloadData(forRowIndexes: indexes, columnIndexes: NSIndexSet(index: 0) as IndexSet)
}
// MARK: - Cell Configuring
private func calculateRowHeight() -> CGFloat {
let longTitle = "But I must explain to you how all this mistaken idea of denouncing pleasure and praising pain was born and I will give you a complete account of the system, and expound the actual teachings of the great explorer of the truth, the master-builder of human happiness. No one rejects, dislikes, or avoids pleasure itself, because it is pleasure, but because those who do not know how to pursue pleasure rationally encounter consequences that are extremely painful. Nor again is there anyone who loves or pursues or desires to obtain pain of itself, because it is pain, but because occasionally circumstances occur in which toil and pain can procure him some great pleasure. To take a trivial example, which of us ever undertakes laborious physical exercise, except to obtain some advantage from it? But who has any right to find fault with a man who chooses to enjoy a pleasure that has no annoying consequences, or one who avoids a pain that produces no resultant pleasure?"
let prototypeID = "prototype"
let status = ArticleStatus(articleID: prototypeID, read: false, starred: false, dateArrived: Date())
let prototypeArticle = Article(accountID: prototypeID, articleID: prototypeID, webFeedID: prototypeID, uniqueID: prototypeID, title: longTitle, contentHTML: nil, contentText: nil, url: nil, externalURL: nil, summary: nil, imageURL: nil, datePublished: nil, dateModified: nil, authors: nil, status: status)
let prototypeCellData = TimelineCellData(article: prototypeArticle, showFeedName: .feed, feedName: "Prototype Feed Name", byline: nil, iconImage: nil, showIcon: false, featuredImage: nil)
let height = TimelineCellLayout.height(for: 100, cellData: prototypeCellData, appearance: cellAppearance)
return height
}
private func updateRowHeights() {
currentRowHeight = calculateRowHeight()
updateTableViewRowHeight()
}
@objc func fetchAndMergeArticles() {
guard let representedObjects = representedObjects else {
return
}
fetchUnsortedArticlesAsync(for: representedObjects) { [weak self] (unsortedArticles) in
// Merge articles by articleID. For any unique articleID in current articles, add to unsortedArticles.
guard let strongSelf = self else {
return
}
let unsortedArticleIDs = unsortedArticles.articleIDs()
var updatedArticles = unsortedArticles
for article in strongSelf.articles {
if !unsortedArticleIDs.contains(article.articleID) {
updatedArticles.insert(article)
}
}
strongSelf.performBlockAndRestoreSelection {
strongSelf.replaceArticles(with: updatedArticles)
}
}
}
}
// MARK: - NSMenuDelegate
extension TimelineViewController: NSMenuDelegate {
public func menuNeedsUpdate(_ menu: NSMenu) {
menu.removeAllItems()
guard let contextualMenu = contextualMenuForClickedRows() else {
return
}
menu.takeItems(from: contextualMenu)
}
}
// MARK: - NSUserInterfaceValidations
extension TimelineViewController: NSUserInterfaceValidations {
func validateUserInterfaceItem(_ item: NSValidatedUserInterfaceItem) -> Bool {
if item.action == #selector(openArticleInBrowser(_:)) {
if let item = item as? NSMenuItem, item.keyEquivalentModifierMask.contains(.shift) {
item.title = Browser.titleForOpenInBrowserInverted
}
let currentLink = oneSelectedArticle?.preferredLink
return currentLink != nil
}
if item.action == #selector(copy(_:)) {
return NSPasteboard.general.canCopyAtLeastOneObject(selectedArticles)
}
return true
}
}
// MARK: - NSTableViewDataSource
extension TimelineViewController: NSTableViewDataSource {
func numberOfRows(in tableView: NSTableView) -> Int {
return articles.count
}
func tableView(_ tableView: NSTableView, objectValueFor tableColumn: NSTableColumn?, row: Int) -> Any? {
return articles.articleAtRow(row) ?? nil
}
func tableView(_ tableView: NSTableView, pasteboardWriterForRow row: Int) -> NSPasteboardWriting? {
guard let article = articles.articleAtRow(row) else {
return nil
}
return ArticlePasteboardWriter(article: article)
}
}
// MARK: - NSTableViewDelegate
extension TimelineViewController: NSTableViewDelegate {
private static let rowViewIdentifier = NSUserInterfaceItemIdentifier(rawValue: "timelineRow")
func tableView(_ tableView: NSTableView, rowViewForRow row: Int) -> NSTableRowView? {
if let rowView: TimelineTableRowView = tableView.makeView(withIdentifier: TimelineViewController.rowViewIdentifier, owner: nil) as? TimelineTableRowView {
return rowView
}
let rowView = TimelineTableRowView()
rowView.identifier = TimelineViewController.rowViewIdentifier
return rowView
}
private static let timelineCellIdentifier = NSUserInterfaceItemIdentifier(rawValue: "timelineCell")
func tableView(_ tableView: NSTableView, viewFor tableColumn: NSTableColumn?, row: Int) -> NSView? {
func configure(_ cell: TimelineTableCellView) {
cell.cellAppearance = showIcons ? cellAppearanceWithIcon : cellAppearance
if let article = articles.articleAtRow(row) {
configureTimelineCell(cell, article: article)
}
else {
makeTimelineCellEmpty(cell)
}
}
if let cell = tableView.makeView(withIdentifier: TimelineViewController.timelineCellIdentifier, owner: nil) as? TimelineTableCellView {
configure(cell)
return cell
}
let cell = TimelineTableCellView()
cell.identifier = TimelineViewController.timelineCellIdentifier
configure(cell)
return cell
}
func tableViewSelectionDidChange(_ notification: Notification) {
if selectedArticles.isEmpty {
selectionDidChange(nil)
return
}
if selectedArticles.count == 1 {
let article = selectedArticles.first!
if !article.status.read {
markArticles(Set([article]), statusKey: .read, flag: true)
}
}
selectionDidChange(selectedArticles)
}
private func selectionDidChange(_ selectedArticles: ArticleArray?) {
guard selectedArticles != previouslySelectedArticles else { return }
previouslySelectedArticles = selectedArticles
delegate?.timelineSelectionDidChange(self, selectedArticles: selectedArticles)
delegate?.timelineInvalidatedRestorationState(self)
}
private func configureTimelineCell(_ cell: TimelineTableCellView, article: Article) {
cell.objectValue = article
let iconImage = article.iconImage()
cell.cellData = TimelineCellData(article: article, showFeedName: showFeedNames, feedName: article.webFeed?.nameForDisplay, byline: article.byline(), iconImage: iconImage, showIcon: showIcons, featuredImage: nil)
}
private func iconFor(_ article: Article) -> IconImage? {
if !showIcons {
return nil
}
return IconImageCache.shared.imageForArticle(article)
}
private func avatarForAuthor(_ author: Author) -> IconImage? {
return appDelegate.authorAvatarDownloader.image(for: author)
}
private func makeTimelineCellEmpty(_ cell: TimelineTableCellView) {
cell.objectValue = nil
cell.cellData = TimelineCellData()
}
private func toggleArticleRead(_ article: Article) {
guard let undoManager = undoManager, let markUnreadCommand = MarkStatusCommand(initialArticles: [article], markingRead: !article.status.read, undoManager: undoManager) else {
return
}
self.runCommand(markUnreadCommand)
}
private func toggleArticleStarred(_ article: Article) {
guard let undoManager = undoManager, let markUnreadCommand = MarkStatusCommand(initialArticles: [article], markingStarred: !article.status.starred, undoManager: undoManager) else {
return
}
self.runCommand(markUnreadCommand)
}
func tableView(_ tableView: NSTableView, rowActionsForRow row: Int, edge: NSTableView.RowActionEdge) -> [NSTableViewRowAction] {
guard let article = articles.articleAtRow(row) else {
return []
}
switch edge {
case .leading:
let action = NSTableViewRowAction(style: .regular, title: article.status.read ? "Unread" : "Read") { (action, row) in
self.toggleArticleRead(article);
tableView.rowActionsVisible = false
}
action.image = article.status.read ? AppAssets.swipeMarkUnreadImage : AppAssets.swipeMarkReadImage
return [action]
case .trailing:
let action = NSTableViewRowAction(style: .regular, title: article.status.starred ? "Unstar" : "Star") { (action, row) in
self.toggleArticleStarred(article);
tableView.rowActionsVisible = false
}
action.backgroundColor = AppAssets.starColor
action.image = article.status.starred ? AppAssets.swipeMarkUnstarredImage : AppAssets.swipeMarkStarredImage
return [action]
@unknown default:
os_log(.error, "Unknown table row edge: %ld", edge.rawValue)
}
return []
}
}
// MARK: - Private
private extension TimelineViewController {
func fetchAndReplacePreservingSelection() {
if let article = oneSelectedArticle, let account = article.account {
exceptionArticleFetcher = SingleArticleFetcher(account: account, articleID: article.articleID)
}
performBlockAndRestoreSelection {
fetchAndReplaceArticlesSync()
}
}
@objc func reloadAvailableCells() {
if let indexesToReload = tableView.indexesOfAvailableRows() {
reloadCells(for: indexesToReload)
}
}
func updateUnreadCount() {
var count = 0
for article in articles {
if !article.status.read {
count += 1
}
}
unreadCount = count
}
func queueReloadAvailableCells() {
CoalescingQueue.standard.add(self, #selector(reloadAvailableCells))
}
func updateTableViewRowHeight() {
tableView.rowHeight = currentRowHeight
}
func updateShowIcons() {
if showFeedNames == .feed {
self.showIcons = true
return
}
if showFeedNames == .none {
self.showIcons = false
return
}
for article in articles {
if let authors = article.authors {
for author in authors {
if author.avatarURL != nil {
self.showIcons = true
return
}
}
}
}
self.showIcons = false
}
func emptyTheTimeline() {
if !articles.isEmpty {
articles = [Article]()
}
}
func sortParametersDidChange() {
performBlockAndRestoreSelection {
let unsortedArticles = Set(articles)
replaceArticles(with: unsortedArticles)
}
}
func selectedArticleIDs() -> [String] {
return selectedArticles.articleIDs()
}
func restoreSelection(_ articleIDs: [String]) {
selectArticles(articleIDs)
if tableView.selectedRow != -1 {
tableView.scrollRowToVisible(tableView.selectedRow)
}
}
func performBlockAndRestoreSelection(_ block: (() -> Void)) {
let savedSelection = selectedArticleIDs()
block()
restoreSelection(savedSelection)
}
func rows(for articleID: String) -> [Int]? {
updateArticleRowMapIfNeeded()
return articleRowMap[articleID]
}
func rows(for article: Article) -> [Int]? {
return rows(for: article.articleID)
}
func updateArticleRowMap() {
var rowMap = [String: [Int]]()
var index = 0
articles.forEach { (article) in
if var indexes = rowMap[article.articleID] {
indexes.append(index)
rowMap[article.articleID] = indexes
} else {
rowMap[article.articleID] = [index]
}
index += 1
}
articleRowMap = rowMap
}
func updateArticleRowMapIfNeeded() {
if articleRowMap.isEmpty {
updateArticleRowMap()
}
}
func indexesForArticleIDs(_ articleIDs: Set<String>) -> IndexSet {
var indexes = IndexSet()
articleIDs.forEach { (articleID) in
guard let rowsIndex = rows(for: articleID) else {
return
}
for rowIndex in rowsIndex {
indexes.insert(rowIndex)
}
}
return indexes
}
// MARK: - Appearance Change
private func fontSizeDidChange() {
cellAppearance = TimelineCellAppearance(showIcon: false, fontSize: fontSize)
cellAppearanceWithIcon = TimelineCellAppearance(showIcon: true, fontSize: fontSize)
updateRowHeights()
performBlockAndRestoreSelection {
tableView.reloadData()
}
}
// MARK: - Fetching Articles
func fetchAndReplaceArticlesSync() {
// To be called when the user has made a change of selection in the sidebar.
// It blocks the main thread, so that there’s no async delay,
// so that the entire display refreshes at once.
// It’s a better user experience this way.
cancelPendingAsyncFetches()
guard var representedObjects = representedObjects else {
emptyTheTimeline()
return
}
if exceptionArticleFetcher != nil {
representedObjects.append(exceptionArticleFetcher as AnyObject)
exceptionArticleFetcher = nil
}
let fetchedArticles = fetchUnsortedArticlesSync(for: representedObjects)
replaceArticles(with: fetchedArticles)
}
func fetchAndReplaceArticlesAsync() {
// To be called when we need to do an entire fetch, but an async delay is okay.
// Example: we have the Today feed selected, and the calendar day just changed.
cancelPendingAsyncFetches()
guard var representedObjects = representedObjects else {
emptyTheTimeline()
return
}
if exceptionArticleFetcher != nil {
representedObjects.append(exceptionArticleFetcher as AnyObject)
exceptionArticleFetcher = nil
}
fetchUnsortedArticlesAsync(for: representedObjects) { [weak self] (articles) in
self?.replaceArticles(with: articles)
}
}
func cancelPendingAsyncFetches() {
fetchSerialNumber += 1
fetchRequestQueue.cancelAllRequests()
}
func replaceArticles(with unsortedArticles: Set<Article>) {
articles = Array(unsortedArticles).sortedByDate(sortDirection, groupByFeed: groupByFeed)
}
func fetchUnsortedArticlesSync(for representedObjects: [Any]) -> Set<Article> {
cancelPendingAsyncFetches()
let fetchers = representedObjects.compactMap{ $0 as? ArticleFetcher }
if fetchers.isEmpty {
return Set<Article>()
}
var fetchedArticles = Set<Article>()
for fetchers in fetchers {
if (fetchers as? Feed)?.readFiltered(readFilterEnabledTable: readFilterEnabledTable) ?? true {
if let articles = try? fetchers.fetchUnreadArticles() {
fetchedArticles.formUnion(articles)
}
} else {
if let articles = try? fetchers.fetchArticles() {
fetchedArticles.formUnion(articles)
}
}
}
return fetchedArticles
}
func fetchUnsortedArticlesAsync(for representedObjects: [Any], completion: @escaping ArticleSetBlock) {
// The callback will *not* be called if the fetch is no longer relevant — that is,
// if it’s been superseded by a newer fetch, or the timeline was emptied, etc., it won’t get called.
precondition(Thread.isMainThread)
cancelPendingAsyncFetches()
let fetchers = representedObjects.compactMap { $0 as? ArticleFetcher }
let fetchOperation = FetchRequestOperation(id: fetchSerialNumber, readFilterEnabledTable: readFilterEnabledTable, fetchers: fetchers) { [weak self] (articles, operation) in
precondition(Thread.isMainThread)
guard !operation.isCanceled, let strongSelf = self, operation.id == strongSelf.fetchSerialNumber else {
return
}
completion(articles)
}
fetchRequestQueue.add(fetchOperation)
}
func selectArticles(_ articleIDs: [String]) {
let indexesToSelect = indexesForArticleIDs(Set(articleIDs))
if indexesToSelect.isEmpty {
tableView.deselectAll(self)
return
}
tableView.selectRowIndexes(indexesToSelect, byExtendingSelection: false)
}
func queueFetchAndMergeArticles() {
TimelineViewController.fetchAndMergeArticlesQueue.add(self, #selector(fetchAndMergeArticles))
}
func representedObjectArraysAreEqual(_ objects1: [AnyObject]?, _ objects2: [AnyObject]?) -> Bool {
if objects1 == nil && objects2 == nil {
return true
}
guard let objects1 = objects1, let objects2 = objects2 else {
return false
}
if objects1.count != objects2.count {
return false
}
var ix = 0
for oneObject in objects1 {
if oneObject !== objects2[ix] {
return false
}
ix += 1
}
return true
}
func representedObjectsContainsAnyPseudoFeed() -> Bool {
return representedObjects?.contains(where: { $0 is PseudoFeed}) ?? false
}
func representedObjectsContainsTodayFeed() -> Bool {
return representedObjects?.contains(where: { $0 === SmartFeedsController.shared.todayFeed }) ?? false
}
func representedObjectsContainAnyFolder() -> Bool {
return representedObjects?.contains(where: { $0 is Folder }) ?? false
}
func representedObjectsContainsAnyWebFeed(_ webFeeds: Set<WebFeed>) -> Bool {
// Return true if there’s a match or if a folder contains (recursively) one of feeds
guard let representedObjects = representedObjects else {
return false
}
for representedObject in representedObjects {
if let feed = representedObject as? WebFeed {
for oneFeed in webFeeds {
if feed.webFeedID == oneFeed.webFeedID || feed.url == oneFeed.url {
return true
}
}
}
else if let folder = representedObject as? Folder {
for oneFeed in webFeeds {
if folder.hasWebFeed(with: oneFeed.webFeedID) || folder.hasWebFeed(withURL: oneFeed.url) {
return true
}
}
}
}
return false
}
}
| mit | 42ef07082b1d42dac4459f1c0dbcf45d | 29.667199 | 990 | 0.746448 | 3.988996 | false | false | false | false |
Raiden9000/Sonarus | PlaylistSongs.swift | 1 | 7143 | //
// PlaylistSongs.swift
// Sonarus
//
// Created by Christopher Arciniega on 8/21/17.
// Copyright © 2017 HQZenithLabs. All rights reserved.
//
/*TODO
[] 1. Add whole playlist to queue from song chosen, with repeat option
*/
import Foundation
class PlaylistSong:UITableViewController{
var partialPlaylist:SPTPartialPlaylist!
var tracks = [SPTPartialTrack]()
var trackCount:Int = 0
init(playlist: SPTPartialPlaylist) {
super.init(nibName: nil, bundle: nil)
self.partialPlaylist = playlist
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func viewDidLoad() {
super.viewDidLoad()
self.tableView.register(SongCell.self, forCellReuseIdentifier: "PlaylistSongs")
view.backgroundColor = UIColor.darkGray
tableView.dataSource = self
tableView.allowsMultipleSelectionDuringEditing = false
tableView.tableFooterView = UIView()//removes empty cells
tableView.backgroundColor = UIColor.black
tableView.separatorColor = UIColor.clear
//NotificationCenter.default.addObserver(self, selector: #selector(PlayerViewController.loginSetup), name: Notification.Name(rawValue: "addPlaylistToQueue"), object: nil)
//get session variable
if let sessionObj:AnyObject = UserDefaults.standard.value(forKey: "SpotifySession") as AnyObject?{
let sessionDataObj = sessionObj as! Data
let firstTimeSession = NSKeyedUnarchiver.unarchiveObject(with: sessionDataObj) as! SPTSession
session = firstTimeSession
}
getPlaylistSongs()
}
func getPlaylistSongs(){
//First, extract full playlist snapshot
SPTPlaylistSnapshot.playlist(withURI: partialPlaylist.playableUri, accessToken: session.accessToken, callback: {(error, result) in
if error != nil{
print("Error: getting playlist tracks for queue")
}
let snapshot = result as? SPTPlaylistSnapshot
let listPage:SPTListPage = (snapshot?.firstTrackPage)!
self.extractListPageTracks(listPage: listPage)
if listPage.hasNextPage{
self.getNextPage(currentPage: listPage)
}
else{//End
self.trackCount = listPage.items.count
self.tableView.reloadData()
}
} as SPTRequestCallback!)
}
func extractListPageTracks(listPage:SPTListPage){
let pageCount:Int = (listPage.items.count) - 1
for index in 0...pageCount{
let track:SPTPartialTrack = (listPage.items[(index)] as? SPTPartialTrack)!
if !track.uri.absoluteString.contains("spotify:local"){
tracks.append(track)
//self.getFullTrackAndAddToList(uri: track.uri)
}
}
}
func getNextPage(currentPage: SPTListPage){
currentPage.requestNextPage(withAccessToken: session.accessToken, callback: {(error, result) in
let newPage = result as! SPTListPage
self.extractListPageTracks(listPage: newPage)
if newPage.hasNextPage{
self.getNextPage(currentPage: newPage)
self.trackCount += newPage.items.count
}
else{//end
self.trackCount += newPage.items.count
self.tableView.reloadData()
}
})
}
//Set Cell
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
//deque grabs cell that has already scrolled off of the screen, and resuses it. Saves mem, allows quicker scroll
let cell = tableView.dequeueReusableCell(withIdentifier: "PlaylistSongs", for: indexPath) as? SongCell
if indexPath.row <= (tracks.count - 1){
let currentTrack = tracks[indexPath.row]
cell?.link = currentTrack.playableUri
cell?.trackID = currentTrack.identifier
cell?.topLabel.text = currentTrack.name
let artist = currentTrack.artists.first as! SPTPartialArtist
cell?.lowerLabel.text = artist.name
setAlbumArt(cell: cell!,smallArtUrl: currentTrack.album.smallestCover.imageURL, largeArtUrl: currentTrack.album.largestCover.imageURL)
//Info
cell?.artistName = artist.name
cell?.songName = currentTrack.name
}
else{//local mp3 from computer produce empty cells
cell?.hideButton()
cell?.selectionStyle = .none
}
return cell!
}
override func tableView(_ tableView: UITableView, didHighlightRowAt indexPath: IndexPath) {
let selectedCell = tableView.cellForRow(at: indexPath) as! SongCell
print(selectedCell.link)
//let link = selectedCell.link
NotificationCenter.default.post(name: Notification.Name(rawValue: "playSongFromMusicCell"), object: selectedCell)
tableView.deselectRow(at: indexPath, animated: true)
}
override func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return trackCount
}
override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return CGFloat(65)
}
//Sets a cell's album art provided a URL
func setAlbumArt(cell : SongCell, smallArtUrl : URL, largeArtUrl : URL){
//Set proper labels to show
cell.lowerLabel.isHidden = false
cell.artView.isHidden = false
cell.topLabel.isHidden = false
cell.singleLabel.isHidden = true
//Set cover
//print("Getting album art from url")
var coverImageSmall : UIImage? = nil
var coverImageLarge : UIImage? = nil
DispatchQueue.global(qos: .userInitiated).async{
do{
let imageDataSmall = try Data(contentsOf: smallArtUrl)
coverImageSmall = UIImage(data: imageDataSmall)
let imageDataLarge = try Data(contentsOf: largeArtUrl)
coverImageLarge = UIImage(data: imageDataLarge)
}//End do
catch{
print(error.localizedDescription)
}
DispatchQueue.main.async{
if coverImageSmall != nil{
//print("setting cover")
cell.artView.image = coverImageSmall
cell.smallArt = coverImageSmall!
}
else{
print("no image for cell")
}
if coverImageLarge != nil{
//print("setting cover")
cell.largeArt = coverImageLarge!
}
else{
print("no image for cell")
}
}//End dispatch main
}//End Dispatch Global
}
}
| mit | 98e3524cfe3bb458823e8045b666604e | 38.241758 | 178 | 0.610613 | 5.068843 | false | false | false | false |
codestergit/swift | test/SILOptimizer/devirt_covariant_return.swift | 3 | 7813 | // RUN: %target-swift-frontend -Xllvm -sil-full-demangle -O -Xllvm -disable-sil-cm-rr-cm=0 -Xllvm -sil-inline-generics=false -primary-file %s -emit-sil -sil-inline-threshold 1000 -sil-verify-all | %FileCheck %s
// Make sure that we can dig all the way through the class hierarchy and
// protocol conformances with covariant return types correctly. The verifier
// should trip if we do not handle things correctly.
//
// As a side-test it also checks if all allocs can be promoted to the stack.
// CHECK-LABEL: sil hidden @_T023devirt_covariant_return6driveryyF : $@convention(thin) () -> () {
// CHECK: bb0
// CHECK: alloc_ref [stack]
// CHECK: alloc_ref [stack]
// CHECK: alloc_ref [stack]
// CHECK: function_ref @unknown1a : $@convention(thin) () -> ()
// CHECK: apply
// CHECK: function_ref @defenestrate : $@convention(thin) () -> ()
// CHECK: apply
// CHECK: function_ref @unknown2a : $@convention(thin) () -> ()
// CHECK: apply
// CHECK: apply
// CHECK: function_ref @unknown3a : $@convention(thin) () -> ()
// CHECK: apply
// CHECK: apply
// CHECK: dealloc_ref [stack]
// CHECK: dealloc_ref [stack]
// CHECK: dealloc_ref [stack]
// CHECK: tuple
// CHECK: return
@_silgen_name("unknown1a")
func unknown1a() -> ()
@_silgen_name("unknown1b")
func unknown1b() -> ()
@_silgen_name("unknown2a")
func unknown2a() -> ()
@_silgen_name("unknown2b")
func unknown2b() -> ()
@_silgen_name("unknown3a")
func unknown3a() -> ()
@_silgen_name("unknown3b")
func unknown3b() -> ()
@_silgen_name("defenestrate")
func defenestrate() -> ()
class B<T> {
// We do not specialize typealias's correctly now.
//typealias X = B
func doSomething() -> B<T> {
unknown1a()
return self
}
// See comment in protocol P
//class func doSomethingMeta() {
// unknown1b()
//}
func doSomethingElse() {
defenestrate()
}
}
class B2<T> : B<T> {
// When we have covariance in protocols, change this to B2.
// We do not specialize typealias correctly now.
//typealias X = B
override func doSomething() -> B2<T> {
unknown2a()
return self
}
// See comment in protocol P
//override class func doSomethingMeta() {
// unknown2b()
//}
}
class B3<T> : B2<T> {
override func doSomething() -> B3<T> {
unknown3a()
return self
}
}
func WhatShouldIDo<T>(_ b : B<T>) -> B<T> {
b.doSomething().doSomethingElse()
return b
}
func doSomethingWithB<T>(_ b : B<T>) {
}
struct S {}
func driver() -> () {
let b = B<S>()
let b2 = B2<S>()
let b3 = B3<S>()
WhatShouldIDo(b)
WhatShouldIDo(b2)
WhatShouldIDo(b3)
}
driver()
public class Bear {
public init?(fail: Bool) {
if fail { return nil }
}
// Check that devirtualizer can handle convenience initializers, which have covariant optional
// return types.
// CHECK-LABEL: sil @_T023devirt_covariant_return4BearC{{[_0-9a-zA-Z]*}}fc
// CHECK: checked_cast_br [exact] %{{.*}} : $Bear to $PolarBear
// CHECK: upcast %{{.*}} : $Optional<PolarBear> to $Optional<Bear>
// CHECK: }
public convenience init?(delegateFailure: Bool, failAfter: Bool) {
self.init(fail: delegateFailure)
if failAfter { return nil }
}
}
final class PolarBear: Bear {
override init?(fail: Bool) {
super.init(fail: fail)
}
init?(chainFailure: Bool, failAfter: Bool) {
super.init(fail: chainFailure)
if failAfter { return nil }
}
}
class Payload {
let value: Int32
init(_ n: Int32) {
value = n
}
func getValue() -> Int32 {
return value
}
}
final class Payload1: Payload {
override init(_ n: Int32) {
super.init(n)
}
}
class C {
func doSomething() -> Payload? {
return Payload(1)
}
}
final class C1:C {
// Override base method, but return a non-optional result
override func doSomething() -> Payload {
return Payload(2)
}
}
final class C2:C {
// Override base method, but return a non-optional result of a type,
// which is derived from the expected type.
override func doSomething() -> Payload1 {
return Payload1(2)
}
}
// Check that the Optional return value from doSomething
// gets properly unwrapped into a Payload object and then further
// devirtualized.
// CHECK-LABEL: sil hidden @_T023devirt_covariant_return7driver1s5Int32VAA2C1CFTf4d_n
// CHECK: integer_literal $Builtin.Int32, 2
// CHECK: struct $Int32 (%{{.*}} : $Builtin.Int32)
// CHECK-NOT: class_method
// CHECK-NOT: function_ref
// CHECK: return
func driver1(_ c: C1) -> Int32 {
return c.doSomething().getValue()
}
// Check that the Optional return value from doSomething
// gets properly unwrapped into a Payload object and then further
// devirtualized.
// CHECK-LABEL: sil hidden @_T023devirt_covariant_return7driver3s5Int32VAA1CCFTf4g_n
// CHECK: bb{{[0-9]+}}(%{{[0-9]+}} : $C2):
// CHECK-NOT: bb{{.*}}:
// check that for C2, we convert the non-optional result into an optional and then cast.
// CHECK: enum $Optional
// CHECK-NEXT: upcast
// CHECK: return
func driver3(_ c: C) -> Int32 {
return c.doSomething()!.getValue()
}
public class D {
let v: Int32
init(_ n: Int32) {
v = n
}
}
public class D1 : D {
public func foo() -> D? {
return nil
}
public func boo() -> Int32 {
return foo()!.v
}
}
let sD = D(0)
public class D2: D1 {
// Override base method, but return a non-optional result
override public func foo() -> D {
return sD
}
}
// Check that the boo call gets properly devirtualized and that
// that D2.foo() is inlined thanks to this.
// CHECK-LABEL: sil hidden @_T023devirt_covariant_return7driver2s5Int32VAA2D2CFTf4g_n
// CHECK-NOT: class_method
// CHECK: checked_cast_br [exact] %{{.*}} : $D1 to $D2
// CHECK: bb2
// CHECK: global_addr
// CHECK: load
// CHECK: ref_element_addr
// CHECK: bb3
// CHECK: class_method
// CHECK: }
func driver2(_ d: D2) -> Int32 {
return d.boo()
}
class AA {
}
class BB : AA {
}
class CCC {
@inline(never)
func foo(_ b: BB) -> (AA, AA) {
return (b, b)
}
}
class DDD : CCC {
@inline(never)
override func foo(_ b: BB) -> (BB, BB) {
return (b, b)
}
}
class EEE : CCC {
@inline(never)
override func foo(_ b: BB) -> (AA, AA) {
return (b, b)
}
}
// Check that c.foo() is devirtualized, because the optimizer can handle the casting the return type
// correctly, i.e. it can cast (BBB, BBB) into (AAA, AAA)
// CHECK-LABEL: sil hidden @_T023devirt_covariant_return37testDevirtOfMethodReturningTupleTypesAA2AAC_ADtAA3CCCC_AA2BBC1btFTf4gg_n
// CHECK: checked_cast_br [exact] %{{.*}} : $CCC to $CCC
// CHECK: checked_cast_br [exact] %{{.*}} : $CCC to $DDD
// CHECK: checked_cast_br [exact] %{{.*}} : $CCC to $EEE
// CHECK: class_method
// CHECK: }
func testDevirtOfMethodReturningTupleTypes(_ c: CCC, b: BB) -> (AA, AA) {
return c.foo(b)
}
class AAAA {
}
class BBBB : AAAA {
}
class CCCC {
let a: BBBB
var foo : (AAAA, AAAA) {
@inline(never)
get {
return (a, a)
}
}
init(x: BBBB) { a = x }
}
class DDDD : CCCC {
override var foo : (BBBB, BBBB) {
@inline(never)
get {
return (a, a)
}
}
}
// Check devirtualization of methods with optional results, where
// optional results need to be casted.
// CHECK-LABEL: sil @{{.*}}testOverridingMethodWithOptionalResult
// CHECK: checked_cast_br [exact] %{{.*}} : $F to $F
// CHECK: checked_cast_br [exact] %{{.*}} : $F to $G
// CHECK: switch_enum
// CHECK: checked_cast_br [exact] %{{.*}} : $F to $H
// CHECK: switch_enum
public func testOverridingMethodWithOptionalResult(_ f: F) -> (F?, Int)? {
return f.foo()
}
public class F {
@inline(never)
public func foo() -> (F?, Int)? {
return (F(), 1)
}
}
public class G: F {
@inline(never)
override public func foo() -> (G?, Int)? {
return (G(), 2)
}
}
public class H: F {
@inline(never)
override public func foo() -> (H?, Int)? {
return nil
}
}
| apache-2.0 | 5f28c57829d363af428337cd8a19c889 | 21.451149 | 212 | 0.634583 | 3.158044 | false | false | false | false |
think-dev/MadridBUS | MadridBUS/Source/UI/Commons/Spinner.swift | 1 | 3274 | import UIKit
protocol Spinner {
}
class SpinnerBase: UIViewController, Spinner {
fileprivate var radius: CGFloat = 20
fileprivate var color: UIColor = Colors.pink
fileprivate let spinnerLayer = CAShapeLayer()
fileprivate var startAngle: CGFloat = CGFloat(M_PI * -0.5)
fileprivate var finalAngle: CGFloat {
get { return CGFloat(2 * M_PI * 0.95) + CGFloat(M_PI * -0.5) }
set { }
}
override func loadView() {
super.loadView()
view.backgroundColor = .white
drawSpinner()
animateSpinner()
}
override func viewDidLoad() {
super.viewDidLoad()
transitioningDelegate = self
}
private func drawSpinner() {
let spinnerCenter = CGPoint(x: view.bounds.midX, y: view.bounds.midY)
let circlePath = UIBezierPath(arcCenter: spinnerCenter,
radius: radius,
startAngle: startAngle,
endAngle: finalAngle,
clockwise: true)
spinnerLayer.path = circlePath.cgPath
spinnerLayer.fillColor = UIColor.clear.cgColor
spinnerLayer.lineWidth = 5
spinnerLayer.strokeEnd = 0.0
spinnerLayer.strokeColor = color.cgColor
spinnerLayer.lineCap = kCALineCapRound
spinnerLayer.position = spinnerCenter
spinnerLayer.anchorPoint = CGPoint(x: 0.5, y: 0.5)
spinnerLayer.frame = view.frame
view.layer.addSublayer(spinnerLayer)
}
private func animateSpinner() {
DispatchQueue.main.async {
let fillAnimation = CABasicAnimation(keyPath: "strokeEnd")
fillAnimation.duration = 1.0
fillAnimation.fromValue = 0
fillAnimation.toValue = 1
fillAnimation.autoreverses = true
fillAnimation.repeatCount = Float.infinity
self.spinnerLayer.add(fillAnimation, forKey: "fill spinner circle")
let spinnerRotation = CABasicAnimation(keyPath: "transform.rotation.z")
spinnerRotation.duration = 0.8
spinnerRotation.repeatCount = Float.infinity
spinnerRotation.fromValue = 0.0
spinnerRotation.toValue = Float(M_PI * 2.0)
self.spinnerLayer.add(spinnerRotation, forKey: "rotate around center")
}
}
}
extension SpinnerBase: UIViewControllerTransitioningDelegate {
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
let controller = segue.destination
controller.transitioningDelegate = self
controller.modalPresentationStyle = .custom
}
func animationController(forPresented presented: UIViewController, presenting: UIViewController, source: UIViewController) -> UIViewControllerAnimatedTransitioning? {
return SpinnerPresentationBase(withDuration: 0.6, forTransitionType: .presenting, originFrame: presenting.view.frame)
}
func animationController(forDismissed dismissed: UIViewController) -> UIViewControllerAnimatedTransitioning? {
return SpinnerPresentationBase(withDuration: 0.6, forTransitionType: .dismissing, originFrame: dismissed.view.frame)
}
}
| mit | cd2d6721957d1af1b78c5bb4df73e1de | 37.517647 | 170 | 0.641112 | 5.289176 | false | false | false | false |
AliSoftware/SwiftGen | Sources/SwiftGenKit/Parsers/Files/FilesParser.swift | 1 | 1127 | //
// SwiftGenKit
// Copyright © 2020 SwiftGen
// MIT Licence
//
import CoreServices
import Foundation
import PathKit
public enum Files {
public enum ParserError: Error, CustomStringConvertible {
case invalidFile(path: Path, reason: String)
public var description: String {
switch self {
case .invalidFile(let path, let reason):
return "Unable to parse file at \(path). \(reason)"
}
}
}
// MARK: Files Parser
public final class Parser: SwiftGenKit.Parser {
var files: [String: [File]] = [:]
internal let options: ParserOptionValues
public var warningHandler: Parser.MessageHandler?
public required init(options: [String: Any] = [:], warningHandler: Parser.MessageHandler? = nil) throws {
self.options = try ParserOptionValues(options: options, available: Parser.allOptions)
self.warningHandler = warningHandler
}
public static let defaultFilter: String = ".*"
public func parse(path: Path, relativeTo parent: Path) throws {
files[parent.lastComponent, default: []].append(try File(path: path, relativeTo: parent))
}
}
}
| mit | 460bad25def15865a63d16b0b3854662 | 26.463415 | 109 | 0.685613 | 4.415686 | false | false | false | false |
Keanyuan/SwiftContact | SwiftContent/SwiftContent/Classes/ContentView/shareView/YMActionSheet.swift | 1 | 4352 | //
// YMActionSheet.swift
// DanTang
//
// Created by 杨蒙 on 16/7/23.
// Copyright © 2016年 hrscy. All rights reserved.
//
import UIKit
import SnapKit
// 分享按钮背景高度
private let kTopViewH: CGFloat = 230
/// 动画时长
private let kAnimationDuration = 0.25
/// 间距
private let kMargin: CGFloat = 10.0
/// 圆角
private let kCornerRadius: CGFloat = 5.0
class YMActionSheet: UIView {
class func show() {
let actionSheet = YMActionSheet()
actionSheet.frame = UIScreen.main.bounds
actionSheet.backgroundColor = UIColor(red: 0/255.0, green: 0/255.0, blue: 0/255.0, alpha: 0.6)
let window = UIApplication.shared.keyWindow
window?.addSubview(actionSheet)
}
override init(frame: CGRect) {
super.init(frame: frame)
setupUI()
}
private func setupUI() {
addSubview(bgView)
// 上部 分享界面
bgView.addSubview(topView)
// 下部取消按钮
bgView.addSubview(cancelButton)
// 分享到 标签
topView.addSubview(shareLabel)
// 6 个分享按钮的 view
topView.addSubview(shareButtonView)
topView.snp.makeConstraints { (make) in
make.bottom.equalTo(cancelButton.snp.top).offset(-kMargin)
make.left.equalTo(cancelButton.snp.left)
make.right.equalTo(cancelButton.snp.right)
make.height.equalTo(kTopViewH)
}
cancelButton.snp.makeConstraints { (make) in
make.left.equalTo(bgView).offset(kMargin)
make.right.bottom.equalTo(bgView).offset(-kMargin)
make.height.equalTo(44)
}
shareLabel.snp.makeConstraints { (make) in
make.left.right.top.equalTo(topView)
make.height.equalTo(30)
}
}
override func layoutSubviews() {
super.layoutSubviews()
UIView.animate(withDuration: kAnimationDuration) {
self.bgView.y = SCREENH - self.bgView.height
}
}
// 底部 view
private lazy var bgView: UIView = {
let bgView = UIView()
bgView.frame = CGRect(x: 0, y: SCREENH, width: SCREENW, height: 280)
return bgView
}()
// 上部 view
private lazy var topView: UIView = {
let topView = UIView()
topView.backgroundColor = UIColor.white
topView.layer.cornerRadius = kCornerRadius
topView.layer.masksToBounds = true
return topView
}()
// 分享到标签
private lazy var shareLabel: UILabel = {
let shareLabel = UILabel()
shareLabel.text = "分享到"
shareLabel.textColor = UIColor(red: 0/255.0, green: 0/255.0, blue: 0/255.0, alpha: 0.7)
shareLabel.textAlignment = .center
return shareLabel
}()
// 6个按钮
private lazy var shareButtonView: YMShareButtonView = {[weak self] in
let shareButtonView = YMShareButtonView()
shareButtonView.frame = CGRect(x: 0, y: 30, width: SCREENW - 20, height: kTopViewH - 30)
shareButtonView.shareButtonBlock = {(index) in
self?.cancelButtonClick()
}
return shareButtonView
}()
private lazy var cancelButton: UIButton = {
let cancelButton = UIButton()
cancelButton.setTitle("取消", for: .normal)
cancelButton.titleLabel?.font = UIFont.systemFont(ofSize: 18)
cancelButton.setTitleColor(UIColor(red: 37/255.0, green: 142/255.0, blue: 240/255.0, alpha: 1.0), for: .normal)
cancelButton.backgroundColor = UIColor.white
cancelButton.addTarget(self, action: #selector(cancelButtonClick), for: .touchUpInside)
cancelButton.layer.cornerRadius = kCornerRadius
cancelButton.layer.masksToBounds = true
return cancelButton
}()
func cancelButtonClick() {
UIView.animate(withDuration: kAnimationDuration, animations: {
self.bgView.y = SCREENH
}) { (_) in
self.removeFromSuperview()
}
}
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
cancelButtonClick()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
| mit | b7c3bfcf719947ee6a16fe4c00928365 | 29.021277 | 119 | 0.606662 | 4.372934 | false | false | false | false |
sumitlni/LNICoverFlowLayout | LNICoverFlowLayout/Classes/LNICoverFlowLayout.swift | 1 | 10415 | // LNICoverFlowLayout.swift
//
// The MIT License (MIT)
//
// Copyright (c) 2017 Loud Noise Inc.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
import UIKit
/**
Collection Flow Layout in Swift 3.
Adds cover flow effect to collection view scrolling.
Currently supports only horizontal flow direction.
*/
open class LNICoverFlowLayout:UICollectionViewFlowLayout {
/**
* Maximum degree that can be applied to individual item.
* Default to 45 degrees.
*/
open var maxCoverDegree:CGFloat = 45 {
didSet {
if maxCoverDegree < -360 {
maxCoverDegree = -360
} else if maxCoverDegree > 360 {
maxCoverDegree = 360
}
}
}
/**
* Determines how elements covers each other.
* Should be in range 0..1.
* Default to 0.25.
* Examples:
* 0 means that items are placed within a continuous line.
* 0.5 means that half of 3rd and 1st item will be behind 2nd.
*/
open var coverDensity:CGFloat = 0.25 {
didSet {
if coverDensity < 0 {
coverDensity = 0
} else if coverDensity > 1 {
coverDensity = 1
}
}
}
/**
* Min opacity that can be applied to individual item.
* Default to 1.0 (alpha 100%).
*/
open var minCoverOpacity:CGFloat = 1.0 {
didSet {
if minCoverOpacity < 0 {
minCoverOpacity = 0
} else if minCoverOpacity > 1 {
minCoverOpacity = 1
}
}
}
/**
* Min scale that can be applied to individual item.
* Default to 1.0 (no scale).
*/
open var minCoverScale:CGFloat = 1.0 {
didSet {
if minCoverScale < 0 {
minCoverScale = 0
} else if minCoverScale > 1 {
minCoverScale = 1
}
}
}
// Private Constant. Not a good naming convention but keeping as close to inspiration as possible
fileprivate let kDistanceToProjectionPlane:CGFloat = 500.0
// MARK: Overrides
// Thanks to property initializations we do not need to override init(*)
override open func prepare() {
super.prepare()
assert(self.collectionView?.numberOfSections == 1, "[LNICoverFlowLayout]: Multiple sections are not supported")
assert(self.scrollDirection == .horizontal, "[LNICoverFlowLayout]: Vertical scrolling is not supported")
}
override open func shouldInvalidateLayout(forBoundsChange newBounds: CGRect) -> Bool {
return true
}
override open func layoutAttributesForElements(in rect: CGRect) -> [UICollectionViewLayoutAttributes]? {
let idxPaths = indexPathsContainedInRect(rect)
var resultingAttributes = [UICollectionViewLayoutAttributes]()
for path in idxPaths {
resultingAttributes.append(layoutAttributesForItem(at: path))
}
return resultingAttributes
}
override open func layoutAttributesForItem(at indexPath:IndexPath)->UICollectionViewLayoutAttributes {
let attributes = UICollectionViewLayoutAttributes(forCellWith:indexPath)
attributes.size = self.itemSize
attributes.center = CGPoint(x: collectionViewWidth()*CGFloat(indexPath.row) + collectionViewWidth(),
y: collectionViewHeight()/2)
let contentOffsetX = collectionView?.contentOffset.x ?? 0
return interpolateAttributes(attributes, forOffset: contentOffsetX)
}
override open var collectionViewContentSize : CGSize {
if let collectionView = collectionView {
return CGSize(width: collectionView.bounds.size.width * CGFloat(collectionView.numberOfItems(inSection: 0)),
height: collectionView.bounds.size.height)
}
return CGSize.zero
}
// MARK: Accessors
fileprivate func collectionViewHeight() -> CGFloat {
let height = collectionView?.bounds.size.height ?? 0
return height
}
fileprivate func collectionViewWidth() -> CGFloat {
let width = collectionView?.bounds.size.width ?? 0
return width
}
// MARK: Private
fileprivate func itemCenterForRow(_ row:Int)->CGPoint {
let collectionViewSize = collectionView?.bounds.size ?? CGSize.zero
return CGPoint(x: CGFloat(row) * collectionViewSize.width + collectionViewSize.width / 2,
y: collectionViewSize.height/2)
}
fileprivate func minXForRow(_ row:Int)->CGFloat {
return itemCenterForRow(row - 1).x + (1.0 / 2 - self.coverDensity) * self.itemSize.width
}
fileprivate func maxXForRow(_ row:Int)->CGFloat {
return itemCenterForRow(row + 1).x - (1.0 / 2 - self.coverDensity) * self.itemSize.width
}
fileprivate func minXCenterForRow(_ row:Int)->CGFloat {
let halfWidth = self.itemSize.width / 2
let maxRads = degreesToRad(self.maxCoverDegree)
let center = itemCenterForRow(row - 1).x
let prevItemRightEdge = center + halfWidth
let projectedLeftEdgeLocal = halfWidth * cos(maxRads) * kDistanceToProjectionPlane / (kDistanceToProjectionPlane + halfWidth * sin(maxRads))
return prevItemRightEdge - (self.coverDensity * self.itemSize.width) + projectedLeftEdgeLocal
}
fileprivate func maxXCenterForRow(_ row:Int)->CGFloat {
let halfWidth = self.itemSize.width / 2
let maxRads = degreesToRad(self.maxCoverDegree)
let center = itemCenterForRow(row + 1).x
let nextItemLeftEdge = center - halfWidth
let projectedRightEdgeLocal = abs(halfWidth * cos(maxRads) * kDistanceToProjectionPlane / (-halfWidth * sin(maxRads) - kDistanceToProjectionPlane))
return nextItemLeftEdge + (self.coverDensity * self.itemSize.width) - projectedRightEdgeLocal
}
fileprivate func degreesToRad(_ degrees:CGFloat)->CGFloat {
return CGFloat(Double(degrees) * .pi / 180)
}
fileprivate func indexPathsContainedInRect(_ rect:CGRect)->[IndexPath] {
let noI = collectionView?.numberOfItems(inSection: 0) ?? 0
if noI == 0 {
return []
}
let cvW = collectionViewWidth()
// Find min and max rows that can be determined for sure
var minRow = Int(max(rect.origin.x/cvW, 0))
var maxRow = 0
if cvW != 0 {
maxRow = Int(rect.maxX / cvW)
}
// Additional check for rows that also can be included (our rows are moving depending on content size)
let candidateMinRow = max(minRow-1, 0)
if maxXForRow(candidateMinRow) >= rect.origin.x {
minRow = candidateMinRow
}
let candidateMaxRow = min(maxRow + 1, noI - 1)
if minXForRow(candidateMaxRow) <= rect.maxX {
maxRow = candidateMaxRow
}
// Simply add index paths between min and max.
var resultingIdxPaths = [IndexPath]()
// Fix for 1-item collections - see issue #8 - Thanks gstrobl17
if maxRow > 0 && (minRow < maxRow || noI != 1) {
for i in minRow...maxRow {
resultingIdxPaths.append(IndexPath(row: i, section: 0))
}
} else {
resultingIdxPaths = [IndexPath(row: 0, section: 0)]
}
return resultingIdxPaths
}
fileprivate func interpolateAttributes(_ attributes:UICollectionViewLayoutAttributes, forOffset offset:CGFloat)->UICollectionViewLayoutAttributes {
let attributesPath = attributes.indexPath
let minInterval = CGFloat(attributesPath.row - 1) * collectionViewWidth()
let maxInterval = CGFloat(attributesPath.row + 1) * collectionViewWidth()
let minX = minXCenterForRow(attributesPath.row)
let maxX = maxXCenterForRow(attributesPath.row)
let spanX = maxX - minX
// Interpolate by formula
let interpolatedX = min(max(minX + ((spanX / (maxInterval - minInterval)) * (offset - minInterval)), minX), maxX)
attributes.center = CGPoint(x: interpolatedX, y: attributes.center.y)
var transform = CATransform3DIdentity
// Add perspective
transform.m34 = -1.0 / kDistanceToProjectionPlane
// Then rotate.
let angle = -self.maxCoverDegree + (interpolatedX - minX) * 2 * self.maxCoverDegree / spanX
transform = CATransform3DRotate(transform, degreesToRad(angle), 0, 1, 0)
// Then scale: 1 - abs(1 - Q - 2 * x * (1 - Q))
let scale = 1.0 - abs(1 - self.minCoverScale - (interpolatedX - minX) * 2 * (1.0 - self.minCoverScale) / spanX)
transform = CATransform3DScale(transform, scale, scale, scale)
// Apply transform
attributes.transform3D = transform
// Add opacity: 1 - abs(1 - Q - 2 * x * (1 - Q))
let opacity = 1.0 - abs(1 - self.minCoverOpacity - (interpolatedX - minX) * 2 * (1 - self.minCoverOpacity) / spanX)
attributes.alpha = opacity
// print(String(format:"IDX: %d. MinX: %.2f. MaxX: %.2f. Interpolated: %.2f. Interpolated angle: %.2f",
// attributesPath.row,
// minX,
// maxX,
// interpolatedX,
// angle));
return attributes
}
}
| mit | 222b23f9265a265cc338943755729905 | 35.038062 | 155 | 0.633317 | 4.540105 | false | false | false | false |
sztoth/PodcastChapters | PodcastChapters/Utilities/Misc/StatusBarItem.swift | 1 | 2719 | //
// StatusBarItem.swift
// PodcastChapters
//
// Created by Szabolcs Toth on 2016. 02. 07..
// Copyright © 2016. Szabolcs Toth. All rights reserved.
//
import Cocoa
import RxCocoa
import RxSwift
class StatusBarItem {
var event: Observable<Event> {
return _event.asObservable()
}
fileprivate let _event = PublishSubject<Event>()
fileprivate let statusItem: NSStatusItem
fileprivate let eventMonitor: EventMonitor
fileprivate let disposeBag = DisposeBag()
fileprivate var visible = false
init(statusItem: NSStatusItem = NSStatusItem.pch_statusItem(), eventMonitor: EventMonitor) {
self.statusItem = statusItem
self.eventMonitor = eventMonitor
setupBindings()
self.eventMonitor.start()
}
}
// MARK: - Setup
fileprivate extension StatusBarItem {
func setupBindings() {
statusItem.event?
.map(statusItemEvent)
.bindTo(_event)
.addDisposableTo(disposeBag)
statusItem.event?
.filter(isToggleEvent)
.subscribe { _ in
self.toggle()
}
.addDisposableTo(disposeBag)
eventMonitor.event
.subscribe { _ in
self.mainViewWillHide()
}
.addDisposableTo(disposeBag)
eventMonitor.event
.map { _ in Event.close }
.bindTo(_event)
.addDisposableTo(disposeBag)
}
}
// MARK: - Visibility methods
fileprivate extension StatusBarItem {
func toggle() {
visible ? mainViewWillHide() : mainViewWillShow()
}
func mainViewWillShow() {
visible = true
statusItem.highlighted = true
eventMonitor.start()
}
func mainViewWillHide() {
visible = false
statusItem.highlighted = false
eventMonitor.stop()
}
}
// MARK: - RxSwift methods
fileprivate extension StatusBarItem {
func isToggleEvent(_ event: StatusItemView.Event) -> Bool {
if case .toggleMainView(_) = event {
return true
}
return false
}
func statusItemEvent(from event: StatusItemView.Event) -> Event {
switch event {
case .toggleMainView(_) where visible:
return .close
case .toggleMainView(let view) where !visible:
return .open(view)
case .openSettings:
return .openSettings
case .quit:
return .quit
default:
fatalError("Should not have more options")
}
}
}
// MARK: - Event
extension StatusBarItem {
enum Event {
case open(NSView)
case close
case openSettings
case quit
}
}
| mit | 803c41b21602e1d65ea210186d40f417 | 21.840336 | 96 | 0.594555 | 5.033333 | false | false | false | false |
sztoth/PodcastChapters | PodcastChapters/Utilities/Popover/PopoverAnimator.swift | 1 | 1685 | //
// PopoverAnimator.swift
// PodcastChapters
//
// Created by Szabolcs Toth on 2016. 02. 16..
// Copyright © 2016. Szabolcs Toth. All rights reserved.
//
import AppKit
import Foundation
typealias PopoverAnimationCompletion = (PopoverAnimator.AnimationDirection) -> ()
class PopoverAnimator {
fileprivate(set) var animating = false
}
// MARK: - Animation
extension PopoverAnimator {
func animate(_ window: NSWindow, direction: AnimationDirection, completion: @escaping PopoverAnimationCompletion) {
guard !animating else { return }
animating = true
var calculatedFrame = window.frame
calculatedFrame.origin.y += CGFloat(AnimationSettings.distance)
let alpha: Double
let startFrame, endFrame: NSRect
switch direction {
case .in:
alpha = 1.0
startFrame = calculatedFrame
endFrame = window.frame
case .out:
alpha = 0.0
startFrame = window.frame
endFrame = calculatedFrame
}
window.setFrame(startFrame, display: true)
NSAnimationContext.runAnimationGroup({ context in
context.duration = AnimationSettings.duration
context.timingFunction = AnimationSettings.timing
let animator = window.animator()
animator.setFrame(endFrame, display: false)
animator.alphaValue = CGFloat(alpha)
}, completionHandler: { _ in
self.animating = false
completion(direction)
})
}
}
// MARK: - AnimationDirection
extension PopoverAnimator {
enum AnimationDirection {
case `in`
case out
}
}
| mit | 40b1d6dbba5d24fa909e507f39c8ac1b | 24.907692 | 119 | 0.635392 | 5.134146 | false | false | false | false |
nathawes/swift | test/AutoDiff/stdlib/optional.swift | 6 | 3370 | // RUN: %target-run-simple-swift
// REQUIRES: executable_test
import _Differentiation
import StdlibUnittest
var OptionalDifferentiationTests = TestSuite("OptionalDifferentiation")
OptionalDifferentiationTests.test("Optional operations") {
// Differentiable.move(along:)
do {
var some: Float? = 2
some.move(along: .init(3))
expectEqual(5, some)
var none: Float? = nil
none.move(along: .init(3))
expectEqual(nil, none)
}
// Differentiable.zeroTangentVectorInitializer
do {
let some: [Float]? = [1, 2, 3]
expectEqual(.init([0, 0, 0]), some.zeroTangentVectorInitializer())
let none: [Float]? = nil
expectEqual(.init(nil), none.zeroTangentVectorInitializer())
}
}
OptionalDifferentiationTests.test("Optional.TangentVector operations") {
// Differentiable.move(along:)
do {
var some: Optional<Float>.TangentVector = .init(2)
some.move(along: .init(3))
expectEqual(5, some.value)
var none: Optional<Float>.TangentVector = .init(nil)
none.move(along: .init(3))
expectEqual(nil, none.value)
var nestedSome: Optional<Optional<Float>>.TangentVector = .init(.init(2))
nestedSome.move(along: .init(.init(3)))
expectEqual(.init(5), nestedSome.value)
var nestedNone: Optional<Optional<Float>>.TangentVector = .init(.init(nil))
nestedNone.move(along: .init(.init(3)))
expectEqual(.init(nil), nestedNone.value)
}
// Differentiable.zeroTangentVectorInitializer
do {
let some: [Float]? = [1, 2, 3]
expectEqual(.init([0, 0, 0]), some.zeroTangentVectorInitializer())
let none: [Float]? = nil
expectEqual(.init(nil), none.zeroTangentVectorInitializer())
let nestedSome: [Float]?? = [1, 2, 3]
expectEqual(.init(.init([0, 0, 0])), nestedSome.zeroTangentVectorInitializer())
let nestedNone: [Float]?? = nil
expectEqual(.init(nil), nestedNone.zeroTangentVectorInitializer())
}
// AdditiveArithmetic.zero
expectEqual(.init(Float.zero), Float?.TangentVector.zero)
expectEqual(.init([Float].TangentVector.zero), [Float]?.TangentVector.zero)
expectEqual(.init(.init(Float.zero)), Float??.TangentVector.zero)
expectEqual(.init(.init([Float].TangentVector.zero)), [Float]??.TangentVector.zero)
// AdditiveArithmetic.+, AdditiveArithmetic.-
do {
let some: Optional<Float>.TangentVector = .init(2)
let none: Optional<Float>.TangentVector = .init(nil)
expectEqual(.init(4), some + some)
expectEqual(.init(2), some + none)
expectEqual(.init(2), none + some)
expectEqual(.init(nil), none + none)
expectEqual(.init(0), some - some)
expectEqual(.init(2), some - none)
expectEqual(.init(-2), none - some)
expectEqual(.init(nil), none - none)
let nestedSome: Optional<Optional<Float>>.TangentVector = .init(.init(2))
let nestedNone: Optional<Optional<Float>>.TangentVector = .init(.init(nil))
expectEqual(.init(.init(4)), nestedSome + nestedSome)
expectEqual(.init(.init(2)), nestedSome + nestedNone)
expectEqual(.init(.init(2)), nestedNone + nestedSome)
expectEqual(.init(.init(nil)), nestedNone + nestedNone)
expectEqual(.init(.init(0)), nestedSome - nestedSome)
expectEqual(.init(.init(2)), nestedSome - nestedNone)
expectEqual(.init(.init(-2)), nestedNone - nestedSome)
expectEqual(.init(.init(nil)), nestedNone - nestedNone)
}
}
runAllTests()
| apache-2.0 | 75b596d34d51946c4153b2eded384fce | 31.718447 | 85 | 0.685163 | 3.833902 | false | true | false | false |
brentsimmons/Frontier | BeforeTheRename/FrontierData/FrontierData/Value/ValueType.swift | 1 | 2140 | //
// ValueType.swift
// FrontierData
//
// Created by Brent Simmons on 4/20/17.
// Copyright © 2017 Ranchero Software. All rights reserved.
//
import Foundation
public enum ValueType: Int {
// Use care -- the numbers are saved on disk inside symbol tables.
case uninitialized = -1
case noValue = 0
case char = 1
case int = 2
case long = 3
case oldString = 4
case binary = 5
case boolean = 6
case token = 7
case date = 8
case address = 9
case code = 10
case double = 11
case string = 12
case external = 13
case direction = 14
case password = 15
case osType = 16
case unused = 17
case point = 18
case qdRect = 19
case qdPattern = 20
case qdRGB = 21
case fixed = 22
case single = 23
case oldDouble = 24
case objSpec = 25
case fileSpec = 26
case alias = 27
case enumValue = 28
case list = 29
case record = 30
/* The following value types, outline - pictvaluetype, are never used directly.
The value would actually be .external; these are for flattening
external types into a ValueType. */
case outline = 31
case word = 32
case head = 33
case table = 34
case script = 35
case menu = 36
case qdPict = 37
}
public extension ValueType {
// MARK: Coercion
func commonCoercionType(otherValueType: ValueType) -> ValueType {
if self == otherValueType {
return self
}
if self.coercionWeight() >= otherValueType.coercionWeight() {
return self
}
return otherValueType
}
func coercionWeight() -> Int {
// OrigFrontier: langvalue.c cercionweight function.
switch self {
case .noValue, .uninitialized:
return 0
case .boolean:
return 1
case .int, .token:
return 2
case .direction, .char, .long, .osType, .point:
return 3
case .date:
return 4
case .fixed, .single:
return 5
case .double:
return 7
case .qdRect, .qdPattern, .qdRGB, .fileSpec, .alias, .address, .external:
return 8
case .objSpec:
return 9
case .string, .password:
return 10
case .binary:
return 11
case .list:
return 12
case .record:
return 13
default:
return 1
}
}
}
| gpl-2.0 | 92470500c9ae48aa45e68577fb967677 | 15.97619 | 80 | 0.652174 | 3.255708 | false | false | false | false |
devios1/Gravity | Class Support/UILabel+Gravity.swift | 1 | 2357 | //
// UILabel+Gravity.swift
// Gravity
//
// Created by Logan Murray on 2016-01-27.
// Copyright © 2016 Logan Murray. All rights reserved.
//
import Foundation
@available(iOS 9.0, *)
extension UILabel: GravityElement {
// public var recognizedAttributes: [String]? {
// get {
// return ["wrap"]
// }
// }
// public func processAttribute(node: GravityNode, attribute: String, value: GravityNode) -> GravityResult {
//// guard let stringValue = value.stringValue else {
//// return .NotHandled
//// }
//
// switch attribute {
// case "wrap":
// if value.boolValue == true {
// self.numberOfLines = 0
// }
//
// // TODO: we may want to set preferredMaxLayoutWidth to the label's maxWidth (possibly looking for a parental max?)
//
// return .Handled
//
// default:
// break
// }
//
// return .NotHandled//super.processAttribute(gravity, attribute: attribute, value: value)
// }
// public func processElement(node: GravityNode) {
public func handleAttribute(node: GravityNode, attribute: String?, value: GravityNode?) -> GravityResult {
if attribute == "wrap" || attribute == nil {
if let wrap = value?.boolValue {
self.numberOfLines = wrap ? 0 : 1
return .Handled
} else {
self.numberOfLines = 1
}
}
// label.setContentCompressionResistancePriority(100, forAxis: UILayoutConstraintAxis.Horizontal)
return .NotHandled
}
public func postprocessNode(node: GravityNode) {
switch node.gravity.horizontal { // TODO: should improve this, possibly by splitting into horizontalGravity and verticalGravity properties
case GravityDirection.Left:
self.textAlignment = NSTextAlignment.Left
break
case GravityDirection.Center:
self.textAlignment = NSTextAlignment.Center
break
case GravityDirection.Right:
self.textAlignment = NSTextAlignment.Right
break
// case GravityDirection.Wide:
// self.textAlignment = NSTextAlignment.Justified // does this make sense?
// break
default:
// TODO: throw
break
}
self.font = node.font
if node["textColor"] == nil {
self.textColor = node.color
}
if let maxWidth = node.maxWidth {
// FIXME: we probably want to improve this a lot, perhaps by using swizzling to insert logic during the layout pass
self.preferredMaxLayoutWidth = CGFloat(maxWidth)
}
}
} | mit | 500234fab489a6b0faa3903679be29ee | 26.091954 | 140 | 0.681239 | 3.647059 | false | false | false | false |
msfeldstein/Frameless | Frameless/HistoryManager.swift | 2 | 6158 | //
// HistoryManager.swift
// Frameless
//
// Created by Jay Stakelon on 8/6/15.
// Copyright (c) 2015 Jay Stakelon. All rights reserved.
//
import WebKit
class HistoryManager: NSObject {
static let manager = HistoryManager()
let _maxHistoryItems = 50
var _fullHistory: Array<HistoryEntry>?
var totalEntries: Int {
get {
return _fullHistory!.count
}
}
var studio: HistoryEntry?
var matches: Array<HistoryEntry> = Array<HistoryEntry>()
var history: Array<HistoryEntry> = Array<HistoryEntry>()
override init() {
super.init()
_fullHistory = readHistory()
}
func getHistoryDataFor(originalString: String) {
var stringToFind = originalString.lowercaseString
studio = nil
history.removeAll(keepCapacity: false)
matches.removeAll(keepCapacity: false)
var framerMatches = Array<HistoryEntry>()
var domainMatches = Array<HistoryEntry>()
var titleMatches = Array<HistoryEntry>()
for entry:HistoryEntry in _fullHistory! {
var entryUrl = entry.urlString.lowercaseString
var entryTitle = entry.title?.lowercaseString
if entryTitle?.rangeOfString("framer studio projects") != nil {
// Put Framer Studio home in the top matches
studio = entry
} else if entryUrl.rangeOfString(stringToFind) != nil {
if entryUrl.lowercaseString.rangeOfString(".framer") != nil {
// is it a framer project URL? these go first
framerMatches.insert(entry, atIndex: 0)
} else {
if entryUrl.hasPrefix(stringToFind) && entryUrl.lowercaseString.rangeOfString(".framer") == nil {
// is it a domain match? if it's a letter-for-letter match put in top matches
// unless it's a local Framer Studio URL because that list will get long
matches.append(entry)
} else {
// otherwise add to history
domainMatches.insert(entry, atIndex: 0)
}
}
} else if entryTitle?.rangeOfString(stringToFind) != nil {
// is it a title match? cause these go last
titleMatches.insert(entry, atIndex: 0)
}
history = framerMatches + domainMatches + titleMatches
}
NSNotificationCenter.defaultCenter().postNotificationName(HISTORY_UPDATED_NOTIFICATION, object: nil)
}
func addToHistory(webView: WKWebView) {
if NSUserDefaults.standardUserDefaults().objectForKey(AppDefaultKeys.KeepHistory.rawValue) as! Bool == true {
if let urlStr = webView.URL?.absoluteString as String! {
if verifyUniquenessOfURL(urlStr) {
checkForFramerStudio(webView)
var title = webView.title
if title == nil || title == "" {
title = " "
}
let historyEntry = HistoryEntry(url: webView.URL!, urlString: createDisplayURLString(webView.URL!), title: title)
_fullHistory?.append(historyEntry)
trimHistory()
saveHistory()
NSNotificationCenter.defaultCenter().postNotificationName(HISTORY_UPDATED_NOTIFICATION, object: nil)
}
}
}
}
func trimHistory() {
if let arr = _fullHistory {
if arr.count > _maxHistoryItems {
var count = arr.count as Int
var extraCount = count - _maxHistoryItems
var newarr = arr[extraCount...(arr.endIndex-1)]
_fullHistory = Array<HistoryEntry>(newarr)
}
}
}
func createDisplayURLString(url: NSURL) -> String {
var str = url.resourceSpecifier!
if str.hasPrefix("//") {
str = str.substringFromIndex(advance(str.startIndex, 2))
}
if str.hasPrefix("www.") {
str = str.substringFromIndex(advance(str.startIndex, 4))
}
if str.hasSuffix("/") {
str = str.substringToIndex(str.endIndex.predecessor())
}
return str
}
func verifyUniquenessOfURL(urlStr: String) -> Bool {
for entry:HistoryEntry in _fullHistory! {
let fullURLString = entry.url.absoluteString as String!
if fullURLString == urlStr {
return false
}
}
return true
}
func checkForFramerStudio(webView:WKWebView) {
// if this is a Framer Studio URL
if webView.title?.lowercaseString.rangeOfString("framer studio projects") != nil {
// remove old framer studios
var filteredHistory = _fullHistory!.filter({
return $0.title?.lowercaseString.rangeOfString("framer studio projects") == nil
})
_fullHistory = filteredHistory
saveHistory()
}
}
func clearHistory() {
history.removeAll(keepCapacity: false)
matches.removeAll(keepCapacity: false)
_fullHistory?.removeAll(keepCapacity: false)
saveHistory()
NSNotificationCenter.defaultCenter().postNotificationName(HISTORY_UPDATED_NOTIFICATION, object: nil)
}
func saveHistory() {
let archivedObject = NSKeyedArchiver.archivedDataWithRootObject(_fullHistory as Array<HistoryEntry>!)
let defaults = NSUserDefaults.standardUserDefaults()
defaults.setObject(archivedObject, forKey: AppDefaultKeys.History.rawValue)
defaults.synchronize()
}
func readHistory() -> Array<HistoryEntry>? {
if let unarchivedObject = NSUserDefaults.standardUserDefaults().objectForKey(AppDefaultKeys.History.rawValue) as? NSData {
return (NSKeyedUnarchiver.unarchiveObjectWithData(unarchivedObject) as? [HistoryEntry])!
} else {
return Array<HistoryEntry>()
}
}
}
| mit | 90f8c0d1b1d4cb55ce772be8ce6610e3 | 37.72956 | 133 | 0.584443 | 5.093466 | false | false | false | false |
raphaelseher/CE-App | CE/SearchViewController.swift | 1 | 15407 | //Event App with data from veranstaltungen.kaernten.at
//Copyright (C) 2015 Raphael Seher
//
//This program is free software; you can redistribute it and/or modify
//it under the terms of the GNU General Public License as published by
//the Free Software Foundation; either version 2 of the License, or
//(at your option) any later version.
//
//This program is distributed in the hope that it will be useful,
//but WITHOUT ANY WARRANTY; without even the implied warranty of
//MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
//GNU General Public License for more details.
//
//You should have received a copy of the GNU General Public License along
//with this program; if not, write to the Free Software Foundation, Inc.,
//51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
import UIKit
import CoreLocation
import MBProgressHUD
class SearchViewController: UIViewController, UITextFieldDelegate, UIPickerViewDataSource, UIPickerViewDelegate, CLLocationManagerDelegate, UITableViewDelegate {
let manager = CLLocationManager()
let dayMonthYearDateFormatter : NSDateFormatter = NSDateFormatter()
let timeFormatter : NSDateFormatter = NSDateFormatter()
@IBOutlet weak var searchViewLayoutTopConstraint: NSLayoutConstraint!
@IBOutlet weak var pickerViewTopAlignmentConstraint: NSLayoutConstraint!
@IBOutlet weak var datePickerTopAlignmentConstraint: NSLayoutConstraint!
@IBOutlet weak var searchView: UIView!
@IBOutlet weak var searchButton: UIButton!
@IBOutlet weak var datePickerView: UIView!
@IBOutlet weak var datePicker: UIDatePicker!
@IBOutlet weak var categoryPickerView: UIView!
@IBOutlet weak var categoryPicker: UIPickerView!
@IBOutlet weak var nearYouSwitch: UISwitch!
@IBOutlet weak var eventTableView: UITableView!
@IBOutlet weak var searchButtonImageView: UIImageView!
@IBOutlet weak var nothingFoundLabel: UILabel!
@IBOutlet weak var startDateTextField: UITextField! { didSet { startDateTextField.delegate = self } }
@IBOutlet weak var endDateTextField: UITextField! { didSet { endDateTextField.delegate = self } }
@IBOutlet weak var categorieTextField: UITextField! { didSet { categorieTextField.delegate = self } }
@IBOutlet weak var nearYouDistance: UITextField! { didSet { nearYouDistance.delegate = self } }
var arrowDownImage : UIImage? = UIImage(named:"arrow-down")!.imageWithRenderingMode(UIImageRenderingMode.AlwaysTemplate)
var activeTextField: UITextField!
var tapOutsideDatepickerRecognizer = UITapGestureRecognizer()
var tapOutsideCategoriepickerRecognizer = UITapGestureRecognizer()
var tapBackgroundRecognizer = UITapGestureRecognizer()
var isDatePickerOpen : Bool = false
var isCategoriePickerOpen : Bool = false
var isSearchViewOpen : Bool = true
var categories : [AnyObject]! = []
var choosenCategorie : Categories = Categories()
var eventsToDisplay : [AnyObject] = []
var userLocation : CLLocation = CLLocation()
override func viewDidLoad() {
super.viewDidLoad()
dayMonthYearDateFormatter.dateFormat = "dd.MM.YYYY"
timeFormatter.dateFormat = "HH:mm"
//add image to searchButtonImageView
self.searchButtonImageView.image = arrowDownImage
self.searchButtonImageView.tintColor = UIColor(red:0.11, green:0.38, blue:0.48, alpha:1.0)
//init location manager
self.manager.delegate = self
self.manager.desiredAccuracy = kCLLocationAccuracyBest
self.manager.distanceFilter = 500
//init tableview
let nib = UINib(nibName: "EventTableViewCell", bundle: nil)
self.eventTableView.registerNib(nib, forCellReuseIdentifier: "EventTableViewCell")
self.eventTableView.rowHeight = 320
//init gesture recognizers
self.tapOutsideDatepickerRecognizer = UITapGestureRecognizer(target: self, action: Selector("tapOutsideDatepicker"))
self.tapOutsideCategoriepickerRecognizer = UITapGestureRecognizer(target: self, action: Selector("tapOutsideCategoriepicker"))
self.tapBackgroundRecognizer = UITapGestureRecognizer(target: self, action:Selector("closeNumpad"))
self.startDateTextField.text = dayMonthYearDateFormatter.stringFromDate(NSDate())
self.endDateTextField.text = dayMonthYearDateFormatter.stringFromDate(NSDate())
//init categories
EventApi.sharedInstance().categories { (categ) -> Void in
self.categories = categ
//"Alle Kategorien" added
let allCategory = Categories()
allCategory.name = "Alle Kategorien"
allCategory.id = nil
self.categories.insert(allCategory, atIndex: 0)
//update choosen categorie
self.choosenCategorie = allCategory
self.categoryPicker.reloadAllComponents()
}
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
self.navigationController?.setNavigationBarHidden(true, animated: false)
//analytics
let tracker = GAI.sharedInstance().defaultTracker
tracker.set(kGAIScreenName, value: "SearchActivity")
let builder = GAIDictionaryBuilder.createScreenView()
tracker.send(builder.build() as [NSObject : AnyObject])
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: - Location
@IBAction func switchChanged(sender: UISwitch) {
if(sender.on) {
if CLLocationManager.locationServicesEnabled() {
if CLLocationManager.authorizationStatus() == .NotDetermined {
manager.requestWhenInUseAuthorization()
} else if CLLocationManager.authorizationStatus() == .AuthorizedWhenInUse {
self.nearYouSwitch.enabled = true
manager.startUpdatingLocation()
} else {
self.nearYouSwitch.enabled = false
}
}
} else {
manager.stopUpdatingLocation()
}
}
func locationManager(manager: CLLocationManager, didChangeAuthorizationStatus status: CLAuthorizationStatus) {
if status == CLAuthorizationStatus.AuthorizedWhenInUse {
manager.startUpdatingLocation()
}
}
func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
print("LocationUpdate")
print(locations)
self.userLocation = locations.last as CLLocation!
}
// MARK: - Search Button
@IBAction func searchButtonTouch(sender: AnyObject) {
//analytics
GAI.sharedInstance().defaultTracker.send(GAIDictionaryBuilder.createEventWithCategory("UX", action: "Button click", label: "Search", value: nil).build() as [NSObject : AnyObject])
if self.isSearchViewOpen {
MBProgressHUD.showHUDAddedTo(self.view, animated: true)
closeSearchView()
} else {
MBProgressHUD.hideHUDForView(self.view, animated: true)
openSearchView()
return
}
var lat : Double = 0
var lon : Double = 0
var distance : Int32 = 0
//close pickers when open
if isCategoriePickerOpen {
self.updateCategorieTextField()
self.closeCategoryPicker()
} else if isDatePickerOpen {
self.updateDateTextField()
self.closeDatePicker()
}
if self.nearYouDistance.isFirstResponder() {
self.closeNumpad()
}
if self.nearYouSwitch.on {
lat = self.userLocation.coordinate.latitude
lon = self.userLocation.coordinate.longitude
distance = (self.nearYouDistance.text as NSString!).intValue
}
//do search
EventApi.sharedInstance().eventsFromPage(0, andPageSize: 10, withCategorie: self.choosenCategorie.id, fromDate: nil, toDate: nil, withLat: lat, andLon: lon, andDistance: distance) { (events, links) -> Void in
MBProgressHUD.hideHUDForView(self.view, animated: true)
self.eventsToDisplay = events
self.eventTableView.reloadData()
if events.count == 0 {
self.nothingFoundLabel.hidden = false
} else {
self.nothingFoundLabel.hidden = true
}
}
}
// MARK: - Update TextFields
func updateDateTextField() {
self.activeTextField.text = dayMonthYearDateFormatter.stringFromDate(self.datePicker.date)
self.activeTextField = nil
}
func updateCategorieTextField() {
self.categorieTextField.text = self.choosenCategorie.name
}
// MARK: - Gesture Recognizer Selector
func tapOutsideDatepicker() {
self.updateDateTextField()
self.closeDatePicker()
}
func tapOutsideCategoriepicker() {
self.updateCategorieTextField()
self.closeCategoryPicker()
}
func closeNumpad() {
self.nearYouDistance.resignFirstResponder()
self.view.removeGestureRecognizer(tapBackgroundRecognizer)
}
// MARK: - Picker Source & Delegate
func numberOfComponentsInPickerView(pickerView: UIPickerView) -> Int {
return 1
}
func pickerView(pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
return self.categories.count
}
func pickerView(pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
return self.categories[row].name
}
func pickerView(pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
self.choosenCategorie = self.categories[row] as! Categories
}
// MARK: - UITextField Delegates
func textFieldShouldBeginEditing(textField: UITextField) -> Bool {
//close pickers when open
if isCategoriePickerOpen {
self.updateCategorieTextField()
self.closeCategoryPicker()
return false;
} else if isDatePickerOpen {
self.updateDateTextField()
self.closeDatePicker()
return false;
}
if self.nearYouDistance.isFirstResponder() {
self.closeNumpad()
return false;
}
if textField.tag == 1 {
self.openCategoryPicker()
} else if textField.tag == 2{
self.openDatePicker()
self.activeTextField = textField
} else {
self.view.addGestureRecognizer(tapBackgroundRecognizer)
return true;
}
return false;
}
func textFieldShouldReturn(textField: UITextField) -> Bool {
textField.resignFirstResponder();
return false;
}
// MARK: - Animations
func openSearchView() {
if !isSearchViewOpen {
self.view.layoutIfNeeded()
UIView.animateWithDuration(0.5, delay: 0.0, options: UIViewAnimationOptions.CurveEaseOut, animations: {
self.searchViewLayoutTopConstraint.constant += self.searchView.frame.size.height - 20
self.searchButton.backgroundColor = UIColor(red:0.11, green:0.38, blue:0.48, alpha:1.0)
self.view.layoutIfNeeded()
}, completion: {
void in
self.isSearchViewOpen = true
})
}
}
func closeSearchView() {
if isSearchViewOpen {
self.view.layoutIfNeeded()
UIView.animateWithDuration(0.5, delay: 0.0, options: UIViewAnimationOptions.CurveEaseOut, animations: {
self.searchViewLayoutTopConstraint.constant -= self.searchView.frame.size.height - 20
self.searchButton.backgroundColor = UIColor(red:0.16, green:0.58, blue:0.73, alpha:1.0)
self.view.layoutIfNeeded()
}, completion: {
void in
self.isSearchViewOpen = false
})
}
}
func openDatePicker() {
if !isDatePickerOpen {
isDatePickerOpen = true
self.view.addGestureRecognizer(tapOutsideDatepickerRecognizer)
self.datePickerView.layoutIfNeeded()
UIView.animateWithDuration(0.5, delay: 0.0, options: UIViewAnimationOptions.CurveEaseIn, animations: {
self.datePickerTopAlignmentConstraint.constant += self.datePickerView.frame.size.height
self.datePickerView.layoutIfNeeded()
}, completion: nil)
}
}
func closeDatePicker() {
if isDatePickerOpen {
isDatePickerOpen = false
self.view.removeGestureRecognizer(tapOutsideDatepickerRecognizer)
self.datePickerView.layoutIfNeeded()
UIView.animateWithDuration(0.5, delay: 0.0, options: UIViewAnimationOptions.CurveEaseOut, animations: {
self.datePickerTopAlignmentConstraint.constant -= self.datePickerView.frame.size.height
self.datePickerView.layoutIfNeeded()
}, completion: nil)
}
}
func openCategoryPicker() {
if !isCategoriePickerOpen && categories.count > 0 {
isCategoriePickerOpen = true
self.view.addGestureRecognizer(tapOutsideCategoriepickerRecognizer)
self.categoryPickerView.layoutIfNeeded()
UIView.animateWithDuration(0.5, delay: 0.0, options: UIViewAnimationOptions.CurveEaseIn, animations: {
self.pickerViewTopAlignmentConstraint.constant += self.categoryPickerView.frame.size.height
self.categoryPickerView.layoutIfNeeded()
}, completion: nil)
}
}
func closeCategoryPicker() {
if isCategoriePickerOpen {
isCategoriePickerOpen = false
self.view.removeGestureRecognizer(tapOutsideCategoriepickerRecognizer)
self.categoryPickerView.layoutIfNeeded()
UIView.animateWithDuration(0.5, delay: 0.0, options: UIViewAnimationOptions.CurveEaseOut, animations: {
self.pickerViewTopAlignmentConstraint.constant -= self.categoryPickerView.frame.size.height
self.categoryPickerView.layoutIfNeeded()
}, completion: nil)
}
}
// MARK: - TableView Delegate
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return self.eventsToDisplay.count
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell:EventTableViewCell = self.eventTableView.dequeueReusableCellWithIdentifier("EventTableViewCell") as! EventTableViewCell
//reset cell
cell.eventStartDate.hidden = false
cell.eventStartDateLabel.hidden = false
let event : Event = self.eventsToDisplay[indexPath.row] as! Event
cell.eventCategorieLabel.text = event.categories.first?.name
cell.eventTitleLabel.text = event.name;
cell.eventImageView.setImageWithURL(NSURL(string: event.image.contentUrl))
cell.eventLocationLabel.text = event.location.name
cell.eventStartDate.text = timeFormatter.stringFromDate(event.startDate)
if let endDate = event.endDate as NSDate? {
cell.eventEndDate.text = self.timeFormatter.stringFromDate(event.endDate)
cell.eventStartDateLabel.text = "von"
cell.eventEndDateLabel.text = "bis"
} else {
cell.eventEndDateLabel.text = "um"
cell.eventEndDate.text = timeFormatter.stringFromDate(event.startDate)
cell.eventStartDate.hidden = true
cell.eventStartDateLabel.hidden = true
}
cell.layoutIfNeeded()
return cell
}
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
performSegueWithIdentifier("showEventDetail", sender: self)
}
// 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?) {
if segue.identifier == "showEventDetail" {
if let destination = segue.destinationViewController as? EventDetailViewController {
if let blogIndex = self.eventTableView.indexPathForSelectedRow?.row {
destination.event = self.eventsToDisplay[blogIndex] as! Event
}
}
}
}
}
| gpl-2.0 | 2740585cad9f38f3a53e4a3040f39937 | 35.423168 | 212 | 0.719154 | 4.781813 | false | false | false | false |
rjeprasad/RappleColorPicker | Pod/Classes/RappleColorPickerViewController.swift | 1 | 14312 | /* **
RappleColorPicker.swift
Custom Activity Indicator with swift
Created by Rajeev Prasad on 28/11/15.
The MIT License (MIT)
Copyright (c) 2018 Rajeev Prasad <[email protected]>
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
** */
import UIKit
class RappleColorPickerViewController: UIViewController {
fileprivate var collectionView : UICollectionView!
fileprivate var titleLabel : UILabel!
var completion: (( _ color: UIColor, _ tag: Int) -> Void)?
var tag: Int = 1
var size: CGSize = CGSize(width: 230, height: 384)
var cellSize = CGSize(width: 20, height: 20)
var attributes : [RappleCPAttributeKey : AnyObject] = [
.Title : "Color Picker" as AnyObject,
.BGColor : UIColor.black,
.TintColor : UIColor.white,
.Style : RappleCPStyleCircle as AnyObject
]
fileprivate var colorDic = [Int: [UIColor]]()
fileprivate var allColors = [UIColor]()
override func viewDidLoad() {
super.viewDidLoad()
setAllColor()
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
self.view.backgroundColor = attributes[.BGColor] as? UIColor
self.view.layer.cornerRadius = 4.0
self.view.layer.masksToBounds = true
if let border = attributes[.BorderColor] as? UIColor {
self.view.layer.borderColor = border.cgColor
self.view.layer.borderWidth = 2
} else {
self.view.layer.borderWidth = 0
}
if let title = attributes[.Title] as? String {
titleLabel = UILabel(frame: .zero)
titleLabel.translatesAutoresizingMaskIntoConstraints = false
titleLabel.font = UIFont.systemFont(ofSize: 18, weight: .medium)
titleLabel.textAlignment = .center
titleLabel.textColor = attributes[.TintColor] as? UIColor
titleLabel.text = title
self.view.addSubview(titleLabel)
}
collectionView = UICollectionView(frame: .zero, collectionViewLayout: UICollectionViewFlowLayout())
collectionView.translatesAutoresizingMaskIntoConstraints = false
collectionView.dataSource = self
collectionView.delegate = self
collectionView.register(UICollectionViewCell.self, forCellWithReuseIdentifier: "Cell")
collectionView.backgroundColor = UIColor.clear
self.view.addSubview(collectionView)
collectionView.reloadData()
if titleLabel != nil {
titleLabel.topAnchor.constraint(equalTo: self.view.topAnchor, constant: 8).isActive = true
titleLabel.leftAnchor.constraint(equalTo: self.view.leftAnchor).isActive = true
titleLabel.rightAnchor.constraint(equalTo: self.view.rightAnchor).isActive = true
titleLabel.heightAnchor.constraint(equalToConstant: 27).isActive = true
collectionView.topAnchor.constraint(equalTo: titleLabel.bottomAnchor).isActive = true
} else {
collectionView.topAnchor.constraint(equalTo: self.view.topAnchor).isActive = true
}
collectionView.leftAnchor.constraint(equalTo: self.view.leftAnchor).isActive = true
collectionView.rightAnchor.constraint(equalTo: self.view.rightAnchor).isActive = true
collectionView.bottomAnchor.constraint(equalTo: self.view.bottomAnchor).isActive = true
self.view.layoutIfNeeded()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
}
extension RappleColorPickerViewController: UICollectionViewDataSource, UICollectionViewDelegate, UICollectionViewDelegateFlowLayout {
func numberOfSections(in collectionView: UICollectionView) -> Int {
return 1
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return allColors.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "Cell", for: indexPath)
cell.backgroundColor = getColor((indexPath as NSIndexPath).section, row: (indexPath as NSIndexPath).row)
if attributes[.Style] as? String == RappleCPStyleCircle {
cell.layer.cornerRadius = cellSize.width / 2
} else {
cell.layer.cornerRadius = 1.0
}
cell.layer.borderColor = (attributes[.TintColor] as? UIColor)?.cgColor
cell.layer.borderWidth = 1.0
return cell
}
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
let color = getColor((indexPath as NSIndexPath).section, row: (indexPath as NSIndexPath).row)
self.completion?(color, tag)
}
func getColor(_ section:Int, row:Int) -> UIColor {
return allColors[row]
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
return cellSize
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat {
return 2
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumInteritemSpacingForSectionAt section: Int) -> CGFloat {
return 2
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets {
return UIEdgeInsets(top: 4, left: 4, bottom: 4, right: 4)
}
}
extension RappleColorPickerViewController {
fileprivate func setAllColor(){
colorDic[0] = [
UIColor(red: 1.0, green: 1.0, blue: 1.0, alpha: 1.0),
UIColor(red: 0.886274509803922, green: 0.886274509803922, blue: 0.886274509803922, alpha: 1.0),
UIColor(red: 0.666666666666667, green: 0.666666666666667, blue: 0.666666666666667, alpha: 1.0),
UIColor(red: 0.43921568627451, green: 0.43921568627451, blue: 0.43921568627451, alpha: 1.0),
UIColor(red: 0.219607843137255, green: 0.219607843137255, blue: 0.219607843137255, alpha: 1.0),
UIColor(red: 0.109803921568627, green: 0.109803921568627, blue: 0.109803921568627, alpha: 1.0),
UIColor(red: 0.0, green: 0.0, blue: 0.0, alpha: 1.0)
]
colorDic[1] = [
UIColor(red: 0.847058823529412, green: 1.0, blue: 0.972549019607843, alpha: 1.0),
UIColor(red: 0.568627450980392, green: 1.0, blue: 0.925490196078431, alpha: 1.0),
UIColor(red: 0.0, green: 1.0, blue: 0.831372549019608, alpha: 1.0),
UIColor(red: 0.0, green: 0.717647058823529, blue: 0.6, alpha: 1.0),
UIColor(red: 0.0, green: 0.458823529411765, blue: 0.380392156862745, alpha: 1.0),
UIColor(red: 0.0, green: 0.329411764705882, blue: 0.274509803921569, alpha: 1.0),
UIColor(red: 0.0, green: 0.2, blue: 0.164705882352941, alpha: 1.0)
]
colorDic[2] = [
UIColor(red: 0.847058823529412, green: 1.0, blue: 0.847058823529412, alpha: 1.0),
UIColor(red: 0.63921568627451, green: 1.0, blue: 0.63921568627451, alpha: 1.0),
UIColor(red: 0.219607843137255, green: 1.0, blue: 0.219607843137255, alpha: 1.0),
UIColor(red: 0.0, green: 0.83921568627451, blue: 0.0, alpha: 1.0),
UIColor(red: 0.0, green: 0.517647058823529, blue: 0.0, alpha: 1.0),
UIColor(red: 0.0, green: 0.356862745098039, blue: 0.0, alpha: 1.0),
UIColor(red: 0.0, green: 0.2, blue: 0.0, alpha: 1.0)
]
colorDic[3] = [
UIColor(red: 1.0, green: 1.0, blue: 0.847058823529412, alpha: 1.0),
UIColor(red: 1.0, green: 1.0, blue: 0.568627450980392, alpha: 1.0),
UIColor(red: 1.0, green: 1.0, blue: 0.0, alpha: 1.0),
UIColor(red: 0.717647058823529, green: 0.717647058823529, blue: 0.0, alpha: 1.0),
UIColor(red: 0.458823529411765, green: 0.458823529411765, blue: 0.0, alpha: 1.0),
UIColor(red: 0.329411764705882, green: 0.329411764705882, blue: 0.0, alpha: 1.0),
UIColor(red: 0.2, green: 0.2, blue: 0.0, alpha: 1.0)
]
colorDic[4] = [
UIColor(red: 1.0, green: 0.92156862745098, blue: 0.847058823529412, alpha: 1.0),
UIColor(red: 1.0, green: 0.83921568627451, blue: 0.67843137254902, alpha: 1.0),
UIColor(red: 1.0, green: 0.666666666666667, blue: 0.337254901960784, alpha: 1.0),
UIColor(red: 1.0, green: 0.498039215686275, blue: 0.0, alpha: 1.0),
UIColor(red: 0.627450980392157, green: 0.313725490196078, blue: 0.0, alpha: 1.0),
UIColor(red: 0.43921568627451, green: 0.219607843137255, blue: 0.0, alpha: 1.0),
UIColor(red: 0.247058823529412, green: 0.12156862745098, blue: 0.0, alpha: 1.0)
]
colorDic[5] = [
UIColor(red: 1.0, green: 0.886274509803922, blue: 0.847058823529412, alpha: 1.0),
UIColor(red: 1.0, green: 0.756862745098039, blue: 0.67843137254902, alpha: 1.0),
UIColor(red: 1.0, green: 0.501960784313725, blue: 0.337254901960784, alpha: 1.0),
UIColor(red: 1.0, green: 0.247058823529412, blue: 0.0, alpha: 1.0),
UIColor(red: 0.658823529411765, green: 0.164705882352941, blue: 0.0, alpha: 1.0),
UIColor(red: 0.47843137254902, green: 0.117647058823529, blue: 0.0, alpha: 1.0),
UIColor(red: 0.298039215686275, green: 0.0745098039215686, blue: 0.0, alpha: 1.0)
]
colorDic[6] = [
UIColor(red: 1.0, green: 0.847058823529412, blue: 0.847058823529412, alpha: 1.0),
UIColor(red: 1.0, green: 0.67843137254902, blue: 0.67843137254902, alpha: 1.0),
UIColor(red: 1.0, green: 0.337254901960784, blue: 0.337254901960784, alpha: 1.0),
UIColor(red: 1.0, green: 0.0, blue: 0.0, alpha: 1.0),
UIColor(red: 0.627450980392157, green: 0.0, blue: 0.0, alpha: 1.0),
UIColor(red: 0.43921568627451, green: 0.0, blue: 0.0, alpha: 1.0),
UIColor(red: 0.247058823529412, green: 0.0, blue: 0.0, alpha: 1.0)
]
colorDic[7] = [
UIColor(red: 1.0, green: 0.847058823529412, blue: 1.0, alpha: 1.0),
UIColor(red: 1.0, green: 0.63921568627451, blue: 1.0, alpha: 1.0),
UIColor(red: 1.0, green: 0.219607843137255, blue: 1.0, alpha: 1.0),
UIColor(red: 0.83921568627451, green: 0.0, blue: 0.83921568627451, alpha: 1.0),
UIColor(red: 0.517647058823529, green: 0.0, blue: 0.517647058823529, alpha: 1.0),
UIColor(red: 0.356862745098039, green: 0.0, blue: 0.356862745098039, alpha: 1.0),
UIColor(red: 0.2, green: 0.0, blue: 0.2, alpha: 1.0)
]
colorDic[8] = [
UIColor(red: 0.92156862745098, green: 0.847058823529412, blue: 1.0, alpha: 1.0),
UIColor(red: 0.83921568627451, green: 0.67843137254902, blue: 1.0, alpha: 1.0),
UIColor(red: 0.666666666666667, green: 0.337254901960784, blue: 1.0, alpha: 1.0),
UIColor(red: 0.498039215686275, green: 0.0, blue: 1.0, alpha: 1.0),
UIColor(red: 0.298039215686275, green: 0.0, blue: 0.6, alpha: 1.0),
UIColor(red: 0.2, green: 0.0, blue: 0.4, alpha: 1.0),
UIColor(red: 0.0980392156862745, green: 0.0, blue: 0.2, alpha: 1.0)
]
colorDic[9] = [
UIColor(red: 0.847058823529412, green: 0.847058823529412, blue: 1.0, alpha: 1.0),
UIColor(red: 0.67843137254902, green: 0.67843137254902, blue: 1.0, alpha: 1.0),
UIColor(red: 0.337254901960784, green: 0.337254901960784, blue: 1.0, alpha: 1.0),
UIColor(red: 0.0, green: 0.0, blue: 1.0, alpha: 1.0),
UIColor(red: 0.0, green: 0.0, blue: 0.627450980392157, alpha: 1.0),
UIColor(red: 0.0, green: 0.0, blue: 0.43921568627451, alpha: 1.0),
UIColor(red: 0.0, green: 0.0, blue: 0.247058823529412, alpha: 1.0)
]
colorDic[10] = [
UIColor(red: 0.847058823529412, green: 0.898039215686275, blue: 1.0, alpha: 1.0),
UIColor(red: 0.67843137254902, green: 0.784313725490196, blue: 1.0, alpha: 1.0),
UIColor(red: 0.337254901960784, green: 0.556862745098039, blue: 1.0, alpha: 1.0),
UIColor(red: 0.0, green: 0.333333333333333, blue: 1.0, alpha: 1.0),
UIColor(red: 0.0, green: 0.2, blue: 0.6, alpha: 1.0),
UIColor(red: 0.0, green: 0.133333333333333, blue: 0.4, alpha: 1.0),
UIColor(red: 0.0, green: 0.0666666666666667, blue: 0.2, alpha: 1.0)
]
for i in 0...10 {
allColors += colorDic[i]!
}
}
}
| mit | bfe960b429cc75a0561a5343a31c385d | 46.866221 | 175 | 0.628773 | 3.738767 | false | false | false | false |
tinrobots/CoreDataPlus | Tests/NSManagedObjectContextInvestigationTests.swift | 1 | 15405 | // CoreDataPlus
import CoreData
import XCTest
final class NSManagedObjectContextInvestigationTests: InMemoryTestCase {
/// Investigation test: calling refreshAllObjects calls refreshObject:mergeChanges on all objects in the context.
func testInvestigationRefreshAllObjects() throws {
let viewContext = container.viewContext
let car1 = Car(context: viewContext)
car1.numberPlate = "car1"
let car2 = Car(context: viewContext)
car2.numberPlate = "car2"
try viewContext.save()
car1.numberPlate = "car1_updated"
viewContext.refreshAllObjects()
XCTAssertFalse(car1.isFault)
XCTAssertTrue(car2.isFault)
XCTAssertEqual(car1.numberPlate, "car1_updated")
}
/// Investigation test: KVO is fired whenever a property changes (even if the object is not saved in the context).
func testInvestigationKVO() throws {
let context = container.viewContext
let expectation = self.expectation(description: "\(#function)\(#line)")
let sportCar1 = SportCar(context: context)
var count = 0
let token = sportCar1.observe(\.maker, options: .new) { (car, changes) in
count += 1
if count == 2 {
expectation.fulfill()
}
}
sportCar1.maker = "McLaren"
sportCar1.model = "570GT"
sportCar1.numberPlate = "203"
sportCar1.maker = "McLaren 2"
try context.save()
waitForExpectations(timeout: 10)
token.invalidate()
}
/// Investigation test: automaticallyMergesChangesFromParent behaviour
func testInvestigationAutomaticallyMergesChangesFromParent() throws {
// automaticallyMergesChangesFromParent = true
do {
let psc = NSPersistentStoreCoordinator(managedObjectModel: model)
let storeURL = URL.newDatabaseURL(withID: UUID())
try psc.addPersistentStore(ofType: NSSQLiteStoreType, configurationName: nil, at: storeURL, options: nil)
let parentContext = NSManagedObjectContext(concurrencyType: .mainQueueConcurrencyType)
parentContext.persistentStoreCoordinator = psc
let car1 = Car(context: parentContext)
car1.maker = "FIAT"
car1.model = "Panda"
car1.numberPlate = UUID().uuidString
try parentContext.save()
let childContext = NSManagedObjectContext(concurrencyType: .privateQueueConcurrencyType)
childContext.parent = parentContext
childContext.automaticallyMergesChangesFromParent = true
let childCar = try childContext.performAndWaitResult { context -> Car in
let car = try XCTUnwrap(try Car.existingObject(with: car1.objectID, in: context))
XCTAssertEqual(car.maker, "FIAT")
return car
}
try parentContext.performSaveAndWait { context in
let car = try XCTUnwrap(try Car.existingObject(with: car1.objectID, in: context))
XCTAssertEqual(car.maker, "FIAT")
car.maker = "😀"
XCTAssertEqual(car.maker, "😀")
}
// this will fail without automaticallyMergesChangesFromParent to true
childContext.performAndWait {
XCTAssertEqual(childCar.maker, "😀")
}
}
// automaticallyMergesChangesFromParent = false
do {
let psc = NSPersistentStoreCoordinator(managedObjectModel: model)
let storeURL = URL.newDatabaseURL(withID: UUID())
try psc.addPersistentStore(ofType: NSSQLiteStoreType, configurationName: nil, at: storeURL, options: nil)
let parentContext = NSManagedObjectContext(concurrencyType: .mainQueueConcurrencyType)
parentContext.persistentStoreCoordinator = psc
let car1 = Car(context: parentContext)
car1.maker = "FIAT"
car1.model = "Panda"
car1.numberPlate = UUID().uuidString
try parentContext.save()
let childContext = NSManagedObjectContext(concurrencyType: .privateQueueConcurrencyType)
childContext.parent = parentContext
childContext.automaticallyMergesChangesFromParent = false
let childCar = try childContext.performAndWaitResult { context -> Car in
let car = try XCTUnwrap(try Car.existingObject(with: car1.objectID, in: context))
XCTAssertEqual(car.maker, "FIAT")
return car
}
try parentContext.performSaveAndWait { context in
let car = try XCTUnwrap(try Car.existingObject(with: car1.objectID, in: context))
XCTAssertEqual(car.maker, "FIAT")
car.maker = "😀"
XCTAssertEqual(car.maker, "😀")
}
childContext.performAndWait {
XCTAssertEqual(childCar.maker, "FIAT") // no changes
}
}
// automaticallyMergesChangesFromParent = true
do {
let parentContext = container.viewContext
let car1 = Car(context: parentContext)
car1.maker = "FIAT"
car1.model = "Panda"
car1.numberPlate = UUID().uuidString
try parentContext.save()
let childContext = NSManagedObjectContext(concurrencyType: .privateQueueConcurrencyType)
childContext.parent = parentContext
childContext.automaticallyMergesChangesFromParent = true
let childCar = try childContext.performAndWaitResult { context -> Car in
let car = try XCTUnwrap(try Car.existingObject(with: car1.objectID, in: context))
XCTAssertEqual(car.maker, "FIAT")
return car
}
try parentContext.performSaveAndWait { context in
let car = try XCTUnwrap(try Car.existingObject(with: car1.objectID, in: context))
XCTAssertEqual(car.maker, "FIAT")
car.maker = "😀"
XCTAssertEqual(car.maker, "😀")
}
// this will fail without automaticallyMergesChangesFromParent to true
childContext.performAndWait {
XCTAssertEqual(childCar.maker, "😀")
}
}
// automaticallyMergesChangesFromParent = false
do {
let parentContext = container.viewContext
let car1 = Car(context: parentContext)
car1.maker = "FIAT"
car1.model = "Panda"
car1.numberPlate = UUID().uuidString
try parentContext.save()
let childContext = NSManagedObjectContext(concurrencyType: .privateQueueConcurrencyType)
childContext.parent = parentContext
childContext.automaticallyMergesChangesFromParent = false
let childCar = try childContext.performAndWaitResult { context -> Car in
let car = try XCTUnwrap(try Car.existingObject(with: car1.objectID, in: context))
XCTAssertEqual(car.maker, "FIAT")
return car
}
try parentContext.performSaveAndWait { context in
let car = try XCTUnwrap(try Car.existingObject(with: car1.objectID, in: context))
XCTAssertEqual(car.maker, "FIAT")
car.maker = "😀"
XCTAssertEqual(car.maker, "😀")
}
childContext.performAndWait {
XCTAssertEqual(childCar.maker, "FIAT") // no changes
}
}
}
func testInvestigationStalenessInterval() throws {
// Given
let context = container.viewContext
let car = Car(context: context)
car.maker = "FIAT"
car.model = "Panda"
car.numberPlate = UUID().uuidString
try context.save()
let fiatPredicate = NSPredicate(format: "%K == %@", #keyPath(Car.maker), "FIAT")
let result = try Car.batchUpdate(using: context) {
$0.resultType = .updatedObjectIDsResultType
$0.propertiesToUpdate = [#keyPath(Car.maker): "FCA"]
$0.includesSubentities = true
$0.predicate = fiatPredicate
}
XCTAssertEqual(result.updates?.count, 1)
// When, Then
car.refresh()
XCTAssertEqual(car.maker, "FIAT")
// When, Then
context.refreshAllObjects()
XCTAssertEqual(car.maker, "FIAT")
// When, Then
context.stalenessInterval = 0 // issue a new fetch request instead of using the row cache
car.refresh()
XCTAssertEqual(car.maker, "FCA")
context.stalenessInterval = -1 // default
// The default is a negative value, which represents infinite staleness allowed. 0.0 represents “no staleness acceptable”.
}
func testInvestigationShouldRefreshRefetchedObjectsIsStillBroken() throws {
// https://mjtsai.com/blog/2019/10/17/
// I've opened a feedback myself too: FB7419788
// Given
let readContext = container.viewContext
let writeContext = container.newBackgroundContext()
var writeCar: Car? = nil
try writeContext.performAndWaitResult {
writeCar = Car(context: writeContext)
writeCar?.maker = "FIAT"
writeCar?.model = "Panda"
writeCar?.numberPlate = UUID().uuidString
try $0.save()
}
// When
var readEntity: Car? = nil
readContext.performAndWait {
readEntity = try! readContext.fetch(Car.newFetchRequest()).first!
// Initially the attribute should be FIAT
XCTAssertNotNil(readEntity)
XCTAssertEqual(readEntity?.maker, "FIAT")
}
try writeContext.performAndWaitResult {
writeCar?.maker = "FCA"
try $0.save()
}
// Then
readContext.performAndWait {
let request = Car.newFetchRequest()
request.shouldRefreshRefetchedObjects = true
_ = try! readContext.fetch(request)
// ⚠️ Now the attribute should be FCA, but it is still FIAT
// This should be XCTAssertEqual, XCTAssertNotEqual is used only to make the test pass until
// the problem is fixed
XCTAssertNotEqual(readEntity?.maker, "FCA")
readContext.refresh(readEntity!, mergeChanges: false)
// However, manually refreshing does update it to FCA
XCTAssertEqual(readEntity?.maker, "FCA")
}
}
func testInvestigationTransientProperties() throws {
let container = InMemoryPersistentContainer.makeNew()
let viewContext = container.viewContext
let car = Car(context: viewContext)
car.maker = "FIAT"
car.model = "Panda"
car.numberPlate = UUID().uuidString
car.currentDrivingSpeed = 50
try viewContext.save()
XCTAssertEqual(car.currentDrivingSpeed, 50)
viewContext.refreshAllObjects()
XCTAssertEqual(car.currentDrivingSpeed, 0)
car.currentDrivingSpeed = 100
XCTAssertEqual(car.currentDrivingSpeed, 100)
viewContext.reset()
XCTAssertEqual(car.currentDrivingSpeed, 0)
}
func testInvestigationTransientPropertiesBehaviorInParentChildContextRelationship() throws {
let container = InMemoryPersistentContainer.makeNew()
let viewContext = container.viewContext
let childContext = viewContext.newBackgroundContext(asChildContext: true)
var carID: NSManagedObjectID?
let plateNumber = UUID().uuidString
let predicate = NSPredicate(format: "%K == %@", #keyPath(Car.numberPlate), plateNumber)
childContext.performAndWait {
let car = Car(context: $0)
car.maker = "FIAT"
car.model = "Panda"
car.numberPlate = plateNumber
car.currentDrivingSpeed = 50
try! $0.save()
carID = car.objectID
XCTAssertEqual(car.currentDrivingSpeed, 50)
print($0.registeredObjects)
car.currentDrivingSpeed = 20 // ⚠️ dirting the context again
}
childContext.performAndWait {
print(childContext.registeredObjects)
}
let id = try XCTUnwrap(carID)
let car = try XCTUnwrap(Car.object(with: id, in: viewContext))
XCTAssertEqual(car.maker, "FIAT")
XCTAssertEqual(car.model, "Panda")
XCTAssertEqual(car.numberPlate, plateNumber)
XCTAssertEqual(car.currentDrivingSpeed, 50, "The transient property value should be equal to the one saved by the child context.")
try childContext.performAndWait {
XCTAssertFalse(childContext.registeredObjects.isEmpty) // ⚠️ this condition is verified only because we have dirted the context after a save
let car = try XCTUnwrap($0.object(with: id) as? Car)
XCTAssertEqual(car.currentDrivingSpeed, 20)
try $0.save()
}
XCTAssertEqual(car.currentDrivingSpeed, 20, "The transient property value should be equal to the one saved by the child context.")
try childContext.performAndWait {
XCTAssertTrue(childContext.registeredObjects.isEmpty) // ⚠️ it seems that after a save, the objects are freed unless the context gets dirted again
let car = try XCTUnwrap(try Car.fetchUnique(in: $0, where: predicate))
XCTAssertEqual(car.currentDrivingSpeed, 0)
}
// see testInvestigationContextRegisteredObjectBehaviorAfterSaving
}
func testInvestigationContextRegisteredObjectBehaviorAfterSaving() throws {
let context = container.newBackgroundContext()
// A context keeps registered objects until it's dirted
try context.performAndWait {
let person = Person(context: context)
person.firstName = "Alessandro"
person.lastName = "Marzoli"
try $0.save()
let person2 = Person(context: context)
person2.firstName = "Andrea"
person2.lastName = "Marzoli"
// context dirted because person2 isn't yet saved
}
context.performAndWait {
XCTAssertFalse(context.registeredObjects.isEmpty)
}
try context.performAndWait {
try $0.save()
// context is no more dirted, everything has been saved
}
context.performAndWait {
XCTAssertTrue(context.registeredObjects.isEmpty)
}
try context.performAndWait {
let person = Person(context: context)
person.firstName = "Valedmaro"
person.lastName = "Marzoli"
try $0.save()
// context is no more dirted, everything has been saved
}
context.performAndWait {
XCTAssertTrue(context.registeredObjects.isEmpty)
}
}
func testFetchAsNSArrayUsingBatchSize() throws {
// For this investigation you have to enable SQL logs in the test plan (-com.apple.CoreData.SQLDebug 3)
let context = container.viewContext
context.fillWithSampleData()
try context.save()
context.reset()
// NSFetchedResultsController isn't affected
do {
let request = Car.fetchRequest()
request.addSortDescriptors([NSSortDescriptor(key: #keyPath(Car.maker), ascending: true)])
request.fetchBatchSize = 10
let frc = NSFetchedResultsController(fetchRequest: request, managedObjectContext: context, sectionNameKeyPath: nil, cacheName: nil)
try frc.performFetch()
// A SELECT with LIMIT 10 is executed every 10 looped cars ✅
frc.fetchedObjects?.forEach { car in
let _ = car as! Car
}
}
// Running a Swift fetch request with a batch size doesn't work, you have to find a way to fallback to Obj-C
// https://mjtsai.com/blog/2021/03/31/making-nsfetchrequest-fetchbatchsize-work-with-swift/
// https://developer.apple.com/forums/thread/651325
// This fetch will execute SELECT with LIMIT 10 just one time ✅
// let cars_batchLimit_working = try Car.fetch(in: context) { $0.fetchLimit = 10 }
// This fetch will execute SELECT with LIMIT 10 as many times as needed to fetch all the cars ❌
//let cars_batchSize_not_working = try Car.fetch(in: context) { $0.fetchBatchSize = 10 }
// cars is a _PFBatchFaultingArray proxy
let cars = try Car.fetchNSArray(in: context) { $0.fetchBatchSize = 10 }
// This for loop will trigger a SELECT with LIMIT 10 every 10 looped cars. ✅
cars.forEach { car in
let _ = car as! Car
}
// This enumeration will trigger a SELECT with LIMIT 10 every 10 enumerated cars. ✅
cars.enumerateObjects { car, _, _ in
let _ = car as! Car
}
// firstObject will trigger only a single SELECT with LIMIT 10 ✅
let _ = cars.firstObject as! Car
}
}
| mit | 3466edb7803d348c15104fdafc20555f | 34.681395 | 152 | 0.69302 | 4.503375 | false | false | false | false |
blighli/iPhone2015 | 21551008王荣烨/iOS大作业/Timer/Timer/TimerView.swift | 1 | 6381 | //
// TimerView.swift
// Timer
//
// Created by Hardor on 15/12/31.
// Copyright © 2015年 Hardor. All rights reserved.
//
import UIKit
import QuartzCore
final class TimerView: UIView {
var durationInSeconds: CGFloat = 0.0
var maxValue: CGFloat = 60.0
var showRemaining = true
let timerShapeLayer: CAShapeLayer
let secondsShapeLayer: CAShapeLayer
let timeLabel: UILabel
override init(frame: CGRect) {
timerShapeLayer = CAShapeLayer()
// fullShapeLayer = CAShapeLayer()
secondsShapeLayer = CAShapeLayer()
timeLabel = {
let label = UILabel()
label.translatesAutoresizingMaskIntoConstraints = false
// label.font = UIFont.systemFontOfSize(80)
// label.font = UIFont(name: "HiraKakuProN-W3", size: 80)
label.font = UIFont(name: "HelveticaNeue-Thin", size: 80)
// label.adjustsFontSizeToFitWidth = true
label.textAlignment = .Center
label.textColor = TimerStyleKit.timerColor
// label.backgroundColor = UIColor.yellowColor()
return label
}()
super.init(frame: frame)
backgroundColor = UIColor.clearColor()
addSubview(timeLabel)
layer.addSublayer(timerShapeLayer)
// layer.addSublayer(fullShapeLayer)
layer.addSublayer(secondsShapeLayer)
var constraints = [NSLayoutConstraint]()
constraints.append(timeLabel.centerXAnchor.constraintEqualToAnchor(centerXAnchor))
constraints.append(timeLabel.centerYAnchor.constraintEqualToAnchor(centerYAnchor))
NSLayoutConstraint.activateConstraints(constraints)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
override func drawRect(rect: CGRect)
{
// TimerStyleKit.drawTimer(durationInSeconds, maxValue: maxValue, showRemaining: showRemaining)
var percentage: CGFloat
var dummyInt: Int
if !showRemaining {
dummyInt = Int(100000.0*(1 - (durationInSeconds-1) / maxValue))
// percentage = 1 - durationInSeconds / maxValue
} else {
dummyInt = Int(100000.0*(durationInSeconds-1) / maxValue)
// percentage = durationInSeconds / maxValue
}
percentage = CGFloat(dummyInt)/100000.0
let timerCenter = CGPointMake(CGRectGetMidX(rect), CGRectGetMidY(rect))
let radius = rect.size.width / 2 - 10
let startAngle = 3 * CGFloat(M_PI)/2
let timerRingPath = UIBezierPath(arcCenter: timerCenter, radius: radius, startAngle: startAngle, endAngle: startAngle-0.001, clockwise: true)
// timerRingPath.addArcWithCenter(timerCenter, radius: radius, startAngle: startAngle, endAngle: startAngle - 0.001, clockwise: true)
// println("percentage: \(percentage)")
timerShapeLayer.fillColor = UIColor.clearColor().CGColor
timerShapeLayer.strokeColor = TimerStyleKit.timerColor.CGColor
timerShapeLayer.lineWidth = 3
timerShapeLayer.strokeEnd = percentage
timerShapeLayer.path = timerRingPath.CGPath
// timerShapeLayer.shadowColor = TimerStyleKit.timerColor.CGColor
// timerShapeLayer.shadowOffset = CGSizeMake(0.1, -0.1)
// timerShapeLayer.shadowRadius = 3
// timerShapeLayer.shadowOpacity = 1.0
let totalMinutes = (maxValue-1) / 60
let dashLength = 2*radius*CGFloat(M_PI)/totalMinutes;
timerShapeLayer.lineDashPattern = [dashLength-2, 2]
var secondsPercentage: CGFloat
if showRemaining {
secondsPercentage = (durationInSeconds-1) % 60.0
} else {
secondsPercentage = 60.0 - (durationInSeconds-1) % 60.0
}
let secondsRingPath = UIBezierPath(arcCenter: timerCenter, radius: radius-4, startAngle: startAngle, endAngle: startAngle-0.001, clockwise: true)
secondsShapeLayer.fillColor = UIColor.clearColor().CGColor
secondsShapeLayer.strokeColor = TimerStyleKit.timerColor.CGColor
secondsShapeLayer.lineWidth = 1.0
secondsShapeLayer.strokeEnd = CGFloat(secondsPercentage)/60.0
secondsShapeLayer.path = secondsRingPath.CGPath
// secondsShapeLayer.shadowColor = TimerStyleKit.timerColor.CGColor
// secondsShapeLayer.shadowOffset = CGSizeMake(0.1, -0.1)
// secondsShapeLayer.shadowRadius = 3
// secondsShapeLayer.shadowOpacity = 1.0
// println("timerShapeLayer \(timerShapeLayer)")
TimerStyleKit.timerColor.set()
let fullRingPath = UIBezierPath(arcCenter: timerCenter, radius: radius+4, startAngle: startAngle, endAngle: startAngle - 0.001, clockwise: true)
fullRingPath.lineWidth = 1.0
fullRingPath.stroke()
// fullShapeLayer.fillColor = UIColor.clearColor().CGColor
// fullShapeLayer.strokeColor = TimerStyleKit.timerColor.CGColor
// fullShapeLayer.lineWidth = 1
// fullShapeLayer.strokeEnd = 1.0
// fullShapeLayer.path = fullRingPath.CGPath
// let path = UIBezierPath(arcCenter: timerCenter, radius: radius-4, startAngle: startAngle, endAngle: startAngle - 0.001, clockwise: true)
// path.lineWidth = 0.5
// path.stroke()
if !showRemaining {
durationInSeconds = maxValue - durationInSeconds
}
let seconds = Int(durationInSeconds % 60)
let minutes = Int(durationInSeconds / 60.0)
let format = "02"
let labelText = "\(minutes.format(format))" + ":" + "\(seconds.format(format))"
timeLabel.text = labelText
timeLabel.setNeedsLayout()
}
override func touchesEnded(touches: Set<UITouch>, withEvent event: UIEvent?) {
showRemaining = !showRemaining
setNeedsDisplay()
}
}
| mit | 304ccfde134b63c70c11393974bc5a3d | 40.686275 | 154 | 0.62402 | 5.106485 | false | false | false | false |
matrix-org/matrix-ios-sdk | MatrixSDK/Aggregations/LocationSharing/Store/Realm/MXRealmBeacon.swift | 1 | 1944 | //
// Copyright 2022 The Matrix.org Foundation C.I.C
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
import Foundation
import Realm
class MXRealmBeacon: RLMObject {
// MARK: - Properties
/// Coordinate latitude
@objc dynamic var latitude: Double = 0
/// Coordinate longitude
@objc dynamic var longitude: Double = 0
/// URI string (i.e. "geo:51.5008,0.1247;u=35")
@objc dynamic var geoURI: String = ""
/// Location description
@objc dynamic var desc: String?
/// The event id of the associated beaco info
@objc dynamic var beaconInfoEventId: String = ""
/// Creation timestamp of the beacon on the client
/// Milliseconds since UNIX epoch
@objc dynamic var timestamp: Int = 0
// MARK: - Setup
convenience init(latitude: Double,
longitude: Double,
geoURI: String,
desc: String? = nil,
beaconInfoEventId: String,
timestamp: Int) {
// https://www.mongodb.com/docs/realm-legacy/docs/swift/latest/#adding-custom-initializers-to-object-subclasses
self.init() //Please note this says 'self' and not 'super'
self.latitude = latitude
self.longitude = longitude
self.geoURI = geoURI
self.desc = desc
self.beaconInfoEventId = beaconInfoEventId
self.timestamp = timestamp
}
}
| apache-2.0 | 0e6098b3877ef98338ff99dcb49ce166 | 30.354839 | 119 | 0.644033 | 4.458716 | false | false | false | false |
benlangmuir/swift | test/Constraints/protocols.swift | 2 | 15878 | // RUN: %target-typecheck-verify-swift
protocol Fooable { func foo() }
protocol Barable { func bar() }
extension Int : Fooable, Barable {
func foo() {}
func bar() {}
}
extension Float32 : Barable {
func bar() {}
}
func f0(_: Barable) {}
func f1(_ x: Fooable & Barable) {}
func f2(_: Float) {}
let nilFunc: Optional<(Barable) -> ()> = nil
func g(_: (Barable & Fooable) -> ()) {}
protocol Classable : AnyObject {}
class SomeArbitraryClass {}
func fc0(_: Classable) {}
func fc1(_: Fooable & Classable) {}
func fc2(_: AnyObject) {}
func fc3(_: SomeArbitraryClass) {}
func gc(_: (Classable & Fooable) -> ()) {}
var i : Int
var f : Float
var b : Barable
//===----------------------------------------------------------------------===//
// Conversion to and among existential types
//===----------------------------------------------------------------------===//
f0(i)
f0(f)
f0(b)
f1(i)
f1(f) // expected-error{{argument type 'Float' does not conform to expected type 'Fooable'}}
f1(b) // expected-error{{argument type 'any Barable' does not conform to expected type 'Fooable'}}
//===----------------------------------------------------------------------===//
// Subtyping
//===----------------------------------------------------------------------===//
g(f0) // okay (subtype)
g(f1) // okay (exact match)
g(f2) // expected-error{{cannot convert value of type '(Float) -> ()' to expected argument type '(any Barable & Fooable) -> ()'}}
g(nilFunc ?? f0)
gc(fc0) // okay
gc(fc1) // okay
gc(fc2) // okay
gc(fc3) // expected-error{{cannot convert value of type '(SomeArbitraryClass) -> ()' to expected argument type '(any Classable & Fooable) -> ()'}}
// rdar://problem/19600325
func getAnyObject() -> AnyObject? {
return SomeArbitraryClass()
}
func castToClass(_ object: Any) -> SomeArbitraryClass? {
return object as? SomeArbitraryClass
}
_ = getAnyObject().map(castToClass)
_ = { (_: Any) -> Void in
return
} as ((Int) -> Void)
let _: (Int) -> Void = {
(_: Any) -> Void in
return
}
let _: () -> Any = {
() -> Int in
return 0
}
let _: () -> Int = {
() -> String in // expected-error {{declared closure result 'String' is incompatible with contextual type 'Int'}}
return ""
}
//===----------------------------------------------------------------------===//
// Members of archetypes
//===----------------------------------------------------------------------===//
func id<T>(_ t: T) -> T { return t }
protocol Initable {
init()
}
protocol P : Initable {
func bar(_ x: Int)
mutating func mut(_ x: Int)
static func tum()
typealias E = Int
typealias F = Self.E
typealias G = Array
}
protocol ClassP : class {
func bas(_ x: Int)
func quux(_ x: Int)
}
class ClassC : ClassP {
func bas(_ x: Int) {}
}
extension ClassP {
func quux(_ x: Int) {}
func bing(_ x: Int) {}
}
func generic<T: P>(_ t: T) {
var t = t
// Instance member of archetype
let _: (Int) -> () = id(t.bar)
let _: () = id(t.bar(0))
// Static member of archetype metatype
let _: () -> () = id(T.tum)
// Instance member of archetype metatype
let _: (T) -> (Int) -> () = id(T.bar)
let _: (Int) -> () = id(T.bar(t))
_ = t.mut // expected-error{{cannot reference 'mutating' method as function value}}
_ = t.tum // expected-error{{static member 'tum' cannot be used on instance of type 'T'}}
}
func genericClassP<T: ClassP>(_ t: T) {
// Instance member of archetype)
let _: (Int) -> () = id(t.bas)
let _: () = id(t.bas(0))
// Instance member of archetype metatype)
let _: (T) -> (Int) -> () = id(T.bas)
let _: (Int) -> () = id(T.bas(t))
let _: () = id(T.bas(t)(1))
}
func genericClassC<C : ClassC>(_ c: C) {
// Make sure that we can find members of protocol extensions
// on a class-bound archetype
let _ = c.bas(123)
let _ = c.quux(123)
let _ = c.bing(123)
}
//===----------------------------------------------------------------------===//
// Members of existentials
//===----------------------------------------------------------------------===//
func existential(_ p: P) {
var p = p
// Fully applied mutating method
p.mut(1)
_ = p.mut // expected-error{{cannot reference 'mutating' method as function value}}
// Instance member of existential)
let _: (Int) -> () = id(p.bar)
let _: () = id(p.bar(0))
// Static member of existential metatype)
let _: () -> () = id(type(of: p).tum)
}
func staticExistential(_ p: P.Type, pp: P.Protocol) {
let _ = p() // expected-error{{initializing from a metatype value must reference 'init' explicitly}}
let _ = p().bar // expected-error{{initializing from a metatype value must reference 'init' explicitly}}
let _ = p().bar(1) // expected-error{{initializing from a metatype value must reference 'init' explicitly}}
let ppp: P = p.init()
_ = pp() // expected-error{{value of type '(any P).Type' is a protocol; it cannot be instantiated}}
_ = pp().bar // expected-error{{value of type '(any P).Type' is a protocol; it cannot be instantiated}}
_ = pp().bar(2) // expected-error{{value of type '(any P).Type' is a protocol; it cannot be instantiated}}
_ = pp.init() // expected-error{{type 'any P' cannot be instantiated}}
_ = pp.init().bar // expected-error{{type 'any P' cannot be instantiated}}
_ = pp.init().bar(3) // expected-error{{type 'any P' cannot be instantiated}}
_ = P() // expected-error{{type 'any P' cannot be instantiated}}
_ = P().bar // expected-error{{type 'any P' cannot be instantiated}}
_ = P().bar(4) // expected-error{{type 'any P' cannot be instantiated}}
// Instance member of metatype
let _: (P) -> (Int) -> () = P.bar
let _: (Int) -> () = P.bar(ppp)
P.bar(ppp)(5)
// Instance member of metatype value
let _: (P) -> (Int) -> () = pp.bar
let _: (Int) -> () = pp.bar(ppp)
pp.bar(ppp)(5)
// Static member of existential metatype value
let _: () -> () = p.tum
// Instance member of existential metatype -- not allowed
_ = p.bar // expected-error{{instance member 'bar' cannot be used on type 'P'}}
_ = p.mut // expected-error{{instance member 'mut' cannot be used on type 'P'}}
// expected-error@-1 {{cannot reference 'mutating' method as function value}}
// Static member of metatype -- not allowed
_ = pp.tum // expected-error{{static member 'tum' cannot be used on protocol metatype '(any P).Type'}}
_ = P.tum // expected-error{{static member 'tum' cannot be used on protocol metatype '(any P).Type'}}
// Access typealias through protocol and existential metatypes
_ = pp.E.self
_ = p.E.self
_ = pp.F.self
_ = p.F.self
// Make sure that we open generics
let _: [Int].Type = p.G.self
}
protocol StaticP {
static func foo(a: Int)
}
extension StaticP {
func bar() {
_ = StaticP.foo(a:) // expected-error{{static member 'foo(a:)' cannot be used on protocol metatype '(any StaticP).Type'}} {{9-16=Self}}
func nested() {
_ = StaticP.foo(a:) // expected-error{{static member 'foo(a:)' cannot be used on protocol metatype '(any StaticP).Type'}} {{11-18=Self}}
}
}
}
func existentialClassP(_ p: ClassP) {
// Instance member of existential)
let _: (Int) -> () = id(p.bas)
let _: () = id(p.bas(0))
// Instance member of existential metatype)
let _: (ClassP) -> (Int) -> () = id(ClassP.bas)
let _: (Int) -> () = id(ClassP.bas(p))
let _: () = id(ClassP.bas(p)(1))
}
// Partial application of curried protocol methods
protocol Scalar {}
protocol Vector {
func scale(_ c: Scalar) -> Self
}
protocol Functional {
func apply(_ v: Vector) -> Scalar
}
protocol Coalgebra {
func coproduct(_ f: Functional) -> (_ v1: Vector, _ v2: Vector) -> Scalar
}
// Make sure existential is closed early when we partially apply
func wrap<T>(_ t: T) -> T {
return t
}
func exercise(_ c: Coalgebra, f: Functional, v: Vector) {
let _: (Vector, Vector) -> Scalar = wrap(c.coproduct(f))
let _: (Scalar) -> Vector = v.scale
}
// Make sure existential isn't closed too late
protocol Copyable {
func copy() -> Self
}
func copyTwice(_ c: Copyable) -> Copyable {
return c.copy().copy()
}
//===----------------------------------------------------------------------===//
// Dynamic self
//===----------------------------------------------------------------------===//
protocol Clonable {
func maybeClone() -> Self?
func doubleMaybeClone() -> Self??
func subdivideClone() -> (Self, Self)
func metatypeOfClone() -> Self.Type
func goodClonerFn() -> (() -> Self)
}
extension Clonable {
func badClonerFn() -> ((Self) -> Self) { }
func veryBadClonerFn() -> ((inout Self) -> ()) { }
func extClone() -> Self { }
func extMaybeClone(_ b: Bool) -> Self? { }
func extProbablyClone(_ b: Bool) -> Self! { }
static func returnSelfStatic() -> Self { }
static func returnSelfOptionalStatic(_ b: Bool) -> Self? { }
static func returnSelfIUOStatic(_ b: Bool) -> Self! { }
}
func testClonableArchetype<T : Clonable>(_ t: T) {
// Instance member of extension returning Self)
let _: (T) -> () -> T = id(T.extClone)
let _: () -> T = id(T.extClone(t))
let _: T = id(T.extClone(t)())
let _: () -> T = id(t.extClone)
let _: T = id(t.extClone())
let _: (T) -> (Bool) -> T? = id(T.extMaybeClone)
let _: (Bool) -> T? = id(T.extMaybeClone(t))
let _: T? = id(T.extMaybeClone(t)(false))
let _: (Bool) -> T? = id(t.extMaybeClone)
let _: T? = id(t.extMaybeClone(true))
let _: (T) -> (Bool) -> T? = id(T.extProbablyClone as (T) -> (Bool) -> T?)
let _: (Bool) -> T? = id(T.extProbablyClone(t) as (Bool) -> T?)
let _: T! = id(T.extProbablyClone(t)(true))
let _: (Bool) -> T? = id(t.extProbablyClone as (Bool) -> T?)
let _: T! = id(t.extProbablyClone(true))
// Static member of extension returning Self)
let _: () -> T = id(T.returnSelfStatic)
let _: T = id(T.returnSelfStatic())
let _: (Bool) -> T? = id(T.returnSelfOptionalStatic)
let _: T? = id(T.returnSelfOptionalStatic(false))
let _: (Bool) -> T? = id(T.returnSelfIUOStatic as (Bool) -> T?)
let _: T! = id(T.returnSelfIUOStatic(true))
}
func testClonableExistential(_ v: Clonable, _ vv: Clonable.Type) {
let _: Clonable? = v.maybeClone()
let _: Clonable?? = v.doubleMaybeClone()
let _: (Clonable, Clonable) = v.subdivideClone()
let _: Clonable.Type = v.metatypeOfClone()
let _: () -> Clonable = v.goodClonerFn()
// Instance member of extension returning Self
let _: () -> Clonable = id(v.extClone)
let _: Clonable = id(v.extClone())
let _: Clonable? = id(v.extMaybeClone(true))
let _: Clonable! = id(v.extProbablyClone(true))
// Static member of extension returning Self)
let _: () -> Clonable = id(vv.returnSelfStatic)
let _: Clonable = id(vv.returnSelfStatic())
let _: (Bool) -> Clonable? = id(vv.returnSelfOptionalStatic)
let _: Clonable? = id(vv.returnSelfOptionalStatic(false))
let _: (Bool) -> Clonable? = id(vv.returnSelfIUOStatic as (Bool) -> Clonable?)
let _: Clonable! = id(vv.returnSelfIUOStatic(true))
let _ = v.badClonerFn() // expected-error {{member 'badClonerFn' cannot be used on value of type 'any Clonable'; consider using a generic constraint instead}}
let _ = v.veryBadClonerFn() // expected-error {{member 'veryBadClonerFn' cannot be used on value of type 'any Clonable'; consider using a generic constraint instead}}
}
// rdar://problem/50099849
protocol Trivial {
associatedtype T
}
func rdar_50099849() {
struct A : Trivial {
typealias T = A
}
struct B<C : Trivial> : Trivial { // expected-note {{'C' declared as parameter to type 'B'}}
typealias T = C.T
}
struct C<W: Trivial, Z: Trivial> : Trivial where W.T == Z.T {
typealias T = W.T
}
let _ = C<A, B>() // expected-error {{generic parameter 'C' could not be inferred}}
// expected-note@-1 {{explicitly specify the generic arguments to fix this issue}} {{17-17=<<#C: Trivial#>>}}
}
// rdar://problem/50512161 - improve diagnostic when generic parameter cannot be deduced
func rdar_50512161() {
struct Item {}
struct TrivialItem : Trivial {
typealias T = Item?
}
func foo<I>(_: I.Type = I.self, item: I.T) where I : Trivial { // expected-note {{in call to function 'foo(_:item:)'}}
fatalError()
}
func bar(_ item: Item) {
foo(item: item) // expected-error {{generic parameter 'I' could not be inferred}}
}
}
// https://github.com/apple/swift/issues/54017
// Compiler crash on missing conformance for default param
do {
func foo<T : Initable>(_ x: T = .init()) -> T { x } // expected-note {{where 'T' = 'String'}}
let _: String = foo()
// expected-error@-1 {{local function 'foo' requires that 'String' conform to 'Initable'}}
}
// rdar://70814576 -- failed to produce a diagnostic when implicit value-to-optional conversion is involved.
func rdar70814576() {
struct S {}
func test(_: Fooable?) {
}
test(S()) // expected-error {{argument type 'S' does not conform to expected type 'Fooable'}}
}
extension Optional : Trivial {
typealias T = Wrapped
}
extension UnsafePointer : Trivial {
typealias T = Int
}
extension AnyHashable : Trivial {
typealias T = Int
}
extension UnsafeRawPointer : Trivial {
typealias T = Int
}
extension UnsafeMutableRawPointer : Trivial {
typealias T = Int
}
func test_inference_through_implicit_conversion() {
struct C : Hashable {}
func test<T: Trivial>(_: T) -> T {}
var arr: [C] = []
let ptr: UnsafeMutablePointer<C> = UnsafeMutablePointer(bitPattern: 0)!
let rawPtr: UnsafeMutableRawPointer = UnsafeMutableRawPointer(bitPattern: 0)!
let _: C? = test(C()) // Ok -> argument is implicitly promoted into an optional
let _: UnsafePointer<C> = test([C()]) // Ok - argument is implicitly converted to a pointer
let _: UnsafeRawPointer = test([C()]) // Ok - argument is implicitly converted to a raw pointer
let _: UnsafeMutableRawPointer = test(&arr) // Ok - inout Array<T> -> UnsafeMutableRawPointer
let _: UnsafePointer<C> = test(ptr) // Ok - UnsafeMutablePointer<T> -> UnsafePointer<T>
let _: UnsafeRawPointer = test(ptr) // Ok - UnsafeMutablePointer<T> -> UnsafeRawPointer
let _: UnsafeRawPointer = test(rawPtr) // Ok - UnsafeMutableRawPointer -> UnsafeRawPointer
let _: UnsafeMutableRawPointer = test(ptr) // Ok - UnsafeMutablePointer<T> -> UnsafeMutableRawPointer
let _: AnyHashable = test(C()) // Ok - argument is implicitly converted to `AnyHashable` because it's Hashable
}
// Make sure that conformances transitively checked through implicit conversions work with conditional requirements
protocol TestCond {}
extension Optional : TestCond where Wrapped == Int? {}
func simple<T : TestCond>(_ x: T) -> T { x }
func overloaded<T: TestCond>(_ x: T) -> T { x }
func overloaded<T: TestCond>(_ x: String) -> T { fatalError() }
func overloaded_result() -> Int { 42 }
func overloaded_result() -> String { "" }
func test_arg_conformance_with_conditional_reqs(i: Int) {
let _: Int?? = simple(i)
let _: Int?? = overloaded(i)
let _: Int?? = simple(overloaded_result())
let _: Int?? = overloaded(overloaded_result())
}
// rdar://77570994 - regression in type unification for literal collections
protocol Elt {
}
extension Int : Elt {}
extension Int64 : Elt {}
extension Dictionary : Elt where Key == String, Value: Elt {}
struct Object {}
extension Object : ExpressibleByDictionaryLiteral {
init(dictionaryLiteral elements: (String, Elt)...) {
}
}
enum E {
case test(cond: Bool, v: Int64)
var test_prop: Object {
switch self {
case let .test(cond, v):
return ["obj": ["a": v, "b": cond ? 0 : 42]] // Ok
}
}
}
// https://github.com/apple/swift/issues/58231
protocol P_58231 {}
struct S_58231 {}
func f1_58231(x: Int) -> P_58231 {
return S_58231() // expected-error{{return expression of type 'S_58231' does not conform to 'P_58231'}}
}
func f2_58231(x: Int) -> P_58231? {
return S_58231() // expected-error{{return expression of type 'S_58231' does not conform to 'P_58231'}}
}
| apache-2.0 | 7e033d453e7b003a4bf3c649bb8059a3 | 28.678505 | 168 | 0.602595 | 3.627599 | false | false | false | false |
gregomni/swift | validation-test/compiler_crashers_2_fixed/0192-rdar39826863.swift | 3 | 823 | // RUN: %target-swift-frontend -emit-ir %s -requirement-machine-protocol-signatures=on
protocol Tuple {
associatedtype Head
associatedtype Tail : Tuple
}
extension Pair : Tuple where Second : Tuple {
typealias Head = First
typealias Tail = Second
}
protocol HomogeneousTuple : Tuple, Collection
where Tail : HomogeneousTuple, Head == Tail.Head {}
extension HomogeneousTuple {
typealias Element = Head
typealias Index = Int
var startIndex: Int { return 0 }
var endIndex: Int { return 0 }
func index(after i: Int) -> Int { return i + 1 }
subscript(n: Int) -> Head {
fatalError()
}
}
extension Pair : Sequence, Collection, HomogeneousTuple
where Second : HomogeneousTuple, First == Second.Head {
typealias Iterator = IndexingIterator<Pair<Head, Tail>>
}
struct Pair<First, Second> {}
| apache-2.0 | fd8f9ea8afe230075777cc23e9b212f5 | 23.205882 | 86 | 0.710814 | 3.792627 | false | false | false | false |
Sage-Bionetworks/BridgeAppSDK | BridgeAppSDK/SBANotificationsManager.swift | 1 | 4553 | //
// SBANotificationsManager.swift
// BridgeAppSDK
//
// Copyright © 2016 Sage Bionetworks. All rights reserved.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
// 1. Redistributions of source code must retain the above copyright notice, this
// list of conditions and the following disclaimer.
//
// 2. Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation and/or
// other materials provided with the distribution.
//
// 3. Neither the name of the copyright holder(s) nor the names of any contributors
// may be used to endorse or promote products derived from this software without
// specific prior written permission. No license is granted to the trademarks of
// the copyright holders even if such marks are included in this software.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE
// FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
// DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
// OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
import UIKit
enum SBAScheduledNotificationType: String {
case scheduledActivity
}
open class SBANotificationsManager: NSObject, SBASharedInfoController {
static let notificationType = "notificationType"
static let identifier = "identifier"
@objc(sharedManager)
public static let shared = SBANotificationsManager()
lazy open var sharedAppDelegate: SBAAppInfoDelegate = {
return UIApplication.shared.delegate as! SBAAppInfoDelegate
}()
lazy open var sharedApplication: UIApplication = {
return UIApplication.shared
}()
lazy open var permissionsManager: SBAPermissionsManager = {
return SBAPermissionsManager.shared
}()
@objc(setupNotificationsForScheduledActivities:)
open func setupNotifications(for scheduledActivities: [SBBScheduledActivity]) {
permissionsManager.requestPermission(for: SBANotificationPermissionObjectType.localNotifications()) { [weak self] (granted, _) in
if granted {
self?.scheduleNotifications(scheduledActivities: scheduledActivities)
}
}
}
fileprivate func scheduleNotifications(scheduledActivities activities: [SBBScheduledActivity]) {
// Cancel previous notifications
cancelNotifications(notificationType: .scheduledActivity)
// Add a notification for the scheduled activities that should include one
let app = sharedApplication
for sa in activities {
if let taskRef = self.sharedBridgeInfo.taskReferenceForSchedule(sa)
, taskRef.scheduleNotification {
let notif = UILocalNotification()
notif.fireDate = sa.scheduledOn
notif.soundName = UILocalNotificationDefaultSoundName
notif.alertBody = Localization.localizedStringWithFormatKey("SBA_TIME_FOR_%@", sa.activity.label)
notif.userInfo = [ SBANotificationsManager.notificationType: SBAScheduledNotificationType.scheduledActivity.rawValue,
SBANotificationsManager.identifier: sa.activity.guid ]
app.scheduleLocalNotification(notif)
}
}
}
fileprivate func cancelNotifications(notificationType: SBAScheduledNotificationType) {
let app = sharedApplication
if let scheduledNotifications = app.scheduledLocalNotifications {
for notif in scheduledNotifications {
if let type = notif.userInfo?[SBANotificationsManager.notificationType] as? String,
let notifType = SBAScheduledNotificationType(rawValue: type) , notifType == notificationType {
app.cancelLocalNotification(notif)
}
}
}
}
}
| bsd-3-clause | 62199c50c5f813b1449fde854de6af9a | 44.069307 | 137 | 0.710896 | 5.524272 | false | false | false | false |
ashfurrow/Moya | Sources/Moya/MoyaProvider.swift | 2 | 8953 | import Foundation
/// Closure to be executed when a request has completed.
public typealias Completion = (_ result: Result<Moya.Response, MoyaError>) -> Void
/// Closure to be executed when progress changes.
public typealias ProgressBlock = (_ progress: ProgressResponse) -> Void
/// A type representing the progress of a request.
public struct ProgressResponse {
/// The optional response of the request.
public let response: Response?
/// An object that conveys ongoing progress for a given request.
public let progressObject: Progress?
/// Initializes a `ProgressResponse`.
public init(progress: Progress? = nil, response: Response? = nil) {
self.progressObject = progress
self.response = response
}
/// The fraction of the overall work completed by the progress object.
public var progress: Double {
if completed {
return 1.0
} else if let progressObject = progressObject, progressObject.totalUnitCount > 0 {
// if the Content-Length is specified we can rely on `fractionCompleted`
return progressObject.fractionCompleted
} else {
// if the Content-Length is not specified, return progress 0.0 until it's completed
return 0.0
}
}
/// A Boolean value stating whether the request is completed.
public var completed: Bool {
return response != nil
}
}
/// A protocol representing a minimal interface for a MoyaProvider.
/// Used by the reactive provider extensions.
public protocol MoyaProviderType: AnyObject {
associatedtype Target: TargetType
/// Designated request-making method. Returns a `Cancellable` token to cancel the request later.
func request(_ target: Target, callbackQueue: DispatchQueue?, progress: Moya.ProgressBlock?, completion: @escaping Moya.Completion) -> Cancellable
}
/// Request provider class. Requests should be made through this class only.
open class MoyaProvider<Target: TargetType>: MoyaProviderType {
/// Closure that defines the endpoints for the provider.
public typealias EndpointClosure = (Target) -> Endpoint
/// Closure that decides if and what request should be performed.
public typealias RequestResultClosure = (Result<URLRequest, MoyaError>) -> Void
/// Closure that resolves an `Endpoint` into a `RequestResult`.
public typealias RequestClosure = (Endpoint, @escaping RequestResultClosure) -> Void
/// Closure that decides if/how a request should be stubbed.
public typealias StubClosure = (Target) -> Moya.StubBehavior
/// A closure responsible for mapping a `TargetType` to an `EndPoint`.
public let endpointClosure: EndpointClosure
/// A closure deciding if and what request should be performed.
public let requestClosure: RequestClosure
/// A closure responsible for determining the stubbing behavior
/// of a request for a given `TargetType`.
public let stubClosure: StubClosure
public let session: Session
/// A list of plugins.
/// e.g. for logging, network activity indicator or credentials.
public let plugins: [PluginType]
public let trackInflights: Bool
open internal(set) var inflightRequests: [Endpoint: [Moya.Completion]] = [:]
/// Propagated to Alamofire as callback queue. If nil - the Alamofire default (as of their API in 2017 - the main queue) will be used.
let callbackQueue: DispatchQueue?
let lock: NSRecursiveLock = NSRecursiveLock()
/// Initializes a provider.
public init(endpointClosure: @escaping EndpointClosure = MoyaProvider.defaultEndpointMapping,
requestClosure: @escaping RequestClosure = MoyaProvider.defaultRequestMapping,
stubClosure: @escaping StubClosure = MoyaProvider.neverStub,
callbackQueue: DispatchQueue? = nil,
session: Session = MoyaProvider<Target>.defaultAlamofireSession(),
plugins: [PluginType] = [],
trackInflights: Bool = false) {
self.endpointClosure = endpointClosure
self.requestClosure = requestClosure
self.stubClosure = stubClosure
self.session = session
self.plugins = plugins
self.trackInflights = trackInflights
self.callbackQueue = callbackQueue
}
/// Returns an `Endpoint` based on the token, method, and parameters by invoking the `endpointClosure`.
open func endpoint(_ token: Target) -> Endpoint {
return endpointClosure(token)
}
/// Designated request-making method. Returns a `Cancellable` token to cancel the request later.
@discardableResult
open func request(_ target: Target,
callbackQueue: DispatchQueue? = .none,
progress: ProgressBlock? = .none,
completion: @escaping Completion) -> Cancellable {
let callbackQueue = callbackQueue ?? self.callbackQueue
return requestNormal(target, callbackQueue: callbackQueue, progress: progress, completion: completion)
}
// swiftlint:disable function_parameter_count
/// When overriding this method, call `notifyPluginsOfImpendingStub` to prepare your request
/// and then use the returned `URLRequest` in the `createStubFunction` method.
/// Note: this was previously in an extension, however it must be in the original class declaration to allow subclasses to override.
@discardableResult
open func stubRequest(_ target: Target, request: URLRequest, callbackQueue: DispatchQueue?, completion: @escaping Moya.Completion, endpoint: Endpoint, stubBehavior: Moya.StubBehavior) -> CancellableToken {
let callbackQueue = callbackQueue ?? self.callbackQueue
let cancellableToken = CancellableToken { }
let preparedRequest = notifyPluginsOfImpendingStub(for: request, target: target)
let plugins = self.plugins
let stub: () -> Void = createStubFunction(cancellableToken, forTarget: target, withCompletion: completion, endpoint: endpoint, plugins: plugins, request: preparedRequest)
switch stubBehavior {
case .immediate:
switch callbackQueue {
case .none:
stub()
case .some(let callbackQueue):
callbackQueue.async(execute: stub)
}
case .delayed(let delay):
let killTimeOffset = Int64(CDouble(delay) * CDouble(NSEC_PER_SEC))
let killTime = DispatchTime.now() + Double(killTimeOffset) / Double(NSEC_PER_SEC)
(callbackQueue ?? DispatchQueue.main).asyncAfter(deadline: killTime) {
stub()
}
case .never:
fatalError("Method called to stub request when stubbing is disabled.")
}
return cancellableToken
}
// swiftlint:enable function_parameter_count
}
// MARK: Stubbing
/// Controls how stub responses are returned.
public enum StubBehavior {
/// Do not stub.
case never
/// Return a response immediately.
case immediate
/// Return a response after a delay.
case delayed(seconds: TimeInterval)
}
public extension MoyaProvider {
// Swift won't let us put the StubBehavior enum inside the provider class, so we'll
// at least add some class functions to allow easy access to common stubbing closures.
/// Do not stub.
final class func neverStub(_: Target) -> Moya.StubBehavior {
return .never
}
/// Return a response immediately.
final class func immediatelyStub(_: Target) -> Moya.StubBehavior {
return .immediate
}
/// Return a response after a delay.
final class func delayedStub(_ seconds: TimeInterval) -> (Target) -> Moya.StubBehavior {
return { _ in return .delayed(seconds: seconds) }
}
}
/// A public function responsible for converting the result of a `URLRequest` to a Result<Moya.Response, MoyaError>.
public func convertResponseToResult(_ response: HTTPURLResponse?, request: URLRequest?, data: Data?, error: Swift.Error?) ->
Result<Moya.Response, MoyaError> {
switch (response, data, error) {
case let (.some(response), data, .none):
let response = Moya.Response(statusCode: response.statusCode, data: data ?? Data(), request: request, response: response)
return .success(response)
case let (.some(response), _, .some(error)):
let response = Moya.Response(statusCode: response.statusCode, data: data ?? Data(), request: request, response: response)
let error = MoyaError.underlying(error, response)
return .failure(error)
case let (_, _, .some(error)):
let error = MoyaError.underlying(error, nil)
return .failure(error)
default:
let error = MoyaError.underlying(NSError(domain: NSURLErrorDomain, code: NSURLErrorUnknown, userInfo: nil), nil)
return .failure(error)
}
}
| mit | aa9db4cb950fe7f26f72a016b86f1420 | 40.64186 | 209 | 0.67899 | 5.190145 | false | false | false | false |
robertzhang/Enterprise-Phone | EP/ElasticView.swift | 1 | 4691 | //
// ElasticView.swift
// EP
//
// Created by Robert Zhang on 27/9/15.
// Copyright (c) 2015年 [email protected]. All rights reserved.
//
import UIKit
class ElasticView: UIView {
private let topControlPointView = UIView()
private let leftControlPointView = UIView()
private let bottomControlPointView = UIView()
private let rightControlPointView = UIView()
private let elasticShape = CAShapeLayer()
private lazy var displayLink : CADisplayLink = {
let displayLink = CADisplayLink(target: self, selector: Selector("updateLoop"))
displayLink.addToRunLoop(NSRunLoop.currentRunLoop(), forMode: NSRunLoopCommonModes)
return displayLink
}()
override init(frame: CGRect) {
super.init(frame: frame)
setupComponents()
positionControlPoints()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
setupComponents()
positionControlPoints()
}
private func setupComponents() {
elasticShape.fillColor = backgroundColor?.CGColor
elasticShape.path = UIBezierPath(rect: self.bounds).CGPath
layer.addSublayer(elasticShape)
for controlPoint in [topControlPointView, leftControlPointView, bottomControlPointView,rightControlPointView] {
addSubview(controlPoint)
controlPoint.frame = CGRect(x: 0.0, y: 0.0,width: 5.0,height: 5.0)
// controlPoint.backgroundColor = UIColor.blueColor()
clipsToBounds = false
}
}
private func positionControlPoints() {
topControlPointView.center = CGPoint(x: bounds.midX, y: 0.0)
leftControlPointView.center = CGPoint(x: 0.0, y:bounds.midY)
bottomControlPointView.center = CGPoint(x: bounds.midX, y: bounds.maxY)
rightControlPointView.center = CGPoint(x: bounds.maxX, y:bounds.midY)
}
private func bezierPathForControlPoints()->CGPathRef {
// 1
let path = UIBezierPath()
// 2
let top = topControlPointView.layer.presentationLayer()!.position
let left = leftControlPointView.layer.presentationLayer()!.position
let bottom = bottomControlPointView.layer.presentationLayer()!.position
let right = rightControlPointView.layer.presentationLayer()!.position
let width = frame.size.width
let height = frame.size.height
// 3
path.moveToPoint(CGPointMake(0, 0))
path.addQuadCurveToPoint(CGPointMake(width, 0), controlPoint: top)
path.addQuadCurveToPoint(CGPointMake(width, height), controlPoint:right)
path.addQuadCurveToPoint(CGPointMake(0, height), controlPoint:bottom)
path.addQuadCurveToPoint(CGPointMake(0, 0), controlPoint: left)
// 4
return path.CGPath
}
func updateLoop() {
elasticShape.path = bezierPathForControlPoints()
}
private func startUpdateLoop() {
displayLink.paused = false
}
private func stopUpdateLoop() {
displayLink.paused = true
}
@IBInspectable var overshootAmount : CGFloat = 20
func animateControlPoints() {
//1
let overshootAmount = self.overshootAmount
// 2
UIView.animateWithDuration(0.25, delay: 0.0, usingSpringWithDamping: 0.9, initialSpringVelocity: 1.5,
options: [], animations: {
// 3
self.topControlPointView.center.y -= overshootAmount
self.leftControlPointView.center.x -= overshootAmount
self.bottomControlPointView.center.y += overshootAmount
self.rightControlPointView.center.x += overshootAmount
},
completion: { _ in
// 4
UIView.animateWithDuration(0.45, delay: 0.0, usingSpringWithDamping: 0.15, initialSpringVelocity: 5.5,
options: [], animations: {
// 5
self.positionControlPoints()
},
completion: { _ in
// 6
self.stopUpdateLoop()
})
})
}
override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
startUpdateLoop()
animateControlPoints()
}
override var backgroundColor: UIColor? {
willSet {
if let newValue = newValue {
elasticShape.fillColor = newValue.CGColor
super.backgroundColor = UIColor.clearColor()
}
}
}
}
| mit | 5f2c69a049f752aefe9320e7ff9f9d00 | 32.733813 | 119 | 0.605246 | 5.12459 | false | false | false | false |
tspecht/SwiftLint | Source/SwiftLintFramework/Rules/TypeBodyLengthRule.swift | 1 | 2888 | //
// TypeBodyLengthRule.swift
// SwiftLint
//
// Created by JP Simard on 2015-05-16.
// Copyright (c) 2015 Realm. All rights reserved.
//
import SourceKittenFramework
import SwiftXPC
public struct TypeBodyLengthRule: ASTRule, ParameterizedRule {
public init() {}
public let identifier = "type_body_length"
public let parameters = [
RuleParameter(severity: .VeryHigh, value: 1000)
]
public func validateFile(file: File) -> [StyleViolation] {
return validateFile(file, dictionary: file.structure.dictionary)
}
public func validateFile(file: File, dictionary: XPCDictionary) -> [StyleViolation] {
return (dictionary["key.substructure"] as? XPCArray ?? []).flatMap { subItem in
var violations = [StyleViolation]()
if let subDict = subItem as? XPCDictionary,
let kindString = subDict["key.kind"] as? String,
let kind = flatMap(kindString, { SwiftDeclarationKind(rawValue: $0) }) {
violations.extend(validateFile(file, dictionary: subDict))
violations.extend(validateFile(file, kind: kind, dictionary: subDict))
}
return violations
}
}
public func validateFile(file: File,
kind: SwiftDeclarationKind,
dictionary: XPCDictionary) -> [StyleViolation] {
let typeKinds: [SwiftDeclarationKind] = [
.Class,
.Struct,
.Enum
]
if !contains(typeKinds, kind) {
return []
}
if let offset = flatMap(dictionary["key.offset"] as? Int64, { Int($0) }),
let bodyOffset = flatMap(dictionary["key.bodyoffset"] as? Int64, { Int($0) }),
let bodyLength = flatMap(dictionary["key.bodylength"] as? Int64, { Int($0) }) {
let location = Location(file: file, offset: offset)
let startLine = file.contents.lineAndCharacterForByteOffset(bodyOffset)
let endLine = file.contents.lineAndCharacterForByteOffset(bodyOffset + bodyLength)
for parameter in reverse(parameters) {
if let startLine = startLine?.line, let endLine = endLine?.line
where endLine - startLine > parameter.value {
return [StyleViolation(type: .Length,
location: location,
severity: parameter.severity,
reason: "Type body should be span 1000 lines or less: currently spans " +
"\(endLine - startLine) lines")]
}
}
}
return []
}
public let example = RuleExample(
ruleName: "Type body Length Rule",
ruleDescription: "Type body should span 1000 lines or less.",
nonTriggeringExamples: [],
triggeringExamples: [],
showExamples: false
)
}
| mit | 349d9117b00813d51f4a5bc57ba69531 | 37 | 97 | 0.590028 | 4.886633 | false | false | false | false |
cellsplicer/SwiftCalculator | Calculator/Calculator/Calculator/HistoryViewController.swift | 1 | 1796 | //
// HistoryViewController.swift
// Calculator
//
// Created by Ray Tran on 16/04/2015.
// Copyright (c) 2015 Ray Tran. All rights reserved.
//
import UIKit
import Foundation
protocol HistoryViewControllerDelegate : class {
func giveStringForIndex(index: Int) -> String
func giveNumberOfRows() -> Int
}
class HistoryViewController : UIViewController, UITableViewDataSource, UITableViewDelegate
{
@IBOutlet var tbView: UITableView!
let textCellIdentifier = "TextCell"
var historyViewControllerDelegate : HistoryViewControllerDelegate?
override func viewDidLoad() {
super.viewDidLoad()
tbView.delegate = self
tbView.dataSource = self
}
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if ( historyViewControllerDelegate != nil) {
var numberOfRows = historyViewControllerDelegate!.giveNumberOfRows()
return numberOfRows
}
return 0
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier(textCellIdentifier, forIndexPath: indexPath) as! UITableViewCell
let row = indexPath.row
if(historyViewControllerDelegate != nil) {
cell.textLabel?.text = historyViewControllerDelegate!.giveStringForIndex(indexPath.row)
}
return cell
}
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
tableView.deselectRowAtIndexPath(indexPath, animated: true)
let row = indexPath.row
}
} | bsd-2-clause | 3ac4fad76b2a7915d0078da189c0708e | 28.459016 | 127 | 0.684855 | 5.701587 | false | false | false | false |
HuanDay/Booster | Booster/BModule/BSTMainMenuVC.swift | 1 | 5887 | //
// BSTMainMenuVC.swift
// Booster
//
// Created by Michael Zhai on 22/02/17.
// Copyright © 2017 Michael Zhai. All rights reserved.
//
import Foundation
class BSTMainMenuVC : BSTBaseVC, UITableViewDataSource, UITableViewDelegate {
@IBOutlet weak var investorTypeTableView: UITableView!
@IBOutlet weak var questionnaireBtn: UIButton!
@IBOutlet weak var submitBtn: UIButton!
var QIsFinished: Bool = false
var isSubmitted: Bool = false
var scoreNum: NSInteger = 0
var investorTypeList = [""]
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
btnsStatusChanged()
}
override func viewDidLoad() {
super.viewDidLoad()
initQuestionnaireBtn()
initSubmitBtn()
initTableView()
}
func initTableView() {
let emptyView = UIView.init(frame: CGRect(x: 0, y: 0, width: Constants.SCREEN.SCREEN_WIDTH, height: 0.5))
emptyView.backgroundColor = UIColor.lightGray
investorTypeTableView.tableFooterView = emptyView
investorTypeList = BSTInvestorTypeModel.getAllInvestorType()
investorTypeTableView.register(menuCell.self, forCellReuseIdentifier: "menuCell")
investorTypeTableView.dataSource = self
investorTypeTableView.delegate = self
}
func initQuestionnaireBtn() {
questionnaireBtn.backgroundColor = Constants.COLOR.blueColor
BoosterUtility.setUnknownViewNoBorderColor(questionnaireBtn)
}
func initSubmitBtn() {
submitBtn.isUserInteractionEnabled = false
submitBtn.backgroundColor = Constants.COLOR.borderColor
BoosterUtility.setUnknownViewNoBorderColor(submitBtn)
}
// UITableView
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return investorTypeList.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "menuCell", for: indexPath) as? menuCell
cell?.setCell(title: investorTypeList[indexPath.row])
return cell!
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let fundDetailVC = self.storyboard?.instantiateViewController(withIdentifier: "BSTFundDetailVC") as? BSTFundDetailVC
fundDetailVC?.setUp(investorType: investorTypeList[indexPath.row])
self.navigationController?.pushViewController(fundDetailVC!, animated: true)
}
func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
return "INVESTOR TYPE"
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return 55
}
func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
return 40
}
// status changes
func btnsStatusChanged() {
if self.QIsFinished == true {
if isSubmitted == true {
questionnaireBtn.backgroundColor = Constants.COLOR.blueColor
submitBtn.backgroundColor = Constants.COLOR.yellowColor
questionnaireBtn.layer.borderColor = Constants.COLOR.blueColor.cgColor
submitBtn.layer.borderColor = Constants.COLOR.yellowColor.cgColor
questionnaireBtn.isUserInteractionEnabled = true
submitBtn.isUserInteractionEnabled = false
submitBtn.setTitle("Submitted", for: .normal)
} else {
questionnaireBtn.backgroundColor = Constants.COLOR.borderColor
submitBtn.backgroundColor = Constants.COLOR.greenColor
questionnaireBtn.layer.borderColor = Constants.COLOR.borderColor.cgColor
submitBtn.layer.borderColor = Constants.COLOR.greenColor.cgColor
questionnaireBtn.isUserInteractionEnabled = false
submitBtn.isUserInteractionEnabled = true
}
}
}
func clearStatus() {
self.scoreNum = 0
self.QIsFinished = false
self.isSubmitted = false
submitBtn.setTitle("Submit", for: .normal)
}
// btn onClick event
@IBAction func questionnaireBtnOnClick(_ sender: Any) {
clearStatus()
let questionnaireVC = self.storyboard?.instantiateViewController(withIdentifier:"BSTQuestionnaireVC") as? BSTQuestionnaireVC
self.navigationController?.pushViewController(questionnaireVC!, animated: true)
}
@IBAction func submitBtnOnClick(_ sender: Any) {
let userInfoVC = self.storyboard?.instantiateViewController(withIdentifier: "BSTUserInfoVC") as? BSTUserInfoVC
userInfoVC?.scoreNum = self.scoreNum
self.navigationController?.pushViewController(userInfoVC!, animated: true)
}
}
class menuCell : UITableViewCell {
var titleLab: UILabel?
override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
self.selectionStyle = .none
self.initLabel()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
func initLabel() {
let width = self.frame.size.width-30
self.titleLab = UILabel.init(frame: CGRect.init(x:15, y: 0, width: width, height: 60))
self.titleLab?.font = UIFont.systemFont(ofSize: 20)
self.titleLab?.textAlignment = .left
self.titleLab?.numberOfLines = 1
self.contentView.addSubview(self.titleLab!)
}
func setCell(title: String) {
self.titleLab?.text = title
}
}
| mit | 0b760a41d43bb75e59c20a0a0898864b | 34.672727 | 132 | 0.658682 | 5.096104 | false | false | false | false |
adamkaplan/swifter | Swifter/Promise.swift | 1 | 4632 | //
// Promise.swift
// Swifter
//
// Created by Daniel Hanggi on 6/19/14.
// Copyright (c) 2014 Yahoo!. All rights reserved.
//
import Foundation
/** A PromiseState encapsulates all possible states of the Promise: .Pending,
or .Fulfilled with either a .Success(T) or a .Failure(E). */
private enum PromiseState<T> {
case Fulfilled([T]) // TODO: REMOVE WORKAROUND [T] -> T
case Pending
var value: T? {
get {
switch self {
case .Fulfilled(let f):
return f[0]
case .Pending:
return nil
}
}
}
}
/** A Promise is an object that contains only a state of an asynchronous computation:
it is either .Pending or .Fulfilled with a value. Promises themselves do not
enact computation, but act as state endpoints in a computation. */
public class Promise<T> {
private var state: PromiseState<T>
private let lock: NSLock
private var callbacks = List<Executable<T>>()
public var future: Future<T> {
get {
return Future<T>(linkedPromise: self)
}
}
public var value: T? {
get {
return self.state.value
}
}
init() {
Log(.Promise, "Promise made")
self.state = .Pending
self.lock = NSLock()
}
convenience init(_ value: T) {
self.init()
self.tryFulfill(value)
}
deinit {
DLog(.Promise, "Deinitializing Promise")
}
/** Applies fulfilled to a .Fufilled(Try<T>) and pending to a .Pending. */
public func fold<S>(fulfilled: T -> S, pending: () -> S) -> S {
return self.lock.perform {
// [unowned self] () -> S in // TODO Is this necessary? It doesn't matter if it's owned?
switch self.state {
case .Fulfilled(let f):
return fulfilled(f[0])
case .Pending:
return pending()
}
}
}
/** Attempts to change the state of the Promise to a .Fulfilled(Try<T>), and
returns whether or not the state change occured. */
public func tryFulfill(value: T) -> Bool {
return self.fold({
_ in
Log(.Promise, "Attempted to fulfill an already-fulfilled promise (\(self.state)).")
return false
}, {
Log(.Promise, "Promise fulfilled with \(value)")
self.state = .Fulfilled([value])
self.callback()
return true
})
}
/** Returns whether the Promise has reached a .Fulfilled(T) state. */
public func isFulfilled() -> Bool {
return self.fold({ _ in true }, { false })
}
/** Fulfills the Promise simultaneously with this Promise. */
public func alsoFulfill(promise: Promise<T>) -> () {
self.executeOrMap(Executable<T>(queue: Scheduler.assignQueue()) { _ = promise.tryFulfill($0) })
}
private func callback() -> () {
self.callbacks.iter { $0.executeWithValue(self.value!) }
}
/** Executes the Executable with the value of the .Fulfilled promise, or
otherwise schedules the Executable to be executed after the Promise reaches
the .Fulfilled state. */
internal func executeOrMap(exec: Executable<T>) -> () {
self.fold({ exec.executeWithValue($0) }, { self.callbacks = exec^^self.callbacks })
}
/** Schedules the Task to be executed for when the Promise is .Fulfilled. */
public func onComplete(task: T -> ()) -> () {
self.executeOrMap(Executable(queue: Scheduler.assignQueue(), task: task))
}
}
extension Promise : Awaitable {
typealias AwaitedResult = Promise<T>
typealias CompletedResult = T
public var completedResult: CompletedResult {
get {
do {} while !self.isFulfilled()
return self.state.value!
}
}
public func isComplete() -> Bool {
return self.isFulfilled()
}
public func await() -> Promise<T> {
return self.await(NSTimeInterval.infinity, timeout: nil)
}
public func await(time: NSTimeInterval, timeout: (Promise<T> -> Promise<T>)!) -> Promise<T> {
let timer = NSTimer.scheduledTimerWithTimeInterval(time, userInfo: nil, repeats: false) {
_ in
Log(.Timer, "Timing out")
if !self.isComplete() {
timeout(self)
}
}
do {} while !self.isComplete() && !timer.hasFired()
if self.isComplete() {
return self
} else {
return timeout(self)
}
}
}
| apache-2.0 | a974e3c48c400e73f00e1297b37776da | 28.316456 | 103 | 0.565199 | 4.361582 | false | false | false | false |
lioonline/Swift | UIImagePickerControllerCamera/UIImagePickerControllerCamera/ViewController.swift | 1 | 3091 | //
// ViewController.swift
// UIImagePickerControllerCamera
//
// Created by Carlos Butron on 08/12/14.
// Copyright (c) 2014 Carlos Butron.
//
// This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public
// License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later
// version.
// This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied
// warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
// You should have received a copy of the GNU General Public License along with this program. If not, see
// http:/www.gnu.org/licenses/.
//
import UIKit
import MediaPlayer
import MobileCoreServices
class ViewController: UIViewController, UINavigationControllerDelegate, UIImagePickerControllerDelegate {
@IBOutlet weak var myImage: UIImageView!
@IBAction func useCamera(sender: UIButton) {
let imagePicker = UIImagePickerController()
imagePicker.delegate = self
imagePicker.sourceType = UIImagePickerControllerSourceType.Camera
//to select only camera controls, not video
imagePicker.mediaTypes = [kUTTypeImage]
imagePicker.showsCameraControls = true
//imagePicker.allowsEditing = true
self.presentViewController(imagePicker, animated: true, completion: nil)
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func imagePickerController(picker: UIImagePickerController!, didFinishPickingMediaWithInfo info: [NSObject : AnyObject]!){
let image = info[UIImagePickerControllerOriginalImage] as UIImage
let imageData = UIImagePNGRepresentation(image) as NSData
//save in photo album
UIImageWriteToSavedPhotosAlbum(image, self, "image:didFinishSavingWithError:contextInfo:", nil)
//save in documents
let documentsPath = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.UserDomainMask, true).last as NSString
let filePath = documentsPath.stringByAppendingPathComponent("pic.png")
imageData.writeToFile(filePath, atomically: true)
myImage.image = image
self.dismissViewControllerAnimated(true, completion: nil)
}
func image(image: UIImage, didFinishSavingWithError error: NSErrorPointer, contextInfo: UnsafePointer<()>){
if(error != nil){
println("ERROR IMAGE \(error.debugDescription)")
}
}
func imagePickerControllerDidCancel(picker: UIImagePickerController!){
self.dismissViewControllerAnimated(true, completion: nil)
}
}
| gpl-3.0 | 0f5ea4fbd9e0c2af7e62e1e8fdf1cde9 | 36.695122 | 166 | 0.71045 | 5.724074 | false | false | false | false |
rwebaz/Simple-Swift-OS | photoFilters/photoFilters/photoFilters/CalcMBA/CalcMBA.playground/section-1.swift | 2 | 5372 | // MBA Calculator by Xpadap Inc All rights reserved ©2014
// 1st import the superclass
import UIKit
// 2nd declare a variable and implicitly assign a value to that variable
var str = "Hello, playground";
str
/* Here, the variable name declared is 'str' and the value assigned is a string
However, the 'type' of variable is inferred from the value */
// Note: The semi-colon at the end of a code statement is optional
/* To declare a variable and explicitly assign a type to the value of that
variable (a type annotation) */
var stringvar:NSString = "Hi! I'm an explicit string variable!";
// You can also split the declaration of the variable from the assignment
var stringvar1:NSString;
stringvar1 = "I'm a string!";
stringvar1
var stringvar2:String;
stringvar2 = "I'm a string, too!";
stringvar2
/* Now, let's test the contents of each string variable placeholder by simply
typing the name of the variable */
str;
stringvar;
stringvar1;
stringvar2;
// Declare and instantiate separately a couple of numeric 'Double' variables,
var doublevar:Double;
doublevar = 3.50;
doublevar
var doublevar1:Double = 7.67;
// Multiply the two 'Double' variables to create a product
doublevar1
var product:Double = doublevar * doublevar1;
product;
// Declare and instantiate separately a couple of numeric 'int' variables
var integerone:Int;
integerone = 2;
var intergertwo:Int = 3;
var sum:Int = integerone + intergertwo;
sum;
/* If you wish to make a variable constant, use the 'let' keyword
instead of var */
let animal:NSNumber = 15;
// See! You can't change a constant!
animal;
/* Now, let's try declaring a constant to be a color
Note: UIColor is an inheriting class of the above superclass UIKit */
let blue = UIColor.blueColor();
blue
// The four attributes of UIColor are red, green, blue, and opacity (alpha)
// You can also let the dimensions of a rectangle
let dimrect = CGRect(x: 0, y: 0, width: 200, height: 200);
// The 'for loop' processes a variable multiple times via iteration
for index in 1...10{
index
}
// Declare three variables implicitly
var title = "Mr";
var firstname = "Robert";
var lastname = "Smith";
// Concantenate using long notation
var result = "The record is " + title + " " + firstname + " " + lastname;
result
// Concantenate using short-swift notation
var result1 = "Hello \(title) \(firstname) \(lastname) !";
result1
// Short-swift notation can also be used to output numeric values
var output = "The product of the two above 'Double' variables is: \(product)";
output
var output1 = "The sum of the two above 'Int' variables is: \(sum)";
output1
// Imput an array of strings using swift os
var StitchColorNames = ["Luster Sky Blue", "Forest Green", "Tuplip Red",
"Light Kelly Green", "Ashley Gold"];
// Output each value of the 'StitchColorNames' array manually
StitchColorNames[0];
StitchColorNames[1];
StitchColorNames[2];
StitchColorNames[3];
StitchColorNames[4];
// Use a for loop to output each value of the 'StitchColorNames' array
for eachname in StitchColorNames{
println(eachname);
}
for var i = 0; i < 5; ++i {
println(StitchColorNames[i]);
}
// How to create and execute a function (method) I
func sayHello(name: String) ->String {
let content = "Say Hello " + name + "!"
return content
}
println(sayHello("Bob"))
// How to create and execute a function (method) II
func red(blue: String) ->String {
let green = "Hello " + blue + "!"
return green
}
println(red("Rasim"))
// How to create and work with a dictionary
var House: Dictionary<String, String> = ["a": "apple", "b": "boy", "c": "cookie"]
House
println(House["a"])
// How to create and work with a dictionary
var Patio: [String : Int] = ["One":1, "Two":2, "Three":3];
Patio
println(Patio["Two"]);
// How to change values within a dictionary
House["a"] = "Avocado"
println(House["a"])
// variables as emojis; unicode characters as variables
let 🐶 = "Fido"
🐶
// Change the variable type to an alias
typealias 🔢 = Int
var placeholder: 🔢
placeholder = 99;
// Declare a Boolean variable
var trueofalse: Bool;
trueofalse = false;
// New Type Tuple (like an array)
var parrot = ( wingcolor: "green", facecolor: "peach", headcolor: "red")
parrot.0
parrot.wingcolor
parrot.1
parrot.facecolor
parrot.2
parrot.headcolor
var (wingcolor,facecolor,headcolor) = parrot
parrot
// Optional A
var age = "87".toInt();
if age {
age!
}
// Optional B
var name: String?;
name = "fido"
name = nil;
// Numeric Literals
var a: Float = 1_000_000
// Numeric Type Conversion from Int to Double
var x:Int = 3;
var y:Double = 0.14159;
var pi = Double(x) + y;
pi;
// Non-production grade assertions (for debugging)
assert(age >= 0, "Age cannot be less than zero");
// Looping Through A String
var loopie: String = "Kathy";
for unicodecharacter in loopie {
println(unicodecharacter)
}
// Compound Assignment Operators
pi -= 2;
// How to count the elements within a string
countElements(title);
// Classes are superior to 'structures'
class Dog {
var dogage:Int = 12
var color:String = "brown"
var name:String = "Fido"
}
struct Doggie {
}
// How to initialize an empty string
var lionanimal:String = "";
var animalhyena = String();
if lionanimal.isEmpty {
}
| agpl-3.0 | 8e394050c196cb8ef332bdd46e2004a0 | 14.399425 | 81 | 0.692853 | 3.324442 | false | false | false | false |
rinat-enikeev/UILabel-attributed-text-swift | UILabel+AttributedText.swift | 1 | 1076 | import Foundation
public extension UILabel {
public func at_setAllSubstringsColor(substring : String?, color: UIColor?) {
if substring != nil && color != nil {
let attributedString = NSMutableAttributedString(attributedString: self.attributedText)
let text = attributedString.mutableString
let expression = NSRegularExpression(pattern: "(" + substring! + ")", options: NSRegularExpressionOptions.allZeros, error: nil)
expression?.enumerateMatchesInString(text, options: NSMatchingOptions.allZeros, range: NSMakeRange(0, text.length), usingBlock: { (result: NSTextCheckingResult!, flags: NSMatchingFlags, stop: UnsafeMutablePointer<ObjCBool>) -> Void in
// docs: "A result must have at least one range"
let wordRange = result.rangeAtIndex(0)
attributedString.addAttribute(NSForegroundColorAttributeName, value: color!, range: wordRange)
})
self.attributedText = attributedString
}
}
} | apache-2.0 | c4830a7a3bbada44c5628351d7b20857 | 50.285714 | 246 | 0.653346 | 6.044944 | false | false | false | false |
ben-ng/swift | validation-test/compiler_crashers_fixed/26339-llvm-ondiskchainedhashtable-swift-modulefile-decltableinfo-find.swift | 1 | 2843 | // This source file is part of the Swift.org open source project
// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
// RUN: not %target-swift-frontend %s -typecheck
typealias e : d where h: AnyObject
protocol A {
enum S<c {
typealias e : AnyObject
struct B<d where B : Boolean, A : A}
protocol c : Boolean, A : a
protocol A {enum S<T {
struct Q<T where h: a {
}
class b
class A : T:
}
let t: d where B { func b {
protocol A : Int = c<T {
class b {
typealias e =[Void
class d<T where h: A{
protocol A : a
}
protocol A : Boolean, A {
func < {
let a {
typealias e : B<T where B :
enum S<T : Int -> {
class A {
let f = c{
class a {
}
extension String {
class b
protocol c {() -> {
struct B { func c
struct Q<T where h: d {
typealias e : e:
class a {class
enum e)"[Void
let f = F>(a}
if true {
}
typealias e : b: a {
struct X<T where H:
struct d<T {let f = c
class a {
class A : p
if true {
typealias e : a{
class a {
{
class A : B
case c
}
func c,
protocol A : Boolean, A : Int -> {struct B<c : a {
struct A : A : A}
case c
protocol A : AnyObject
{
class a {
struct B:A
}
enum a
class b: A {
enum a
class d
class b<c {
class A : Boolean, A {
typealias e)"\() -> {
let t: A {
let a {
func j<T where g: AnyObject
case c<T where B { func g:a:
for ( )"[Void{
}
struct B
func a{
struct B<T where h: e)"[]struct Q<T where H : Boolean, A : P {enum a
struct X<T {
let a {
class a {{
func c( )
struct B<d where h: e)"[1)"[1)"\() -> {
}
}
class a {
{
}
class A {
protocol A {
class A}
let f = [Void
for ( )"[1)"[Void{
protocol c
typealias e : T:A
class a {
class A : Int -> {
let t: Boolean, A {
enum S<T where h: Int = []struct S<h {
extension String {
struct Q<h where h: A
}
struct Q<T {{
}
}func d<d {
}
class A : A
enum b{
class
protocol A : e
protocol A : d {
struct Q<T {
{
struct B : a {
typealias e : e:N
protocol A {
protocol A {
func a
for ( )"[1)"[Void
struct Q<T where h: e
extension String {
protocol c,
let t: C {
}
struct B<T where T
class A {}
typealias e : Boolean, A {
extension String {
struct B
let f = c<T where B :a
func A
struct Q<T where a
protocol A {
let a {
}
struct Q<T where h: p
struct Q<T where T
struct Q<T where h: e
let a {
struct d<T where B : b
struct S<h where h: A
enum S<T:
}
}
protocol A
protocol c : T:
{
case
func j<S : b<T where h: e)
class b: a
protocol A {
protocol A : a
case,
func c
var b {
typealias e : a=[Void{
typealias e : Boolean, A {
protocol A {
class b<T where g
protocol A : e)
protocol A {
enum S<d {
class
extension String {
typealias e : AnyObject
protocol c{
for ( )"\(
{
extension String {{
for ( )"[Void
func b
let f = [Void{
struct Q<T where d<T where h: a {
| apache-2.0 | a7cf6dfbc4f8b3581ce111c98141df32 | 14.882682 | 79 | 0.637003 | 2.66448 | false | false | false | false |
schibsted/layout | Layout/UICollectionView+Layout.swift | 1 | 18360 | // Copyright © 2017 Schibsted. All rights reserved.
import UIKit
private let placeholderID = NSUUID().uuidString
private class Box {
weak var node: LayoutNode?
init(_ node: LayoutNode) {
self.node = node
}
}
extension UICollectionViewLayout {
fileprivate static func defaultLayout(for node: LayoutNode) -> UICollectionViewFlowLayout {
let flowLayout = UICollectionViewFlowLayout()
if node.expressions["collectionViewLayout.itemSize"] ??
node.expressions["collectionViewLayout.itemSize.width"] ??
node.expressions["collectionViewLayout.itemSize.height"] == nil {
flowLayout.estimatedItemSize = flowLayout.itemSize
}
if #available(iOS 10.0, *) {
flowLayout.itemSize = UICollectionViewFlowLayout.automaticSize
} else {
flowLayout.itemSize = CGSize(width: UIView.noIntrinsicMetric, height: UIView.noIntrinsicMetric)
}
return flowLayout
}
}
private class LayoutCollectionView: UICollectionView {
open override var intrinsicContentSize: CGSize {
guard layoutNode != nil else {
return super.intrinsicContentSize
}
return CGSize(
width: contentSize.width + contentInset.left + contentInset.right,
height: contentSize.height + contentInset.top + contentInset.bottom
)
}
open override var contentSize: CGSize {
didSet {
if oldValue != contentSize, let layoutNode = layoutNode {
layoutNode.contentSizeChanged()
}
}
}
}
private var swizzled = NSMutableSet()
private extension UICollectionView {
@objc var layout_intrinsicContentSize: CGSize {
guard layoutNode != nil else {
if imp(of: #selector(getter: intrinsicContentSize), of: type(of: self),
matches: #selector(getter: self.layout_intrinsicContentSize)) {
return super.intrinsicContentSize
}
return self.layout_intrinsicContentSize
}
return CGSize(
width: contentSize.width + contentInset.left + contentInset.right,
height: contentSize.height + contentInset.top + contentInset.bottom
)
}
@objc func layout_setContentSize(_ size: CGSize) {
if imp(of: #selector(setter: contentSize), of: type(of: self),
matches: #selector(layout_setContentSize(_:))) {
super.contentSize = size
} else {
layout_setContentSize(size)
}
if size != contentSize, let layoutNode = layoutNode {
layoutNode.contentSizeChanged()
}
}
}
extension UICollectionView: LayoutBacked {
open override class func create(with node: LayoutNode) throws -> UICollectionView {
// UICollectionView cannot be created with a nil collectionViewLayout
// so we cannot allow create(with:) to throw. Instead, we'll intercept the error
let layout = node.attempt {
try node.value(forExpression: "collectionViewLayout")
} as? UICollectionViewLayout ?? .defaultLayout(for: node)
let collectionView: UICollectionView = {
if self == UICollectionView.self {
return LayoutCollectionView(frame: .zero, collectionViewLayout: layout)
} else {
if !isSubclass(of: LayoutCollectionView.self), !swizzled.contains(self) {
replace(#selector(getter: intrinsicContentSize), of: self,
with: #selector(getter: layout_intrinsicContentSize))
replace(#selector(setter: contentSize), of: self,
with: #selector(layout_setContentSize(_:)))
swizzled.add(self)
}
return self.init(frame: .zero, collectionViewLayout: layout)
}
}()
collectionView.register(UICollectionViewCell.self, forCellWithReuseIdentifier: placeholderID)
return collectionView
}
open override class var expressionTypes: [String: RuntimeType] {
var types = super.expressionTypes
for (key, type) in UICollectionViewFlowLayout.allPropertyTypes() {
types["collectionViewLayout.\(key)"] = type
}
types["collectionViewLayout.sectionInsetReference"] = .uiCollectionViewFlowLayoutSectionInsetReference
types["collectionViewLayout.scrollDirection"] = .uiCollectionViewScrollDirection
types["reorderingCadence"] = .uiCollectionViewReorderingCadence
for name in [
"contentSize",
"contentSize.height",
"contentSize.width",
] {
types[name] = .unavailable()
}
return types
}
open override func setAnimatedValue(_ value: Any, forExpression name: String) throws {
switch name {
case "collectionViewLayout":
setCollectionViewLayout(value as! UICollectionViewLayout, animated: true)
default:
try super.setAnimatedValue(value, forExpression: name)
}
}
open override func setValue(_ value: Any, forExpression name: String) throws {
switch name {
case "reorderingCadence", "collectionViewLayout.sectionInsetReference":
// Does nothing on iOS 10 and earlier
if #available(iOS 11.0, *) {
fallthrough
}
default:
try super.setValue(value, forExpression: name)
}
}
open override func shouldInsertChildNode(_ node: LayoutNode, at _: Int) -> Bool {
if node.viewClass is UICollectionViewCell.Type {
do {
if let reuseIdentifier = try node.value(forExpression: "reuseIdentifier") as? String {
registerLayout(Layout(node), forCellReuseIdentifier: reuseIdentifier)
} else {
layoutError(.message("UICollectionViewCell template missing reuseIdentifier"))
}
} catch {
layoutError(LayoutError(error))
}
return false
}
return true
}
open override func didInsertChildNode(_ node: LayoutNode, at index: Int) {
if backgroundView == nil {
backgroundView = node.view // TODO: this is a bit inconsistent with UITableView - reconsider?
} else {
super.didInsertChildNode(node, at: index)
}
}
open override func willRemoveChildNode(_ node: LayoutNode, at index: Int) {
let hadView = (node._view != nil)
super.willRemoveChildNode(node, at: index)
if node._view == backgroundView {
backgroundView = nil
}
// Check we didn't accidentally instantiate the view
// TODO: it would be better to do this in a unit test
assert(hadView || node._view == nil)
}
open override func didUpdateLayout(for _: LayoutNode) {
for cell in visibleCells {
cell.layoutNode?.update()
}
}
}
extension UICollectionView: LayoutDelegate {
public func layoutValue(forKey key: String) throws -> Any? {
if let layoutNode = layoutNode {
return try layoutNode.value(forParameterOrVariableOrConstant: key)
}
return nil
}
}
extension UICollectionViewController: LayoutBacked {
open override class func create(with node: LayoutNode) throws -> UICollectionViewController {
let layout = try node.value(forExpression: "collectionViewLayout") as? UICollectionViewLayout ?? .defaultLayout(for: node)
let viewController = self.init(collectionViewLayout: layout)
guard let collectionView = viewController.collectionView else {
throw LayoutError("Failed to create collectionView")
}
if !node.children.contains(where: { $0.viewClass is UICollectionView.Type }) {
collectionView.register(UICollectionViewCell.self, forCellWithReuseIdentifier: placeholderID)
} else if node.expressions.keys.contains(where: { $0.hasPrefix("collectionView.") }) {
// TODO: figure out how to propagate this config to the view once it has been created
}
return viewController
}
open override class var expressionTypes: [String: RuntimeType] {
var types = super.expressionTypes
types["collectionViewLayout"] = RuntimeType(UICollectionViewFlowLayout.self)
for (key, type) in UICollectionViewFlowLayout.allPropertyTypes() {
types["collectionViewLayout.\(key)"] = type
}
types["collectionViewLayout.sectionInsetReference"] = .uiCollectionViewFlowLayoutSectionInsetReference
types["collectionViewLayout.scrollDirection"] = .uiCollectionViewScrollDirection
for (key, type) in UICollectionView.cachedExpressionTypes {
types["collectionView.\(key)"] = type
}
return types
}
open override func setValue(_ value: Any, forExpression name: String) throws {
switch name {
case "collectionViewLayout":
collectionView?.collectionViewLayout = value as! UICollectionViewLayout
case _ where name.hasPrefix("collectionViewLayout."):
try collectionView?.setValue(value, forExpression: name)
case _ where name.hasPrefix("collectionView."):
try collectionView?.setValue(value, forExpression: String(name["collectionView.".endIndex ..< name.endIndex]))
default:
try super.setValue(value, forExpression: name)
}
}
open override func shouldInsertChildNode(_ node: LayoutNode, at index: Int) -> Bool {
switch node.viewClass {
case is UICollectionViewCell.Type:
return collectionView?.shouldInsertChildNode(node, at: index) ?? false
default:
return true
}
}
open override func didInsertChildNode(_ node: LayoutNode, at index: Int) {
// TODO: what if more than one collectionView is added?
if node.viewClass is UICollectionView.Type {
let wasLoaded = (viewIfLoaded != nil)
collectionView = node.view as? UICollectionView
if wasLoaded {
viewDidLoad()
}
return
}
collectionView?.didInsertChildNode(node, at: index)
}
open override func willRemoveChildNode(_ node: LayoutNode, at index: Int) {
if node.viewClass is UICollectionView.Type {
collectionView = nil
return
}
collectionView?.willRemoveChildNode(node, at: index)
}
}
private var cellDataKey = 0
private var nodesKey = 0
extension UICollectionView {
private enum LayoutData {
case success(Layout, Any, [String: Any])
case failure(Error)
}
private func registerLayoutData(
_ layoutData: LayoutData,
forCellReuseIdentifier identifier: String
) {
var layoutsData = objc_getAssociatedObject(self, &cellDataKey) as? NSMutableDictionary
if layoutsData == nil {
layoutsData = [:]
objc_setAssociatedObject(self, &cellDataKey, layoutsData, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
}
layoutsData![identifier] = layoutData
}
fileprivate func registerLayout(
_ layout: Layout,
state: Any = (),
constants: [String: Any]...,
forCellReuseIdentifier identifier: String
) {
do {
let viewClass: AnyClass = try layout.getClass()
guard var cellClass = viewClass as? UICollectionViewCell.Type else {
throw LayoutError.message("\(viewClass)) is not a subclass of UICollectionViewCell")
}
if cellClass == UICollectionViewCell.self {
cellClass = LayoutCollectionViewCell.self
} else if !cellClass.isSubclass(of: LayoutCollectionViewCell.self),
!swizzled.contains(cellClass) {
replace(#selector(getter: intrinsicContentSize), of: cellClass,
with: #selector(getter: layout_intrinsicContentSize))
replace(#selector(sizeThatFits(_:)), of: cellClass,
with: #selector(UICollectionViewCell.layout_sizeThatFits(_:)))
swizzled.add(cellClass)
}
register(cellClass, forCellWithReuseIdentifier: identifier)
registerLayoutData(.success(layout, state, merge(constants)), forCellReuseIdentifier: identifier)
} catch {
layoutError(LayoutError(error))
registerLayoutData(.failure(error), forCellReuseIdentifier: identifier)
}
}
public func registerLayout(
named: String,
bundle: Bundle = Bundle.main,
relativeTo: String = #file,
state: Any = (),
constants: [String: Any]...,
forCellReuseIdentifier identifier: String
) {
do {
let layout = try LayoutLoader().loadLayout(
named: named,
bundle: bundle,
relativeTo: relativeTo
)
registerLayout(
layout,
state: state,
constants: merge(constants),
forCellReuseIdentifier: identifier
)
} catch {
registerLayoutData(.failure(error), forCellReuseIdentifier: identifier)
}
}
public func dequeueReusableCellNode(withIdentifier identifier: String, for indexPath: IndexPath) -> LayoutNode {
do {
guard let layoutsData = objc_getAssociatedObject(self, &cellDataKey) as? NSMutableDictionary,
let layoutData = layoutsData[identifier] as? LayoutData else {
throw LayoutError.message("No cell layout has been registered for \(identifier)")
}
let cell = dequeueReusableCell(withReuseIdentifier: identifier, for: indexPath)
if let node = cell.layoutNode {
node.update() // Ensure frame is updated before re-use
return node
}
switch layoutData {
case let .success(layout, state, constants):
let node = try LayoutNode(
layout: layout,
state: state,
constants: constants
)
var nodes = objc_getAssociatedObject(self, &nodesKey) as? NSMutableArray
if nodes == nil {
nodes = []
objc_setAssociatedObject(self, &nodesKey, nodes, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
}
nodes?.add(node)
node.delegate = self
assert(node._view == nil)
node._view = cell
try node.bind(to: cell) // TODO: find a better solution for binding
return node
case let .failure(error):
throw error
}
} catch {
layoutError(LayoutError(error))
return LayoutNode(view: dequeueReusableCell(withReuseIdentifier: placeholderID, for: indexPath))
}
}
}
private class LayoutCollectionViewCell: UICollectionViewCell {
open override var intrinsicContentSize: CGSize {
guard let layoutNode = layoutNode, layoutNode.children.isEmpty else {
return super.intrinsicContentSize
}
return CGSize(width: UIView.noIntrinsicMetric, height: 44)
}
open override func sizeThatFits(_ size: CGSize) -> CGSize {
if let layoutNode = layoutNode {
let height = (try? layoutNode.doubleValue(forSymbol: "height")) ?? 0
return CGSize(width: size.width, height: CGFloat(height))
}
return super.sizeThatFits(size)
}
}
private extension UICollectionViewCell {
@objc var layout_intrinsicContentSize: CGSize {
guard let layoutNode = layoutNode, layoutNode.children.isEmpty else {
if imp(of: #selector(getter: intrinsicContentSize), of: type(of: self),
matches: #selector(getter: self.layout_intrinsicContentSize)) {
return super.intrinsicContentSize
} else {
return self.layout_intrinsicContentSize
}
}
return CGSize(width: UIView.noIntrinsicMetric, height: 44)
}
@objc func layout_sizeThatFits(_ size: CGSize) -> CGSize {
if let layoutNode = layoutNode {
let height = (try? layoutNode.doubleValue(forSymbol: "height")) ?? 0
return CGSize(width: size.width, height: CGFloat(height))
}
if imp(of: #selector(sizeThatFits(_:)), of: type(of: self),
matches: #selector(layout_sizeThatFits(_:))) {
return super.sizeThatFits(size)
} else {
return layout_sizeThatFits(size)
}
}
}
extension UICollectionViewCell: LayoutBacked {
open override class func create(with _: LayoutNode) throws -> UICollectionViewCell {
throw LayoutError.message("UICollectionViewCells must be created by UICollectionView")
}
open override class var parameterTypes: [String: RuntimeType] {
return ["reuseIdentifier": .string]
}
open override class var expressionTypes: [String: RuntimeType] {
var types = super.expressionTypes
for (key, type) in UIView.cachedExpressionTypes {
types["contentView.\(key)"] = type
types["backgroundView.\(key)"] = type
types["selectedBackgroundView.\(key)"] = type
}
return types
}
open override func setValue(_ value: Any, forExpression name: String) throws {
if name.hasPrefix("backgroundView."), backgroundView == nil {
// Add a backgroundView view if required
backgroundView = UIView(frame: bounds)
} else if name.hasPrefix("selectedBackgroundView."), selectedBackgroundView == nil {
// Add a selectedBackgroundView view if required
selectedBackgroundView = UIView(frame: bounds)
}
try super.setValue(value, forExpression: name)
}
open override func didInsertChildNode(_ node: LayoutNode, at index: Int) {
// Insert child views into `contentView` instead of directly
contentView.didInsertChildNode(node, at: index)
}
}
| mit | 770948dc44b0bc05b978b7e6b6be94d5 | 38.738095 | 130 | 0.61828 | 5.382293 | false | false | false | false |
gmoral/SwiftTraining2016 | Training_Swift/ViewController.swift | 1 | 2907 | //
// ViewController.swift
// Training_Swift
//
// Created by Guillermo Moral on 2/12/16.
// Copyright © 2016 Guillermo Moral. All rights reserved.
//
import UIKit
class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource, CollectionVCDelegate
{
@IBOutlet weak var tableView: UITableView!
var currentSelect : NSInteger = 0
var data: NSMutableArray = ["Test 1", "Test 2", "Test 3"]
var username = ""
//MARK: --- UI
override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: NSBundle?)
{
super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil)
}
required init?(coder aDecoder: NSCoder)
{
super.init(coder: aDecoder)
}
override func viewDidLoad()
{
super.viewDidLoad()
tableView.delegate = self;
tableView.dataSource = self
tableView.estimatedRowHeight = 100
tableView.separatorStyle = UITableViewCellSeparatorStyle.None
title = username
}
override func viewWillAppear(animated: Bool)
{
super.viewWillAppear(animated);
tableView .reloadData()
}
//MARK: UITableViewDelegate
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int
{
return self.data.count
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell
{
let cell: CustomCell = tableView.dequeueReusableCellWithIdentifier(CustomCell.identifier()) as! CustomCell
let title = self.data .objectAtIndex(indexPath.row) as? String
cell.configure(title!, Avatar: UIImage(named: "Avatar.png")!)
return cell
}
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath)
{
currentSelect = indexPath.row
}
//MARK: ---
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?)
{
if segue.identifier == "CollectionVC"
{
if let destinationVC = segue.destinationViewController as? CollectionViewController
{
destinationVC.title = self.data .objectAtIndex(self.currentSelect) as? String
// How to set a delegate.
destinationVC.delegate = self;
}
}
}
//MARK: - CollectionVCDelegate
func didSelectPhoto(collection: CollectionViewController, state : Bool)
{
navigationController?.popViewControllerAnimated(true)
}
//MARK: - Constructor
class func instantiate()->UIViewController
{
let storyboard = UIStoryboard(name: "Main", bundle: nil)
let vc = storyboard.instantiateViewControllerWithIdentifier("ViewController")
return vc
}
} | mit | d860c7b5aeeb65ad9cd3aee130f76189 | 26.685714 | 114 | 0.630764 | 5.535238 | false | false | false | false |
razvn/touchbardemo-macOS | TouchBarDemo/TouchBarDemo/MySpriteView.swift | 1 | 1657 | //
// MyWindow.swift
// TouchBarDemo
//
// Created by Razvan Bunea on 26/11/2016.
// Copyright © 2016 Razvan Bunea. All rights reserved.
//
import SpriteKit
@available(OSX 10.12.2, *)
class MySpriteView: SKView {
let pauseNotification = Notification.Name("PauseNotificationId")
let swipeNotification = Notification.Name("SwipeNotificationId")
var startX = 0
override init(frame frameRect: NSRect) {
super.init(frame: frameRect)
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func touchesBegan(with event: NSEvent) {
//Swift.print("begin", event)
if let touch = event.touches(matching: .began, in: self).first, touch.type == .direct {
let location = touch.location(in: self)
startX = Int(location.x)
//Swift.print("Start", location)
}
}
override func touchesEnded(with event: NSEvent) {
//Swift.print("end", event)
if let touch = event.touches(matching: .ended, in: self).first, touch.type == .direct {
let location = touch.location(in: self)
let endX = Int(location.x)
//Swift.print("Ended: start:", startX, "end:",endX)
if abs(endX - startX) > 5 {
NotificationCenter.default.post(name: swipeNotification, object: event)
//Swift.print("Pause")
} else {
NotificationCenter.default.post(name: pauseNotification, object: event)
//Swift.print("Swipe")
}
}
}
}
| mit | 5ba1739c4ac78fd4a79a8765a2dd853f | 28.571429 | 95 | 0.576691 | 4.21374 | false | false | false | false |
julienbodet/wikipedia-ios | Wikipedia/Code/Panels.swift | 1 | 21738 |
class EnableReadingListSyncPanelViewController : ScrollableEducationPanelViewController {
override func viewDidLoad() {
super.viewDidLoad()
image = UIImage(named: "reading-list-syncing")
heading = WMFLocalizedString("reading-list-sync-enable-title", value:"Turn on reading list syncing?", comment:"Title describing reading list syncing.")
subheading = WMFLocalizedString("reading-list-sync-enable-subtitle", value:"Your saved articles and reading lists can now be saved to your Wikipedia account and synced across Wikipedia apps.", comment:"Subtitle describing reading list syncing.")
primaryButtonTitle = WMFLocalizedString("reading-list-sync-enable-button-title", value:"Enable syncing", comment:"Title for button enabling reading list syncing.")
}
}
class AddSavedArticlesToReadingListPanelViewController : ScrollableEducationPanelViewController {
override func viewDidLoad() {
super.viewDidLoad()
image = UIImage(named: "reading-list-saved")
heading = WMFLocalizedString("reading-list-add-saved-title", value:"Saved articles found", comment:"Title explaining saved articles were found.")
subheading = WMFLocalizedString("reading-list-add-saved-subtitle", value:"There are articles saved to your Wikipedia app. Would you like to keep them and merge with reading lists synced to your account?", comment:"Subtitle explaining that saved articles can be added to reading lists.")
primaryButtonTitle = WMFLocalizedString("reading-list-add-saved-button-title", value:"Yes, add them to my reading lists", comment:"Title for button to add saved articles to reading list.")
secondaryButtonTitle = CommonStrings.readingListDoNotKeepSubtitle
}
}
class LoginToSyncSavedArticlesToReadingListPanelViewController : ScrollableEducationPanelViewController {
override func viewDidLoad() {
super.viewDidLoad()
image = UIImage(named: "reading-list-login")
heading = WMFLocalizedString("reading-list-login-title", value:"Sync your saved articles?", comment:"Title for syncing save articles.")
subheading = CommonStrings.readingListLoginSubtitle
primaryButtonTitle = CommonStrings.readingListLoginButtonTitle
}
}
@objc enum KeepSavedArticlesTrigger: Int {
case logout, syncDisabled
}
class KeepSavedArticlesOnDevicePanelViewController : ScrollableEducationPanelViewController {
private let trigger: KeepSavedArticlesTrigger
init(triggeredBy trigger: KeepSavedArticlesTrigger, showCloseButton: Bool, primaryButtonTapHandler: ScrollableEducationPanelButtonTapHandler?, secondaryButtonTapHandler: ScrollableEducationPanelButtonTapHandler?, dismissHandler: ScrollableEducationPanelDismissHandler?, discardDismissHandlerOnPrimaryButtonTap: Bool, theme: Theme) {
self.trigger = trigger
super.init(showCloseButton: showCloseButton, primaryButtonTapHandler: primaryButtonTapHandler, secondaryButtonTapHandler: secondaryButtonTapHandler, dismissHandler: dismissHandler, theme: theme)
}
required public init?(coder aDecoder: NSCoder) {
return nil
}
override func viewDidLoad() {
super.viewDidLoad()
image = UIImage(named: "reading-list-saved")
heading = WMFLocalizedString("reading-list-keep-title", value: "Keep saved articles on device?", comment: "Title for keeping save articles on device.")
primaryButtonTitle = WMFLocalizedString("reading-list-keep-button-title", value: "Yes, keep articles on device", comment: "Title for button to keep synced articles on device.")
if trigger == .logout {
subheading = CommonStrings.keepSavedArticlesOnDeviceMessage
secondaryButtonTitle = CommonStrings.readingListDoNotKeepSubtitle
} else if trigger == .syncDisabled {
subheading = CommonStrings.keepSavedArticlesOnDeviceMessage + "\n\n" + WMFLocalizedString("reading-list-keep-sync-disabled-additional-subtitle", value: "Turning sync off will remove these articles from your account. If you remove them from your device they will not be recoverable by turning sync on again in the future.", comment: "Additional subtitle informing user that turning sync off will remove saved articles from their account.")
secondaryButtonTitle = WMFLocalizedString("reading-list-keep-sync-disabled-remove-article-button-title", value: "No, remove articles from device and my Wikipedia account", comment: "Title for button that removes save articles from device and Wikipedia account.")
}
}
}
class SyncEnabledPanelViewController: ScrollableEducationPanelViewController {
override func viewDidLoad() {
super.viewDidLoad()
image = UIImage(named: "reading-lists-sync-enabled-disabled")
heading = WMFLocalizedString("reading-list-sync-enabled-panel-title", value: "Sync is enabled on this account", comment: "Title for panel informing user that sync was disabled on their Wikipedia account on another device")
subheading = WMFLocalizedString("reading-list-sync-enabled-panel-message", value: "Reading list syncing is enabled for this account. To stop syncing, you can turn sync off for this account by updating your settings.", comment: "Message for panel informing user that sync is enabled for their account.")
primaryButtonTitle = CommonStrings.gotItButtonTitle
}
}
class SyncDisabledPanelViewController: ScrollableEducationPanelViewController {
override func viewDidLoad() {
super.viewDidLoad()
image = UIImage(named: "reading-lists-sync-enabled-disabled")
heading = WMFLocalizedString("reading-list-sync-disabled-panel-title", value: "Sync disabled", comment: "Title for panel informing user that sync was disabled on their Wikipedia account on another device")
subheading = WMFLocalizedString("reading-list-sync-disabled-panel-message", value: "Reading list syncing has been disabled for your Wikipedia account on another device. You can turn sync back on by updating your settings.", comment: "Message for panel informing user that sync was disabled on their Wikipedia account on another device.")
primaryButtonTitle = CommonStrings.gotItButtonTitle
}
}
class EnableLocationPanelViewController : ScrollableEducationPanelViewController {
override func viewDidLoad() {
super.viewDidLoad()
image = UIImage(named: "places-auth-arrow")
heading = CommonStrings.localizedEnableLocationTitle
primaryButtonTitle = CommonStrings.localizedEnableLocationButtonTitle
footer = CommonStrings.localizedEnableLocationDescription
}
}
class ReLoginFailedPanelViewController : ScrollableEducationPanelViewController {
override func viewDidLoad() {
super.viewDidLoad()
image = UIImage(named: "relogin-failed")
heading = WMFLocalizedString("relogin-failed-title", value:"Unable to re-establish log in", comment:"Title for letting user know they are no longer logged in.")
subheading = WMFLocalizedString("relogin-failed-subtitle", value:"Your session may have expired or previous log in credentials are no longer valid.", comment:"Subtitle for letting user know they are no longer logged in.")
primaryButtonTitle = WMFLocalizedString("relogin-failed-retry-login-button-title", value:"Try to log in again", comment:"Title for button to let user attempt to log in again.")
secondaryButtonTitle = WMFLocalizedString("relogin-failed-stay-logged-out-button-title", value:"Keep me logged out", comment:"Title for button for user to choose to remain logged out.")
}
}
class LoginOrCreateAccountToSyncSavedArticlesToReadingListPanelViewController : ScrollableEducationPanelViewController {
override func viewDidLoad() {
super.viewDidLoad()
image = UIImage(named: "reading-list-user")
heading = WMFLocalizedString("reading-list-login-or-create-account-title", value:"Log in to sync saved articles", comment:"Title for syncing saved articles.")
subheading = CommonStrings.readingListLoginSubtitle
primaryButtonTitle = WMFLocalizedString("reading-list-login-or-create-account-button-title", value:"Log in or create account", comment:"Title for button to login or create account to sync saved articles and reading lists.")
}
}
class LimitHitForUnsortedArticlesPanelViewController: ScrollableEducationPanelViewController {
override func viewDidLoad() {
super.viewDidLoad()
heading = WMFLocalizedString("reading-list-limit-hit-for-unsorted-articles-title", value: "Limit hit for unsorted articles", comment: "Title for letting the user know that the limit for unsorted articles was reached.")
subheading = WMFLocalizedString("reading-list-limit-hit-for-unsorted-articles-subtitle", value: "There is a limit of 5000 unsorted articles. Please sort your existing articles into lists to continue the syncing of unsorted articles.", comment: "Subtitle letting the user know that there is a limit of 5000 unsorted articles.")
primaryButtonTitle = WMFLocalizedString("reading-list-limit-hit-for-unsorted-articles-button-title", value: "Sort articles", comment: "Title for button to sort unsorted articles.")
}
}
extension UIViewController {
fileprivate func hasSavedArticles() -> Bool {
let articleRequest = WMFArticle.fetchRequest()
articleRequest.predicate = NSPredicate(format: "savedDate != NULL")
articleRequest.fetchLimit = 1
articleRequest.sortDescriptors = []
let fetchedResultsController = NSFetchedResultsController(fetchRequest: articleRequest, managedObjectContext: SessionSingleton.sharedInstance().dataStore.viewContext, sectionNameKeyPath: nil, cacheName: nil)
do {
try fetchedResultsController.performFetch()
} catch _ {
return false
}
guard let fetchedObjects = fetchedResultsController.fetchedObjects else {
return false
}
return fetchedObjects.count > 0
}
@objc func wmf_showEnableReadingListSyncPanel(theme: Theme, oncePerLogin: Bool = false, didNotPresentPanelCompletion: (() -> Void)? = nil, dismissHandler: ScrollableEducationPanelDismissHandler? = nil) {
if oncePerLogin {
guard !UserDefaults.wmf_userDefaults().wmf_didShowEnableReadingListSyncPanel() else {
didNotPresentPanelCompletion?()
return
}
}
let presenter = self.presentedViewController ?? self
guard !isAlreadyPresenting(presenter),
WMFAuthenticationManager.sharedInstance.isLoggedIn,
SessionSingleton.sharedInstance().dataStore.readingListsController.isSyncRemotelyEnabled,
!SessionSingleton.sharedInstance().dataStore.readingListsController.isSyncEnabled else {
didNotPresentPanelCompletion?()
return
}
let enableSyncTapHandler: ScrollableEducationPanelButtonTapHandler = { _ in
self.presentedViewController?.dismiss(animated: true, completion: {
guard self.hasSavedArticles() else {
SessionSingleton.sharedInstance().dataStore.readingListsController.setSyncEnabled(true, shouldDeleteLocalLists: false, shouldDeleteRemoteLists: false)
SettingsFunnel.shared.logEnableSyncPopoverSyncEnabled()
return
}
self.wmf_showAddSavedArticlesToReadingListPanel(theme: theme)
})
}
let panelVC = EnableReadingListSyncPanelViewController(showCloseButton: true, primaryButtonTapHandler: enableSyncTapHandler, secondaryButtonTapHandler: nil, dismissHandler: dismissHandler, theme: theme)
presenter.present(panelVC, animated: true, completion: {
UserDefaults.wmf_userDefaults().wmf_setDidShowEnableReadingListSyncPanel(true)
// we don't want to present the "Sync disabled" panel if "Enable sync" was presented, wmf_didShowSyncDisabledPanel will be set to false when app is paused.
UserDefaults.wmf_userDefaults().wmf_setDidShowSyncDisabledPanel(true)
SettingsFunnel.shared.logEnableSyncPopoverImpression()
})
}
@objc func wmf_showSyncDisabledPanel(theme: Theme, wasSyncEnabledOnDevice: Bool) {
guard !UserDefaults.wmf_userDefaults().wmf_didShowSyncDisabledPanel(),
wasSyncEnabledOnDevice else {
return
}
let primaryButtonTapHandler: ScrollableEducationPanelButtonTapHandler = { _ in
self.presentedViewController?.dismiss(animated: true)
}
let panel = SyncDisabledPanelViewController(showCloseButton: true, primaryButtonTapHandler: primaryButtonTapHandler, secondaryButtonTapHandler: nil, dismissHandler: nil, theme: theme)
let presenter = self.presentedViewController ?? self
presenter.present(panel, animated: true) {
UserDefaults.wmf_userDefaults().wmf_setDidShowSyncDisabledPanel(true)
}
}
private func isAlreadyPresenting(_ presenter: UIViewController) -> Bool {
let presenter = self.presentedViewController ?? self
guard presenter is WMFThemeableNavigationController else {
return false
}
return presenter.presentedViewController != nil
}
@objc func wmf_showSyncEnabledPanelOncePerLogin(theme: Theme, wasSyncEnabledOnDevice: Bool) {
let presenter = self.presentedViewController ?? self
guard !isAlreadyPresenting(presenter),
!UserDefaults.wmf_userDefaults().wmf_didShowSyncEnabledPanel(),
!wasSyncEnabledOnDevice else {
return
}
let primaryButtonTapHandler: ScrollableEducationPanelButtonTapHandler = { _ in
self.presentedViewController?.dismiss(animated: true)
}
let panel = SyncEnabledPanelViewController(showCloseButton: true, primaryButtonTapHandler: primaryButtonTapHandler, secondaryButtonTapHandler: nil, dismissHandler: nil, theme: theme)
presenter.present(panel, animated: true) {
UserDefaults.wmf_userDefaults().wmf_setDidShowSyncEnabledPanel(true)
}
}
fileprivate func wmf_showAddSavedArticlesToReadingListPanel(theme: Theme) {
let addSavedArticlesToReadingListsTapHandler: ScrollableEducationPanelButtonTapHandler = { _ in
SessionSingleton.sharedInstance().dataStore.readingListsController.setSyncEnabled(true, shouldDeleteLocalLists: false, shouldDeleteRemoteLists: false)
SettingsFunnel.shared.logEnableSyncPopoverSyncEnabled()
self.presentedViewController?.dismiss(animated: true, completion: nil)
}
let deleteSavedArticlesFromDeviceTapHandler: ScrollableEducationPanelButtonTapHandler = { _ in
SessionSingleton.sharedInstance().dataStore.readingListsController.setSyncEnabled(true, shouldDeleteLocalLists: true, shouldDeleteRemoteLists: false)
SettingsFunnel.shared.logEnableSyncPopoverSyncEnabled()
self.presentedViewController?.dismiss(animated: true, completion: nil)
}
let panelVC = AddSavedArticlesToReadingListPanelViewController(showCloseButton: false, primaryButtonTapHandler: addSavedArticlesToReadingListsTapHandler, secondaryButtonTapHandler: deleteSavedArticlesFromDeviceTapHandler, dismissHandler: nil, theme: theme)
present(panelVC, animated: true, completion: nil)
}
@objc func wmf_showLoginViewController(theme: Theme, loginSuccessCompletion: (() -> Void)? = nil, loginDismissedCompletion: (() -> Void)? = nil) {
guard let loginVC = WMFLoginViewController.wmf_initialViewControllerFromClassStoryboard() else {
assertionFailure("Expected view controller(s) not found")
return
}
loginVC.loginSuccessCompletion = loginSuccessCompletion
loginVC.loginDismissedCompletion = loginDismissedCompletion
loginVC.apply(theme: theme)
present(WMFThemeableNavigationController(rootViewController: loginVC, theme: theme), animated: true)
}
@objc func wmf_showReloginFailedPanelIfNecessary(theme: Theme) {
guard WMFAuthenticationManager.sharedInstance.hasKeychainCredentials else {
return
}
let tryLoginAgainTapHandler: ScrollableEducationPanelButtonTapHandler = { _ in
self.presentedViewController?.dismiss(animated: true, completion: {
self.wmf_showLoginViewController(theme: theme)
})
}
let stayLoggedOutTapHandler: ScrollableEducationPanelButtonTapHandler = { _ in
self.presentedViewController?.dismiss(animated: true, completion: {
self.wmf_showKeepSavedArticlesOnDevicePanelIfNecessary(triggeredBy: .logout, theme: theme) {
WMFAuthenticationManager.sharedInstance.logout()
}
})
}
let panelVC = ReLoginFailedPanelViewController(showCloseButton: false, primaryButtonTapHandler: tryLoginAgainTapHandler, secondaryButtonTapHandler: stayLoggedOutTapHandler, dismissHandler: nil, theme: theme)
present(panelVC, animated: true, completion: nil)
}
@objc func wmf_showLoginOrCreateAccountToSyncSavedArticlesToReadingListPanel(theme: Theme, dismissHandler: ScrollableEducationPanelDismissHandler? = nil, loginSuccessCompletion: (() -> Void)? = nil, loginDismissedCompletion: (() -> Void)? = nil) {
LoginFunnel.shared.logLoginImpressionInSyncPopover()
let loginToSyncSavedArticlesTapHandler: ScrollableEducationPanelButtonTapHandler = { _ in
self.presentedViewController?.dismiss(animated: true, completion: {
self.wmf_showLoginViewController(theme: theme, loginSuccessCompletion: loginSuccessCompletion, loginDismissedCompletion: loginDismissedCompletion)
LoginFunnel.shared.logLoginStartInSyncPopover()
})
}
let panelVC = LoginOrCreateAccountToSyncSavedArticlesToReadingListPanelViewController(showCloseButton: true, primaryButtonTapHandler: loginToSyncSavedArticlesTapHandler, secondaryButtonTapHandler: nil, dismissHandler: dismissHandler, discardDismissHandlerOnPrimaryButtonTap: true, theme: theme)
present(panelVC, animated: true)
}
@objc func wmf_showLoginToSyncSavedArticlesToReadingListPanelOncePerDevice(theme: Theme) {
guard
!WMFAuthenticationManager.sharedInstance.isLoggedIn &&
!UserDefaults.wmf_userDefaults().wmf_didShowLoginToSyncSavedArticlesToReadingListPanel() &&
!SessionSingleton.sharedInstance().dataStore.readingListsController.isSyncEnabled
else {
return
}
LoginFunnel.shared.logLoginImpressionInSyncPopover()
let loginToSyncSavedArticlesTapHandler: ScrollableEducationPanelButtonTapHandler = { _ in
self.presentedViewController?.dismiss(animated: true, completion: {
self.wmf_showLoginViewController(theme: theme)
LoginFunnel.shared.logLoginStartInSyncPopover()
})
}
let panelVC = LoginToSyncSavedArticlesToReadingListPanelViewController(showCloseButton: true, primaryButtonTapHandler: loginToSyncSavedArticlesTapHandler, secondaryButtonTapHandler: nil, dismissHandler: nil, theme: theme)
present(panelVC, animated: true, completion: {
UserDefaults.wmf_userDefaults().wmf_setDidShowLoginToSyncSavedArticlesToReadingListPanel(true)
})
}
@objc func wmf_showKeepSavedArticlesOnDevicePanelIfNecessary(triggeredBy keepSavedArticlesTrigger: KeepSavedArticlesTrigger, theme: Theme, completion: @escaping (() -> Swift.Void) = {}) {
guard self.hasSavedArticles() else {
completion()
return
}
let keepSavedArticlesOnDeviceTapHandler: ScrollableEducationPanelButtonTapHandler = { _ in
SessionSingleton.sharedInstance().dataStore.readingListsController.setSyncEnabled(false, shouldDeleteLocalLists: false, shouldDeleteRemoteLists: false)
self.presentedViewController?.dismiss(animated: true, completion: nil)
}
let deleteSavedArticlesFromDeviceTapHandler: ScrollableEducationPanelButtonTapHandler = { _ in
SessionSingleton.sharedInstance().dataStore.readingListsController.setSyncEnabled(false, shouldDeleteLocalLists: true, shouldDeleteRemoteLists: false)
self.presentedViewController?.dismiss(animated: true, completion: nil)
}
let dismissHandler: ScrollableEducationPanelDismissHandler = {
completion()
}
let panelVC = KeepSavedArticlesOnDevicePanelViewController(triggeredBy: keepSavedArticlesTrigger, showCloseButton: false, primaryButtonTapHandler: keepSavedArticlesOnDeviceTapHandler, secondaryButtonTapHandler: deleteSavedArticlesFromDeviceTapHandler, dismissHandler: dismissHandler, discardDismissHandlerOnPrimaryButtonTap: false, theme: theme)
present(panelVC, animated: true, completion: nil)
}
@objc func wmf_showLimitHitForUnsortedArticlesPanelViewController(theme: Theme, primaryButtonTapHandler: @escaping ScrollableEducationPanelButtonTapHandler, completion: @escaping () -> Void) {
let panelVC = LimitHitForUnsortedArticlesPanelViewController(showCloseButton: true, primaryButtonTapHandler: primaryButtonTapHandler, secondaryButtonTapHandler: nil, dismissHandler: nil, theme: theme)
present(panelVC, animated: true, completion: completion)
}
}
| mit | 80e3f97fa67570939807ac206578c878 | 63.696429 | 450 | 0.73544 | 5.605467 | false | false | false | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.