repo_name
stringlengths 6
91
| path
stringlengths 6
999
| copies
stringclasses 283
values | size
stringlengths 1
7
| content
stringlengths 3
1.05M
| license
stringclasses 15
values |
---|---|---|---|---|---|
y0ke/actor-platform | actor-sdk/sdk-core-ios/ActorSDK/Sources/ElegantPresentationController.swift | 2 | 6274 | //
// ElegantPresentation.swift
// TwitterPresentationController
//
// Created by Kyle Bashour on 2/21/16.
// Copyright © 2016 Kyle Bashour. All rights reserved.
//
import UIKit
typealias CoordinatedAnimation = UIViewControllerTransitionCoordinatorContext? -> Void
class ElegantPresentationController: UIPresentationController {
// MARK: - Properties
/// Dims the presenting view controller, if option is set
private lazy var dimmingView: UIView = {
let view = UIView()
view.backgroundColor = UIColor.blackColor().colorWithAlphaComponent(0.5)
view.alpha = 0
view.userInteractionEnabled = false
return view
}()
/// For dismissing on tap if option is set
private lazy var recognizer: UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: Selector("dismiss:"))
/// An options struct containing the customization options set
private let options: PresentationOptions
// MARK: - Lifecycle
/**
Initializes and returns a presentation controller for transitioning between the specified view controllers
- parameter presentedViewController: The view controller being presented modally.
- parameter presentingViewController: The view controller whose content represents the starting point of the transition.
- parameter options: An options struct for customizing the appearance and behavior of the presentation.
- returns: An initialized presentation controller object.
*/
init(presentedViewController: UIViewController, presentingViewController: UIViewController, options: PresentationOptions) {
self.options = options
super.init(presentedViewController: presentedViewController, presentingViewController: presentingViewController)
}
// MARK: - Presenting and dismissing
override func presentationTransitionWillBegin() {
// If the option is set, then add the gesture recognizer for dismissal to the container
if options.dimmingViewTapDismisses {
containerView!.addGestureRecognizer(recognizer)
}
// Prepare and position the dimming view
dimmingView.alpha = 0
dimmingView.frame = containerView!.bounds
containerView?.insertSubview(dimmingView, atIndex: 0)
// Animate these properties with the transtion coordinator if possible
let animations: CoordinatedAnimation = { [unowned self] _ in
self.dimmingView.alpha = self.options.dimmingViewAlpha
self.presentingViewController.view.transform = self.options.presentingTransform
}
transtionWithCoordinator(animations)
}
override func dismissalTransitionWillBegin() {
// Animate these properties with the transtion coordinator if possible
let animations: CoordinatedAnimation = { [unowned self] _ in
self.dimmingView.alpha = 0
self.presentingViewController.view.transform = CGAffineTransformIdentity
}
transtionWithCoordinator(animations)
}
// MARK: - Adaptation
override func viewWillTransitionToSize(size: CGSize, withTransitionCoordinator coordinator: UIViewControllerTransitionCoordinator) {
/*
There's a bug when rotating that makes the presented view controller permanently
larger or smaller if this isn't here. I'm probably doing something wrong :P
It jumps because it's not in the animation block, but isn't noticiable unless in
slow-mo. Placing it in the animation block does not fix the issue, so here it is.
*/
presentingViewController.view.transform = CGAffineTransformIdentity
// Animate these with the coordinator
let animations: CoordinatedAnimation = { [unowned self] _ in
self.dimmingView.frame = self.containerView!.bounds
self.presentingViewController.view.transform = self.options.presentingTransform
self.presentedView()?.frame = self.frameOfPresentedViewInContainerView()
}
coordinator.animateAlongsideTransition(animations, completion: nil)
}
override func sizeForChildContentContainer(container: UIContentContainer, withParentContainerSize parentSize: CGSize) -> CGSize {
// Percent height doesn't make sense as a negative value or greater than zero, so we'll enforce it
let percentHeight = min(abs(options.presentedPercentHeight), 1)
// Return the appropiate height based on which option is set
if options.usePercentHeight {
return CGSize(width: parentSize.width, height: parentSize.height * CGFloat(percentHeight))
}
else if options.presentedHeight > 0 {
return CGSize(width: parentSize.width, height: options.presentedHeight)
}
return parentSize
}
override func frameOfPresentedViewInContainerView() -> CGRect {
// Grab the parent and child sizes
let parentSize = containerView!.bounds.size
let childSize = sizeForChildContentContainer(presentedViewController, withParentContainerSize: parentSize)
// Create and return an appropiate frame
return CGRect(x: 0, y: parentSize.height - childSize.height, width: childSize.width, height: childSize.height)
}
// MARK: - Helper functions
// For the tap-to-dismiss
func dismiss(sender: UITapGestureRecognizer) {
presentedViewController.dismissViewControllerAnimated(true, completion: nil)
}
/*
I noticed myself doing this a lot (more so in earlier versions) so I made a quick function.
Simply takes a closure with animations in them and attempts to animate with the coordinator.
*/
private func transtionWithCoordinator(animations: CoordinatedAnimation) {
if let coordinator = presentingViewController.transitionCoordinator() {
coordinator.animateAlongsideTransition(animations, completion: nil)
}
else {
animations(nil)
}
}
} | agpl-3.0 |
milseman/swift | test/TypeCoercion/overload_noncall.swift | 9 | 1937 | // RUN: %target-typecheck-verify-swift
struct X { }
struct Y { }
struct Z { }
func f0(_ x1: X, x2: X) -> X {} // expected-note{{found this candidate}}
func f0(_ y1: Y, y2: Y) -> Y {} // expected-note{{found this candidate}}
var f0 : X // expected-note {{found this candidate}} expected-note {{'f0' previously declared here}}
func f0_init(_ x: X, y: Y) -> X {}
var f0 : (_ x : X, _ y : Y) -> X = f0_init // expected-error{{invalid redeclaration}}
func f1(_ x: X) -> X {}
func f2(_ g: (_ x: X) -> X) -> ((_ y: Y) -> Y) { }
func test_conv() {
var _ : (_ x1 : X, _ x2 : X) -> X = f0
var _ : (X, X) -> X = f0
var _ : (Y, X) -> X = f0 // expected-error{{ambiguous reference to member 'f0(_:x2:)'}}
var _ : (X) -> X = f1
var a7 : (X) -> (X) = f1
var a8 : (_ x2 : X) -> (X) = f1
var a9 : (_ x2 : X) -> ((X)) = f1
a7 = a8
a8 = a9
a9 = a7
var _ : ((X) -> X) -> ((Y) -> Y) = f2
var _ : ((_ x2 : X) -> (X)) -> (((_ y2 : Y) -> (Y))) = f2
typealias fp = ((X) -> X) -> ((Y) -> Y)
var _ = f2
}
var xy : X // expected-note {{previously declared here}}
var xy : Y // expected-error {{invalid redeclaration of 'xy'}}
func accept_X(_ x: inout X) { }
func accept_XY(_ x: inout X) -> X { }
func accept_XY(_ y: inout Y) -> Y { }
func accept_Z(_ z: inout Z) -> Z { }
func test_inout() {
var x : X
accept_X(&x);
accept_X(xy); // expected-error{{passing value of type 'X' to an inout parameter requires explicit '&'}} {{12-12=&}}
accept_X(&xy);
_ = accept_XY(&x);
x = accept_XY(&xy);
x = xy
x = &xy; // expected-error{{cannot assign value of type 'inout X' to type 'X'}}
accept_Z(&xy); // expected-error{{cannot convert value of type 'X' to expected argument type 'Z'}}
}
func lvalue_or_rvalue(_ x: inout X) -> X { }
func lvalue_or_rvalue(_ x: X) -> Y { }
func test_lvalue_or_rvalue() {
var x : X
var y : Y
let x1 = lvalue_or_rvalue(&x)
x = x1
let y1 = lvalue_or_rvalue(x)
y = y1
_ = y
}
| apache-2.0 |
beyerss/CalendarKit | CalendarKitTests/MonthTests.swift | 1 | 8953 | //
// MonthTests.swift
// CalendarKit
//
// Created by Steven Beyers on 6/17/16.
// Copyright © 2016 Beyers Apps, LLC. All rights reserved.
//
import XCTest
@testable import CalendarKit
class MonthTests: XCTestCase {
let initialDate = NSDate()
override func setUp() {
super.setUp()
// Put setup code here. This method is called before the invocation of each test method in the class.
}
override func tearDown() {
// Put teardown code here. This method is called after the invocation of each test method in the class.
super.tearDown()
}
func createMonth() -> Month {
return Month(monthDate: initialDate)
}
func testCreateMonth() {
XCTAssertTrue(initialDate == createMonth().date, "Date not set properly")
}
func testMonthName() {
let month = createMonth()
let dateFormat = "MMM"
month.useMonthFormat(dateFormat)
let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = dateFormat
let name = dateFormatter.stringFromDate(month.date)
XCTAssertTrue(name == month.monthName(), "The month name should be \(name)")
}
func testIsEqualTrue() {
let firstMonth = createMonth()
let secondMonth = createMonth()
XCTAssertTrue(firstMonth.isEqual(firstMonth), "A Month should be equal to itself")
XCTAssertTrue(firstMonth.isEqual(secondMonth), "A month should be equal to another month in the same month and year")
XCTAssertTrue(secondMonth.isEqual(firstMonth), "Reversing the months should produce the same result")
}
func testIsEqualForNonMonth() {
let firstMonth = createMonth()
let secondObject = NSObject()
XCTAssertFalse(firstMonth.isEqual(secondObject), "A month is not equal to a non-Month object")
}
func testIsEqualForOutsideOfMonth() {
let firstMonth = createMonth()
let secondMonth = Month(monthDate: NSDate(timeIntervalSinceNow: 60*60*24*32))
XCTAssertFalse(firstMonth.isEqual(secondMonth), "A month is not equal to a Month object in another month")
}
func testIsEqualForOutsideOfYear() {
let firstMonth = createMonth()
let secondMonth = Month(monthDate: NSDate(timeIntervalSinceNow: 60*60*24*365))
XCTAssertFalse(firstMonth.isEqual(secondMonth), "A month is not equal to a month object of the same month but a different year")
}
func testCreateMonthWithOffset() {
let firstMonth = createMonth()
for i in 0...10 {
let nextMonthDate = NSCalendar.currentCalendar().dateByAddingUnit(.Month, value: i, toDate: initialDate, options: [])!
let secondMonth = Month(otherMonth: firstMonth, offsetMonths: i)
XCTAssertTrue(nextMonthDate == secondMonth.date, "Date of second month should be the same as the next month date")
}
}
func testNumberOfDaysInMonth() {
let calendar = NSCalendar.currentCalendar()
let components = calendar.components([.Day, .Month, .Year], fromDate: NSDate())
components.year = 2016
components.day = 1
for i in 1...12 {
let correctNumberOfDats: Int
switch i {
case 1:
correctNumberOfDats = 31
case 2:
correctNumberOfDats = 29 // 2016 is a leap year
case 3:
correctNumberOfDats = 31
case 4:
correctNumberOfDats = 30
case 5:
correctNumberOfDats = 31
case 6:
correctNumberOfDats = 30
case 7:
correctNumberOfDats = 31
case 8:
correctNumberOfDats = 31
case 9:
correctNumberOfDats = 30
case 10:
correctNumberOfDats = 31
case 11:
correctNumberOfDats = 30
default:
correctNumberOfDats = 31
}
components.month = i
if let dateFromComponents = calendar.dateFromComponents(components) {
let month = Month(monthDate: dateFromComponents)
XCTAssertTrue(correctNumberOfDats == month.numberOfDaysInMonth(), "Incorrect number of days in month returned.")
} else {
XCTFail("The month date was not created")
}
}
}
func testFirstDayOfWeek() {
let calendar = NSCalendar.currentCalendar()
let components = calendar.components([.Day, .Month, .Year], fromDate: NSDate())
components.year = 2016
components.day = 1
for i in 1...12 {
let firstDay: Int
switch i {
case 1:
firstDay = 5
case 2:
firstDay = 1
case 3:
firstDay = 2
case 4:
firstDay = 5
case 5:
firstDay = 0
case 6:
firstDay = 3
case 7:
firstDay = 5
case 8:
firstDay = 1
case 9:
firstDay = 4
case 10:
firstDay = 6
case 11:
firstDay = 2
default:
firstDay = 4
}
components.month = i
if let dateFromComponents = calendar.dateFromComponents(components) {
let month = Month(monthDate: dateFromComponents)
XCTAssertTrue(firstDay == month.firstDayOfWeek(), "Incorrect first day returned.")
} else {
XCTFail("The month date was not created")
}
}
}
func testWeeksInMonth() {
let calendar = NSCalendar.currentCalendar()
let components = calendar.components([.Day, .Month, .Year], fromDate: NSDate())
components.day = 1
for i in 1...12 {
components.year = 2016
let numberOfWeeks: Int
switch i {
case 1:
numberOfWeeks = 6
case 2:
// set the year to 2015 since it is exactly 4 weeks
components.year = 2015
numberOfWeeks = 4
case 3:
numberOfWeeks = 5
case 4:
numberOfWeeks = 5
case 5:
numberOfWeeks = 5
case 6:
numberOfWeeks = 5
case 7:
numberOfWeeks = 6
case 8:
numberOfWeeks = 5
case 9:
numberOfWeeks = 5
case 10:
numberOfWeeks = 6
case 11:
numberOfWeeks = 5
default:
numberOfWeeks = 5
}
components.month = i
if let dateFromComponents = calendar.dateFromComponents(components) {
let month = Month(monthDate: dateFromComponents)
XCTAssertTrue(numberOfWeeks == month.weeksInMonth(), "Incorrect weeks in month returned.")
} else {
XCTFail("The month date was not created")
}
}
}
func testGetDateForCell() {
let calendar = NSCalendar.currentCalendar()
let components = calendar.components([.Day, .Month, .Year], fromDate: NSDate())
components.day = 1
components.month = 6
components.year = 2016
let month: Month
guard let dateFromComponents = calendar.dateFromComponents(components) else {
XCTFail("Could not create first date from components")
return
}
month = Month(monthDate: dateFromComponents)
for i in 3...30 {
let retDate = month.getDateForCell(indexPath: NSIndexPath(forRow: i, inSection: 0))
let retComponents = calendar.components([.Day, .Month, .Year], fromDate: retDate)
XCTAssertTrue(retComponents.day == components.day, "The returned day is not correct")
XCTAssertTrue(retComponents.month == components.month, "The returned month is not correct")
XCTAssertTrue(retComponents.year == components.year, "The returned year is not correct")
components.day = components.day + 1
}
}
func testIsDateOutOfMonthFalse() {
XCTAssertFalse(createMonth().isDateOutOfMonth(initialDate), "The initial date should never be outside of the month")
}
func testIsDateOutOfMonthTrue() {
XCTAssertTrue(createMonth().isDateOutOfMonth(NSDate(timeIntervalSinceNow: 60*60*24*40)), "The date should always be outside of the month")
}
}
| mit |
jboullianne/EndlessTunes | EndlessSoundFeed/ETEvent.swift | 1 | 2133 | //
// ETEvent.swift
// EndlessSoundFeed
//
// Created by Jean-Marc Boullianne on 6/18/17.
// Copyright © 2017 Jean-Marc Boullianne. All rights reserved.
//
import Foundation
class ETEvent {
var type:ETEventType
var author:String
var authorUID:String
var track:Track?
var playlist:Playlist?
var follower:String?
var followerUID:String?
var date:Date
init(type: ETEventType, author:String, authorUID:String, date:Date) {
self.type = type
self.author = author
self.authorUID = authorUID
self.date = date
}
}
extension ETEvent {
var dateString:String {
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss zzz"
return dateFormatter.string(from: self.date)
}
static func getDateFromString(dateString: String) -> Date {
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss zzz"
return dateFormatter.date(from: dateString)!
}
func timeStringFromNow() -> String {
let dateInterval = DateInterval(start: self.date, end: Date())
let difference = dateInterval.duration
let minutes = Int(difference.divided(by: 60))
let hours = Int(difference.divided(by: 3600))
let days = Int(difference.divided(by: 86400))
if(days > 1){
return "\(days) days ago"
}else if (days == 1){
return "Yesterday"
}else if(hours == 1){
return "1 hour ago"
}else if(hours > 1){
return "\(hours) hours ago"
}else if(minutes > 1){
return "\(minutes) minutes ago"
}
return "Just Now"
}
}
enum ETEventType {
case SharedPlaylist
case CreatedPlaylist
case Activity
func toString() -> String{
switch self {
case .Activity:
return "Activity"
case .CreatedPlaylist:
return "Created Playlist"
case .SharedPlaylist:
return "Shared Playlist"
}
}
}
| gpl-3.0 |
36Kr-Mobile/StatusBarNotificationCenter | Pod/Configuration/NotificationCenterConfiguration.swift | 1 | 2544 | //
// NotificationCenterConfiguration.swift
// StatusBarNotification
//
// Created by Shannon Wu on 9/18/15.
// Copyright © 2015 Shannon Wu. All rights reserved.
//
import Foundation
/**
* Customize the overall configuration information of the notification, most of the property's default value is OK for most circumstance, but you can customize it if you want
*/
public struct NotificationCenterConfiguration {
/// The window below the notification window, you must set this property, or the notification will not work correctly
var baseWindow: UIWindow
/// The style of the notification, default to status bar notification
public var style = StatusBarNotificationCenter.Style.statusBar
/// The animation type of the notification, default to overlay
public var animationType = StatusBarNotificationCenter.AnimationType.overlay
/// The animate in direction of the notification, default to top
public var animateInDirection = StatusBarNotificationCenter.AnimationDirection.top
/// The animate out direction of the notification, default to top
public var animateOutDirection = StatusBarNotificationCenter.AnimationDirection.top
/// Whether the user can tap on the notification to dismiss the notification, default to true
public var dismissible = true
/// The animate in time of the notification
public var animateInLength: TimeInterval = 0.25
/// The animate out time of the notification
public var animateOutLength: TimeInterval = 0.25
/// The height of the notification view, if you want to use a custom height, set the style of the notification to custom, or it will use the status bar and navigation bar height
public var height: CGFloat = 0
/// If the status bar is hidden, if it is hidden, the hight of the navigation style notification height is the height of the navigation bar, default to false
public var statusBarIsHidden: Bool = false
/// The height of the navigation bar, default to 44.0 points
public var navigationBarHeight: CGFloat = 44.0
/// Should allow the user to interact with the content outside the notification
public var userInteractionEnabled = true
/// The window level of the notification window
public var level: CGFloat = UIWindowLevelNormal
/**
Initializer
- parameter baseWindow: the base window of the notification
- returns: a default NotificationCenterConfiguration instance
*/
public init(baseWindow: UIWindow) {
self.baseWindow = baseWindow
}
}
| mit |
P0ed/Fx | Sources/Fx/Reactive/Disposable.swift | 1 | 3989 | /// Represents something that can be “disposed,” usually associated with freeing
/// resources or canceling work.
public protocol Disposable: AnyObject {
func dispose()
}
/// A disposable that will not dispose on deinit
public final class ManualDisposable: Disposable {
private let action: Atomic<(() -> Void)?>
/// Initializes the disposable to run the given action upon disposal.
public init(action: @escaping () -> Void) {
self.action = Atomic(action)
}
public func dispose() {
let oldAction = action.swap(nil)
oldAction?()
}
}
/// A disposable that will run an action upon disposal. Disposes on deinit.
public final class ActionDisposable: Disposable {
private let manualDisposable: ManualDisposable
/// Initializes the disposable to run the given action upon disposal.
public init(action: @escaping () -> Void) {
manualDisposable = ManualDisposable(action: action)
}
deinit {
dispose()
}
public func dispose() {
manualDisposable.dispose()
}
}
/// A disposable that will dispose of any number of other disposables. Disposes on deinit.
public final class CompositeDisposable: Disposable {
private let disposables: Atomic<Bag<Disposable>>
/// Initializes a CompositeDisposable containing the given sequence of
/// disposables.
public init<S: Sequence>(_ disposables: S) where S.Iterator.Element == Disposable {
var bag: Bag<Disposable> = Bag()
for disposable in disposables {
_ = bag.insert(disposable)
}
self.disposables = Atomic(bag)
}
/// Initializes an empty CompositeDisposable.
public convenience init() {
self.init([])
}
deinit {
dispose()
}
public func dispose() {
let ds = disposables.swap(Bag())
for d in ds.reversed() {
d.dispose()
}
}
/// Adds the given disposable to the list, then returns a handle which can
/// be used to opaquely remove the disposable later (if desired).
public func addDisposable(_ disposable: Disposable) -> ManualDisposable {
var token: RemovalToken!
disposables.modify {
token = $0.insert(disposable)
}
return ManualDisposable { [weak self] in
self?.disposables.modify {
$0.removeValueForToken(token)
}
}
}
/// Adds the right-hand-side disposable to the left-hand-side
/// `CompositeDisposable`.
///
/// disposable += producer
/// .filter { ... }
/// .map { ... }
/// .start(observer)
///
@discardableResult
public static func +=(lhs: CompositeDisposable, rhs: Disposable) -> ManualDisposable {
lhs.addDisposable(rhs)
}
@discardableResult
public static func += (disposable: CompositeDisposable, action: @escaping () -> Void) -> ManualDisposable {
disposable += ActionDisposable(action: action)
}
@discardableResult
public func capture(_ object: Any) -> ManualDisposable {
self += { Fx.capture(object) }
}
}
/// A disposable that will optionally dispose of another disposable. Disposes on deinit.
public final class SerialDisposable: Disposable {
private let atomicDisposable = Atomic(Disposable?.none)
/// The inner disposable to dispose of.
///
/// Whenever this property is set (even to the same value!), the previous
/// disposable is automatically disposed.
public var innerDisposable: Disposable? {
get {
atomicDisposable.value
}
set {
let oldDisposable = atomicDisposable.swap(newValue)
oldDisposable?.dispose()
}
}
/// Initializes the receiver to dispose of the argument when the
/// SerialDisposable is disposed.
public init(_ disposable: Disposable? = nil) {
innerDisposable = disposable
}
deinit {
dispose()
}
public func dispose() {
innerDisposable = nil
}
}
public extension ManualDisposable {
static func • (lhs: ManualDisposable, rhs: ManualDisposable) -> ManualDisposable {
ManualDisposable(action: lhs.dispose • rhs.dispose)
}
}
public extension ActionDisposable {
static func • (lhs: ActionDisposable, rhs: ActionDisposable) -> ActionDisposable {
ActionDisposable(action: lhs.dispose • rhs.dispose)
}
}
| mit |
Cosmo/TinyConsole | TinyConsole/Extensions/UIButtonExtensions.swift | 1 | 338 | //
// UIButtonExtensions.swift
// TinyConsole
//
// Created by Devran on 30.09.19.
//
import UIKit
internal extension UIButton {
func applyMiniStyle() {
contentEdgeInsets = UIEdgeInsets(top: 8, left: 8, bottom: 8, right: 8)
backgroundColor = UIColor(white: 1.0, alpha: 0.1)
layer.cornerRadius = 4
}
}
| mit |
mindbody/Conduit | Tests/ConduitTests/Networking/ResultTests.swift | 1 | 3474 | //
// ResultTests.swift
// ConduitTests
//
// Created by Eneko Alonso on 3/27/17.
// Copyright © 2017 MINDBODY. All rights reserved.
//
import XCTest
import Conduit
class ResultTests: XCTestCase {
func testResultShouldStoreAnInt() {
let sut = Result.value(3)
if case .value(let int) = sut {
XCTAssertEqual(int, 3)
}
else {
XCTFail("Expected .value(<Int>)")
}
}
func testResultShouldBeAbleToStoreAnError() {
let sut = Result<Int>.error(SomeError.someCase)
if case .error(let err) = sut, let error = err as? SomeError, case .someCase = error {
// Pass
}
else {
XCTFail("Expected .error(.other(\"something wrong\")")
}
}
func testResultShouldStoreVoid() {
let sut = Result<Void>.value(())
if case .value = sut {
// Pass
}
else {
XCTFail("Expected .value, got \(sut)")
}
}
func testRewrappingAResultShouldAllowDifferentTypesWithoutChangingTheUnderlyingError() {
let result = Result<Int>.error(MyError.errorOne)
let rNew = result.convert { return Int64($0) } // Conversion we don't care about.
if case .error(let error) = rNew {
if let error = error as? MyError {
XCTAssertEqual(error, MyError.errorOne)
}
else {
XCTFail("Unexpected error type")
}
}
else {
XCTFail("Didn't get an error")
}
}
func testShouldAllowRewrappingTheErrorWithADifferentError() {
let result = Result<Int>.error(MyError.errorOne)
// Converts the underlying error to a different case, but leaves the value unchanged.
let rNew = result.convert(errorConverter: { _ in
return MyError.errorTwo
}, valueConverter: { return $0 })
if case .error(let error) = rNew {
if let error = error as? MyError {
XCTAssertEqual(error, MyError.errorTwo)
}
else {
XCTFail("Unexpected error type")
}
}
else {
XCTFail("Didn't get an error")
}
}
func testOptionalValueGetter() {
XCTAssertEqual(Result<Int>.value(1).value, 1)
XCTAssertNil(Result<Int>.error(SomeError.someCase).value)
}
func testOptionalErrorGetter() {
let error = Result<Int>.error(MyError.errorOne).error
XCTAssertNotNil(error)
guard case .some(MyError.errorOne) = error else {
XCTFail("Unexpected error")
return
}
XCTAssertNil(Result<Int>.value(1).error)
}
func testThrowingValueGetter() throws {
XCTAssertEqual(try Result<Int>.value(1).valueOrThrow(), 1)
XCTAssertThrowsError(try Result<Int>.error(SomeError.someCase).valueOrThrow())
}
func testThrowingValueGetterWithVoid() {
XCTAssertNoThrow(try Result<Void>.value(()).valueOrThrow())
}
func testThrowingValueGetterErrorType() throws {
do {
_ = try Result<Int>.error(SomeError.someCase).valueOrThrow()
}
catch SomeError.someCase {
// Pass
}
catch {
XCTFail("Unexpected error type")
}
}
}
private enum SomeError: Error {
case someCase
}
private enum MyError: Error, Equatable {
case errorOne
case errorTwo
}
| apache-2.0 |
TheAppCookbook/MiseEnPlace | Source/KeyboardLayoutConstraint.swift | 1 | 2497 | //
// KeyboardLayoutConstraint.swift
// MiseEnPlace
//
// Inspired by James Tang's work with Spring.
//
// Created by PATRICK PERINI on 9/12/15.
// Copyright © 2015 pcperini. All rights reserved.
//
import UIKit
public class KeyboardLayoutConstraint: NSLayoutConstraint {
// MARK: Properties
private var offset: CGFloat = 0.0
private var keyboardHeight: CGFloat = 0.0 {
didSet {
self.constant = self.offset + self.keyboardHeight
}
}
// MARK: Mutators
private func updateKeyboardHeight(userInfo: NSDictionary) {
if let frameValue = userInfo[UIKeyboardFrameEndUserInfoKey] as? NSValue {
let frame = frameValue.CGRectValue()
self.keyboardHeight = frame.height
} else {
self.keyboardHeight = 0.0
}
if let durationValue = userInfo[UIKeyboardAnimationDurationUserInfoKey] as? NSNumber,
let curveValue = userInfo[UIKeyboardAnimationCurveUserInfoKey] as? NSNumber {
let options = UIViewAnimationOptions(rawValue: curveValue.unsignedLongValue)
let duration = NSTimeInterval(durationValue.doubleValue)
UIView.animateWithDuration(duration, delay: 0, options: options, animations: { () -> Void in
UIApplication.sharedApplication().keyWindow?.layoutIfNeeded()
}, completion: nil)
}
}
// MARK: Lifecycle
public override func awakeFromNib() {
super.awakeFromNib()
self.offset = self.constant
NSNotificationCenter.defaultCenter().addObserver(self,
selector: "keyboardWillShow:",
name: UIKeyboardWillShowNotification,
object: nil)
NSNotificationCenter.defaultCenter().addObserver(self,
selector: "keyboardWillHide:",
name: UIKeyboardWillHideNotification,
object: nil)
}
deinit {
NSNotificationCenter.defaultCenter().removeObserver(self)
}
// MARK: Responders
func keyboardWillShow(notification: NSNotification) {
guard let userInfo = notification.userInfo else { return }
self.updateKeyboardHeight(userInfo)
}
func keyboardWillHide(notification: NSNotification) {
guard var userInfo = notification.userInfo else { return }
userInfo.removeValueForKey(UIKeyboardFrameEndUserInfoKey)
self.updateKeyboardHeight(userInfo)
}
}
| mit |
jam891/BFKit-Swift | Source/BFKit/BFLog.swift | 3 | 3269 | //
// BFLog.swift
// BFKit
//
// The MIT License (MIT)
//
// Copyright (c) 2015 Fabrizio Brancati. All rights reserved.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
import Foundation
import UIKit
// MARK: - Global variables -
/// Use this variable to activate or deactivate the BFLog function
public var BFLogActive: Bool = true
// MARK: - Global functions -
/**
Exented NSLog
:param: message Console message
:param: filename File
:param: function Function name
:param: line Line number
*/
public func BFLog(var message: String, filename: String = __FILE__, function: String = __FUNCTION__, line: Int = __LINE__)
{
if BFLogActive
{
if message.hasSuffix("\n") == false
{
message += "\n"
}
BFLogClass.logString += message
let filenameNoExt = NSString(UTF8String: filename)!.lastPathComponent.stringByDeletingPathExtension
let log = "(\(function)) (\(filenameNoExt):\(line) \(message)"
let timestamp = NSDate.dateInformationDescriptionWithInformation(NSDate().dateInformation(), dateSeparator: "-", usFormat: true, nanosecond: true)
print("\(timestamp) \(filenameNoExt):\(line) \(function): \(message)")
BFLogClass.detailedLogString += log
}
}
/// Get the log string
public var BFLogString: String
{
if BFLogActive
{
return BFLogClass.logString
}
else
{
return ""
}
}
/// Get the detailed log string
public var BFDetailedLogString: String
{
if BFLogActive
{
return BFLogClass.detailedLogString
}
else
{
return ""
}
}
/**
Clear the log string
*/
public func BFLogClear()
{
if BFLogActive
{
BFLogClass.clearLog()
}
}
/// The private BFLogClass created to manage the log strings
private class BFLogClass
{
// MARK: - Variables -
/// The log string
private static var logString: String = ""
/// The detailed log string
private static var detailedLogString: String = ""
// MARK: - Class functions -
/**
Private, clear the log string
*/
private static func clearLog()
{
logString = ""
detailedLogString = ""
}
}
| mit |
bre7/FBAnnotationClusteringSwift | Source/FBAnnotationCluster.swift | 1 | 508 | //
// FBAnnotationCluster.swift
// FBAnnotationClusteringSwift
//
// Created by Robert Chen on 4/2/15.
// Copyright (c) 2015 Robert Chen. All rights reserved.
//
import Foundation
import MapKit
public class FBAnnotationCluster : NSObject {
public var coordinate = CLLocationCoordinate2D(latitude: 0.0, longitude: 0.0)
public var title:String? = ""
public var subtitle:String? = nil
public var annotations:[MKAnnotation] = []
}
extension FBAnnotationCluster : MKAnnotation { } | mit |
naoty/Playground | Repository/Repository/Repository.swift | 1 | 1062 | //
// Repository.swift
// Repository
//
// Created by Naoto Kaneko on 3/4/16.
// Copyright © 2016 Naoto Kaneko. All rights reserved.
//
import SwiftTask
import AnyQuery
protocol Repository {
typealias Domain
func find(ID: UInt) -> Task<Float, Domain, ErrorType>
func findAll() -> Task<Float, [Domain], ErrorType>
func findAll(query query: AnyQuery?, sort: AnySort?) -> Task<Float, [Domain], ErrorType>
func save(domains: [Domain])
func delete(domains: [Domain])
}
extension Repository {
func find(ID: UInt) -> Task<Float, Domain, ErrorType> {
fatalError("Not implemented")
}
func findAll() -> Task<Float, [Domain], ErrorType> {
return findAll(query: .None, sort: .None)
}
func findAll(query query: AnyQuery?, sort: AnySort?) -> Task<Float, [Domain], ErrorType> {
fatalError("Not implemented")
}
func save(domains: [Domain]) {
fatalError("Not implemented")
}
func delete(domains: [Domain]) {
fatalError("Not implemented")
}
}
| mit |
michalkonturek/MKUnits | MKUnits/Classes/Unit.swift | 1 | 6595 | //
// Unit.swift
// MKUnits
//
// Copyright (c) 2016 Michal Konturek <michal.konturek@gmail.com>
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
import Foundation
/**
Represents an `unit of measurement`.
- author: Michal Konturek
*/
open class Unit {
open let name: String
open let symbol: String
open let ratio: NSDecimalNumber
/**
Instantiates an `Unit` object.
- parameter name: `unit name`.
- parameter symbol: `unit symbol`.
- parameter ratio: conversion ratio to a `base unit`.
- author: Michal Konturek
*/
public init(name: String, symbol: String, ratio: NSNumber) {
self.name = name
self.symbol = symbol
self.ratio = NSDecimalNumber(decimal: ratio.decimalValue)
}
/**
Converts given `amount` from `base unit` to `this unit`.
- parameter amount: `amount` in `base unit`.
- returns: `amount` converted to `this unit`.
- author: Michal Konturek
*/
open func convertFromBaseUnit(_ amount: NSNumber) -> NSNumber {
let converted = NSDecimalNumber(decimal: amount.decimalValue)
return converted.dividing(by: self.ratio)
}
/**
Converts given `amount` from `this unit` to `base unit`.
- parameter amount: `amount` in `this unit`.
- returns: `amount` converted to `base unit`.
- author: Michal Konturek
*/
open func convertToBaseUnit(_ amount: NSNumber) -> NSNumber {
let converted = NSDecimalNumber(decimal: amount.decimalValue)
return converted.multiplying(by: self.ratio)
}
}
// MARK: - CustomStringConvertible
extension Unit: CustomStringConvertible {
public var description: String {
return self.symbol
}
}
// MARK: - UnitConvertible
/**
A type with ability to convert between units.
- author: Michal Konturek
*/
public protocol UnitConvertible {
/**
Converts `amount` from `this unit` to `destination unit`.
- parameter amount: `amount` in `this unit`.
- parameter to: `destination unit`.
- returns: `amount` converted to `destination unit`.
- author: Michal Konturek
*/
func convert(_ amount: NSNumber, to: Unit) -> NSNumber
/**
Converts `amount` from `source unit` to `this unit`.
- parameter amount: `amount` in `source unit`.
- parameter from: `source unit`.
- returns: `amount` converted from `source unit` to `this unit`.
- author: Michal Konturek
*/
func convert(_ amount: NSNumber, from: Unit) -> NSNumber
/**
Converts `amount` from `source unit` to `destination unit`.
- parameter amount: `amount` in `source unit`.
- parameter from: `source unit`.
- parameter to: `destination unit`.
- returns: `amount` converted from `source unit` to `destination unit`.
- author: Michal Konturek
*/
func convert(_ amount: NSNumber, from: Unit, to: Unit) -> NSNumber
/**
Returns `true` if `this unit` is convertible with `other unit`.
- parameter with: `other unit` to compare with.
- author: Michal Konturek
*/
func isConvertible(_ with: Unit) -> Bool
}
extension Unit: UnitConvertible {
/**
Converts `amount` from `this unit` to `destination unit`.
- parameter amount: `amount` in `this unit`.
- parameter to: `destination unit`.
- returns: `amount` converted to `destination unit`.
- author: Michal Konturek
*/
public func convert(_ amount: NSNumber, to: Unit) -> NSNumber {
return self.convert(amount, from: self, to: to)
}
/**
Converts `amount` from `source unit` to `this unit`.
- parameter amount: `amount` in `source unit`.
- parameter from: `source unit`.
- returns: `amount` converted from `source unit` to `this unit`.
- author: Michal Konturek
*/
public func convert(_ amount: NSNumber, from: Unit) -> NSNumber {
return self.convert(amount, from: from, to: self)
}
/**
Converts `amount` from `source unit` to `destination unit`.
- parameter amount: `amount` in `source unit`.
- parameter from: `source unit`.
- parameter to: `destination unit`.
- returns: `amount` converted from `source unit` to `destination unit`.
- author: Michal Konturek
*/
public func convert(_ amount: NSNumber, from: Unit, to: Unit) -> NSNumber {
let baseAmount = from.convertToBaseUnit(amount)
let converted = to.convertFromBaseUnit(baseAmount)
return converted
}
/**
Returns `true` if `this unit` is convertible with `other unit`.
- parameter with: `other unit` to compare with.
- author: Michal Konturek
*/
public func isConvertible(_ with: Unit) -> Bool {
return type(of: with) == type(of: self)
}
}
// MARK: - Equatable
extension Unit: Equatable {
/**
Returns `true` if `this unit` is the same as `other unit`.
- important: Comparison is done on `type` and `unit symbol`.
- parameter other: `other unit` to compare with.
- author: Michal Konturek
*/
public func equals(_ other: Unit) -> Bool {
if type(of: other) !== type(of: self) {
return false
}
return self.symbol == other.symbol
}
}
public func == <T>(lhs: T, rhs: T) -> Bool where T: Unit {
return lhs.equals(rhs)
}
| mit |
nathawes/swift | test/decl/class/actor/noconcurrency.swift | 1 | 153 | // RUN: %target-typecheck-verify-swift
actor class C { } // expected-error{{'actor' attribute is only valid when experimental concurrency is enabled}}
| apache-2.0 |
nathawes/swift | test/SILGen/generic_closures.swift | 8 | 15391 |
// RUN: %target-swift-emit-silgen -module-name generic_closures -parse-stdlib %s | %FileCheck %s
import Swift
var zero: Int
// CHECK-LABEL: sil hidden [ossa] @$s16generic_closures0A21_nondependent_context{{[_0-9a-zA-Z]*}}F
func generic_nondependent_context<T>(_ x: T, y: Int) -> Int {
func foo() -> Int { return y }
func bar() -> Int { return y }
// CHECK: [[FOO:%.*]] = function_ref @$s16generic_closures0A21_nondependent_context{{.*}} : $@convention(thin) (Int) -> Int
// CHECK: [[FOO_CLOSURE:%.*]] = partial_apply [callee_guaranteed] [[FOO]](%1)
// CHECK: destroy_value [[FOO_CLOSURE]]
let _ = foo
// CHECK: [[BAR:%.*]] = function_ref @$s16generic_closures0A21_nondependent_context{{.*}} : $@convention(thin) (Int) -> Int
// CHECK: [[BAR_CLOSURE:%.*]] = partial_apply [callee_guaranteed] [[BAR]](%1)
// CHECK: destroy_value [[BAR_CLOSURE]]
let _ = bar
// CHECK: [[FOO:%.*]] = function_ref @$s16generic_closures0A21_nondependent_context{{.*}} : $@convention(thin) (Int) -> Int
// CHECK: [[FOO_CLOSURE:%.*]] = apply [[FOO]]
_ = foo()
// CHECK: [[BAR:%.*]] = function_ref @$s16generic_closures0A21_nondependent_context{{.*}} : $@convention(thin) (Int) -> Int
// CHECK: [[BAR_CLOSURE:%.*]] = apply [[BAR]]
// CHECK: [[BAR_CLOSURE]]
return bar()
}
// CHECK-LABEL: sil hidden [ossa] @$s16generic_closures0A8_capture{{[_0-9a-zA-Z]*}}F
func generic_capture<T>(_ x: T) -> Any.Type {
func foo() -> Any.Type { return T.self }
// CHECK: [[FOO:%.*]] = function_ref @$s16generic_closures0A8_capture{{.*}} : $@convention(thin) <τ_0_0> () -> @thick Any.Type
// CHECK: [[FOO_CLOSURE:%.*]] = partial_apply [callee_guaranteed] [[FOO]]<T>()
// CHECK: destroy_value [[FOO_CLOSURE]]
let _ = foo
// CHECK: [[FOO:%.*]] = function_ref @$s16generic_closures0A8_capture{{.*}} : $@convention(thin) <τ_0_0> () -> @thick Any.Type
// CHECK: [[FOO_CLOSURE:%.*]] = apply [[FOO]]<T>()
// CHECK: return [[FOO_CLOSURE]]
return foo()
}
// CHECK-LABEL: sil hidden [ossa] @$s16generic_closures0A13_capture_cast{{[_0-9a-zA-Z]*}}F
func generic_capture_cast<T>(_ x: T, y: Any) -> Bool {
func foo(_ a: Any) -> Bool { return a is T }
// CHECK: [[FOO:%.*]] = function_ref @$s16generic_closures0A13_capture_cast{{.*}} : $@convention(thin) <τ_0_0> (@in_guaranteed Any) -> Bool
// CHECK: [[FOO_CLOSURE:%.*]] = partial_apply [callee_guaranteed] [[FOO]]<T>()
// CHECK: destroy_value [[FOO_CLOSURE]]
let _ = foo
// CHECK: [[FOO:%.*]] = function_ref @$s16generic_closures0A13_capture_cast{{.*}} : $@convention(thin) <τ_0_0> (@in_guaranteed Any) -> Bool
// CHECK: [[FOO_CLOSURE:%.*]] = apply [[FOO]]<T>([[ARG:%.*]])
// CHECK: return [[FOO_CLOSURE]]
return foo(y)
}
protocol Concept {
var sensical: Bool { get }
}
// CHECK-LABEL: sil hidden [ossa] @$s16generic_closures0A22_nocapture_existential{{[_0-9a-zA-Z]*}}F
func generic_nocapture_existential<T>(_ x: T, y: Concept) -> Bool {
func foo(_ a: Concept) -> Bool { return a.sensical }
// CHECK: [[FOO:%.*]] = function_ref @$s16generic_closures0A22_nocapture_existential{{.*}} : $@convention(thin) (@in_guaranteed Concept) -> Bool
// CHECK: [[FOO_CLOSURE:%.*]] = thin_to_thick_function [[FOO]]
// CHECK: destroy_value [[FOO_CLOSURE]]
let _ = foo
// CHECK: [[FOO:%.*]] = function_ref @$s16generic_closures0A22_nocapture_existential{{.*}} : $@convention(thin) (@in_guaranteed Concept) -> Bool
// CHECK: [[FOO_CLOSURE:%.*]] = apply [[FOO]]([[ARG:%.*]])
// CHECK: return [[FOO_CLOSURE]]
return foo(y)
}
// CHECK-LABEL: sil hidden [ossa] @$s16generic_closures0A18_dependent_context{{[_0-9a-zA-Z]*}}F
func generic_dependent_context<T>(_ x: T, y: Int) -> T {
func foo() -> T { return x }
// CHECK: [[FOO:%.*]] = function_ref @$s16generic_closures0A18_dependent_context{{.*}} : $@convention(thin) <τ_0_0> (@in_guaranteed τ_0_0) -> @out τ_0_0
// CHECK: [[FOO_CLOSURE:%.*]] = partial_apply [callee_guaranteed] [[FOO]]<T>([[BOX:%.*]])
// CHECK: [[FOO_CLOSURE_CONV:%.*]] = convert_function [[FOO_CLOSURE]]
// CHECK: destroy_value [[FOO_CLOSURE_CONV]]
let _ = foo
// CHECK: [[FOO:%.*]] = function_ref @$s16generic_closures0A18_dependent_context{{.*}} : $@convention(thin) <τ_0_0> (@in_guaranteed τ_0_0) -> @out τ_0_0
// CHECK: [[FOO_CLOSURE:%.*]] = apply [[FOO]]<T>
// CHECK: return
return foo()
}
enum Optionable<Wrapped> {
case none
case some(Wrapped)
}
class NestedGeneric<U> {
class func generic_nondependent_context<T>(_ x: T, y: Int, z: U) -> Int {
func foo() -> Int { return y }
let _ = foo
return foo()
}
class func generic_dependent_inner_context<T>(_ x: T, y: Int, z: U) -> T {
func foo() -> T { return x }
let _ = foo
return foo()
}
class func generic_dependent_outer_context<T>(_ x: T, y: Int, z: U) -> U {
func foo() -> U { return z }
let _ = foo
return foo()
}
class func generic_dependent_both_contexts<T>(_ x: T, y: Int, z: U) -> (T, U) {
func foo() -> (T, U) { return (x, z) }
let _ = foo
return foo()
}
// CHECK-LABEL: sil hidden [ossa] @$s16generic_closures13NestedGenericC20nested_reabstraction{{[_0-9a-zA-Z]*}}F
// CHECK: [[REABSTRACT:%.*]] = function_ref @$sIeg_ytIegr_TR
// CHECK: partial_apply [callee_guaranteed] [[REABSTRACT]]
func nested_reabstraction<T>(_ x: T) -> Optionable<() -> ()> {
return .some({})
}
}
// <rdar://problem/15417773>
// Ensure that nested closures capture the generic parameters of their nested
// context.
// CHECK: sil hidden [ossa] @$s16generic_closures018nested_closure_in_A0yxxlF : $@convention(thin) <T> (@in_guaranteed T) -> @out T
// CHECK: function_ref [[OUTER_CLOSURE:@\$s16generic_closures018nested_closure_in_A0yxxlFxyXEfU_]]
// CHECK: sil private [ossa] [[OUTER_CLOSURE]] : $@convention(thin) <T> (@in_guaranteed T) -> @out T
// CHECK: function_ref [[INNER_CLOSURE:@\$s16generic_closures018nested_closure_in_A0yxxlFxyXEfU_xyXEfU_]]
// CHECK: sil private [ossa] [[INNER_CLOSURE]] : $@convention(thin) <T> (@in_guaranteed T) -> @out T {
func nested_closure_in_generic<T>(_ x:T) -> T {
return { { x }() }()
}
// CHECK-LABEL: sil hidden [ossa] @$s16generic_closures16local_properties{{[_0-9a-zA-Z]*}}F
func local_properties<T>(_ t: inout T) {
var prop: T {
get {
return t
}
set {
t = newValue
}
}
// CHECK: [[GETTER_REF:%[0-9]+]] = function_ref [[GETTER_CLOSURE:@\$s16generic_closures16local_properties[_0-9a-zA-Z]*]] : $@convention(thin) <τ_0_0> (@inout_aliasable τ_0_0) -> @out τ_0_0
// CHECK: apply [[GETTER_REF]]
t = prop
// CHECK: [[SETTER_REF:%[0-9]+]] = function_ref [[SETTER_CLOSURE:@\$s16generic_closures16local_properties[_0-9a-zA-Z]*]] : $@convention(thin) <τ_0_0> (@in τ_0_0, @inout_aliasable τ_0_0) -> ()
// CHECK: apply [[SETTER_REF]]
prop = t
var prop2: T {
get {
return t
}
set {
// doesn't capture anything
}
}
// CHECK: [[GETTER2_REF:%[0-9]+]] = function_ref [[GETTER2_CLOSURE:@\$s16generic_closures16local_properties[_0-9a-zA-Z]*]] : $@convention(thin) <τ_0_0> (@inout_aliasable τ_0_0) -> @out τ_0_0
// CHECK: apply [[GETTER2_REF]]
t = prop2
// CHECK: [[SETTER2_REF:%[0-9]+]] = function_ref [[SETTER2_CLOSURE:@\$s16generic_closures16local_properties[_0-9a-zA-Z]*]] : $@convention(thin) <τ_0_0> (@in τ_0_0) -> ()
// CHECK: apply [[SETTER2_REF]]
prop2 = t
}
protocol Fooable {
static func foo() -> Bool
}
// <rdar://problem/16399018>
func shmassert(_ f: @autoclosure () -> Bool) {}
// CHECK-LABEL: sil hidden [ossa] @$s16generic_closures08capture_A6_param{{[_0-9a-zA-Z]*}}F
func capture_generic_param<A: Fooable>(_ x: A) {
shmassert(A.foo())
}
// Make sure we use the correct convention when capturing class-constrained
// member types: <rdar://problem/24470533>
class Class {}
protocol HasClassAssoc { associatedtype Assoc : Class }
// CHECK-LABEL: sil hidden [ossa] @$s16generic_closures027captures_class_constrained_A0_1fyx_5AssocQzAEctAA08HasClassF0RzlF
// CHECK: bb0([[ARG1:%.*]] : $*T, [[ARG2:%.*]] : @guaranteed $@callee_guaranteed @substituted <τ_0_0, τ_0_1 where τ_0_0 : _RefCountedObject, τ_0_1 : _RefCountedObject> (@guaranteed τ_0_0) -> @owned τ_0_1 for <T.Assoc, T.Assoc>):
// CHECK: [[GENERIC_FN:%.*]] = function_ref @$s16generic_closures027captures_class_constrained_A0_1fyx_5AssocQzAEctAA08HasClassF0RzlFA2EcycfU_
// CHECK: [[ARG2_COPY:%.*]] = copy_value [[ARG2]]
// CHECK: [[CONCRETE_FN:%.*]] = partial_apply [callee_guaranteed] [[GENERIC_FN]]<T>([[ARG2_COPY]])
func captures_class_constrained_generic<T : HasClassAssoc>(_ x: T, f: @escaping (T.Assoc) -> T.Assoc) {
let _: () -> (T.Assoc) -> T.Assoc = { f }
}
// Make sure local generic functions can have captures
// CHECK-LABEL: sil hidden [ossa] @$s16generic_closures06outer_A01t1iyx_SitlF : $@convention(thin) <T> (@in_guaranteed T, Int) -> ()
func outer_generic<T>(t: T, i: Int) {
func inner_generic_nocapture<U>(u: U) -> U {
return u
}
func inner_generic1<U>(u: U) -> Int {
return i
}
func inner_generic2<U>(u: U) -> T {
return t
}
let _: (()) -> () = inner_generic_nocapture
// CHECK: [[FN:%.*]] = function_ref @$s16generic_closures06outer_A01t1iyx_SitlF06inner_A10_nocaptureL_1uqd__qd___tr__lF : $@convention(thin) <τ_0_0><τ_1_0> (@in_guaranteed τ_1_0) -> @out τ_1_0
// CHECK: [[CLOSURE:%.*]] = partial_apply [callee_guaranteed] [[FN]]<T, ()>() : $@convention(thin) <τ_0_0><τ_1_0> (@in_guaranteed τ_1_0) -> @out τ_1_0
// CHECK: [[THUNK:%.*]] = function_ref @$sytytIegnr_Ieg_TR
// CHECK: [[THUNK_CLOSURE:%.*]] = partial_apply [callee_guaranteed] [[THUNK]]([[CLOSURE]])
// CHECK: destroy_value [[THUNK_CLOSURE]]
// CHECK: [[FN:%.*]] = function_ref @$s16generic_closures06outer_A01t1iyx_SitlF06inner_A10_nocaptureL_1uqd__qd___tr__lF : $@convention(thin) <τ_0_0><τ_1_0> (@in_guaranteed τ_1_0) -> @out τ_1_0
// CHECK: [[RESULT:%.*]] = apply [[FN]]<T, T>({{.*}}) : $@convention(thin) <τ_0_0><τ_1_0> (@in_guaranteed τ_1_0) -> @out τ_1_0
_ = inner_generic_nocapture(u: t)
// CHECK: [[FN:%.*]] = function_ref @$s16generic_closures06outer_A01t1iyx_SitlF14inner_generic1L_1uSiqd___tr__lF : $@convention(thin) <τ_0_0><τ_1_0> (@in_guaranteed τ_1_0, Int) -> Int
// CHECK: [[CLOSURE:%.*]] = partial_apply [callee_guaranteed] [[FN]]<T, ()>(%1) : $@convention(thin) <τ_0_0><τ_1_0> (@in_guaranteed τ_1_0, Int) -> Int
// CHECK: [[THUNK:%.*]] = function_ref @$sytSiIegnd_SiIegd_TR
// CHECK: [[THUNK_CLOSURE:%.*]] = partial_apply [callee_guaranteed] [[THUNK]]([[CLOSURE]])
// CHECK: destroy_value [[THUNK_CLOSURE]]
let _: (()) -> Int = inner_generic1
// CHECK: [[FN:%.*]] = function_ref @$s16generic_closures06outer_A01t1iyx_SitlF14inner_generic1L_1uSiqd___tr__lF : $@convention(thin) <τ_0_0><τ_1_0> (@in_guaranteed τ_1_0, Int) -> Int
// CHECK: [[RESULT:%.*]] = apply [[FN]]<T, T>({{.*}}) : $@convention(thin) <τ_0_0><τ_1_0> (@in_guaranteed τ_1_0, Int) -> Int
_ = inner_generic1(u: t)
// CHECK: [[FN:%.*]] = function_ref @$s16generic_closures06outer_A01t1iyx_SitlF14inner_generic2L_1uxqd___tr__lF : $@convention(thin) <τ_0_0><τ_1_0> (@in_guaranteed τ_1_0, @in_guaranteed τ_0_0) -> @out τ_0_0
// CHECK: [[CLOSURE:%.*]] = partial_apply [callee_guaranteed] [[FN]]<T, ()>([[ARG:%.*]]) : $@convention(thin) <τ_0_0><τ_1_0> (@in_guaranteed τ_1_0, @in_guaranteed τ_0_0) -> @out τ_0_0
// CHECK: [[THUNK:%.*]] = function_ref @$sytxIegnr_xIegr_lTR
// CHECK: [[THUNK_CLOSURE:%.*]] = partial_apply [callee_guaranteed] [[THUNK]]<T>([[CLOSURE]])
// CHECK: [[THUNK_CLOSURE_CONV:%.*]] = convert_function [[THUNK_CLOSURE]]
// CHECK: destroy_value [[THUNK_CLOSURE_CONV]]
let _: (()) -> T = inner_generic2
// CHECK: [[FN:%.*]] = function_ref @$s16generic_closures06outer_A01t1iyx_SitlF14inner_generic2L_1uxqd___tr__lF : $@convention(thin) <τ_0_0><τ_1_0> (@in_guaranteed τ_1_0, @in_guaranteed τ_0_0) -> @out τ_0_0
// CHECK: [[RESULT:%.*]] = apply [[FN]]<T, T>({{.*}}) : $@convention(thin) <τ_0_0><τ_1_0> (@in_guaranteed τ_1_0, @in_guaranteed τ_0_0) -> @out τ_0_0
_ = inner_generic2(u: t)
}
// CHECK-LABEL: sil hidden [ossa] @$s16generic_closures14outer_concrete1iySi_tF : $@convention(thin) (Int) -> ()
func outer_concrete(i: Int) {
func inner_generic_nocapture<U>(u: U) -> U {
return u
}
func inner_generic<U>(u: U) -> Int {
return i
}
// CHECK: [[FN:%.*]] = function_ref @$s16generic_closures14outer_concrete1iySi_tF06inner_A10_nocaptureL_1uxx_tlF : $@convention(thin) <τ_0_0> (@in_guaranteed τ_0_0) -> @out τ_0_0
// CHECK: [[CLOSURE:%.*]] = partial_apply [callee_guaranteed] [[FN]]<()>() : $@convention(thin) <τ_0_0> (@in_guaranteed τ_0_0) -> @out τ_0_0
// CHECK: [[THUNK:%.*]] = function_ref @$sytytIegnr_Ieg_TR
// CHECK: [[THUNK_CLOSURE:%.*]] = partial_apply [callee_guaranteed] [[THUNK]]([[CLOSURE]])
// CHECK: destroy_value [[THUNK_CLOSURE]]
let _: (()) -> () = inner_generic_nocapture
// CHECK: [[FN:%.*]] = function_ref @$s16generic_closures14outer_concrete1iySi_tF06inner_A10_nocaptureL_1uxx_tlF : $@convention(thin) <τ_0_0> (@in_guaranteed τ_0_0) -> @out τ_0_0
// CHECK: [[RESULT:%.*]] = apply [[FN]]<Int>({{.*}}) : $@convention(thin) <τ_0_0> (@in_guaranteed τ_0_0) -> @out τ_0_0
_ = inner_generic_nocapture(u: i)
// CHECK: [[FN:%.*]] = function_ref @$s16generic_closures14outer_concrete1iySi_tF06inner_A0L_1uSix_tlF : $@convention(thin) <τ_0_0> (@in_guaranteed τ_0_0, Int) -> Int
// CHECK: [[CLOSURE:%.*]] = partial_apply [callee_guaranteed] [[FN]]<()>(%0) : $@convention(thin) <τ_0_0> (@in_guaranteed τ_0_0, Int) -> Int
// CHECK: [[THUNK:%.*]] = function_ref @$sytSiIegnd_SiIegd_TR
// CHECK: [[THUNK_CLOSURE:%.*]] = partial_apply [callee_guaranteed] [[THUNK]]([[CLOSURE]])
// CHECK: destroy_value [[THUNK_CLOSURE]]
let _: (()) -> Int = inner_generic
// CHECK: [[FN:%.*]] = function_ref @$s16generic_closures14outer_concrete1iySi_tF06inner_A0L_1uSix_tlF : $@convention(thin) <τ_0_0> (@in_guaranteed τ_0_0, Int) -> Int
// CHECK: [[RESULT:%.*]] = apply [[FN]]<Int>({{.*}}) : $@convention(thin) <τ_0_0> (@in_guaranteed τ_0_0, Int) -> Int
_ = inner_generic(u: i)
}
// CHECK-LABEL: sil hidden [ossa] @$s16generic_closures06mixed_A19_nongeneric_nesting1tyx_tlF : $@convention(thin) <T> (@in_guaranteed T) -> ()
func mixed_generic_nongeneric_nesting<T>(t: T) {
func outer() {
func middle<U>(u: U) {
func inner() -> U {
return u
}
inner()
}
middle(u: 11)
}
outer()
}
// CHECK-LABEL: sil private [ossa] @$s16generic_closures06mixed_A19_nongeneric_nesting1tyx_tlF5outerL_yylF : $@convention(thin) <T> () -> ()
// CHECK-LABEL: sil private [ossa] @$s16generic_closures06mixed_A19_nongeneric_nesting1tyx_tlF5outerL_yylF6middleL_1uyqd___tr__lF : $@convention(thin) <T><U> (@in_guaranteed U) -> ()
// CHECK-LABEL: sil private [ossa] @$s16generic_closures06mixed_A19_nongeneric_nesting1tyx_tlF5outerL_yylF6middleL_1uyqd___tr__lF5innerL_qd__yr__lF : $@convention(thin) <T><U> (@in_guaranteed U) -> @out U
protocol Doge {
associatedtype Nose : NoseProtocol
}
protocol NoseProtocol {
associatedtype Squeegee
}
protocol Doggo {}
struct DogSnacks<A : Doggo> {}
func capture_same_type_representative<Daisy: Doge, Roo: Doggo>(slobber: Roo, daisy: Daisy)
where Roo == Daisy.Nose.Squeegee {
var s = DogSnacks<Daisy.Nose.Squeegee>()
_ = { _ = s }
}
| apache-2.0 |
Brightify/ReactantUI | Sources/Live/UIWindow+TopViewController.swift | 1 | 820 | //
// UIWindow+TopViewController.swift
// ReactantUI
//
// Created by Tadeas Kriz.
// Copyright © 2017 Brightify. All rights reserved.
//
import UIKit
extension UIWindow {
public func topViewController() -> UIViewController? {
return rootViewController.map(topViewController)
}
private func topViewController(with root: UIViewController) -> UIViewController {
if let selectedController = (root as? UITabBarController)?.selectedViewController {
return topViewController(with: selectedController)
} else if let visibleController = (root as? UINavigationController)?.visibleViewController {
return topViewController(with: visibleController)
} else {
return root.presentedViewController.map(topViewController) ?? root
}
}
}
| mit |
bizz84/SwiftyStoreKit | Sources/SwiftyStoreKit/SwiftyStoreKit.swift | 1 | 18464 | //
// SwiftyStoreKit.swift
// SwiftyStoreKit
//
// Copyright (c) 2015 Andrea Bizzotto (bizz84@gmail.com)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import StoreKit
public class SwiftyStoreKit {
private let productsInfoController: ProductsInfoController
fileprivate let paymentQueueController: PaymentQueueController
fileprivate let receiptVerificator: InAppReceiptVerificator
init(productsInfoController: ProductsInfoController = ProductsInfoController(),
paymentQueueController: PaymentQueueController = PaymentQueueController(paymentQueue: SKPaymentQueue.default()),
receiptVerificator: InAppReceiptVerificator = InAppReceiptVerificator()) {
self.productsInfoController = productsInfoController
self.paymentQueueController = paymentQueueController
self.receiptVerificator = receiptVerificator
}
// MARK: private methods
fileprivate func retrieveProductsInfo(_ productIds: Set<String>, completion: @escaping (RetrieveResults) -> Void) -> InAppProductRequest {
return productsInfoController.retrieveProductsInfo(productIds, completion: completion)
}
fileprivate func purchaseProduct(_ productId: String, quantity: Int = 1, atomically: Bool = true, applicationUsername: String = "", simulatesAskToBuyInSandbox: Bool = false, completion: @escaping ( PurchaseResult) -> Void) -> InAppProductRequest {
return retrieveProductsInfo(Set([productId])) { result -> Void in
if let product = result.retrievedProducts.first {
self.purchase(product: product, quantity: quantity, atomically: atomically, applicationUsername: applicationUsername, simulatesAskToBuyInSandbox: simulatesAskToBuyInSandbox, completion: completion)
} else if let error = result.error {
completion(.error(error: SKError(_nsError: error as NSError)))
} else if let invalidProductId = result.invalidProductIDs.first {
let userInfo = [ NSLocalizedDescriptionKey: "Invalid product id: \(invalidProductId)" ]
let error = NSError(domain: SKErrorDomain, code: SKError.paymentInvalid.rawValue, userInfo: userInfo)
completion(.error(error: SKError(_nsError: error)))
} else {
let error = NSError(domain: SKErrorDomain, code: SKError.unknown.rawValue, userInfo: nil)
completion(.error(error: SKError(_nsError: error)))
}
}
}
fileprivate func purchase(product: SKProduct, quantity: Int, atomically: Bool, applicationUsername: String = "", simulatesAskToBuyInSandbox: Bool = false, paymentDiscount: PaymentDiscount? = nil, completion: @escaping (PurchaseResult) -> Void) {
paymentQueueController.startPayment(Payment(product: product, paymentDiscount: paymentDiscount, quantity: quantity, atomically: atomically, applicationUsername: applicationUsername, simulatesAskToBuyInSandbox: simulatesAskToBuyInSandbox) { result in
completion(self.processPurchaseResult(result))
})
}
fileprivate func restorePurchases(atomically: Bool = true, applicationUsername: String = "", completion: @escaping (RestoreResults) -> Void) {
paymentQueueController.restorePurchases(RestorePurchases(atomically: atomically, applicationUsername: applicationUsername) { results in
let results = self.processRestoreResults(results)
completion(results)
})
}
fileprivate func completeTransactions(atomically: Bool = true, completion: @escaping ([Purchase]) -> Void) {
paymentQueueController.completeTransactions(CompleteTransactions(atomically: atomically, callback: completion))
}
fileprivate func onEntitlementRevocation(completion: @escaping ([String]) -> Void) {
paymentQueueController.onEntitlementRevocation(EntitlementRevocation(callback: completion))
}
fileprivate func finishTransaction(_ transaction: PaymentTransaction) {
paymentQueueController.finishTransaction(transaction)
}
private func processPurchaseResult(_ result: TransactionResult) -> PurchaseResult {
switch result {
case .purchased(let purchase):
return .success(purchase: purchase)
case .deferred(let purchase):
return .deferred(purchase: purchase)
case .failed(let error):
return .error(error: error)
case .restored(let purchase):
return .error(error: storeInternalError(description: "Cannot restore product \(purchase.productId) from purchase path"))
}
}
private func processRestoreResults(_ results: [TransactionResult]) -> RestoreResults {
var restoredPurchases: [Purchase] = []
var restoreFailedPurchases: [(SKError, String?)] = []
for result in results {
switch result {
case .purchased(let purchase):
let error = storeInternalError(description: "Cannot purchase product \(purchase.productId) from restore purchases path")
restoreFailedPurchases.append((error, purchase.productId))
case .deferred(let purchase):
let error = storeInternalError(description: "Cannot purchase product \(purchase.productId) from restore purchases path")
restoreFailedPurchases.append((error, purchase.productId))
case .failed(let error):
restoreFailedPurchases.append((error, nil))
case .restored(let purchase):
restoredPurchases.append(purchase)
}
}
return RestoreResults(restoredPurchases: restoredPurchases, restoreFailedPurchases: restoreFailedPurchases)
}
private func storeInternalError(code: SKError.Code = SKError.unknown, description: String = "") -> SKError {
let error = NSError(domain: SKErrorDomain, code: code.rawValue, userInfo: [ NSLocalizedDescriptionKey: description ])
return SKError(_nsError: error)
}
}
extension SwiftyStoreKit {
// MARK: Singleton
fileprivate static let sharedInstance = SwiftyStoreKit()
// MARK: Public methods - Purchases
/// Check if the current device can make payments.
/// - returns: `false` if this device is not able or allowed to make payments
public class var canMakePayments: Bool {
return SKPaymentQueue.canMakePayments()
}
/// Retrieve products information
/// - Parameter productIds: The set of product identifiers to retrieve corresponding products for
/// - Parameter completion: handler for result
/// - returns: A cancellable `InAppRequest` object
@discardableResult
public class func retrieveProductsInfo(_ productIds: Set<String>, completion: @escaping (RetrieveResults) -> Void) -> InAppRequest {
return sharedInstance.retrieveProductsInfo(productIds, completion: completion)
}
/// Purchase a product
/// - Parameter productId: productId as specified in App Store Connect
/// - Parameter quantity: quantity of the product to be purchased
/// - Parameter atomically: whether the product is purchased atomically (e.g. `finishTransaction` is called immediately)
/// - Parameter applicationUsername: an opaque identifier for the user’s account on your system
/// - Parameter completion: handler for result
/// - returns: A cancellable `InAppRequest` object
@discardableResult
public class func purchaseProduct(_ productId: String, quantity: Int = 1, atomically: Bool = true, applicationUsername: String = "", simulatesAskToBuyInSandbox: Bool = false, completion: @escaping (PurchaseResult) -> Void) -> InAppRequest {
return sharedInstance.purchaseProduct(productId, quantity: quantity, atomically: atomically, applicationUsername: applicationUsername, simulatesAskToBuyInSandbox: simulatesAskToBuyInSandbox, completion: completion)
}
/// Purchase a product
/// - Parameter product: product to be purchased
/// - Parameter quantity: quantity of the product to be purchased
/// - Parameter atomically: whether the product is purchased atomically (e.g. `finishTransaction` is called immediately)
/// - Parameter applicationUsername: an opaque identifier for the user’s account on your system
/// - Parameter product: optional discount to be applied. Must be of `SKProductPayment` type
/// - Parameter completion: handler for result
public class func purchaseProduct(_ product: SKProduct, quantity: Int = 1, atomically: Bool = true, applicationUsername: String = "", simulatesAskToBuyInSandbox: Bool = false, paymentDiscount: PaymentDiscount? = nil, completion: @escaping ( PurchaseResult) -> Void) {
sharedInstance.purchase(product: product, quantity: quantity, atomically: atomically, applicationUsername: applicationUsername, simulatesAskToBuyInSandbox: simulatesAskToBuyInSandbox, paymentDiscount: paymentDiscount, completion: completion)
}
/// Restore purchases
/// - Parameter atomically: whether the product is purchased atomically (e.g. `finishTransaction` is called immediately)
/// - Parameter applicationUsername: an opaque identifier for the user’s account on your system
/// - Parameter completion: handler for result
public class func restorePurchases(atomically: Bool = true, applicationUsername: String = "", completion: @escaping (RestoreResults) -> Void) {
sharedInstance.restorePurchases(atomically: atomically, applicationUsername: applicationUsername, completion: completion)
}
/// Complete transactions
/// - Parameter atomically: whether the product is purchased atomically (e.g. `finishTransaction` is called immediately)
/// - Parameter completion: handler for result
public class func completeTransactions(atomically: Bool = true, completion: @escaping ([Purchase]) -> Void) {
sharedInstance.completeTransactions(atomically: atomically, completion: completion)
}
/// Entitlement revocation notification
/// - Parameter completion: handler for result (list of product identifiers revoked)
@available(iOS 14, tvOS 14, OSX 11, watchOS 7, macCatalyst 14, *)
public class func onEntitlementRevocation(completion: @escaping ([String]) -> Void) {
sharedInstance.onEntitlementRevocation(completion: completion)
}
/// Finish a transaction
///
/// Once the content has been delivered, call this method to finish a transaction that was performed non-atomically
/// - Parameter transaction: transaction to finish
public class func finishTransaction(_ transaction: PaymentTransaction) {
sharedInstance.finishTransaction(transaction)
}
/// Register a handler for `SKPaymentQueue.shouldAddStorePayment` delegate method.
/// - requires: iOS 11.0+
public static var shouldAddStorePaymentHandler: ShouldAddStorePaymentHandler? {
didSet {
sharedInstance.paymentQueueController.shouldAddStorePaymentHandler = shouldAddStorePaymentHandler
}
}
/// Register a handler for `paymentQueue(_:updatedDownloads:)`
/// - seealso: `paymentQueue(_:updatedDownloads:)`
public static var updatedDownloadsHandler: UpdatedDownloadsHandler? {
didSet {
sharedInstance.paymentQueueController.updatedDownloadsHandler = updatedDownloadsHandler
}
}
public class func start(_ downloads: [SKDownload]) {
sharedInstance.paymentQueueController.start(downloads)
}
public class func pause(_ downloads: [SKDownload]) {
sharedInstance.paymentQueueController.pause(downloads)
}
public class func resume(_ downloads: [SKDownload]) {
sharedInstance.paymentQueueController.resume(downloads)
}
public class func cancel(_ downloads: [SKDownload]) {
sharedInstance.paymentQueueController.cancel(downloads)
}
}
extension SwiftyStoreKit {
// MARK: Public methods - Receipt verification
/// Return receipt data from the application bundle. This is read from `Bundle.main.appStoreReceiptURL`.
public static var localReceiptData: Data? {
return sharedInstance.receiptVerificator.appStoreReceiptData
}
/// Verify application receipt
/// - Parameter validator: receipt validator to use
/// - Parameter forceRefresh: If `true`, refreshes the receipt even if one already exists.
/// - Parameter completion: handler for result
/// - returns: A cancellable `InAppRequest` object
@discardableResult
public class func verifyReceipt(using validator: ReceiptValidator, forceRefresh: Bool = false, completion: @escaping (VerifyReceiptResult) -> Void) -> InAppRequest? {
return sharedInstance.receiptVerificator.verifyReceipt(using: validator, forceRefresh: forceRefresh, completion: completion)
}
/// Fetch application receipt
/// - Parameter forceRefresh: If true, refreshes the receipt even if one already exists.
/// - Parameter completion: handler for result
/// - returns: A cancellable `InAppRequest` object
@discardableResult
public class func fetchReceipt(forceRefresh: Bool, completion: @escaping (FetchReceiptResult) -> Void) -> InAppRequest? {
return sharedInstance.receiptVerificator.fetchReceipt(forceRefresh: forceRefresh, completion: completion)
}
/// Verify the purchase of a Consumable or NonConsumable product in a receipt
/// - Parameter productId: the product id of the purchase to verify
/// - Parameter inReceipt: the receipt to use for looking up the purchase
/// - returns: A `VerifyPurchaseResult`, which may be either `notPurchased` or `purchased`.
public class func verifyPurchase(productId: String, inReceipt receipt: ReceiptInfo) -> VerifyPurchaseResult {
return InAppReceipt.verifyPurchase(productId: productId, inReceipt: receipt)
}
/**
* Verify the validity of a subscription (auto-renewable, free or non-renewing) in a receipt.
*
* This method extracts all transactions matching the given productId and sorts them by date in descending order. It then compares the first transaction expiry date against the receipt date to determine its validity.
* - Parameter type: `.autoRenewable` or `.nonRenewing`.
* - Parameter productId: The product id of the subscription to verify.
* - Parameter receipt: The receipt to use for looking up the subscription.
* - Parameter validUntil: Date to check against the expiry date of the subscription. This is only used if a date is not found in the receipt.
* - returns: Either `.notPurchased` or `.purchased` / `.expired` with the expiry date found in the receipt.
*/
public class func verifySubscription(ofType type: SubscriptionType, productId: String, inReceipt receipt: ReceiptInfo, validUntil date: Date = Date()) -> VerifySubscriptionResult {
return InAppReceipt.verifySubscriptions(ofType: type, productIds: [productId], inReceipt: receipt, validUntil: date)
}
/**
* Verify the validity of a set of subscriptions in a receipt.
*
* This method extracts all transactions matching the given productIds and sorts them by date in descending order. It then compares the first transaction expiry date against the receipt date, to determine its validity.
* - Note: You can use this method to check the validity of (mutually exclusive) subscriptions in a subscription group.
* - Remark: The type parameter determines how the expiration dates are calculated for all subscriptions. Make sure all productIds match the specified subscription type to avoid incorrect results.
* - Parameter type: `.autoRenewable` or `.nonRenewing`.
* - Parameter productIds: The product IDs of the subscriptions to verify.
* - Parameter receipt: The receipt to use for looking up the subscriptions
* - Parameter validUntil: Date to check against the expiry date of the subscriptions. This is only used if a date is not found in the receipt.
* - returns: Either `.notPurchased` or `.purchased` / `.expired` with the expiry date found in the receipt.
*/
public class func verifySubscriptions(ofType type: SubscriptionType = .autoRenewable, productIds: Set<String>, inReceipt receipt: ReceiptInfo, validUntil date: Date = Date()) -> VerifySubscriptionResult {
return InAppReceipt.verifySubscriptions(ofType: type, productIds: productIds, inReceipt: receipt, validUntil: date)
}
/// Get the distinct product identifiers from receipt.
///
/// This Method extracts all product identifiers. (Including cancelled ones).
/// - Note: You can use this method to get all unique product identifiers from receipt.
/// - Parameter type: `.autoRenewable` or `.nonRenewing`.
/// - Parameter receipt: The receipt to use for looking up product identifiers.
/// - returns: Either `Set<String>` or `nil`.
public class func getDistinctPurchaseIds(ofType type: SubscriptionType = .autoRenewable, inReceipt receipt: ReceiptInfo) -> Set<String>? {
return InAppReceipt.getDistinctPurchaseIds(ofType: type, inReceipt: receipt)
}
}
| mit |
sschiau/swift | test/SourceKit/Sema/injected_vfs_after_edit.swift | 3 | 617 | func foo(_ structDefinedInSameTarget: StructDefinedInSameTarget) {
let _: Double = structDefinedInSameTarget.methodDefinedInSameTarget()
// CHECK: cannot convert value of type '()' to specified type 'Double'
// CHECK: cannot convert value of type '()' to specified type 'Int'
}
// RUN: %sourcekitd-test -req=open -vfs-files=/target_file2.swift=%S/../Inputs/vfs/other_file_in_target.swift %s -pass-as-sourcetext -- %s /target_file2.swift -target %target-triple == \
// RUN: -req=print-diags %s == \
// RUN: -req=edit %s -pos=2:12 -length=6 -replace='Int' == \
// RUN: -req=print-diags %s | %FileCheck %s
| apache-2.0 |
AblePear/Peary | PearyTests/sockaddr_inTests.swift | 1 | 4721 | import XCTest
@testable import Peary
class sockaddr_inTests: XCTestCase {
func testInit() {
let address = sockaddr_in()
XCTAssertEqual(address.sin_len, UInt8(0))
XCTAssertEqual(address.sin_family, sa_family_t(AF_UNSPEC))
XCTAssertEqual(address.sin_addr.s_addr, in_addr_t(0).networkByteOrder)
XCTAssertEqual(address.sin_port, in_port_t(0).networkByteOrder)
XCTAssertEqual(address.address, in_addr("0.0.0.0"))
XCTAssertEqual(address.port, in_port_t(0).hostByteOrder)
XCTAssertEqual("\(address)", "0.0.0.0:0")
XCTAssert(!address.isValid)
}
func testInitWithAddressAndPort() {
let address = sockaddr_in(address: 0x01020304, port: 42)
XCTAssertEqual(address.sin_len, UInt8(MemoryLayout<sockaddr_in>.size))
XCTAssertEqual(address.sin_family, sa_family_t(AF_INET))
XCTAssertEqual(address.sin_addr.s_addr, in_addr_t(0x01020304).networkByteOrder)
XCTAssertEqual(address.sin_port, in_port_t(42).networkByteOrder)
XCTAssertEqual(address.address, in_addr("1.2.3.4"))
XCTAssertEqual(address.port, in_port_t(42).hostByteOrder)
XCTAssertEqual("\(address)", "1.2.3.4:42")
XCTAssert(address.isValid)
}
func testInitWithAddressTextAndPort() {
let address = sockaddr_in("1.2.3.4", port: 42)!
XCTAssertEqual(address.sin_len, UInt8(MemoryLayout<sockaddr_in>.size))
XCTAssertEqual(address.sin_family, sa_family_t(AF_INET))
XCTAssertEqual(address.sin_addr.s_addr, in_addr_t(0x01020304).networkByteOrder)
XCTAssertEqual(address.sin_port, in_port_t(42).networkByteOrder)
XCTAssertEqual(address.address, in_addr("1.2.3.4"))
XCTAssertEqual(address.port, in_port_t(42).hostByteOrder)
XCTAssertEqual("\(address)", "1.2.3.4:42")
XCTAssert(address.isValid)
}
func testInitWithEmptyAddressText() {
let address = sockaddr_in("", port: 42)
XCTAssertNil(address)
}
func testInitWithInvalidAddressText() {
let address = sockaddr_in("invalid", port: 42)
XCTAssertNil(address)
}
func testInitWithSockAddrStorage() {
var storage = sockaddr_storage()
withUnsafeMutablePointer(to: &storage) {
return $0.withMemoryRebound(to: sockaddr_in.self, capacity: 1) {
$0.pointee.sin_len = UInt8(MemoryLayout<sockaddr_storage>.size)
$0.pointee.sin_family = sa_family_t(AF_INET)
$0.pointee.sin_addr = in_addr("1.2.3.4")!
$0.pointee.sin_port = in_port_t(port: 42)
}
}
let address = sockaddr_in(storage)
XCTAssertTrue(address.isValid)
XCTAssertEqual(address.address, in_addr("1.2.3.4"))
XCTAssertEqual(address.port, in_port_t(42).hostByteOrder)
}
func testSetAddress() {
var address = sockaddr_in("1.2.3.4", port: 80)!
XCTAssertEqual(address.sin_addr.s_addr, in_addr_t(0x01020304).networkByteOrder)
XCTAssertEqual(address.address, in_addr("1.2.3.4"))
address.address = in_addr("4.5.6.7")!
XCTAssertEqual(address.sin_addr.s_addr, in_addr_t(0x04050607).networkByteOrder)
XCTAssertEqual(address.address, in_addr("4.5.6.7"))
}
func testSetPort() {
var address = sockaddr_in("1.2.3.4", port: 80)!
XCTAssertEqual(address.sin_port, in_port_t(80).networkByteOrder)
XCTAssertEqual(address.port, in_port_t(80))
address.port = in_port_t(8080)
XCTAssertEqual(address.sin_port, in_port_t(8080).networkByteOrder)
XCTAssertEqual(address.port, in_port_t(8080))
}
func testAsSockaddrPointer() {
let address = sockaddr_in("1.2.3.4", port: 42)!
let result = address.asSockaddrPointer {
sockaddr -> Bool in
XCTAssertEqual(sa_family_t(AF_INET), sockaddr.pointee.sa_family)
XCTAssertEqual(address.length, socklen_t(sockaddr.pointee.sa_len))
return true
}
XCTAssertTrue(result)
}
func testEquatable() {
let address1 = sockaddr_in("1.2.3.4", port: 80)!
let address2 = sockaddr_in("1.2.3.4", port: 80)!
let address3 = sockaddr_in("2.2.3.4", port: 80)!
let address4 = sockaddr_in("2.2.3.4", port: 81)!
XCTAssertEqual(address1, address2)
XCTAssertEqual(address2, address1)
XCTAssertNotEqual(address1, address3)
XCTAssertNotEqual(address3, address1)
XCTAssertNotEqual(address3, address4)
XCTAssertNotEqual(address4, address3)
}
}
| bsd-2-clause |
rdhiggins/PythonMacros | PythonMacros/BaseTextStorage.swift | 1 | 1196 | //
// BaseTextStorage.swift
// PythonTest.Swift
//
// Created by Rodger Higgins on 6/23/16.
// Copyright © 2016 Rodger Higgins. All rights reserved.
//
import UIKit
/// A class used as a base class for declaring custom NSTextStorage classes.
/// This class contains generic implementations of methods required in
/// any NSTextStorage subclasses.
class BaseTextStorage: NSTextStorage {
fileprivate let storage = NSMutableAttributedString()
override var string: String {
return storage.string
}
override func attributes(at location: Int, effectiveRange range: NSRangePointer?) -> [String : Any] {
return storage.attributes(at: location, effectiveRange: range)
}
override func replaceCharacters(in range: NSRange, with str: String) {
let beforeLength = length
storage.replaceCharacters(in: range, with: str)
edited(.editedCharacters, range: range, changeInLength: length - beforeLength)
}
override func setAttributes(_ attrs: [String : Any]?, range: NSRange) {
storage.setAttributes(attrs, range: range)
edited(.editedAttributes, range: range, changeInLength: 0)
}
}
| mit |
practicalswift/swift | test/Sema/fixed_ambiguities/rdar27198177.swift | 34 | 299 |
// RUN: %target-swift-frontend -emit-sil -verify %s -swift-version 4 | %FileCheck %s
let arr = ["A", "B", "C"]
let lazy: LazyMapCollection = arr.lazy.map { $0 }
// CHECK: function_ref @$ss20LazySequenceProtocolPsE6filterys0a6FilterB0Vy8ElementsQzGSb7ElementQzcF
_ = lazy.filter { $0 > "A" }.count
| apache-2.0 |
blockchain/My-Wallet-V3-iOS | Modules/Platform/Sources/PlatformUIKit/Views/Cells/Badge/BadgeAsset/DefaultBadgeAssetPresenter.swift | 1 | 786 | // Copyright © Blockchain Luxembourg S.A. All rights reserved.
import RxRelay
import RxSwift
public final class DefaultBadgeAssetPresenter: BadgeAssetPresenting {
public typealias PresentationState = BadgeAsset.State.BadgeItem.Presentation
public var state: Observable<PresentationState> {
stateRelay.asObservable()
}
public let interactor: BadgeAssetInteracting
private let stateRelay = BehaviorRelay<PresentationState>(value: .loading)
private let disposeBag = DisposeBag()
public init(interactor: BadgeAssetInteracting = DefaultBadgeAssetInteractor()) {
self.interactor = interactor
interactor.state
.map { .init(with: $0) }
.bindAndCatch(to: stateRelay)
.disposed(by: disposeBag)
}
}
| lgpl-3.0 |
nathantannar4/Parse-Dashboard-for-iOS-Pro | Parse Dashboard for iOS/Extensions/Enum+Extensions.swift | 1 | 421 | //
// Enum+Extensions.swift
// Flashh
//
// Created by Nathan Tannar on 3/11/18.
// Copyright © 2018 Nathan Tannar. All rights reserved.
//
import Foundation
func iterateEnum<T: Hashable>(_: T.Type) -> AnyIterator<T> {
var i = 0
return AnyIterator {
let next = withUnsafeBytes(of: &i) { $0.load(as: T.self) }
if next.hashValue != i { return nil }
i += 1
return next
}
}
| mit |
blockchain/My-Wallet-V3-iOS | Modules/FeatureTour/UI/PriceList/LivePricesHeader.swift | 1 | 1510 | // Copyright © Blockchain Luxembourg S.A. All rights reserved.
import BlockchainComponentLibrary
import Localization
import SwiftUI
struct LivePricesHeader: View {
@State private var circleIsVisible = true
@Binding var offset: CGFloat
private let titleHeight: CGFloat = 64
private var clippedTitleHeight: CGFloat {
let calculatedHeight = titleHeight + offset
return calculatedHeight.clamped(to: 0...titleHeight)
}
var body: some View {
VStack(spacing: .zero) {
VStack {
Text(LocalizationConstants.Tour.carouselPricesScreenTitle)
.typography(.title3)
.multilineTextAlignment(.center)
.frame(height: titleHeight)
}
.padding(.bottom, Spacing.padding2)
.frame(width: 180.0, height: clippedTitleHeight)
.clipped()
HStack(alignment: .firstTextBaseline) {
Circle()
.fill(Color.green)
.animation(nil)
.frame(width: 8, height: 8)
.opacity(circleIsVisible ? 1 : 0)
.animation(Animation.easeInOut(duration: 1).repeatForever(autoreverses: true))
.onAppear {
circleIsVisible.toggle()
}
Text(LocalizationConstants.Tour.carouselPricesScreenLivePrices)
.textStyle(.heading)
}
}
}
}
| lgpl-3.0 |
huonw/swift | test/SILGen/metatypes.swift | 1 | 4296 | // RUN: %target-swift-emit-silgen -parse-stdlib -enable-sil-ownership %s | %FileCheck %s
import Swift
protocol SomeProtocol {
func method()
func static_method()
}
protocol A {}
struct SomeStruct : A {}
class SomeClass : SomeProtocol {
func method() {}
func static_method() {}
}
class SomeSubclass : SomeClass {}
// CHECK-LABEL: sil hidden @$S9metatypes07static_A0{{[_0-9a-zA-Z]*}}F
func static_metatypes()
-> (SomeStruct.Type, SomeClass.Type, SomeClass.Type)
{
// CHECK: [[STRUCT:%[0-9]+]] = metatype $@thin SomeStruct.Type
// CHECK: [[CLASS:%[0-9]+]] = metatype $@thick SomeClass.Type
// CHECK: [[SUBCLASS:%[0-9]+]] = metatype $@thick SomeSubclass.Type
// CHECK: [[SUBCLASS_UPCAST:%[0-9]+]] = upcast [[SUBCLASS]] : ${{.*}} to $@thick SomeClass.Type
// CHECK: tuple ([[STRUCT]] : {{.*}}, [[CLASS]] : {{.*}}, [[SUBCLASS_UPCAST]] : {{.*}})
return (SomeStruct.self, SomeClass.self, SomeSubclass.self)
}
// CHECK-LABEL: sil hidden @$S9metatypes07struct_A0{{[_0-9a-zA-Z]*}}F
func struct_metatypes(s: SomeStruct)
-> (SomeStruct.Type, SomeStruct.Type)
{
// CHECK: [[STRUCT1:%[0-9]+]] = metatype $@thin SomeStruct.Type
// CHECK: [[STRUCT2:%[0-9]+]] = metatype $@thin SomeStruct.Type
// CHECK: tuple ([[STRUCT1]] : {{.*}}, [[STRUCT2]] : {{.*}})
return (type(of: s), SomeStruct.self)
}
// CHECK-LABEL: sil hidden @$S9metatypes06class_A0{{[_0-9a-zA-Z]*}}F
func class_metatypes(c: SomeClass, s: SomeSubclass)
-> (SomeClass.Type, SomeClass.Type)
{
// CHECK: [[CLASS:%[0-9]+]] = value_metatype $@thick SomeClass.Type,
// CHECK: [[SUBCLASS:%[0-9]+]] = value_metatype $@thick SomeSubclass.Type,
// CHECK: [[SUBCLASS_UPCAST:%[0-9]+]] = upcast [[SUBCLASS]] : ${{.*}} to $@thick SomeClass.Type
// CHECK: tuple ([[CLASS]] : {{.*}}, [[SUBCLASS_UPCAST]] : {{.*}})
return (type(of: c), type(of: s))
}
// CHECK-LABEL: sil hidden @$S9metatypes010archetype_A0{{[_0-9a-zA-Z]*}}F
// CHECK: bb0(%0 : @trivial $*T):
func archetype_metatypes<T>(t: T) -> (T.Type, T.Type) {
// CHECK: [[STATIC_T:%[0-9]+]] = metatype $@thick T.Type
// CHECK: [[DYN_T:%[0-9]+]] = value_metatype $@thick T.Type, %0
// CHECK: tuple ([[STATIC_T]] : {{.*}}, [[DYN_T]] : {{.*}})
return (T.self, type(of: t))
}
// CHECK-LABEL: sil hidden @$S9metatypes012existential_A0{{[_0-9a-zA-Z]*}}F
func existential_metatypes(p: SomeProtocol) -> SomeProtocol.Type {
// CHECK: existential_metatype $@thick SomeProtocol.Type
return type(of: p)
}
struct SomeGenericStruct<T> {}
func generic_metatypes<T>(x: T)
-> (SomeGenericStruct<T>.Type, SomeGenericStruct<SomeStruct>.Type)
{
// CHECK: metatype $@thin SomeGenericStruct<T>
// CHECK: metatype $@thin SomeGenericStruct<SomeStruct>
return (SomeGenericStruct<T>.self, SomeGenericStruct<SomeStruct>.self)
}
// rdar://16610078
// CHECK-LABEL: sil hidden @$S9metatypes30existential_metatype_from_thinypXpyF : $@convention(thin) () -> @thick Any.Type
// CHECK: [[T0:%.*]] = metatype $@thin SomeStruct.Type
// CHECK-NEXT: [[T1:%.*]] = metatype $@thick SomeStruct.Type
// CHECK-NEXT: [[T2:%.*]] = init_existential_metatype [[T1]] : $@thick SomeStruct.Type, $@thick Any.Type
// CHECK-NEXT: return [[T2]] : $@thick Any.Type
func existential_metatype_from_thin() -> Any.Type {
return SomeStruct.self
}
// CHECK-LABEL: sil hidden @$S9metatypes36existential_metatype_from_thin_valueypXpyF : $@convention(thin) () -> @thick Any.Type
// CHECK: [[T1:%.*]] = metatype $@thin SomeStruct.Type
// CHECK: [[T0:%.*]] = function_ref @$S9metatypes10SomeStructV{{[_0-9a-zA-Z]*}}fC
// CHECK-NEXT: [[T2:%.*]] = apply [[T0]]([[T1]])
// CHECK-NEXT: debug_value [[T2]] : $SomeStruct, let, name "s"
// CHECK-NEXT: [[T0:%.*]] = metatype $@thin SomeStruct.Type
// CHECK-NEXT: [[T1:%.*]] = metatype $@thick SomeStruct.Type
// CHECK-NEXT: [[T2:%.*]] = init_existential_metatype [[T1]] : $@thick SomeStruct.Type, $@thick Any.Type
// CHECK-NEXT: return [[T2]] : $@thick Any.Type
func existential_metatype_from_thin_value() -> Any.Type {
let s = SomeStruct()
return type(of: s)
}
// CHECK-LABEL: sil hidden @$S9metatypes20specialized_metatypes10DictionaryVySSSiGyF
// CHECK: metatype $@thin Dictionary<String, Int>.Type
func specialized_metatype() -> Dictionary<String, Int> {
let dict = Swift.Dictionary<Swift.String, Int>()
return dict
}
| apache-2.0 |
maxim-pervushin/HyperHabit | HyperHabit/HyperHabit/Views/MXCalendarView/Cells/MXAccessoryView.swift | 1 | 1962 | //
// Created by Maxim Pervushin on 19/01/16.
// Copyright (c) 2016 Maxim Pervushin. All rights reserved.
//
import UIKit
@IBDesignable class MXAccessoryView: UIView {
@IBInspectable var value: Int = 0 {
didSet {
setNeedsDisplay()
}
}
@IBInspectable var maxValue: Int = 0 {
didSet {
setNeedsDisplay()
}
}
private var _activeSegmentColor = UIColor.clearColor()
private var _inactiveSegmentColor = UIColor.clearColor()
override func drawRect(rect: CGRect) {
if maxValue == 0 {
return
}
let ctx = UIGraphicsGetCurrentContext()
let borderRectSide = min(bounds.size.width, bounds.size.height) - 4
let radius = (borderRectSide - borderRectSide / 6) / 2
let center = CGPointMake(bounds.size.width / 2, bounds.size.height / 2)
let segmentSize = CGFloat(2.0 * M_PI) / CGFloat(maxValue)
let rotation = CGFloat(-0.5 * M_PI)
for currentSegment in 0 ... maxValue - 1 {
let startAngle = segmentSize * CGFloat(currentSegment) + rotation
let endAngle = segmentSize * CGFloat(currentSegment + 1) + rotation
CGContextAddArc(ctx, center.x, center.y, radius, startAngle, endAngle, 0)
CGContextSetStrokeColorWithColor(ctx, (currentSegment < value ? _activeSegmentColor : _inactiveSegmentColor).CGColor)
CGContextStrokePath(ctx)
}
}
}
extension MXAccessoryView {
// MARK: - UIAppearance
dynamic var activeSegmentColor: UIColor {
// UI_APPEARANCE_SELECTOR
get {
return _activeSegmentColor
}
set {
_activeSegmentColor = newValue
}
}
dynamic var inactiveSegmentColor: UIColor {
// UI_APPEARANCE_SELECTOR
get {
return _inactiveSegmentColor
}
set {
_inactiveSegmentColor = newValue
}
}
} | mit |
faimin/ZDOpenSourceDemo | ZDOpenSourceSwiftDemo/Pods/lottie-ios/lottie-swift/src/Public/AnimationCache/LRUAnimationCache.swift | 1 | 1238 | //
// LRUAnimationCache.swift
// lottie-swift
//
// Created by Brandon Withrow on 2/5/19.
//
import Foundation
/**
An Animation Cache that will store animations up to `cacheSize`.
Once `cacheSize` is reached, the least recently used animation will be ejected.
The default size of the cache is 100.
*/
public class LRUAnimationCache: AnimationCacheProvider {
public init() { }
/// Clears the Cache.
public func clearCache() {
cacheMap.removeAll()
lruList.removeAll()
}
/// The global shared Cache.
public static let sharedCache = LRUAnimationCache()
/// The size of the cache.
public var cacheSize: Int = 100
public func animation(forKey: String) -> Animation? {
guard let animation = cacheMap[forKey] else {
return nil
}
if let index = lruList.firstIndex(of: forKey) {
lruList.remove(at: index)
lruList.append(forKey)
}
return animation
}
public func setAnimation(_ animation: Animation, forKey: String) {
cacheMap[forKey] = animation
lruList.append(forKey)
if lruList.count > cacheSize {
lruList.remove(at: 0)
}
}
fileprivate var cacheMap: [String : Animation] = [:]
fileprivate var lruList: [String] = []
}
| mit |
networkextension/SFSocket | SFSocket/udp/NWUDPSocket.swift | 1 | 2997 | import Foundation
import NetworkExtension
import AxLogger
/// The delegate protocol of `NWUDPSocket`.
public protocol NWUDPSocketDelegate: class {
/**
Socket did receive data from remote.
- parameter data: The data.
- parameter from: The socket the data is read from.
*/
func didReceiveData(_ data: Data, from: NWUDPSocket)
}
/// The wrapper for NWUDPSession.
///
/// - note: This class is thread-safe.
open class NWUDPSocket {
fileprivate let session: NWUDPSession
fileprivate var pendingWriteData: [Data] = []
fileprivate var writing = false
fileprivate let queue: DispatchQueue = DispatchQueue(label: "NWUDPSocket.queue", attributes: [])
/// The delegate instance.
open weak var delegate: NWUDPSocketDelegate?
/// The time when the last activity happens.
///
/// Since UDP do not have a "close" semantic, this can be an indicator of timeout.
open var lastActive: Date = Date()
/**
Create a new UDP socket connecting to remote.
- parameter host: The host.
- parameter port: The port.
*/
init?(host: String, port: Int) {
guard let udpsession = RawSocketFactory.TunnelProvider?.createUDPSession(to: NWHostEndpoint(hostname: host, port: "\(port)"), from: nil) else {
return nil
}
session = udpsession
session.setReadHandler({ [ weak self ] dataArray, error in
guard let sSelf = self else {
return
}
sSelf.updateActivityTimer()
guard error == nil else {
AxLogger.log("Error when reading from remote server. \(String(describing: error))",level: .Error)
return
}
for data in dataArray! {
sSelf.delegate?.didReceiveData(data, from: sSelf)
}
}, maxDatagrams: 32)
}
/**
Send data to remote.
- parameter data: The data to send.
*/
func writeData(_ data: Data) {
queue.async {
self.pendingWriteData.append(data)
self.checkWrite()
}
}
func disconnect() {
queue.async {
self.session.cancel()
}
}
fileprivate func checkWrite() {
queue.async {
self.updateActivityTimer()
guard !self.writing else {
return
}
guard self.pendingWriteData.count > 0 else {
return
}
self.writing = true
self.session.writeMultipleDatagrams(self.pendingWriteData) {_ in
self.writing = false
self.checkWrite()
}
self.pendingWriteData.removeAll(keepingCapacity: true)
}
}
fileprivate func updateActivityTimer() {
lastActive = Date()
}
}
| bsd-3-clause |
faimin/ZDOpenSourceDemo | ZDOpenSourceSwiftDemo/Pods/Cartography/Cartography/AutoresizingMaskLayoutProxy.swift | 6 | 317 | //
// AutoresizingMaskLayoutProxy.swift
// Cartography-iOS
//
// Created by Vitor Travain on 24/10/17.
// Copyright © 2017 Robert Böhnke. All rights reserved.
//
import Foundation
public protocol AutoresizingMaskLayoutProxy: LayoutProxy {
var translatesAutoresizingMaskIntoConstraints: Bool { get set }
}
| mit |
AndreyPanov/ApplicationCoordinator | ApplicationCoordinator/Flows/Items flow/ItemDetailController.swift | 1 | 231 | final class ItemDetailController: UIViewController, ItemDetailView {
//controller handler
var itemList: ItemList?
override func viewDidLoad() {
super.viewDidLoad()
title = itemList?.title ?? "Detail"
}
}
| mit |
3DprintFIT/octoprint-ios-client | OctoPhone/View Related/Print Profile/PrintProfileViewController.swift | 1 | 5556 | //
// PrintProfileViewController.swift
// OctoPhone
//
// Created by Josef Dolezal on 03/04/2017.
// Copyright © 2017 Josef Dolezal. All rights reserved.
//
import UIKit
import ReactiveSwift
import ReactiveCocoa
import Result
/// Print profile detail flow controller
protocol PrintProfileViewControllerDelegate: class {
/// Called when user tapped done button
func doneButtonTapped()
/// Called when user tapped close button
func closeButtonTapped()
/// Called when user tapped on delete button
func deleteButtonTapped()
}
/// Print profile detail controller
class PrintProfileViewController: BaseViewController {
// MARK: - Properties
/// Controller logic
fileprivate var viewModel: PrintProfileViewModelType!
/// Button for done action
private lazy var doneButton: UIBarButtonItem = {
let button = UIBarButtonItem(barButtonSystemItem: .done,
target: self, action: #selector(doneButtonTapped))
return button
}()
/// Button for close action
private lazy var closeButton: UIBarButtonItem = {
let button = UIBarButtonItem(barButtonSystemItem: .cancel, target: self,
action: #selector(closeButtonTapped))
return button
}()
/// Button for delete profile action
private lazy var deleteButton: UIBarButtonItem = {
let button = UIBarButtonItem(barButtonSystemItem: .trash, target: self,
action: #selector(deleteButtonTapped))
return button
}()
/// Input for profile name
private weak var nameField: FormTextInputView!
/// Input for profile identifier
private weak var identifierField: FormTextInputView!
/// Input for printer model
private weak var modelField: FormTextInputView!
// MARK: - Initializers
convenience init(viewModel: PrintProfileViewModelType) {
self.init()
self.viewModel = viewModel
}
// MARK: - Controller lifecycle
override func loadView() {
super.loadView()
let nameField = FormTextInputView()
let identifierField = FormTextInputView()
let modelField = FormTextInputView()
let formInputs = [nameField, identifierField, modelField]
let scrollView = UIScrollView()
let stackView = UIStackView(arrangedSubviews: formInputs, axis: .vertical)
view.addSubview(scrollView)
scrollView.addSubview(stackView)
scrollView.contentOffset.y = navigationController?.navigationBar.frame.height ?? 0.0
scrollView.alwaysBounceVertical = true
scrollView.isScrollEnabled = true
scrollView.snp.makeConstraints { make in
make.edges.equalToSuperview()
}
stackView.snp.makeConstraints { make in
make.edges.width.equalToSuperview()
}
self.nameField = nameField
self.identifierField = identifierField
self.modelField = modelField
navigationItem.leftBarButtonItem = closeButton
navigationItem.rightBarButtonItem = doneButton
}
override func viewDidLoad() {
super.viewDidLoad()
bindViewModel()
}
// MARK: - Internal logic
/// Binds outputs of View Model to UI and converts
/// user interaction to View Model inputs
private func bindViewModel() {
nameField.textField.reactive.continuousTextValues.signal.observeValues { [weak self] text in
self?.viewModel.inputs.profileNameChanged(text)
}
identifierField.textField.reactive.continuousTextValues.signal.observeValues { [weak self] text in
self?.viewModel.inputs.profileIdentifierChanged(text)
}
modelField.textField.reactive.continuousTextValues.signal.observeValues { [weak self] text in
self?.viewModel.inputs.profileModelChanged(text)
}
nameField.descriptionLabel.reactive.text <~ viewModel.outputs.profileNameDescription
nameField.textField.reactive.text <~ viewModel.outputs.profileNameValue
identifierField.descriptionLabel.reactive.text <~ viewModel.outputs.profileIdentifierDescription
identifierField.textField.reactive.text <~ viewModel.outputs.profileIdentifierValue
modelField.descriptionLabel.reactive.text <~ viewModel.outputs.profileModelDescription
modelField.textField.reactive.text <~ viewModel.outputs.profileModelValue
identifierField.textField.reactive.isEnabled <~ viewModel.outputs.profileIdentifierIsEditable
doneButton.reactive.isEnabled <~ viewModel.outputs.doneButtonIsEnabled
if viewModel.outputs.closeButtonIsHidden.value {
navigationItem.leftBarButtonItem = deleteButton
}
viewModel.outputs.displayError.startWithValues { [weak self] error in
self?.presentError(title: error.title, message: error.message)
}
}
/// Done button action callback
func doneButtonTapped() {
viewModel.inputs.doneButtonTapped()
}
/// Close button action callback
func closeButtonTapped() {
viewModel.inputs.closeButtonTapped()
}
/// Delete button action callback
func deleteButtonTapped() {
let controller = DeletionDialogFactory
.createDialog(title: nil, message: tr(.doYouReallyWantToDeletePrintProfile)) { [weak self] in
self?.viewModel.inputs.deleteButtonTapped()
}
present(controller, animated: true, completion: nil)
}
}
| mit |
ustwo/US2MapperKit | US2MapperKit/Shared Test Cases/Classes/TestObjectSeven.swift | 1 | 64 | import Foundation
class TestObjectSeven : _TestObjectSeven {
} | mit |
jovito-royeca/Decktracker | ios/old/Decktracker/View/Decks/StartingHandViewController.swift | 1 | 20716 | //
// StartingHandViewController.swift
// Decktracker
//
// Created by Jovit Royeca on 12/30/14.
// Copyright (c) 2014 Jovito Royeca. All rights reserved.
//
import UIKit
enum StartingHandShowMode: CustomStringConvertible {
case ByHand
case ByGraveyard
case ByLibrary
var description : String {
switch self {
case ByHand: return "Hand"
case ByGraveyard: return "Graveyard"
case ByLibrary: return "Library"
}
}
}
class StartingHandViewController: UIViewController, UITableViewDataSource, UITableViewDelegate, UICollectionViewDataSource, UICollectionViewDelegate {
var initialHand = 7
var viewButton:UIBarButtonItem?
var showButton:UIBarButtonItem?
var newButton:UIBarButtonItem?
var mulliganButton:UIBarButtonItem?
var drawButton:UIBarButtonItem?
var tblHand:UITableView?
var colHand:UICollectionView?
var bottomToolbar:UIToolbar?
var viewMode:String?
var showMode:StartingHandShowMode?
var deck:Deck?
var arrayDeck:[String]?
var arrayHand:[String]?
var arrayGraveyard:[String]?
var arrayLibrary:[String]?
var viewLoadedOnce = true
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
hidesBottomBarWhenPushed = true
let dX:CGFloat = 0
var dY:CGFloat = 0
let dWidth = self.view.frame.size.width
var dHeight = self.view.frame.size.height-44
var frame:CGRect?
viewButton = UIBarButtonItem(image: UIImage(named: "list.png"), style: UIBarButtonItemStyle.Plain, target: self, action: "viewButtonTapped")
showButton = UIBarButtonItem(image: UIImage(named: "view_file.png"), style: UIBarButtonItemStyle.Plain, target: self, action: "showButtonTapped")
newButton = UIBarButtonItem(title: "New Hand", style: UIBarButtonItemStyle.Plain, target: self, action: "newButtonTapped")
mulliganButton = UIBarButtonItem(title: "Mulligan", style: UIBarButtonItemStyle.Plain, target: self, action: "mulliganButtonTapped")
drawButton = UIBarButtonItem(title: "Draw", style: UIBarButtonItemStyle.Plain, target: self, action: "drawButtonTapped")
dY = dHeight
dHeight = 44
frame = CGRect(x:dX, y:dY, width:dWidth, height:dHeight)
bottomToolbar = UIToolbar(frame: frame!)
bottomToolbar!.items = [newButton!,
UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.FlexibleSpace, target: nil, action: nil),
mulliganButton!,
UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.FlexibleSpace, target: nil, action: nil),
drawButton!]
self.navigationItem.title = "Starting Hand"
self.navigationItem.rightBarButtonItems = [showButton!, viewButton!]
if let value = NSUserDefaults.standardUserDefaults().stringForKey(kCardViewMode) {
if value == kCardViewModeList {
self.viewMode = kCardViewModeList
self.showTableView()
} else if value == kCardViewModeGrid2x2 {
self.viewMode = kCardViewModeGrid2x2
viewButton!.image = UIImage(named: "2x2.png")
self.showGridView()
} else if value == kCardViewModeGrid3x3 {
self.viewMode = kCardViewModeGrid3x3
viewButton!.image = UIImage(named: "3x3.png")
self.showGridView()
} else {
self.viewMode = kCardViewModeList
self.showTableView()
}
} else {
self.viewMode = kCardViewModeList
self.showTableView()
}
view.addSubview(bottomToolbar!)
self.viewLoadedOnce = false
self.newButtonTapped()
#if !DEBUG
// send the screen to Google Analytics
if let tracker = GAI.sharedInstance().defaultTracker {
tracker.set(kGAIScreenName, value: "Starting Hand")
tracker.send(GAIDictionaryBuilder.createScreenView().build() as [NSObject : AnyObject])
}
#endif
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func viewButtonTapped() {
var initialSelection = 0
if self.viewMode == kCardViewModeList {
initialSelection = 0
} else if self.viewMode == kCardViewModeGrid2x2 {
initialSelection = 1
} else if self.viewMode == kCardViewModeGrid3x3 {
initialSelection = 2
}
let doneBlock = { (picker: ActionSheetStringPicker?, selectedIndex: NSInteger, selectedValue: AnyObject?) -> Void in
switch selectedIndex {
case 0:
self.viewMode = kCardViewModeList
self.viewButton!.image = UIImage(named: "list.png")
self.showTableView()
case 1:
self.viewMode = kCardViewModeGrid2x2
self.viewButton!.image = UIImage(named: "2x2.png")
self.showGridView()
case 2:
self.viewMode = kCardViewModeGrid3x3
self.viewButton!.image = UIImage(named: "3x3.png")
self.showGridView()
default:
break
}
NSUserDefaults.standardUserDefaults().setObject(self.viewMode, forKey: kCardViewMode)
NSUserDefaults.standardUserDefaults().synchronize()
}
ActionSheetStringPicker.showPickerWithTitle("View As",
rows: [kCardViewModeList, kCardViewModeGrid2x2, kCardViewModeGrid3x3],
initialSelection: initialSelection,
doneBlock: doneBlock,
cancelBlock: nil,
origin: view)
}
func showButtonTapped() {
var initialSelection = 0
switch self.showMode! {
case .ByHand:
initialSelection = 0
case .ByGraveyard:
initialSelection = 1
case .ByLibrary:
initialSelection = 2
}
let doneBlock = { (picker: ActionSheetStringPicker?, selectedIndex: NSInteger, selectedValue: AnyObject?) -> Void in
switch selectedIndex {
case 0:
self.showMode = .ByHand
case 1:
self.showMode = .ByGraveyard
case 2:
self.showMode = .ByLibrary
default:
break
}
if self.viewMode == kCardViewModeList {
self.tblHand!.reloadData()
} else if self.viewMode == kCardViewModeGrid2x2 ||
self.viewMode == kCardViewModeGrid3x3 {
self.colHand!.reloadData()
} else if self.viewMode == kCardViewModeGrid3x3 {
initialSelection = 2
}
}
ActionSheetStringPicker.showPickerWithTitle("Show Cards In",
rows: [StartingHandShowMode.ByHand.description, StartingHandShowMode.ByGraveyard.description, StartingHandShowMode.ByLibrary.description],
initialSelection: initialSelection,
doneBlock: doneBlock,
cancelBlock: nil,
origin: view)
}
func newButtonTapped() {
initialHand = 7
self.mulliganButton!.enabled = true
self.drawButton!.enabled = true
arrayHand = Array()
arrayGraveyard = Array()
arrayLibrary = Array()
self.initDeck()
self.shuffleLibrary()
self.drawCards(initialHand)
self.showMode = StartingHandShowMode.ByHand
if self.viewMode == kCardViewModeList {
tblHand!.reloadData()
} else if self.viewMode == kCardViewModeGrid2x2 ||
self.viewMode == kCardViewModeGrid3x3 {
colHand!.reloadData()
}
}
func mulliganButtonTapped() {
initialHand -= 1
if initialHand <= 1 {
self.mulliganButton!.enabled = false
}
// put cards from hand to library
while arrayHand!.count > 0 {
let cardId = arrayHand!.removeLast()
arrayLibrary!.append(cardId)
}
// put cards from graveyard to library
while arrayGraveyard!.count > 0 {
let cardId = arrayGraveyard!.removeLast()
arrayLibrary!.append(cardId)
}
self.shuffleLibrary()
self.drawCards(initialHand)
self.showMode = StartingHandShowMode.ByHand
if self.viewMode == kCardViewModeList {
tblHand!.reloadData()
} else if self.viewMode == kCardViewModeGrid2x2 ||
self.viewMode == kCardViewModeGrid3x3 {
colHand!.reloadData()
}
}
func drawButtonTapped() {
if arrayLibrary!.count <= 0 {
self.drawButton!.enabled = false
}
self.drawCards(1)
self.showMode = StartingHandShowMode.ByHand
if self.viewMode == kCardViewModeList {
tblHand!.reloadData()
} else if self.viewMode == kCardViewModeGrid2x2 ||
self.viewMode == kCardViewModeGrid3x3{
colHand!.reloadData()
}
}
func showTableView() {
let dX:CGFloat = 0
let dY = viewLoadedOnce ? 0 : UIApplication.sharedApplication().statusBarFrame.size.height + self.navigationController!.navigationBar.frame.size.height
let dWidth = self.view.frame.size.width
let dHeight = self.view.frame.size.height-dY-44
let frame = CGRect(x:dX, y:dY, width:dWidth, height:dHeight)
tblHand = UITableView(frame: frame, style: UITableViewStyle.Plain)
tblHand!.delegate = self
tblHand!.dataSource = self
if colHand != nil {
colHand!.removeFromSuperview()
}
view.addSubview(tblHand!)
}
func showGridView() {
let dX:CGFloat = 0
let dY = viewLoadedOnce ? 0 : UIApplication.sharedApplication().statusBarFrame.size.height + self.navigationController!.navigationBar.frame.size.height
let dWidth = self.view.frame.size.width
let dHeight = self.view.frame.size.height-dY-44
let frame = CGRect(x:dX, y:dY, width:dWidth, height:dHeight)
let divisor:CGFloat = viewMode == kCardViewModeGrid2x2 ? 2 : 3
let layout = CSStickyHeaderFlowLayout()
layout.sectionInset = UIEdgeInsetsMake(0, 0, 0, 0)
layout.minimumInteritemSpacing = 0
layout.minimumLineSpacing = 0
layout.headerReferenceSize = CGSize(width:view.frame.width, height: 22)
layout.itemSize = CGSize(width: frame.width/divisor, height: frame.height/divisor)
colHand = UICollectionView(frame: frame, collectionViewLayout: layout)
colHand!.dataSource = self
colHand!.delegate = self
colHand!.registerClass(CardImageCollectionViewCell.self, forCellWithReuseIdentifier: "Card")
colHand!.registerClass(UICollectionReusableView.self, forSupplementaryViewOfKind: UICollectionElementKindSectionHeader, withReuseIdentifier:"Header")
colHand!.backgroundColor = UIColor(patternImage: UIImage(contentsOfFile: "\(NSBundle.mainBundle().bundlePath)/images/Gray_Patterned_BG.jpg")!)
if tblHand != nil {
tblHand!.removeFromSuperview()
}
view.addSubview(colHand!)
}
func initDeck() {
arrayDeck = Array()
for dict in self.deck!.arrLands {
let d = dict as! Dictionary<String, AnyObject>
let cardId = d["cardId"] as! String
// let card = DTCard(forPrimaryKey: cardId)
let qty = d["qty"] as! NSNumber
for var i=0; i<qty.integerValue; i++ {
arrayDeck!.append(cardId)
}
}
for dict in self.deck!.arrCreatures {
let d = dict as! Dictionary<String, AnyObject>
let cardId = d["cardId"] as! String
// let card = DTCard(forPrimaryKey: cardId)
let qty = d["qty"] as! NSNumber
for var i=0; i<qty.integerValue; i++ {
arrayDeck!.append(cardId)
}
}
for dict in self.deck!.arrOtherSpells {
let d = dict as! Dictionary<String, AnyObject>
let cardId = d["cardId"] as! String
// let card = DTCard(forPrimaryKey: cardId)
let qty = d["qty"] as! NSNumber
for var i=0; i<qty.integerValue; i++ {
arrayDeck!.append(cardId)
}
}
}
func shuffleLibrary() {
var arrayTemp = [String]()
// put cards from deck to library
while arrayDeck!.count > 0 {
let cardId = arrayDeck!.removeLast()
arrayLibrary!.append(cardId)
}
// put cards from library to temp
while arrayLibrary!.count > 0 {
let count = UInt32(arrayLibrary!.count)
let random = Int(arc4random_uniform(count))
let cardId = arrayLibrary!.removeAtIndex(random)
arrayTemp.append(cardId)
}
// put cards from temp to library
while arrayTemp.count > 0 {
let cardId = arrayTemp.removeLast()
arrayLibrary!.append(cardId)
}
}
func drawCards(howMany: Int) {
for var i=0; i<howMany; i++ {
if arrayLibrary!.count <= 0 {
return
}
let cardId = arrayLibrary!.removeLast()
arrayHand!.append(cardId)
}
}
func discardCard(index: Int) {
let cardId = arrayHand!.removeAtIndex(index)
arrayGraveyard!.append(cardId)
if self.viewMode == kCardViewModeList {
tblHand!.reloadData()
} else if self.viewMode == kCardViewModeGrid2x2 ||
self.view == kCardViewModeGrid3x3{
colHand!.reloadData()
}
}
// MARK: UITableViewDataSource
func tableView(tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
var count = 0
switch self.showMode! {
case .ByHand:
count = self.arrayHand!.count
case .ByGraveyard:
count = self.arrayGraveyard!.count
case .ByLibrary:
count = self.arrayLibrary!.count
}
return "Cards In \(self.showMode!.description): \(count)"
}
func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
return CGFloat(CARD_SUMMARY_VIEW_CELL_HEIGHT)
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
switch self.showMode! {
case .ByHand:
return self.arrayHand!.count
case .ByGraveyard:
return self.arrayGraveyard!.count
case .ByLibrary:
return self.arrayLibrary!.count
}
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
var cell:UITableViewCell?
var cardSummaryView:CardSummaryView?
var cardId:String?
switch self.showMode! {
case .ByHand:
if (self.arrayHand!.count > 0) {
cardId = self.arrayHand![indexPath.row]
}
case .ByGraveyard:
if (self.arrayGraveyard!.count > 0) {
cardId = self.arrayGraveyard![indexPath.row]
}
case .ByLibrary:
if (self.arrayLibrary!.count > 0) {
cardId = self.arrayLibrary![indexPath.row]
}
}
if let x = tableView.dequeueReusableCellWithIdentifier(kCardInfoViewIdentifier) as UITableViewCell! {
cell = x
for subView in cell!.contentView.subviews {
if subView is CardSummaryView {
cardSummaryView = subView as? CardSummaryView
break
}
}
} else {
cell = UITableViewCell(style: UITableViewCellStyle.Default, reuseIdentifier: kCardInfoViewIdentifier)
cardSummaryView = NSBundle.mainBundle().loadNibNamed("CardSummaryView", owner: self, options: nil).first as? CardSummaryView
cardSummaryView!.frame = CGRect(x: 0, y: 0, width: tableView.frame.size.width, height: CGFloat(CARD_SUMMARY_VIEW_CELL_HEIGHT))
cell!.contentView.addSubview(cardSummaryView!)
}
cell!.accessoryType = UITableViewCellAccessoryType.None
cell!.selectionStyle = UITableViewCellSelectionStyle.None
cardSummaryView!.displayCard(cardId)
return cell!
}
func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool{
return self.showMode == .ByHand
}
func tableView(tableView: UITableView, titleForDeleteConfirmationButtonForRowAtIndexPath indexPath: NSIndexPath) -> String? {
return "Discard"
}
func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
self.discardCard(indexPath.row)
}
// MARK: UICollectionViewDataSource
func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
switch self.showMode! {
case .ByHand:
return self.arrayHand!.count
case .ByGraveyard:
return self.arrayGraveyard!.count
case .ByLibrary:
return self.arrayLibrary!.count
}
}
func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
var cardId:String?
switch self.showMode! {
case .ByHand:
if (self.arrayHand!.count > 0) {
cardId = self.arrayHand![indexPath.row]
}
case .ByGraveyard:
if (self.arrayGraveyard!.count > 0) {
cardId = self.arrayGraveyard![indexPath.row]
}
case .ByLibrary:
if (self.arrayLibrary!.count > 0) {
cardId = self.arrayLibrary![indexPath.row]
}
}
let cell = collectionView.dequeueReusableCellWithReuseIdentifier("Card", forIndexPath: indexPath) as! CardImageCollectionViewCell
cell.displayCard(cardId!, cropped: false, showName: false, showSetIcon: false)
return cell
}
func collectionView(collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, atIndexPath indexPath: NSIndexPath) -> UICollectionReusableView {
var view:UICollectionReusableView?
if kind == UICollectionElementKindSectionHeader {
var count = 0
switch self.showMode! {
case .ByHand:
count = self.arrayHand!.count
case .ByGraveyard:
count = self.arrayGraveyard!.count
case .ByLibrary:
count = self.arrayLibrary!.count
}
let text = " Cards In \(self.showMode!.description): \(count)"
let label = UILabel(frame: CGRect(x:0, y:0, width:self.view.frame.size.width, height:22))
label.text = text
label.backgroundColor = UIColor.whiteColor()
label.font = UIFont.boldSystemFontOfSize(18)
view = collectionView.dequeueReusableSupplementaryViewOfKind(UICollectionElementKindSectionHeader, withReuseIdentifier:"Header", forIndexPath:indexPath) as UICollectionReusableView!
if view == nil {
view = UICollectionReusableView(frame: CGRect(x:0, y:0, width:self.view.frame.size.width, height:22))
}
view!.addSubview(label)
}
return view!
}
}
| apache-2.0 |
carabina/Static | Static/Value1Cell.swift | 5 | 322 | import UIKit
public class Value1Cell: UITableViewCell, CellType {
public override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
super.init(style: .Value1, reuseIdentifier: reuseIdentifier)
}
public required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
}
| mit |
dyshero/Pictorial-OC | 原始/Pictorial-OC/Pods/ReactiveSwift/Sources/Optional.swift | 26 | 906 | //
// Optional.swift
// ReactiveSwift
//
// Created by Neil Pankey on 6/24/15.
// Copyright (c) 2015 GitHub. All rights reserved.
//
/// An optional protocol for use in type constraints.
public protocol OptionalProtocol {
/// The type contained in the otpional.
associatedtype Wrapped
init(reconstructing value: Wrapped?)
/// Extracts an optional from the receiver.
var optional: Wrapped? { get }
}
extension Optional: OptionalProtocol {
public var optional: Wrapped? {
return self
}
public init(reconstructing value: Wrapped?) {
self = value
}
}
extension SignalProtocol {
/// Turns each value into an Optional.
internal func optionalize() -> Signal<Value?, Error> {
return map(Optional.init)
}
}
extension SignalProducerProtocol {
/// Turns each value into an Optional.
internal func optionalize() -> SignalProducer<Value?, Error> {
return lift { $0.optionalize() }
}
}
| mit |
JohnSundell/SwiftKit | Source/Shared/Require.swift | 1 | 1053 | import Foundation
/// Require that an optional is not nil, or throw an NSError (with an optional explicit message)
public func Require<T>(optional: Optional<T>, errorMessage: String? = nil) throws -> T {
guard let value = optional else {
throw NSError(name: errorMessage ?? "Required value was nil")
}
return value
}
/// Require that a value is not nil, and that it may be cast to another type, or throw an NSError (with an optional explicit message)
public func RequireAndCast<A, B>(value: A?, errorMessage: String? = nil) throws -> B {
guard let value = try Require(value, errorMessage: errorMessage) as? B else {
throw NSError(name: errorMessage ?? "Could not perform cast")
}
return value
}
/// Require that an expression avaluates to true, or throw an NSError (with an optional explicit message)
public func Require(@autoclosure expression: () -> Bool, errorMessage: String? = nil) throws {
if !expression() {
throw NSError(name: errorMessage ?? "Requirement not fulfilled")
}
}
| mit |
readium/r2-streamer-swift | r2-streamer-swift/Parser/Readium/ReadiumWebPubParser.swift | 1 | 5149 | //
// ReadiumWebPubParser.swift
// r2-streamer-swift
//
// Created by Mickaël Menu on 25.06.19.
//
// Copyright 2019 Readium Foundation. All rights reserved.
// Use of this source code is governed by a BSD-style license which is detailed
// in the LICENSE file present in the project repository where this source code is maintained.
//
import Foundation
import R2Shared
public enum ReadiumWebPubParserError: Error {
case parseFailure(url: URL, Error?)
case missingFile(path: String)
}
/// Parser for a Readium Web Publication (packaged, or as a manifest).
public class ReadiumWebPubParser: PublicationParser, Loggable {
public enum Error: Swift.Error {
case manifestNotFound
case invalidManifest
}
private let pdfFactory: PDFDocumentFactory
private let httpClient: HTTPClient
public init(pdfFactory: PDFDocumentFactory, httpClient: HTTPClient) {
self.pdfFactory = pdfFactory
self.httpClient = httpClient
}
public func parse(asset: PublicationAsset, fetcher: Fetcher, warnings: WarningLogger?) throws -> Publication.Builder? {
guard let mediaType = asset.mediaType(), mediaType.isReadiumWebPubProfile else {
return nil
}
let isPackage = !mediaType.isRWPM
// Reads the manifest data from the fetcher.
guard let manifestData: Data = (
isPackage
? try? fetcher.readData(at: "/manifest.json")
// For a single manifest file, reads the first (and only) file in the fetcher.
: try? fetcher.readData(at: fetcher.links.first)
) else {
throw Error.manifestNotFound
}
let manifest = try Manifest(json: JSONSerialization.jsonObject(with: manifestData), isPackaged: isPackage)
var fetcher = fetcher
// For a manifest, we discard the `fetcher` provided by the Streamer, because it was only
// used to read the manifest file. We use an `HTTPFetcher` instead to serve the remote
// resources.
if !isPackage {
let baseURL = manifest.link(withRel: .`self`)?.url(relativeTo: nil)?.deletingLastPathComponent()
fetcher = HTTPFetcher(client: httpClient, baseURL: baseURL)
}
let userProperties = UserProperties()
if mediaType.matches(.readiumWebPub) {
fetcher = TransformingFetcher(fetcher: fetcher, transformers: [
EPUBHTMLInjector(metadata: manifest.metadata, userProperties: userProperties).inject(resource:)
])
}
if mediaType.matches(.lcpProtectedPDF) {
// Checks the requirements from the spec, see. https://readium.org/lcp-specs/drafts/lcpdf
guard
!manifest.readingOrder.isEmpty,
manifest.readingOrder.all(matchMediaType: .pdf) else
{
throw Error.invalidManifest
}
}
return Publication.Builder(
mediaType: mediaType,
format: (mediaType.matches(.lcpProtectedPDF) ? .pdf : .webpub),
manifest: manifest,
fetcher: fetcher,
servicesBuilder: PublicationServicesBuilder(setup: {
switch mediaType {
case .lcpProtectedPDF:
$0.setPositionsServiceFactory(LCPDFPositionsService.makeFactory(pdfFactory: self.pdfFactory))
case .divina, .divinaManifest:
$0.setPositionsServiceFactory(PerResourcePositionsService.makeFactory(fallbackMediaType: "image/*"))
case .readiumAudiobook, .readiumAudiobookManifest, .lcpProtectedAudiobook:
$0.setLocatorServiceFactory(AudioLocatorService.makeFactory())
case .readiumWebPub:
$0.setSearchServiceFactory(_StringSearchService.makeFactory())
default:
break
}
}),
setupPublication: { publication in
if mediaType.matches(.readiumWebPub) {
publication.userProperties = userProperties
publication.userSettingsUIPreset = EPUBParser.userSettingsPreset(for: publication.metadata)
}
}
)
}
@available(*, unavailable, message: "Use an instance of `Streamer` to open a `Publication`")
public static func parse(at url: URL) throws -> (PubBox, PubParsingCallback) {
fatalError("Not available")
}
}
private extension MediaType {
/// Returns whether this media type is of a Readium Web Publication profile.
var isReadiumWebPubProfile: Bool {
matchesAny(
.readiumWebPub, .readiumWebPubManifest, .readiumAudiobook, .readiumAudiobookManifest,
.lcpProtectedAudiobook, .divina, .divinaManifest, .lcpProtectedPDF
)
}
}
@available(*, unavailable, renamed: "ReadiumWebPubParserError")
public typealias WEBPUBParserError = ReadiumWebPubParserError
@available(*, unavailable, renamed: "ReadiumWebPubParser")
public typealias WEBPUBParser = ReadiumWebPubParser
| bsd-3-clause |
StevenDXC/DxRefreshView | DxRefreshView/DxRefreshUIScrollViewExtension.swift | 1 | 1091 | //
// RefreshUIScrollViewExtension.swift
// DxRefreshView
//
// Created by Miutrip on 2016/9/12.
// Copyright © 2016年 dxc. All rights reserved.
//
import UIKit
public extension UIScrollView {
private struct dx_associatedKeys {
static var refreshHeader = "refreshHeader"
}
internal var refreshHeader: DxRefreshView? {
get {
return objc_getAssociatedObject(self, &dx_associatedKeys.refreshHeader) as? DxRefreshView;
}
set {
objc_setAssociatedObject(self, &dx_associatedKeys.refreshHeader, newValue, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN_NONATOMIC)
}
}
internal func setRefreshHeader(refreshHeader:DxRefreshView){
self.insertSubview(refreshHeader, at: 0);
self.refreshHeader = refreshHeader;
self.addObserver(refreshHeader, forKeyPath: "contentOffset", options: NSKeyValueObservingOptions.new, context: nil);
self.addObserver(refreshHeader, forKeyPath: "contentInset", options: NSKeyValueObservingOptions.new,context: nil);
}
}
| apache-2.0 |
reesemclean/MaterialKit | Example/MaterialKitTests/MaterialKitTests.swift | 26 | 914 | //
// MaterialKitTests.swift
// MaterialKitTests
//
// Created by LeVan Nghia on 11/14/14.
// Copyright (c) 2014 Le Van Nghia. All rights reserved.
//
import UIKit
import XCTest
class MaterialKitTests: XCTestCase {
override func setUp() {
super.setUp()
// Put setup code here. This method is called before the invocation of each test method in the class.
}
override func tearDown() {
// Put teardown code here. This method is called after the invocation of each test method in the class.
super.tearDown()
}
func testExample() {
// This is an example of a functional test case.
XCTAssert(true, "Pass")
}
func testPerformanceExample() {
// This is an example of a performance test case.
self.measureBlock() {
// Put the code you want to measure the time of here.
}
}
}
| mit |
fxm90/GradientProgressBar | Example/Pods/SnapshotTesting/Sources/SnapshotTesting/Snapshotting/UIView.swift | 1 | 2380 | #if os(iOS) || os(tvOS)
import UIKit
extension Snapshotting where Value == UIView, Format == UIImage {
/// A snapshot strategy for comparing views based on pixel equality.
public static var image: Snapshotting {
return .image()
}
/// A snapshot strategy for comparing views based on pixel equality.
///
/// - Parameters:
/// - drawHierarchyInKeyWindow: Utilize the simulator's key window in order to render `UIAppearance` and `UIVisualEffect`s. This option requires a host application for your tests and will _not_ work for framework test targets.
/// - precision: The percentage of pixels that must match.
/// - size: A view size override.
/// - traits: A trait collection override.
public static func image(
drawHierarchyInKeyWindow: Bool = false,
precision: Float = 1,
size: CGSize? = nil,
traits: UITraitCollection = .init()
)
-> Snapshotting {
return SimplySnapshotting.image(precision: precision, scale: traits.displayScale).asyncPullback { view in
snapshotView(
config: .init(safeArea: .zero, size: size ?? view.frame.size, traits: .init()),
drawHierarchyInKeyWindow: drawHierarchyInKeyWindow,
traits: traits,
view: view,
viewController: .init()
)
}
}
}
extension Snapshotting where Value == UIView, Format == String {
/// A snapshot strategy for comparing views based on a recursive description of their properties and hierarchies.
public static var recursiveDescription: Snapshotting {
return Snapshotting.recursiveDescription()
}
/// A snapshot strategy for comparing views based on a recursive description of their properties and hierarchies.
public static func recursiveDescription(
size: CGSize? = nil,
traits: UITraitCollection = .init()
)
-> Snapshotting<UIView, String> {
return SimplySnapshotting.lines.pullback { view in
let dispose = prepareView(
config: .init(safeArea: .zero, size: size ?? view.frame.size, traits: traits),
drawHierarchyInKeyWindow: false,
traits: .init(),
view: view,
viewController: .init()
)
defer { dispose() }
return purgePointers(
view.perform(Selector(("recursiveDescription"))).retain().takeUnretainedValue()
as! String
)
}
}
}
#endif
| mit |
ello/ello-ios | Sources/Controllers/Join/JoinProtocols.swift | 1 | 1240 | ////
/// JoinProtocols.swift
//
protocol JoinScreenDelegate: class {
func backAction()
func validate(email: String, username: String, password: String)
func onePasswordAction(_ sender: UIView)
func submit(email: String, username: String, password: String)
func urlAction(title: String, url: URL)
}
protocol JoinScreenProtocol: class {
var prompt: String? { get set }
var email: String { get set }
var isEmailValid: Bool? { get set }
var username: String { get set }
var isUsernameValid: Bool? { get set }
var password: String { get set }
var isPasswordValid: Bool? { get set }
var isTermsChecked: Bool { get set }
var isOnePasswordAvailable: Bool { get set }
var isScreenReady: Bool { get set }
func loadingHUD(visible: Bool)
func showUsernameSuggestions(_ usernames: [String])
func hideUsernameSuggestions()
func showUsernameError(_ text: String)
func hideUsernameError()
func showEmailError(_ text: String)
func hideEmailError()
func showPasswordError(_ text: String)
func hidePasswordError()
func showTermsError(_ text: String)
func hideTermsError()
func showError(_ text: String)
func resignFirstResponder() -> Bool
}
| mit |
ello/ello-ios | Specs/Controllers/WebBrowser/ElloWebBrowserViewControllerSpec.swift | 1 | 1863 | ////
/// ElloWebBrowserViewControllerSpec.swift
//
@testable import Ello
import Quick
import Nimble
class ElloWebBrowserViewControllerSpec: QuickSpec {
override func spec() {
describe("ElloWebBrowserViewController") {
it("is easy to create a navigation controller w/ browser") {
let nav = ElloWebBrowserViewController.navigationControllerWithWebBrowser()
expect(nav.rootWebBrowser()).to(beAKindOf(ElloWebBrowserViewController.self))
}
it("is easy to create a navigation controller w/ custom browser") {
let browser = ElloWebBrowserViewController()
let nav = ElloWebBrowserViewController.navigationControllerWithBrowser(browser)
expect(nav.rootWebBrowser()).to(equal(browser))
}
it("has a fancy done button") {
let nav = ElloWebBrowserViewController.navigationControllerWithWebBrowser()
let browser: ElloWebBrowserViewController = nav.rootWebBrowser()
as! ElloWebBrowserViewController
let xButton = browser.navigationItem.leftBarButtonItem!
expect(xButton.action).to(
equal(#selector(ElloWebBrowserViewController.doneButtonPressed(_:)))
)
}
it("has a fancy share button") {
let nav = ElloWebBrowserViewController.navigationControllerWithWebBrowser()
let browser: ElloWebBrowserViewController = nav.rootWebBrowser()
as! ElloWebBrowserViewController
let shareButton = browser.navigationItem.rightBarButtonItem!
expect(shareButton.action).to(
equal(#selector(ElloWebBrowserViewController.shareButtonPressed(_:)))
)
}
}
}
}
| mit |
leo150/Pelican | Sources/Pelican/API/Types/Markup/InlineKey.swift | 1 | 4536 | //
// InlineKey.swift
// Pelican
//
// Created by Takanu Kyriako on 31/08/2017.
//
import Foundation
import Vapor
import FluentProvider
/**
Defines a single keyboard key on a `MarkupInline` keyboard. Each key supports one of 4 different modes:
_ _ _ _ _
**Callback Data**
This sends a small String back to the bot as a `CallbackQuery`, which is automatically filtered
back to the session and to a `callbackState` if one exists.
Alternatively if the keyboard the button belongs to is part of a `Prompt`, it will automatically
be received by it in the respective ChatSession, and the prompt will respond based on how you have set
it up.
**URL**
The button when pressed will re-direct users to a webpage.
**Inine Query Switch**
This can only be used when the bot supports Inline Queries. This prompts the user to select one of their chats
to open it, and when open the client will insert the bot‘s username and a specified query in the input field.
**Inline Query Current Chat**
This can only be used when the bot supports Inline Queries. Pressing the button will insert the bot‘s username
and an optional specific inline query in the current chat's input field.
*/
final public class MarkupInlineKey: Model, Equatable {
public var storage = Storage()
public var text: String // Label text
public var data: String
public var type: InlineKeyType
/**
Creates a `MarkupInlineKey` as a URL key.
This key type causes the specified URL to be opened by the client
when button is pressed. If it links to a public Telegram chat or bot, it will be immediately opened.
*/
public init(fromURL url: String, text: String) {
self.text = text
self.data = url
self.type = .url
}
/**
Creates a `MarkupInlineKey` as a Callback Data key.
This key sends the defined callback data back to the bot to be handled.
- parameter callback: The data to be sent back to the bot once pressed. Accepts 1-64 bytes of data.
- parameter text: The text label to be shown on the button. Set to nil if you wish it to be the same as the callback.
*/
public init?(fromCallbackData callback: String, text: String?) {
// Check to see if the callback meets the byte requirement.
if callback.lengthOfBytes(using: String.Encoding.utf8) > 64 {
PLog.error("The MarkupKey with the text label, \"\(String(describing:text))\" has a callback of \(callback) that exceeded 64 bytes.")
return nil
}
// Check to see if we have a label
if text != nil { self.text = text! }
else { self.text = callback }
self.data = callback
self.type = .callbackData
}
/**
Creates a `MarkupInlineKey` as a Current Chat Inline Query key.
This key prompts the user to select one of their chats, open it and insert the bot‘s username and the specified query in the input field.
*/
public init(fromInlineQueryCurrent data: String, text: String) {
self.text = text
self.data = data
self.type = .switchInlineQuery_currentChat
}
/**
Creates a `MarkupInlineKey` as a New Chat Inline Query key.
This key inserts the bot‘s username and the specified inline query in the current chat's input field. Can be empty.
*/
public init(fromInlineQueryNewChat data: String, text: String) {
self.text = text
self.data = data
self.type = .switchInlineQuery
}
static public func ==(lhs: MarkupInlineKey, rhs: MarkupInlineKey) -> Bool {
if lhs.text != rhs.text { return false }
if lhs.type != rhs.type { return false }
if lhs.data != rhs.data { return false }
return true
}
// Ignore context, just try and build an object from a node.
public required init(row: Row) throws {
text = try row.get("text")
if row["url"] != nil {
data = try row.get("url")
type = .url
}
else if row["callback_data"] != nil {
data = try row.get("callback_data")
type = .url
}
else if row["switch_inline_query"] != nil {
data = try row.get("switch_inline_query")
type = .url
}
else if row["switch_inline_query_current_chat"] != nil {
data = try row.get("switch_inline_query_current_chat")
type = .url
}
else {
data = ""
type = .url
}
}
public func makeRow() throws -> Row {
var row = Row()
try row.set("text", text)
switch type {
case .url:
try row.set("url", data)
case .callbackData:
try row.set("callback_data", data)
case .switchInlineQuery:
try row.set("switch_inline_query", data)
case .switchInlineQuery_currentChat:
try row.set("switch_inline_query_current_chat", data)
}
return row
}
}
| mit |
austinzheng/swift-compiler-crashes | crashes-duplicates/14648-swift-parser-skipsingle.swift | 11 | 269 | // Distributed under the terms of the MIT license
// Test case submitted to project by https://github.com/practicalswift (practicalswift)
// Test case found by fuzzing
if true {
for {
struct A {
class
case ,
let {
{
{
{
{
{
{
{
( {
( [ {
[ {
{
{
{
{
{
{
{
{
{
{
{
a {
| mit |
ello/ello-ios | Sources/Controllers/LoggedOut/LoggedOutViewController.swift | 1 | 2964 | ////
/// LoggedOutViewController.swift
//
import SnapKit
protocol BottomBarController: class {
var navigationBarsVisible: Bool? { get }
var bottomBarVisible: Bool { get }
var bottomBarHeight: CGFloat { get }
var bottomBarView: UIView { get }
func setNavigationBarsVisible(_ visible: Bool, animated: Bool)
}
class LoggedOutViewController: BaseElloViewController, BottomBarController {
private var _navigationBarsVisible: Bool = true
override var navigationBarsVisible: Bool? { return _navigationBarsVisible }
let bottomBarVisible: Bool = true
var bottomBarHeight: CGFloat { return screen.bottomBarHeight }
var bottomBarView: UIView { return screen.bottomBarView }
var childView: UIView?
private var _mockScreen: LoggedOutScreenProtocol?
var screen: LoggedOutScreenProtocol {
set(screen) { _mockScreen = screen }
get { return fetchScreen(_mockScreen) }
}
private var userActionAttemptedObserver: NotificationObserver?
func setNavigationBarsVisible(_ visible: Bool, animated: Bool) {
_navigationBarsVisible = visible
}
override func addChild(_ childController: UIViewController) {
super.addChild(childController)
childView = childController.view
if isViewLoaded {
screen.setControllerView(childController.view)
}
}
override func loadView() {
let screen = LoggedOutScreen()
screen.delegate = self
view = screen
}
override func viewDidLoad() {
super.viewDidLoad()
if let childView = childView {
screen.setControllerView(childView)
}
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
setupNotificationObservers()
}
override func viewDidDisappear(_ animated: Bool) {
super.viewDidDisappear(animated)
removeNotificationObservers()
}
}
extension LoggedOutViewController {
func setupNotificationObservers() {
userActionAttemptedObserver = NotificationObserver(
notification: LoggedOutNotifications.userActionAttempted
) { [weak self] action in
switch action {
case .relationshipChange:
Tracker.shared.loggedOutRelationshipAction()
case .postTool:
Tracker.shared.loggedOutPostTool()
case .artistInviteSubmit:
Tracker.shared.loggedOutArtistInviteSubmit()
}
self?.screen.showJoinText()
}
}
func removeNotificationObservers() {
userActionAttemptedObserver?.removeObserver()
}
}
extension LoggedOutViewController: LoggedOutProtocol {
func showLoginScreen() {
Tracker.shared.loginButtonTapped()
appViewController?.showLoginScreen()
}
func showJoinScreen() {
Tracker.shared.joinButtonTapped()
appViewController?.showJoinScreen()
}
}
| mit |
emilstahl/swift | test/BuildConfigurations/pound-if-top-level.swift | 12 | 215 | // RUN: %target-parse-verify-swift -D BLAH
// Check that if config statement has range properly nested in its parent
// EOF.
#if BLAH
// expected-error@+1{{expected #else or #endif at end of configuration block}}
| apache-2.0 |
ssathy2/SwiftCollectionViewTest | SwiftCollectionViewTestTests/SwiftCollectionViewTestTests.swift | 1 | 933 | //
// SwiftCollectionViewTestTests.swift
// SwiftCollectionViewTestTests
//
// Created by Sidd Sathyam on 6/3/14.
// Copyright (c) 2014 dotdotdot. All rights reserved.
//
import XCTest
class SwiftCollectionViewTestTests: XCTestCase {
override func setUp() {
super.setUp()
// Put setup code here. This method is called before the invocation of each test method in the class.
}
override func tearDown() {
// Put teardown code here. This method is called after the invocation of each test method in the class.
super.tearDown()
}
func testExample() {
// This is an example of a functional test case.
XCTAssert(true, "Pass")
}
func testPerformanceExample() {
// This is an example of a performance test case.
self.measureBlock() {
// Put the code you want to measure the time of here.
}
}
}
| mit |
mshafer/stock-portfolio-ios | Portfolio/HoldingTableViewCell.swift | 1 | 3162 | //
// HoldingTableViewCell.swift
// Portfolio
//
// Created by Michael Shafer on 22/09/15.
// Copyright © 2015 mshafer. All rights reserved.
//
import Foundation
import UIKit
class HoldingTableViewCell: UITableViewCell {
@IBOutlet var symbol: UILabel!
@IBOutlet var name: UILabel!
@IBOutlet var currentValue: UILabel!
@IBOutlet var quantityAndPrice: UILabel!
@IBOutlet var changeTodayInDollars: UILabel!
@IBOutlet var changeTodayAsPercentage: UILabel!
@IBOutlet var constraintNameAndQuantityPriceHorizontalSpace: NSLayoutConstraint!
@IBOutlet var constraintSymbolAndCurrentValueHorizontalSpace: NSLayoutConstraint!
override func setEditing(editing: Bool, animated: Bool) {
super.setEditing(editing, animated: animated)
self.setVisibilityOfValues(!editing)
}
func setVisibilityOfValues(isVisible: Bool) {
self.currentValue.hidden = !isVisible;
self.quantityAndPrice.hidden = !isVisible;
self.changeTodayInDollars.hidden = !isVisible;
self.changeTodayAsPercentage.hidden = !isVisible;
if isVisible {
self.addConstraint(self.constraintNameAndQuantityPriceHorizontalSpace)
self.addConstraint(self.constraintSymbolAndCurrentValueHorizontalSpace)
} else {
self.removeConstraint(self.constraintNameAndQuantityPriceHorizontalSpace)
self.removeConstraint(self.constraintSymbolAndCurrentValueHorizontalSpace)
}
}
func configureForHolding(holding: Holding) {
self.setHoldingValues(holding)
self.setColours(holding)
}
func setHoldingValues(holding: Holding) {
self.symbol.text = holding.symbol
self.name.text = holding.name
self.currentValue.text = holding.currentValue == nil ? "-" : Util.currencyToString(holding.currentValue!, currencyCode: holding.currencyCode)
self.quantityAndPrice.text = holdingQuantityAndPrice(holding)
self.quantityAndPrice.sizeToFit()
self.changeTodayInDollars.text = holding.changeTodayAsDollars == nil ? "-" : Util.currencyToString(holding.changeTodayAsDollars!, currencyCode: holding.currencyCode)
self.changeTodayAsPercentage.text = holding.changeTodayAsFraction == nil ? "-" : Util.fractionToPercentage(holding.changeTodayAsFraction!)
}
func setColours(holding: Holding) {
let colour: UIColor
if (holding.changeTodayAsDollars == nil || holding.changeTodayAsDollars >= 0) {
colour = UIColor(hex: "#45BF55")
} else {
colour = UIColor.dangerColor()
}
self.changeTodayInDollars.textColor = colour
self.changeTodayAsPercentage.textColor = colour
}
// MARK: - Computed strings for display in the UI
func holdingQuantityAndPrice(holding: Holding) -> String {
let price = holding.currentPrice == nil ? "-" : Util.currencyToString(holding.currentPrice!, currencyCode: holding.currencyCode)
return [
String(holding.numberOfShares),
"@",
price
].joinWithSeparator("")
}
}
| gpl-3.0 |
ayong6/iOSNote | swift语言/swift语言/2. 字符串.playground/Contents.swift | 1 | 1369 | //: Playground - noun: a place where people can play
import UIKit
// 字符串的介绍
// 字符串在任何的开发中使用都是非常频繁的
// OC和Swift中字符串的区别
// 在OC中字符串类型时NSString,在Swift中字符串类型是String
// OC中字符串@"",Swift中字符串""
// 使用 String 的原因
// String 是一个结构体,性能更高
// NSString 是一个 OC 对象,性能略差
// String 支持直接遍历
// Swift 提供了 String 和 NSString 之间的无缝转换
// 字符串遍历
var str = "Hello, Swift"
for c in str.characters {
print(c)
}
// 两个字符串的拼接
let str1 = "Hello"
let str2 = "World"
let str3 = str1 + str2
// 字符串和其他数据类型的拼接
let name = "why"
let age = 18
let info = "my name is \(name), age is \(age)"
// 字符串的格式化
// 比如时间:03:04
let min = 3
let second = 4
let time = String(format: "%02d:%02d", arguments: [min, second])
// 字符串的截取
// Swift中提供了特殊的截取方式
// 该方式非常麻烦
// Index非常难创建
// 简单的方式是将String转成NSString来使用
// 在标识符后加:as NSString即可
let myStr = "www.520it.com"
var subStr = (myStr as NSString).substringFromIndex(4)
subStr = (myStr as NSString).substringToIndex(3)
subStr = (myStr as NSString).substringWithRange(NSRange(location: 4, length: 5))
| apache-2.0 |
ayong6/iOSNote | swift语言/swift语言/3. 数组和字典.playground/Contents.swift | 1 | 3584 | //: Playground - noun: a place where people can play
import UIKit
/********************* 数组 ********************/
// 数组
// 数组使用有序列表存储同一个类型的多个值。
// 1. 数组中的元素可以相同
// 2. 数组中的元素类型必须一致
var array = [1, 2, 3, 1, 2, 3]
// 数组的定义
// swift数组应遵循 Array<Element>这样的形式,可以简写[Element]
// swift开发中,可以使用AnyObject代替NSObject
var array1: [Int]
var array2: Array<Int>
// 创建一个空数组
array1 = [Int]()
array2 = Array<Int>()
var array3: Array<Int> = []
// 数组的操作
// 1> 添加元素
array.append(4)
array1.append(123)
// 2> 删除元素
// 删除指定位置的元素
array.removeAtIndex(0)
//删除第一个位置的元素
array.removeFirst()
// 删除末尾的元素
array.removeLast()
// 删除全部元素
array.removeAll()
array = []
// 3> 修改元素
// 通过下标索引修改元素的值
array1[0] = 999
// 在指定位置插入元素
array1.insert(000, atIndex: 1)
// 通过区间索引赋值,区间不能超过数组的索引范围
array1[0...1] = [111, 999]
// 4> 访问元素
// 通过下标索引访问数组中的元素
array1[0]
// 判断数组是否为空
array.isEmpty
// 对数组的遍历
// 1> 通过下标值遍历
for i in 0..<array1.count {
print(i)
}
// 2> 通过for-in遍历
for i in array1 {
print(i)
}
// 数组的合并
// 1> 类型相同的数组的合并
var array4 = array1 + array2
// 2> 类型不同的数组的合并
let arr1 = [1, 2, 3]
let arr2 = ["one", "two", "three"]
var arr = [AnyObject]()
for item in arr1 {
arr.append(item)
}
for item in arr2 {
arr.append(item)
}
print(arr)
// 创建一个带有默认值的数组
let array5 = [Double](count: 3, repeatedValue: 0.0)
/********************* 字典 ********************/
// 字典
// 字典的定义
// Swift的字典使用Dictionary<Key, Value>定义,其中Key是字典中键的数据类型,Value是字典中对应于键所存储值的数据类型。我们也可以用[Key: Value]这样快捷的形式去创建一个字典类型。
var dic: [String: AnyObject]
var dic1: Dictionary<String, AnyObject>
// 字典初始化
/*
1. 通常字典中,key是字符串,value是任意的类型
2. AnyObject 类似 OC中的 id;但是在swift中真的是万物皆对象
*/
dic = [String: AnyObject]()
dic1 = Dictionary<String, AnyObject>()
var dic2: Dictionary<String, AnyObject> = [:]
// 字典的操作
// 1> 添加元素
dic["name"] = "zhangsan"
dic["age"] = 18
// 2> 删除元素
// 删除key对应的值
dic.removeValueForKey("id")
// 删除全部元素
dic.removeAll()
// 3> 修改元素 ,如果有对应的键值,则修改元素;如果没有对应的键值,则添加元素
dic["name"] = "xiaohei"
// 更新字典中的值,如果不存在,就新建
dic.updateValue(123, forKey: "id")
// 4> 访问元素
// 获取到的值因为是AnyObject对象,需要进行转换!
let name: String = dic["name"] as! String
// 判断字典是否为空
dic.isEmpty
// 对字典的比遍历
// 1> 遍历字典中所有的键
for key in dic.keys {
print(key)
}
// 2> 遍历字典中所有的值
for value in dic.values {
print(value)
}
// 3> 遍历字典中所以的键值对
for (key, value) in dic {
print("key:\(key), value:\(value)")
}
// 字典的合并
// 注意:字典的类型无论是否一致,都不可以通过相加+来合并
dic1["age"] = 22
for (key, value) in dic1 {
dic.updateValue(value, forKey: key)
}
print(dic)
| apache-2.0 |
kylef/RxHyperdrive | Pods/RxSwift/RxSwift/Observables/Implementations/Sink.swift | 1 | 599 | //
// Sink.swift
// Rx
//
// Created by Krunoslav Zaher on 2/19/15.
// Copyright (c) 2015 Krunoslav Zaher. All rights reserved.
//
import Foundation
class Sink<O : ObserverType> : SingleAssignmentDisposable {
private let _observer: O
final func forwardOn(event: Event<O.E>) {
if disposed {
return
}
_observer.on(event)
}
init(observer: O) {
#if TRACE_RESOURCES
OSAtomicIncrement32(&resourceCount)
#endif
_observer = observer
}
deinit {
#if TRACE_RESOURCES
OSAtomicDecrement32(&resourceCount)
#endif
}
} | mit |
jsslai/Action | Carthage/Checkouts/RxSwift/RxCocoa/OSX/NSImageView+Rx.swift | 3 | 2394 | //
// NSImageView+Rx.swift
// RxCocoa
//
// Created by Krunoslav Zaher on 5/17/15.
// Copyright © 2015 Krunoslav Zaher. All rights reserved.
//
import Foundation
#if !RX_NO_MODULE
import RxSwift
#endif
import Cocoa
extension Reactive where Base: NSImageView {
/**
Bindable sink for `image` property.
*/
public var image: AnyObserver<NSImage?> {
return image(transitionType: nil)
}
/**
Bindable sink for `image` property.
- parameter transitionType: Optional transition type while setting the image (kCATransitionFade, kCATransitionMoveIn, ...)
*/
@available(*, deprecated, renamed: "image(transitionType:)")
public func imageAnimated(_ transitionType: String?) -> AnyObserver<NSImage?> {
return UIBindingObserver(UIElement: self.base) { control, value in
if let transitionType = transitionType {
if value != nil {
let transition = CATransition()
transition.duration = 0.25
transition.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseInEaseOut)
transition.type = transitionType
control.layer?.add(transition, forKey: kCATransition)
}
}
else {
control.layer?.removeAllAnimations()
}
control.image = value
}.asObserver()
}
/**
Bindable sink for `image` property.
- parameter transitionType: Optional transition type while setting the image (kCATransitionFade, kCATransitionMoveIn, ...)
*/
public func image(transitionType: String? = nil) -> AnyObserver<NSImage?> {
return UIBindingObserver(UIElement: self.base) { control, value in
if let transitionType = transitionType {
if value != nil {
let transition = CATransition()
transition.duration = 0.25
transition.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseInEaseOut)
transition.type = transitionType
control.layer?.add(transition, forKey: kCATransition)
}
}
else {
control.layer?.removeAllAnimations()
}
control.image = value
}.asObserver()
}
}
| mit |
SwifterSwift/SwifterSwift | Tests/UIKitTests/UIScrollViewExtensionsTests.swift | 1 | 5705 | // UIScrollViewExtensionsTests.swift - Copyright 2020 SwifterSwift
@testable import SwifterSwift
import XCTest
#if canImport(UIKit) && !os(watchOS)
import UIKit
final class UIScrollViewExtensionsTest: XCTestCase {
let scroll = UIScrollView(frame: CGRect(origin: .zero, size: CGSize(width: 100, height: 100)))
override func setUp() {
super.setUp()
scroll.contentSize = CGSize(width: 500, height: 500)
scroll.contentInset = UIEdgeInsets(top: 10, left: 20, bottom: 30, right: 40)
}
func testSnapshot() {
let snapshot = scroll.snapshot
XCTAssertNotNil(snapshot)
let view = UIScrollView()
XCTAssertNil(view.snapshot)
}
func testVisibleRect() {
XCTAssertEqual(scroll.visibleRect, CGRect(origin: .zero, size: CGSize(width: 100, height: 100)))
scroll.contentOffset = CGPoint(x: 50, y: 50)
XCTAssertEqual(scroll.visibleRect, CGRect(origin: CGPoint(x: 50, y: 50), size: CGSize(width: 100, height: 100)))
let offset = CGPoint(x: 490, y: 480)
scroll.contentOffset = offset
XCTAssertEqual(scroll.visibleRect, CGRect(origin: offset, size: CGSize(width: 10, height: 20)))
}
func testScrollToTop() {
scroll.contentOffset = CGPoint(x: 50, y: 50)
scroll.scrollToTop(animated: false)
XCTAssertEqual(scroll.contentOffset, CGPoint(x: 50, y: -10))
}
func testScrollToLeft() {
scroll.contentOffset = CGPoint(x: 50, y: 50)
scroll.scrollToLeft(animated: false)
XCTAssertEqual(scroll.contentOffset, CGPoint(x: -20, y: 50))
}
func testScrollToBottom() {
scroll.contentOffset = CGPoint(x: 50, y: 50)
scroll.scrollToBottom(animated: false)
XCTAssertEqual(scroll.contentOffset, CGPoint(x: 50, y: scroll.contentSize.height - scroll.bounds.height + 30))
}
func testScrollToRight() {
scroll.contentOffset = CGPoint(x: 50, y: 50)
scroll.scrollToRight(animated: false)
XCTAssertEqual(scroll.contentOffset, CGPoint(x: scroll.contentSize.width - scroll.bounds.height + 40, y: 50))
}
func testScrollUp() {
let offset = CGPoint(x: 50, y: 250)
scroll.contentOffset = offset
scroll.scrollUp(animated: false)
XCTAssertEqual(scroll.contentOffset, CGPoint(x: offset.x, y: 150))
scroll.scrollUp(animated: false)
scroll.scrollUp(animated: false)
XCTAssertEqual(scroll.contentOffset, CGPoint(x: offset.x, y: -10))
let scrollView = UIScrollView()
scrollView.scrollUp(animated: false)
XCTAssertEqual(scrollView.contentOffset, .zero)
#if !os(tvOS)
scroll.isPagingEnabled = true
scroll.contentOffset = offset
scroll.scrollUp(animated: false)
XCTAssertEqual(scroll.contentOffset, CGPoint(x: offset.x, y: 90))
scrollView.isPagingEnabled = true
scrollView.scrollUp(animated: false)
XCTAssertEqual(scrollView.contentOffset, .zero)
#endif
}
func testScrollLeft() {
let offset = CGPoint(x: 250, y: 50)
scroll.contentOffset = offset
scroll.scrollLeft(animated: false)
XCTAssertEqual(scroll.contentOffset, CGPoint(x: 150, y: offset.y))
scroll.scrollLeft(animated: false)
scroll.scrollLeft(animated: false)
XCTAssertEqual(scroll.contentOffset, CGPoint(x: -20, y: offset.y))
let scrollView = UIScrollView()
scrollView.scrollLeft(animated: false)
XCTAssertEqual(scrollView.contentOffset, .zero)
#if !os(tvOS)
scroll.isPagingEnabled = true
scroll.contentOffset = offset
scroll.scrollLeft(animated: false)
XCTAssertEqual(scroll.contentOffset, CGPoint(x: 80, y: offset.y))
scrollView.isPagingEnabled = true
scrollView.scrollLeft(animated: false)
XCTAssertEqual(scrollView.contentOffset, .zero)
#endif
}
func testScrollDown() {
let offset = CGPoint(x: 50, y: 250)
scroll.contentOffset = offset
scroll.scrollDown(animated: false)
XCTAssertEqual(scroll.contentOffset, CGPoint(x: offset.x, y: 350))
scroll.scrollDown(animated: false)
XCTAssertEqual(scroll.contentOffset, CGPoint(x: offset.x, y: 430))
let scrollView = UIScrollView()
scrollView.scrollDown(animated: false)
XCTAssertEqual(scrollView.contentOffset, .zero)
#if !os(tvOS)
scroll.isPagingEnabled = true
scroll.contentOffset = offset
scroll.scrollDown(animated: false)
XCTAssertEqual(scroll.contentOffset, CGPoint(x: offset.x, y: 290))
scrollView.isPagingEnabled = true
scrollView.scrollDown(animated: false)
XCTAssertEqual(scrollView.contentOffset, .zero)
#endif
}
func testScrollRight() {
let offset = CGPoint(x: 250, y: 50)
scroll.contentOffset = offset
scroll.scrollRight(animated: false)
XCTAssertEqual(scroll.contentOffset, CGPoint(x: 350, y: offset.y))
scroll.scrollRight(animated: false)
XCTAssertEqual(scroll.contentOffset, CGPoint(x: 440, y: offset.y))
let scrollView = UIScrollView()
scrollView.scrollRight(animated: false)
XCTAssertEqual(scrollView.contentOffset, .zero)
#if !os(tvOS)
scroll.isPagingEnabled = true
scroll.contentOffset = offset
scroll.scrollRight(animated: false)
XCTAssertEqual(scroll.contentOffset, CGPoint(x: 280, y: offset.y))
scrollView.isPagingEnabled = true
scrollView.scrollRight(animated: false)
XCTAssertEqual(scrollView.contentOffset, .zero)
#endif
}
}
#endif
| mit |
material-components/material-components-ios | components/AppBar/examples/AppBarTypicalUseExample.swift | 2 | 4067 | // Copyright 2016-present the Material Components for iOS authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
import Foundation
import MaterialComponents.MaterialAppBar
import MaterialComponents.MaterialAppBar_Theming
import MaterialComponents.MaterialContainerScheme
class AppBarTypicalUseSwiftExample: UITableViewController {
// Step 1: Create and initialize an App Bar.
let appBarViewController = MDCAppBarViewController()
@objc var containerScheme: MDCContainerScheming = MDCContainerScheme()
deinit {
// Required for pre-iOS 11 devices because we've enabled observesTrackingScrollViewScrollEvents.
appBarViewController.headerView.trackingScrollView = nil
}
init() {
super.init(nibName: nil, bundle: nil)
self.title = "App Bar (Swift)"
// Behavioral flags.
appBarViewController.inferTopSafeAreaInsetFromViewController = true
appBarViewController.headerView.minMaxHeightIncludesSafeArea = false
// Step 2: Add the headerViewController as a child.
self.addChild(appBarViewController)
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
override func viewDidLoad() {
super.viewDidLoad()
appBarViewController.applyPrimaryTheme(withScheme: containerScheme)
// Allows us to avoid forwarding events, but means we can't enable shift behaviors.
appBarViewController.headerView.observesTrackingScrollViewScrollEvents = true
// Recommended step: Set the tracking scroll view.
appBarViewController.headerView.trackingScrollView = self.tableView
// Step 2: Register the App Bar views.
view.addSubview(appBarViewController.view)
appBarViewController.didMove(toParent: self)
self.navigationItem.rightBarButtonItem =
UIBarButtonItem(title: "Right", style: .done, target: nil, action: nil)
}
// Optional step: If you allow the header view to hide the status bar you must implement this
// method and return the headerViewController.
override var childForStatusBarHidden: UIViewController? {
return appBarViewController
}
// Optional step: The Header View Controller does basic inspection of the header view's background
// color to identify whether the status bar should be light or dark-themed.
override var childForStatusBarStyle: UIViewController? {
return appBarViewController
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
self.navigationController?.setNavigationBarHidden(true, animated: animated)
}
}
// MARK: Catalog by convention
extension AppBarTypicalUseSwiftExample {
@objc class func catalogMetadata() -> [String: Any] {
return [
"breadcrumbs": ["App Bar", "App Bar (Swift)"],
"primaryDemo": false,
"presentable": false,
]
}
@objc func catalogShouldHideNavigation() -> Bool {
return true
}
}
// MARK: - Typical application code (not Material-specific)
// MARK: UITableViewDataSource
extension AppBarTypicalUseSwiftExample {
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 50
}
override func tableView(
_ tableView: UITableView,
cellForRowAt indexPath: IndexPath
) -> UITableViewCell {
let cell =
self.tableView.dequeueReusableCell(withIdentifier: "cell")
?? UITableViewCell(style: .default, reuseIdentifier: "cell")
cell.layoutMargins = .zero
cell.textLabel?.text = "\(indexPath.row)"
cell.selectionStyle = .none
return cell
}
}
| apache-2.0 |
cdtschange/SwiftMKit | SwiftMKit/Extension/NSTimeInterval+Extension.swift | 1 | 562 | //
// NSTimeInterval+Extension.swift
// SwiftMKitDemo
//
// Created by Mao on 4/27/16.
// Copyright © 2016 cdts. All rights reserved.
//
import Foundation
public extension TimeInterval {
func secondsToHHmmss () -> (Int, Int, Int) {
let seconds : Int = Int(self)
return (seconds / 3600, (seconds % 3600) / 60, seconds % 60)
}
func secondsToHHmmssString () -> String {
let (h, m, s) = secondsToHHmmss ()
return "\(String(format: "%02d", h)):\(String(format: "%02d", m)):\(String(format: "%02d", s))"
}
}
| mit |
edekhayser/Kontact | Kontact/Kontact/KontactURLAddress.swift | 1 | 411 | //
// KontactURLAddress.swift
// Kontact
//
// Created by Evan Dekhayser on 8/26/15.
// Copyright © 2015 Xappox, LLC. All rights reserved.
//
import Contacts
import AddressBook
@objc public class KontactURLAddress: NSObject{
public let label: String
public let urlAddress: String
public init(label: String, urlAddress: String){
self.label = label
self.urlAddress = urlAddress
super.init()
}
} | mit |
cnoon/swift-compiler-crashes | crashes-duplicates/11681-swift-sourcemanager-getmessage.swift | 11 | 282 | // Distributed under the terms of the MIT license
// Test case submitted to project by https://github.com/practicalswift (practicalswift)
// Test case found by fuzzing
{
let a {
{
{
{
{
{
}
enum S
{
var b = {
class A {
protocol C {
struct S {
var d = a( {
}
let {
{
{
class
case ,
| mit |
codefellows/sea-b19-ios | Projects/Week5 Region Monitoring Demo/mapkitdemo/AppDelegate.swift | 1 | 2564 | //
// AppDelegate.swift
// mapkitdemo
//
// Created by Bradley Johnson on 8/18/14.
// Copyright (c) 2014 learnswift. All rights reserved.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(application: UIApplication!, didFinishLaunchingWithOptions launchOptions: NSDictionary!) -> Bool {
//requesting the ability to shedule local notifications
application.registerUserNotificationSettings(UIUserNotificationSettings(forTypes: UIUserNotificationType.Alert, categories: nil))
// Override point for customization after application launch.
return true
}
func application(application: UIApplication, didReceiveLocalNotification notification: UILocalNotification) {
println("local notification!")
}
func applicationWillResignActive(application: UIApplication!) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}
func applicationDidEnterBackground(application: UIApplication!) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(application: UIApplication!) {
// Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(application: UIApplication!) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(application: UIApplication!) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}
}
| gpl-2.0 |
cnoon/swift-compiler-crashes | crashes-fuzzing/26794-firsttarget.swift | 7 | 212 | // Distributed under the terms of the MIT license
// Test case submitted to project by https://github.com/practicalswift (practicalswift)
// Test case found by fuzzing
class C{init(){class A{let en=a:func a<h:A
| mit |
oisdk/SwiftDataStructures | SwiftDataStructuresTests/RangeReplaceableCollectionType.swift | 1 | 1531 | import XCTest
import Foundation
extension RangeReplaceableCollectionType where
Self : SameOrder,
Self : MutableCollectionType,
Generator.Element == Int,
SubSequence.Generator.Element == Int,
SubSequence : FlexibleInitable {
static func test() {
testMultiPass()
testCount()
testSeqInit()
testSameEls()
testIndexing()
testFirst()
testRangeIndexing()
testSplit()
testMutIndexing()
testMutIndexSlicing()
testEmptyInit()
testReplaceRange()
}
static internal func testEmptyInit() {
let empty = Self()
XCTAssert(empty.isEmpty, "Empty initializer did not yield empty self.\nReceived: \(Array(empty))")
}
static internal func testReplaceRange() {
for randAr in randArs() {
let seq = Self(randAr)
for (iA, iS) in zip(randAr.indices, seq.indices) {
for (jA, jS) in zip(iA..<randAr.endIndex, iS..<seq.endIndex) {
var mutAr = randAr
var mutSe = seq
let replacement = (0..<arc4random_uniform(10)).map { _ in Int(arc4random_uniform(10000)) }
mutAr.replaceRange(iA...jA, with: replacement)
mutSe.replaceRange(iS...jS, with: replacement)
XCTAssert(mutAr.elementsEqual(mutSe), "Range subscript replacement did not produce expected result.\nInitialized from array: \(randAr)\nTried to replace range: \(iA...jA) with \(replacement)\nExpected: \(mutAr)\nReceived: \(Array(mutSe))")
XCTAssert(mutSe.invariantPassed, "Invariant broken: \(Array(mutSe))")
}
}
}
}
} | mit |
brentdax/swift | test/IRGen/struct_resilience.swift | 2 | 13112 |
// RUN: %empty-directory(%t)
// RUN: %target-swift-frontend -emit-module -enable-resilience -emit-module-path=%t/resilient_struct.swiftmodule -module-name=resilient_struct %S/../Inputs/resilient_struct.swift
// RUN: %target-swift-frontend -emit-module -enable-resilience -emit-module-path=%t/resilient_enum.swiftmodule -module-name=resilient_enum -I %t %S/../Inputs/resilient_enum.swift
// RUN: %target-swift-frontend -module-name struct_resilience -I %t -emit-ir -enable-resilience %s | %FileCheck %s
// RUN: %target-swift-frontend -module-name struct_resilience -I %t -emit-ir -enable-resilience -O %s
import resilient_struct
import resilient_enum
// CHECK: %TSi = type <{ [[INT:i32|i64]] }>
// CHECK-LABEL: @"$s17struct_resilience26StructWithResilientStorageVMf" = internal global
// Resilient structs from outside our resilience domain are manipulated via
// value witnesses
// CHECK-LABEL: define{{( dllexport)?}}{{( protected)?}} swiftcc void @"$s17struct_resilience30functionWithResilientTypesSize_1f010resilient_A00G0VAFn_A2FnXEtF"(%swift.opaque* noalias nocapture sret, %swift.opaque* noalias nocapture, i8*, %swift.opaque*)
public func functionWithResilientTypesSize(_ s: __owned Size, f: (__owned Size) -> Size) -> Size {
// CHECK: entry:
// CHECK: [[TMP:%.*]] = call swiftcc %swift.metadata_response @"$s16resilient_struct4SizeVMa"([[INT]] 0)
// CHECK: [[METADATA:%.*]] = extractvalue %swift.metadata_response [[TMP]], 0
// CHECK: [[METADATA_ADDR:%.*]] = bitcast %swift.type* [[METADATA]] to i8***
// CHECK: [[VWT_ADDR:%.*]] = getelementptr inbounds i8**, i8*** [[METADATA_ADDR]], [[INT]] -1
// CHECK: [[VWT:%.*]] = load i8**, i8*** [[VWT_ADDR]]
// CHECK-NEXT: [[WITNESS_ADDR:%.*]] = getelementptr inbounds i8*, i8** [[VWT]], i32 8
// CHECK: [[WITNESS:%.*]] = load i8*, i8** [[WITNESS_ADDR]]
// CHECK: [[WITNESS_FOR_SIZE:%.*]] = ptrtoint i8* [[WITNESS]]
// CHECK: [[ALLOCA:%.*]] = alloca i8, {{.*}} [[WITNESS_FOR_SIZE]], align 16
// CHECK: [[STRUCT_ADDR:%.*]] = bitcast i8* [[ALLOCA]] to %swift.opaque*
// CHECK: [[WITNESS_PTR:%.*]] = getelementptr inbounds i8*, i8** [[VWT]], i32 2
// CHECK: [[WITNESS:%.*]] = load i8*, i8** [[WITNESS_PTR]]
// CHECK: [[initializeWithCopy:%.*]] = bitcast i8* [[WITNESS]]
// CHECK: [[STRUCT_LOC:%.*]] = call %swift.opaque* [[initializeWithCopy]](%swift.opaque* noalias [[STRUCT_ADDR]], %swift.opaque* noalias %1, %swift.type* [[METADATA]])
// CHECK: [[FN:%.*]] = bitcast i8* %2 to void (%swift.opaque*, %swift.opaque*, %swift.refcounted*)*
// CHECK: [[SELF:%.*]] = bitcast %swift.opaque* %3 to %swift.refcounted*
// CHECK: call swiftcc void [[FN]](%swift.opaque* noalias nocapture sret %0, %swift.opaque* noalias nocapture [[STRUCT_ADDR]], %swift.refcounted* swiftself [[SELF]])
// CHECK: [[WITNESS_PTR:%.*]] = getelementptr inbounds i8*, i8** [[VWT]], i32 1
// CHECK: [[WITNESS:%.*]] = load i8*, i8** [[WITNESS_PTR]]
// CHECK: [[destroy:%.*]] = bitcast i8* [[WITNESS]] to void (%swift.opaque*, %swift.type*)*
// CHECK: call void [[destroy]](%swift.opaque* noalias %1, %swift.type* [[METADATA]])
// CHECK-NEXT: bitcast
// CHECK-NEXT: call
// CHECK-NEXT: ret void
return f(s)
}
// CHECK-LABEL: declare{{( dllimport)?}} swiftcc %swift.metadata_response @"$s16resilient_struct4SizeVMa"
// CHECK-SAME: ([[INT]])
// Rectangle has fixed layout inside its resilience domain, and dynamic
// layout on the outside.
//
// Make sure we use a type metadata accessor function, and load indirect
// field offsets from it.
// CHECK-LABEL: define{{( dllexport)?}}{{( protected)?}} swiftcc void @"$s17struct_resilience35functionWithResilientTypesRectangleyy010resilient_A00G0VF"(%T16resilient_struct9RectangleV* noalias nocapture)
public func functionWithResilientTypesRectangle(_ r: Rectangle) {
// CHECK: entry:
// CHECK-NEXT: [[TMP:%.*]] = call swiftcc %swift.metadata_response @"$s16resilient_struct9RectangleVMa"([[INT]] 0)
// CHECK-NEXT: [[METADATA:%.*]] = extractvalue %swift.metadata_response [[TMP]], 0
// CHECK-NEXT: [[METADATA_ADDR:%.*]] = bitcast %swift.type* [[METADATA]] to i32*
// CHECK-NEXT: [[FIELD_OFFSET_VECTOR:%.*]] = getelementptr inbounds i32, i32* [[METADATA_ADDR]], [[INT]] [[IDX:2|4]]
// CHECK-NEXT: [[FIELD_OFFSET_PTR:%.*]] = getelementptr inbounds i32, i32* [[FIELD_OFFSET_VECTOR]], i32 2
// CHECK-NEXT: [[FIELD_OFFSET:%.*]] = load i32, i32* [[FIELD_OFFSET_PTR]]
// CHECK-NEXT: [[STRUCT_ADDR:%.*]] = bitcast %T16resilient_struct9RectangleV* %0 to i8*
// CHECK-NEXT: [[FIELD_ADDR:%.*]] = getelementptr inbounds i8, i8* [[STRUCT_ADDR]], i32 [[FIELD_OFFSET]]
// CHECK-NEXT: [[FIELD_PTR:%.*]] = bitcast i8* [[FIELD_ADDR]] to %TSi*
// CHECK-NEXT: [[FIELD_PAYLOAD_PTR:%.*]] = getelementptr inbounds %TSi, %TSi* [[FIELD_PTR]], i32 0, i32 0
// CHECK-NEXT: [[FIELD_PAYLOAD:%.*]] = load [[INT]], [[INT]]* [[FIELD_PAYLOAD_PTR]]
_ = r.color
// CHECK-NEXT: ret void
}
// Resilient structs from inside our resilience domain are manipulated
// directly.
public struct MySize {
public let w: Int
public let h: Int
}
// CHECK-LABEL: define{{( dllexport)?}}{{( protected)?}} swiftcc void @"$s17struct_resilience32functionWithMyResilientTypesSize_1fAA0eH0VAEn_A2EnXEtF"(%T17struct_resilience6MySizeV* noalias nocapture sret, %T17struct_resilience6MySizeV* noalias nocapture dereferenceable({{8|(16)}}), i8*, %swift.opaque*)
public func functionWithMyResilientTypesSize(_ s: __owned MySize, f: (__owned MySize) -> MySize) -> MySize {
// CHECK: alloca
// CHECK: [[TEMP:%.*]] = alloca %T17struct_resilience6MySizeV
// CHECK: bitcast
// CHECK: llvm.lifetime.start
// CHECK: bitcast
// CHECK: [[COPY:%.*]] = bitcast %T17struct_resilience6MySizeV* %5 to i8*
// CHECK: [[ARG:%.*]] = bitcast %T17struct_resilience6MySizeV* %1 to i8*
// CHECK: call void @llvm.memcpy{{.*}}(i8* align {{4|8}} [[COPY]], i8* align {{4|8}} [[ARG]], {{i32 8|i64 16}}, i1 false)
// CHECK: [[FN:%.*]] = bitcast i8* %2
// CHECK: call swiftcc void [[FN]](%T17struct_resilience6MySizeV* {{.*}} %0, {{.*}} [[TEMP]], %swift.refcounted* swiftself %{{.*}})
// CHECK: ret void
return f(s)
}
// Structs with resilient storage from a different resilience domain require
// runtime metadata instantiation, just like generics.
public struct StructWithResilientStorage {
public let s: Size
public let ss: (Size, Size)
public let n: Int
public let i: ResilientInt
}
// Make sure we call a function to access metadata of structs with
// resilient layout, and go through the field offset vector in the
// metadata when accessing stored properties.
// CHECK-LABEL: define{{( dllexport)?}}{{( protected)?}} swiftcc {{i32|i64}} @"$s17struct_resilience26StructWithResilientStorageV1nSivg"(%T17struct_resilience26StructWithResilientStorageV* {{.*}})
// CHECK: [[TMP:%.*]] = call swiftcc %swift.metadata_response @"$s17struct_resilience26StructWithResilientStorageVMa"([[INT]] 0)
// CHECK: [[METADATA:%.*]] = extractvalue %swift.metadata_response [[TMP]], 0
// CHECK-NEXT: [[METADATA_ADDR:%.*]] = bitcast %swift.type* [[METADATA]] to i32*
// CHECK-NEXT: [[FIELD_OFFSET_VECTOR:%.*]] = getelementptr inbounds i32, i32* [[METADATA_ADDR]], [[INT]] [[IDX:2|4]]
// CHECK-NEXT: [[FIELD_OFFSET_PTR:%.*]] = getelementptr inbounds i32, i32* [[FIELD_OFFSET_VECTOR]], i32 2
// CHECK-NEXT: [[FIELD_OFFSET:%.*]] = load i32, i32* [[FIELD_OFFSET_PTR]]
// CHECK-NEXT: [[STRUCT_ADDR:%.*]] = bitcast %T17struct_resilience26StructWithResilientStorageV* %0 to i8*
// CHECK-NEXT: [[FIELD_ADDR:%.*]] = getelementptr inbounds i8, i8* [[STRUCT_ADDR]], i32 [[FIELD_OFFSET]]
// CHECK-NEXT: [[FIELD_PTR:%.*]] = bitcast i8* [[FIELD_ADDR]] to %TSi*
// CHECK-NEXT: [[FIELD_PAYLOAD_PTR:%.*]] = getelementptr inbounds %TSi, %TSi* [[FIELD_PTR]], i32 0, i32 0
// CHECK-NEXT: [[FIELD_PAYLOAD:%.*]] = load [[INT]], [[INT]]* [[FIELD_PAYLOAD_PTR]]
// CHECK-NEXT: ret [[INT]] [[FIELD_PAYLOAD]]
// Indirect enums with resilient payloads are still fixed-size.
public struct StructWithIndirectResilientEnum {
public let s: FunnyShape
public let n: Int
}
// CHECK-LABEL: define{{( dllexport)?}}{{( protected)?}} swiftcc {{i32|i64}} @"$s17struct_resilience31StructWithIndirectResilientEnumV1nSivg"(%T17struct_resilience31StructWithIndirectResilientEnumV* {{.*}})
// CHECK: [[FIELD_PTR:%.*]] = getelementptr inbounds %T17struct_resilience31StructWithIndirectResilientEnumV, %T17struct_resilience31StructWithIndirectResilientEnumV* %0, i32 0, i32 1
// CHECK-NEXT: [[FIELD_PAYLOAD_PTR:%.*]] = getelementptr inbounds %TSi, %TSi* [[FIELD_PTR]], i32 0, i32 0
// CHECK-NEXT: [[FIELD_PAYLOAD:%.*]] = load [[INT]], [[INT]]* [[FIELD_PAYLOAD_PTR]]
// CHECK-NEXT: ret [[INT]] [[FIELD_PAYLOAD]]
// Partial application of methods on resilient value types
public struct ResilientStructWithMethod {
public func method() {}
}
// Corner case -- type is address-only in SIL, but empty in IRGen
// CHECK-LABEL: define{{( dllexport)?}}{{( protected)?}} swiftcc void @"$s17struct_resilience29partialApplyOfResilientMethod1ryAA0f10StructWithG0V_tF"(%T17struct_resilience25ResilientStructWithMethodV* noalias nocapture)
public func partialApplyOfResilientMethod(r: ResilientStructWithMethod) {
_ = r.method
}
// Type is address-only in SIL, and resilient in IRGen
// CHECK-LABEL: define{{( dllexport)?}}{{( protected)?}} swiftcc void @"$s17struct_resilience29partialApplyOfResilientMethod1sy010resilient_A04SizeV_tF"(%swift.opaque* noalias nocapture)
public func partialApplyOfResilientMethod(s: Size) {
_ = s.method
}
public func wantsAny(_ any: Any) {}
public func resilientAny(s : ResilientWeakRef) {
wantsAny(s)
}
// CHECK-LABEL: define{{.*}} swiftcc void @"$s17struct_resilience12resilientAny1sy0c1_A016ResilientWeakRefV_tF"(%swift.opaque* noalias nocapture)
// CHECK: entry:
// CHECK: [[ANY:%.*]] = alloca %Any
// CHECK: [[META:%.*]] = call swiftcc %swift.metadata_response @"$s16resilient_struct16ResilientWeakRefVMa"([[INT]] 0)
// CHECK: [[META2:%.*]] = extractvalue %swift.metadata_response %3, 0
// CHECK: [[TYADDR:%.*]] = getelementptr inbounds %Any, %Any* %1, i32 0, i32 1
// CHECK: store %swift.type* [[META2]], %swift.type** [[TYADDR]]
// CHECK: call %swift.opaque* @__swift_allocate_boxed_opaque_existential_0(%Any* [[ANY]])
// CHECK: call swiftcc void @"$s17struct_resilience8wantsAnyyyypF"(%Any* noalias nocapture dereferenceable({{(32|16)}}) [[ANY]])
// CHECK: call void @__swift_destroy_boxed_opaque_existential_0(%Any* [[ANY]])
// CHECK: ret void
// Public metadata accessor for our resilient struct
// CHECK-LABEL: define{{( dllexport)?}}{{( protected)?}} swiftcc %swift.metadata_response @"$s17struct_resilience6MySizeVMa"
// CHECK-SAME: ([[INT]])
// CHECK: ret %swift.metadata_response { %swift.type* bitcast ([[INT]]* getelementptr inbounds {{.*}} @"$s17struct_resilience6MySizeVMf", i32 0, i32 1) to %swift.type*), [[INT]] 0 }
// CHECK-LABEL: define internal swiftcc %swift.metadata_response @"$s17struct_resilience26StructWithResilientStorageVMr"(%swift.type*, i8*, i8**)
// CHECK: [[FIELDS:%.*]] = alloca [4 x i8**]
// CHECK: [[TUPLE_LAYOUT:%.*]] = alloca %swift.full_type_layout,
// CHECK: [[FIELDS_ADDR:%.*]] = getelementptr inbounds [4 x i8**], [4 x i8**]* [[FIELDS]], i32 0, i32 0
// public let s: Size
// CHECK: [[T0:%.*]] = call swiftcc %swift.metadata_response @"$s16resilient_struct4SizeVMa"([[INT]] 319)
// CHECK: [[SIZE_METADATA:%.*]] = extractvalue %swift.metadata_response [[T0]], 0
// CHECK: [[T0:%.*]] = bitcast %swift.type* [[SIZE_METADATA]] to i8***
// CHECK: [[T1:%.*]] = getelementptr inbounds i8**, i8*** [[T0]], [[INT]] -1
// CHECK: [[SIZE_VWT:%.*]] = load i8**, i8*** [[T1]],
// CHECK: [[SIZE_LAYOUT_1:%.*]] = getelementptr inbounds i8*, i8** [[SIZE_VWT]], i32 8
// CHECK: [[FIELD_1:%.*]] = getelementptr inbounds i8**, i8*** [[FIELDS_ADDR]], i32 0
// CHECK: store i8** [[SIZE_LAYOUT_1:%.*]], i8*** [[FIELD_1]]
// public let ss: (Size, Size)
// CHECK: [[SIZE_LAYOUT_2:%.*]] = getelementptr inbounds i8*, i8** [[SIZE_VWT]], i32 8
// CHECK: [[SIZE_LAYOUT_3:%.*]] = getelementptr inbounds i8*, i8** [[SIZE_VWT]], i32 8
// CHECK: call swiftcc [[INT]] @swift_getTupleTypeLayout2(%swift.full_type_layout* [[TUPLE_LAYOUT]], i8** [[SIZE_LAYOUT_2]], i8** [[SIZE_LAYOUT_3]])
// CHECK: [[T0:%.*]] = bitcast %swift.full_type_layout* [[TUPLE_LAYOUT]] to i8**
// CHECK: [[FIELD_2:%.*]] = getelementptr inbounds i8**, i8*** [[FIELDS_ADDR]], i32 1
// CHECK: store i8** [[T0]], i8*** [[FIELD_2]]
// Fixed-layout aggregate -- we can reference a static value witness table
// public let n: Int
// CHECK: [[FIELD_3:%.*]] = getelementptr inbounds i8**, i8*** [[FIELDS_ADDR]], i32 2
// CHECK: store i8** getelementptr inbounds (i8*, i8** @"$sBi{{32|64}}_WV", i32 {{.*}}), i8*** [[FIELD_3]]
// Resilient aggregate with one field -- make sure we don't look inside it
// public let i: ResilientInt
// CHECK: call swiftcc %swift.metadata_response @"$s16resilient_struct12ResilientIntVMa"([[INT]] 319)
// CHECK: [[FIELD_4:%.*]] = getelementptr inbounds i8**, i8*** [[FIELDS_ADDR]], i32 3
// CHECK: store i8** [[SIZE_AND_ALIGNMENT:%.*]], i8*** [[FIELD_4]]
// CHECK: call void @swift_initStructMetadata(%swift.type* {{.*}}, [[INT]] 256, [[INT]] 4, i8*** [[FIELDS_ADDR]], i32* {{.*}})
| apache-2.0 |
kousun12/RxSwift | RxCocoa/iOS/UIGestureRecognizer+Rx.swift | 4 | 2054 | //
// UIGestureRecognizer+Rx.swift
// Touches
//
// Created by Carlos García on 10/6/15.
// Copyright (c) 2015 Krunoslav Zaher. All rights reserved.
//
#if os(iOS) || os(tvOS)
import UIKit
#if !RX_NO_MODULE
import RxSwift
#endif
// This should be only used from `MainScheduler`
class GestureTarget: RxTarget {
typealias Callback = (UIGestureRecognizer) -> Void
let selector = Selector("eventHandler:")
weak var gestureRecognizer: UIGestureRecognizer?
var callback: Callback?
init(_ gestureRecognizer: UIGestureRecognizer, callback: Callback) {
self.gestureRecognizer = gestureRecognizer
self.callback = callback
super.init()
gestureRecognizer.addTarget(self, action: selector)
let method = self.methodForSelector(selector)
if method == nil {
fatalError("Can't find method")
}
}
func eventHandler(sender: UIGestureRecognizer!) {
if let callback = self.callback, gestureRecognizer = self.gestureRecognizer {
callback(gestureRecognizer)
}
}
override func dispose() {
super.dispose()
self.gestureRecognizer?.removeTarget(self, action: self.selector)
self.callback = nil
}
}
extension UIGestureRecognizer {
/**
Reactive wrapper for gesture recognizer events.
*/
public var rx_event: ControlEvent<UIGestureRecognizer> {
let source: Observable<UIGestureRecognizer> = create { [weak self] observer in
MainScheduler.ensureExecutingOnScheduler()
guard let control = self else {
observer.on(.Completed)
return NopDisposable.instance
}
let observer = GestureTarget(control) {
control in
observer.on(.Next(control))
}
return observer
}.takeUntil(rx_deallocated)
return ControlEvent(source: source)
}
}
#endif
| mit |
tkremenek/swift | test/stdlib/StringTraps.swift | 22 | 4640 | // RUN: %empty-directory(%t)
// RUN: %target-build-swift %s -o %t/a.out_Debug -Onone
// RUN: %target-build-swift %s -o %t/a.out_Release -O
//
// RUN: %target-codesign %t/a.out_Debug
// RUN: %target-codesign %t/a.out_Release
// RUN: %target-run %t/a.out_Debug
// RUN: %target-run %t/a.out_Release
// REQUIRES: executable_test
import StdlibUnittest
let testSuiteSuffix = _isDebugAssertConfiguration() ? "_debug" : "_release"
var StringTraps = TestSuite("StringTraps" + testSuiteSuffix)
StringTraps.test("startIndex/predecessor")
.skip(.custom(
{ _isFastAssertConfiguration() },
reason: "this trap is not guaranteed to happen in -Ounchecked"))
.code {
let s = "abc"
var i = s.startIndex
i = s.index(after: i)
i = s.index(before: i)
expectCrashLater()
i = s.index(before: i)
}
StringTraps.test("endIndex/successor")
.skip(.custom(
{ _isFastAssertConfiguration() },
reason: "this trap is not guaranteed to happen in -Ounchecked"))
.code {
let s = "abc"
var i = s.startIndex
i = s.index(after: i)
i = s.index(after: i)
i = s.index(after: i)
expectCrashLater()
i = s.index(after: i)
}
StringTraps.test("subscript(_:)/endIndex")
.skip(.custom(
{ _isFastAssertConfiguration() },
reason: "this trap is not guaranteed to happen in -Ounchecked"))
.code {
let s = "abc"
var i = s.startIndex
i = s.index(after: i)
i = s.index(after: i)
i = s.index(after: i)
expectCrashLater()
_ = s[i]
}
StringTraps.test("UTF8ViewSubscript/endIndexSuccessor")
.skip(.custom(
{ _isFastAssertConfiguration() },
reason: "this trap is not guaranteed to happen in -Ounchecked"))
.code {
let s = "abc"
var i = s.utf8.startIndex
i = s.utf8.index(after: i)
i = s.utf8.index(after: i)
i = s.utf8.index(after: i)
expectCrashLater()
i = s.utf8.index(after: i)
_ = s.utf8[i]
}
StringTraps.test("UTF8ViewSubscript/endIndex")
.skip(.custom(
{ _isFastAssertConfiguration() },
reason: "this trap is not guaranteed to happen in -Ounchecked"))
.code {
let s = "abc"
var i = s.utf8.startIndex
i = s.utf8.index(after: i)
i = s.utf8.index(after: i)
i = s.utf8.index(after: i)
expectCrashLater()
_ = s.utf8[i]
}
StringTraps.test("UTF16ViewSubscript/DecrementedStartIndex")
.skip(.custom(
{ _isFastAssertConfiguration() },
reason: "this trap is not guaranteed to happen in -Ounchecked"))
.code {
let s = "abc"
var i = s.utf16.startIndex
expectCrashLater()
i = s.utf16.index(before: i)
_ = s.utf16[i]
}
StringTraps.test("UTF16ViewSubscript/endIndex")
.skip(.custom(
{ _isFastAssertConfiguration() },
reason: "this trap is not guaranteed to happen in -Ounchecked"))
.code {
var s = "abc"
var i = s.utf16.startIndex
i = s.utf16.index(after: i)
i = s.utf16.index(after: i)
i = s.utf16.index(after: i)
expectCrashLater()
_ = s.utf16[i]
}
StringTraps.test("UTF16ViewIndex/offsetLimited")
.code {
let sa = "foo"
let u16a = sa.utf16
let s16 = sa + "🤦🏻♀️"
let u16 = s16.utf16
let iaBegin = u16a.index(sa.startIndex, offsetBy: 99, limitedBy: sa.endIndex)
expectNil(iaBegin)
let iaEnd = u16a.index(sa.endIndex, offsetBy: 99, limitedBy: sa.endIndex)
expectNil(iaEnd)
let i16Begin = u16.index(u16.startIndex, offsetBy: 99, limitedBy: u16.endIndex)
expectNil(i16Begin)
let i16End = u16.index(u16.startIndex, offsetBy: 99, limitedBy: u16.endIndex)
expectNil(i16End)
}
StringTraps.test("UTF16ViewIndex/offsetCrash")
.skip(.custom(
{ _isFastAssertConfiguration() },
reason: "this trap is not guaranteed to happen in -Ounchecked"))
.code {
let s16 = "foo🤦🏻♀️"
let u16 = s16.utf16
expectCrashLater()
let i = u16.index(u16.startIndex, offsetBy: 99)
_ = s16.utf16[i]
}
StringTraps.test("UTF8ViewIndex/offsetLimited")
.code {
let sa = "foo"
let u8a = sa.utf8
let s8 = sa + "🤦🏻♀️"
let u8 = s8.utf8
let iaBegin = u8a.index(sa.startIndex, offsetBy: 99, limitedBy: sa.endIndex)
expectNil(iaBegin)
let iaEnd = u8a.index(sa.endIndex, offsetBy: 99, limitedBy: sa.endIndex)
expectNil(iaEnd)
let i8Begin = u8.index(u8.startIndex, offsetBy: 99, limitedBy: u8.endIndex)
expectNil(i8Begin)
let i8End = u8.index(u8.startIndex, offsetBy: 99, limitedBy: u8.endIndex)
expectNil(i8End)
}
StringTraps.test("UTF8ViewIndex/offsetCrash")
.skip(.custom(
{ _isFastAssertConfiguration() },
reason: "this trap is not guaranteed to happen in -Ounchecked"))
.code {
let s8 = "foo🤦🏻♀️"
let u8 = s8.utf8
expectCrashLater()
let i = u8.index(u8.startIndex, offsetBy: 99)
_ = s8.utf8[i]
}
runAllTests()
| apache-2.0 |
Mazy-ma/DemoBySwift | LoopProgressDemo/LoopProgressDemo/ViewController.swift | 1 | 1132 | //
// ViewController.swift
// LoopProgressDemo
//
// Created by Mazy on 2017/5/22.
// Copyright © 2017年 Mazy. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
var loopView: LoopView?
override func viewDidLoad() {
super.viewDidLoad()
// 设置环形视图并添加到主视图
let loopView = LoopView(frame: CGRect(x: 0, y: 0, width: 300, height: 300))
loopView.center = view.center
loopView.backgroundColor = UIColor.blue.withAlphaComponent(0.5)
view.addSubview(loopView)
self.loopView = loopView
// 设置滑块
let slider = UISlider(frame: CGRect(x: 20, y: loopView.frame.origin.y + 300 + 50, width: view.bounds.width-40, height: 30))
slider.addTarget(self, action: #selector(changeMaskValue), for: .valueChanged)
slider.value = 0.5
view.addSubview(slider)
}
/// 通过滑块控制环形视图的角度
func changeMaskValue(slider: UISlider) {
self.loopView?.animationWithStrokeEnd(strokeEnd: CGFloat(slider.value))
}
}
| apache-2.0 |
antonio081014/LeetCode-CodeBase | Swift/find-k-th-smallest-pair-distance.swift | 2 | 2660 | /**
* https://leetcode.com/problems/find-k-th-smallest-pair-distance/
*
*
*/
// Date: Fri May 1 10:21:02 PDT 2020
class Solution {
/// - Complexity:
/// - Time: O(nlogn + n + w + nlogw)
func smallestDistancePair(_ nums: [Int], _ k: Int) -> Int {
// O(nlogn)
let nums = nums.sorted()
let n = nums.count
var occurrence = Array(repeating: 0, count: n)
// O(n)
for index in 1 ..< n {
if nums[index] == nums[index - 1] {
occurrence[index] = 1 + occurrence[index - 1]
}
}
var numberOfPointsBeforeX: [Int] = Array(repeating: 0, count: nums.last! * 2)
var countIndex = 0
// O(w)
for point in 0 ..< numberOfPointsBeforeX.count {
while countIndex < nums.count, point == nums[countIndex] { countIndex += 1 }
numberOfPointsBeforeX[point] = countIndex
}
var left = 0
var right = nums.last! - nums.first! + 1
// O(nlogw)
while left < right {
// Here mid is the distance.
let mid = left + (right - left) / 2
// Calculate the number of pairs starting from each nums[index], end with nums[index] + mid
var count = 0
for index in 0 ..< n {
// Here is why we need an array with size nums.last! * 2.
count += numberOfPointsBeforeX[nums[index] + mid] - numberOfPointsBeforeX[nums[index]] + occurrence[index]
}
if count >= k {
right = mid
} else {
left = mid + 1
}
}
return left == (nums.last! - nums.first! + 1) ? -1 : left
}
}
/**
* https://leetcode.com/problems/find-k-th-smallest-pair-distance/
*
*
*/
// Date: Fri May 1 11:05:06 PDT 2020
class Solution {
func smallestDistancePair(_ nums: [Int], _ k: Int) -> Int {
// O(nlogn)
let nums = nums.sorted()
var left = 0
var right = nums.last! - nums.first! + 1
// O(nlogw)
while left < right {
let mid = left + (right - left) / 2
var count = 0
var start = 0
for end in 0 ..< nums.count {
while nums[end] - nums[start] > mid { start += 1 }
count += end - start
}
if count >= k {
right = mid
} else {
left = mid + 1
}
}
return left == (nums.last! - nums.first! + 1) ? -1 : left
}
}
| mit |
boluomeng/Charts | ChartsRealm/Classes/Data/RealmBubbleData.swift | 1 | 759 | //
// RealmBubbleData.swift
// Charts
//
// Created by Daniel Cohen Gindi on 23/2/15.
//
// 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
import Charts
import Realm
import Realm.Dynamic
open class RealmBubbleData: BubbleChartData
{
public init(results: RLMResults<RLMObject>?, xValueField: String, dataSets: [IChartDataSet]?)
{
if results == nil
{
super.init(xVals: [String](), dataSets: dataSets)
}
else
{
super.init(xVals: RealmChartUtils.toXVals(results: results!, xValueField: xValueField), dataSets: dataSets)
}
}
}
| apache-2.0 |
twtstudio/WePeiYang-iOS | WePeiYang/YellowPage/SearchView.swift | 1 | 2706 |
//
// SearchView.swift
// YellowPage
//
// Created by Halcao on 2017/2/23.
// Copyright © 2017年 Halcao. All rights reserved.
//
import UIKit
import SnapKit
class SearchView: UIView {
let backBtn = UIButton(type: .custom)
let textField = UITextField()
/*
// Only override draw() if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
override func draw(_ rect: CGRect) {
// Drawing code
}
*/
let bgdView = UIView()
override func draw(_ rect: CGRect) {
super.draw(rect)
bgdView.frame = rect
self.addSubview(bgdView)
self.backgroundColor = UIColor(red: 0.1059, green: 0.6352, blue: 0.9019, alpha: 0.5)
bgdView.backgroundColor = UIColor(red: 0.1059, green: 0.6352, blue: 0.9019, alpha: 1)
backBtn.setImage(UIImage(named: "back"), for: .normal)
backBtn.adjustsImageWhenHighlighted = false
bgdView.addSubview(backBtn)
backBtn.snp.makeConstraints { make in
make.width.equalTo(20)
make.height.equalTo(20)
make.centerY.equalTo(self).offset(7)
make.left.equalTo(self).offset(20)
}
let separator = UIView()
separator.backgroundColor = UIColor(red: 0.074, green: 0.466, blue: 0.662, alpha: 1)
bgdView.addSubview(separator)
separator.snp.makeConstraints { make in
make.width.equalTo(1)
make.height.equalTo(20)
make.centerY.equalTo(self).offset(7)
make.left.equalTo(backBtn.snp.right).offset(10)
}
let iconView = UIImageView()
iconView.image = UIImage(named: "search")
bgdView.addSubview(iconView)
iconView.snp.makeConstraints { make in
make.width.equalTo(20)
make.height.equalTo(20)
make.centerY.equalTo(self).offset(7)
make.left.equalTo(separator.snp.right).offset(10)
}
let baseLine = UIView()
baseLine.backgroundColor = UIColor.white
bgdView.addSubview(baseLine)
baseLine.snp.makeConstraints { make in
make.height.equalTo(1)
make.top.equalTo(iconView.snp.bottom).offset(4)
make.left.equalTo(iconView.snp.left)
make.right.equalTo(bgdView).offset(-15)
}
self.addSubview(textField)
textField.snp.makeConstraints { make in
make.left.equalTo(iconView.snp.right).offset(2)
make.right.equalTo(baseLine.snp.right)
make.bottom.equalTo(baseLine.snp.top).offset(-3)
make.height.equalTo(20)
}
}
}
| mit |
mateuszmackowiak/MMLogger | MMLogger/Classes/Logstash/MMAsyncSocketManager.swift | 1 | 3372 | //
// Created by Mateusz Mackowiak on 04/03/2017.
// Copyright (c) 2016 Mateusz Mackowiak. All rights reserved.
//
import Foundation
import CocoaAsyncSocket
protocol MMAsyncSocketManagerDelegate: class {
func socketDidConnect(_ socket: MMAsyncSocketManager)
func socket(_ socket: MMAsyncSocketManager, didWriteDataWithTag tag: Int)
}
class MMAsyncSocketManager: NSObject {
enum AsyncSocketError: Error {
case failedConnection(Error)
}
weak var delegate: MMAsyncSocketManagerDelegate?
private(set) var socket: GCDAsyncSocket!
var debug: Bool = false
let host: String
let port: UInt16
let timeout: TimeInterval
open var useTLS: Bool = false
let localSocketQueue = DispatchQueue(label: "\(NSUUID().uuidString).com.GCDAsyncSocketDelegateQueue")
init(host: String, port: UInt16, timeout: TimeInterval) {
self.host = host
self.port = port
self.timeout = timeout
super.init()
self.socket = GCDAsyncSocket(delegate: self, delegateQueue: localSocketQueue)
}
func send() {
if !self.socket.isConnected {
do {
_ = try self.connect()
} catch {
print("Failed to start socket: \(error)")
return
}
}
if (self.useTLS) {
self.socket.startTLS([String(kCFStreamSSLPeerName): NSString(string: host)])
} else {
self.socketDidSecure(self.socket)
}
}
func write(_ data: Data, withTimeout timeout: TimeInterval, tag: Int) {
self.socket.write(data, withTimeout: timeout, tag: tag)
}
}
extension MMAsyncSocketManager {
func connect() throws -> Bool {
guard !self.socket.isConnected else { return true }
do {
try self.socket.connect(toHost: host, onPort: port, withTimeout: timeout)
} catch {
print("Failed to connect socket: \(error)")
throw AsyncSocketError.failedConnection(error)
}
return true
}
func disconnect() {
self.socket.disconnect()
}
func disconnectSafely() {
self.socket.disconnectAfterWriting()
}
}
extension MMAsyncSocketManager {
func isSecure() -> Bool {
return self.socket.isSecure
}
func isConnected() -> Bool {
return self.socket.isConnected
}
}
extension MMAsyncSocketManager: GCDAsyncSocketDelegate {
func socket(_ sock: GCDAsyncSocket, didConnectToHost host: String, port: UInt16) {
if debug {
print("Socket connected!")
}
}
func socketDidSecure(_ sock: GCDAsyncSocket) {
self.delegate?.socketDidConnect(self)
}
func socket(_ sock: GCDAsyncSocket, didWriteDataWithTag tag: Int) {
if debug {
print("Socket did write")
}
self.delegate?.socket(self, didWriteDataWithTag: tag)
}
func socketDidCloseReadStream(_ sock: GCDAsyncSocket) {
if !debug {
return
}
print("Socket did close read stream")
}
func socketDidDisconnect(_ sock: GCDAsyncSocket, withError err: Error?) {
if !debug {
return
}
if let err = err {
print("Socket disconnected with error: \(err)")
} else {
print("Socket disconnected!")
}
}
}
| mit |
temoki/TortoiseGraphics | PlaygroundBook/Sources/Playground/PlaygroundCanvasLiveView.swift | 1 | 1307 | #if os (iOS)
import UIKit
public class PlaygroundCanvasLiveView: UIViewController {
public init() {
super.init(nibName: nil, bundle: nil)
}
public init(size: CGSize) {
super.init(nibName: nil, bundle: nil)
self.preferredContentSize = size
}
required init?(coder: NSCoder) {
super.init(coder: coder)
}
public var canvas: Canvas {
return playgroundCanvas
}
public override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = .white
_ = playgroundCanvas
}
public override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
playgroundCanvas.canvasDidLayout()
}
lazy var playgroundCanvas: PlaygroundCanvas = {
let canvas = PlaygroundCanvas(size: Vec2D(size: view.bounds.size))
canvas.translatesAutoresizingMaskIntoConstraints = false
view.addSubview(canvas)
NSLayoutConstraint.activate([
view.topAnchor.constraint(equalTo: canvas.topAnchor),
view.bottomAnchor.constraint(equalTo: canvas.bottomAnchor),
view.leftAnchor.constraint(equalTo: canvas.leftAnchor),
view.rightAnchor.constraint(equalTo: canvas.rightAnchor)
])
return canvas
}()
}
#endif
| mit |
atl009/WordPress-iOS | WordPress/Classes/ViewRelated/Aztec/ViewControllers/AztecPostViewController.swift | 1 | 143201 | import Foundation
import UIKit
import Aztec
import CocoaLumberjack
import Gridicons
import WordPressShared
import AFNetworking
import WPMediaPicker
import SVProgressHUD
import AVKit
// MARK: - Aztec's Native Editor!
//
class AztecPostViewController: UIViewController, PostEditor {
/// Closure to be executed when the editor gets closed
///
var onClose: ((_ changesSaved: Bool) -> ())?
/// Indicates if Aztec was launched for Photo Posting
///
var isOpenedDirectlyForPhotoPost = false
/// Format Bar
///
fileprivate(set) lazy var formatBar: Aztec.FormatBar = {
return self.createToolbar()
}()
/// Aztec's Awesomeness
///
fileprivate(set) lazy var richTextView: Aztec.TextView = {
let paragraphStyle = ParagraphStyle.default
// Paragraph style customizations will go here.
paragraphStyle.lineSpacing = 4
let textView = Aztec.TextView(defaultFont: Fonts.regular, defaultParagraphStyle: paragraphStyle, defaultMissingImage: Assets.defaultMissingImage)
textView.inputProcessor =
PipelineProcessor([VideoShortcodeProcessor.videoPressPreProcessor,
VideoShortcodeProcessor.wordPressVideoPreProcessor,
CalypsoProcessorIn()])
textView.outputProcessor =
PipelineProcessor([VideoShortcodeProcessor.videoPressPostProcessor,
VideoShortcodeProcessor.wordPressVideoPostProcessor,
CalypsoProcessorOut()])
let accessibilityLabel = NSLocalizedString("Rich Content", comment: "Post Rich content")
self.configureDefaultProperties(for: textView, accessibilityLabel: accessibilityLabel)
textView.delegate = self
textView.formattingDelegate = self
textView.textAttachmentDelegate = self
textView.backgroundColor = Colors.aztecBackground
textView.linkTextAttributes = [NSUnderlineStyleAttributeName: NSNumber(value: NSUnderlineStyle.styleSingle.rawValue), NSForegroundColorAttributeName: Colors.aztecLinkColor]
textView.textAlignment = .natural
if #available(iOS 11, *) {
textView.smartDashesType = .no
textView.smartQuotesType = .no
}
return textView
}()
/// Aztec's Text Placeholder
///
fileprivate(set) lazy var placeholderLabel: UILabel = {
let label = UILabel()
label.text = NSLocalizedString("Share your story here...", comment: "Aztec's Text Placeholder")
label.textColor = Colors.placeholder
label.font = Fonts.regular
label.isUserInteractionEnabled = false
label.translatesAutoresizingMaskIntoConstraints = false
label.numberOfLines = 0
label.textAlignment = .natural
return label
}()
/// Raw HTML Editor
///
fileprivate(set) lazy var htmlTextView: UITextView = {
let storage = HTMLStorage(defaultFont: Fonts.regular)
let layoutManager = NSLayoutManager()
let container = NSTextContainer()
storage.addLayoutManager(layoutManager)
layoutManager.addTextContainer(container)
let textView = UITextView(frame: .zero, textContainer: container)
let accessibilityLabel = NSLocalizedString("HTML Content", comment: "Post HTML content")
self.configureDefaultProperties(for: textView, accessibilityLabel: accessibilityLabel)
textView.isHidden = true
textView.delegate = self
textView.accessibilityIdentifier = "HTMLContentView"
textView.autocorrectionType = .no
textView.autocapitalizationType = .none
if #available(iOS 11, *) {
textView.smartDashesType = .no
textView.smartQuotesType = .no
}
return textView
}()
/// Title's UITextView
///
fileprivate(set) lazy var titleTextField: UITextView = {
let textView = UITextView()
textView.accessibilityLabel = NSLocalizedString("Title", comment: "Post title")
textView.delegate = self
textView.font = Fonts.title
textView.returnKeyType = .next
textView.textColor = UIColor.darkText
let titleParagraphStyle = NSMutableParagraphStyle()
titleParagraphStyle.alignment = .natural
textView.typingAttributes = [NSForegroundColorAttributeName: UIColor.darkText, NSFontAttributeName: Fonts.title, NSParagraphStyleAttributeName: titleParagraphStyle]
textView.translatesAutoresizingMaskIntoConstraints = false
textView.textAlignment = .natural
textView.isScrollEnabled = false
textView.backgroundColor = .clear
textView.spellCheckingType = .default
return textView
}()
/// Placeholder Label
///
fileprivate(set) lazy var titlePlaceholderLabel: UILabel = {
let placeholderText = NSLocalizedString("Title", comment: "Placeholder for the post title.")
let titlePlaceholderLabel = UILabel()
let attributes = [NSForegroundColorAttributeName: Colors.title, NSFontAttributeName: Fonts.title]
titlePlaceholderLabel.attributedText = NSAttributedString(string: placeholderText, attributes: attributes)
titlePlaceholderLabel.sizeToFit()
titlePlaceholderLabel.translatesAutoresizingMaskIntoConstraints = false
titlePlaceholderLabel.textAlignment = .natural
return titlePlaceholderLabel
}()
/// Title's Height Constraint
///
fileprivate var titleHeightConstraint: NSLayoutConstraint!
/// Title's Top Constraint
///
fileprivate var titleTopConstraint: NSLayoutConstraint!
/// Placeholder's Top Constraint
///
fileprivate var textPlaceholderTopConstraint: NSLayoutConstraint!
/// Separator View
///
fileprivate(set) lazy var separatorView: UIView = {
let v = UIView(frame: CGRect(x: 0, y: 0, width: self.view.frame.size.width, height: 1))
v.backgroundColor = Colors.separator
v.translatesAutoresizingMaskIntoConstraints = false
return v
}()
/// Negative Offset BarButtonItem: Used to fine tune navigationBar Items
///
fileprivate lazy var separatorButtonItem: UIBarButtonItem = {
let separator = UIBarButtonItem(barButtonSystemItem: .fixedSpace, target: nil, action: nil)
return separator
}()
/// NavigationBar's Close Button
///
fileprivate lazy var closeBarButtonItem: UIBarButtonItem = {
let cancelItem = UIBarButtonItem(customView: self.closeButton)
cancelItem.accessibilityLabel = NSLocalizedString("Close", comment: "Action button to close edior and cancel changes or insertion of post")
cancelItem.accessibilityIdentifier = "Close"
return cancelItem
}()
/// NavigationBar's Blog Picker Button
///
fileprivate lazy var blogPickerBarButtonItem: UIBarButtonItem = {
let pickerItem = UIBarButtonItem(customView: self.blogPickerButton)
pickerItem.accessibilityLabel = NSLocalizedString("Switch Blog", comment: "Action button to switch the blog to which you'll be posting")
return pickerItem
}()
/// Media Uploading Status Button
///
fileprivate lazy var mediaUploadingBarButtonItem: UIBarButtonItem = {
let barButton = UIBarButtonItem(customView: self.mediaUploadingButton)
barButton.accessibilityLabel = NSLocalizedString("Media Uploading", comment: "Message to indicate progress of uploading media to server")
return barButton
}()
/// Publish Button
fileprivate(set) lazy var publishButton: UIButton = {
let button = UIButton(type: .system)
button.addTarget(self, action: #selector(publishButtonTapped(sender:)), for: .touchUpInside)
button.setTitle(self.postEditorStateContext.publishButtonText, for: .normal)
button.sizeToFit()
button.isEnabled = self.postEditorStateContext.isPublishButtonEnabled
button.setContentHuggingPriority(UILayoutPriorityRequired, for: .horizontal)
return button
}()
/// Publish Button
fileprivate(set) lazy var publishBarButtonItem: UIBarButtonItem = {
let button = UIBarButtonItem(customView: self.publishButton)
return button
}()
fileprivate lazy var moreButton: UIButton = {
let image = Gridicon.iconOfType(.ellipsis)
let button = UIButton(type: .system)
button.setImage(image, for: .normal)
button.frame = CGRect(origin: .zero, size: image.size)
button.accessibilityLabel = NSLocalizedString("More", comment: "Action button to display more available options")
button.addTarget(self, action: #selector(moreWasPressed), for: .touchUpInside)
button.setContentHuggingPriority(UILayoutPriorityRequired, for: .horizontal)
return button
}()
/// NavigationBar's More Button
///
fileprivate lazy var moreBarButtonItem: UIBarButtonItem = {
let moreItem = UIBarButtonItem(customView: self.moreButton)
return moreItem
}()
/// Dismiss Button
///
fileprivate lazy var closeButton: WPButtonForNavigationBar = {
let cancelButton = WPStyleGuide.buttonForBar(with: Assets.closeButtonModalImage, target: self, selector: #selector(closeWasPressed))
cancelButton.leftSpacing = Constants.cancelButtonPadding.left
cancelButton.rightSpacing = Constants.cancelButtonPadding.right
cancelButton.setContentHuggingPriority(UILayoutPriorityRequired, for: .horizontal)
return cancelButton
}()
/// Blog Picker's Button
///
fileprivate lazy var blogPickerButton: WPBlogSelectorButton = {
let button = WPBlogSelectorButton(frame: .zero, buttonStyle: .typeSingleLine)
button.addTarget(self, action: #selector(blogPickerWasPressed), for: .touchUpInside)
if #available(iOS 11, *) {
button.translatesAutoresizingMaskIntoConstraints = false
}
button.setContentHuggingPriority(UILayoutPriorityDefaultLow, for: .horizontal)
return button
}()
/// Media Uploading Button
///
fileprivate lazy var mediaUploadingButton: WPUploadStatusButton = {
let button = WPUploadStatusButton(frame: CGRect(origin: .zero, size: Constants.uploadingButtonSize))
button.setTitle(NSLocalizedString("Media Uploading", comment: "Message to indicate progress of uploading media to server"), for: .normal)
button.addTarget(self, action: #selector(displayCancelMediaUploads), for: .touchUpInside)
if #available(iOS 11, *) {
button.translatesAutoresizingMaskIntoConstraints = false
}
button.setContentHuggingPriority(UILayoutPriorityDefaultLow, for: .horizontal)
return button
}()
/// Beta Tag Button
///
fileprivate lazy var betaButton: UIButton = {
let button = UIButton(type: .system)
button.translatesAutoresizingMaskIntoConstraints = false
WPStyleGuide.configureBetaButton(button)
button.setContentHuggingPriority(UILayoutPriorityRequired, for: .horizontal)
button.isEnabled = true
button.addTarget(self, action: #selector(betaButtonTapped), for: .touchUpInside)
return button
}()
/// Active Editor's Mode
///
fileprivate(set) var mode = EditMode.richText {
willSet {
switch mode {
case .html:
setHTML(getHTML(), for: .richText)
case .richText:
setHTML(getHTML(), for: .html)
}
}
didSet {
switch mode {
case .html:
htmlTextView.becomeFirstResponder()
case .richText:
richTextView.becomeFirstResponder()
}
refreshEditorVisibility()
refreshPlaceholderVisibility()
refreshTitlePosition()
}
}
/// Post being currently edited
///
fileprivate(set) var post: AbstractPost {
didSet {
removeObservers(fromPost: oldValue)
addObservers(toPost: post)
postEditorStateContext = createEditorStateContext(for: post)
refreshInterface()
}
}
/// Active Downloads
///
fileprivate var activeMediaRequests = [AFImageDownloadReceipt]()
/// Boolean indicating whether the post should be removed whenever the changes are discarded, or not.
///
fileprivate var shouldRemovePostOnDismiss = false
/// Media Library Data Source
///
fileprivate lazy var mediaLibraryDataSource: MediaLibraryPickerDataSource = {
return MediaLibraryPickerDataSource(post: self.post)
}()
/// Device Photo Library Data Source
///
fileprivate lazy var devicePhotoLibraryDataSource = WPPHAssetDataSource()
/// Media Progress Coordinator
///
fileprivate lazy var mediaProgressCoordinator: MediaProgressCoordinator = {
let coordinator = MediaProgressCoordinator()
coordinator.delegate = self
return coordinator
}()
/// Media Progress View
///
fileprivate lazy var mediaProgressView: UIProgressView = {
let progressView = UIProgressView(progressViewStyle: .bar)
progressView.backgroundColor = Colors.progressBackground
progressView.progressTintColor = Colors.progressTint
progressView.trackTintColor = Colors.progressTrack
progressView.translatesAutoresizingMaskIntoConstraints = false
progressView.isHidden = true
return progressView
}()
/// Selected Text Attachment
///
fileprivate var currentSelectedAttachment: MediaAttachment?
/// Last Interface Element that was a First Responder
///
fileprivate var lastFirstResponder: UIView?
/// Maintainer of state for editor - like for post button
///
fileprivate lazy var postEditorStateContext: PostEditorStateContext = {
return self.createEditorStateContext(for: self.post)
}()
/// Current keyboard rect used to help size the inline media picker
///
fileprivate var currentKeyboardFrame: CGRect = .zero
/// Origin of selected media, used for analytics
///
fileprivate var selectedMediaOrigin: WPAppAnalytics.SelectedMediaOrigin = .none
/// Options
///
fileprivate var optionsViewController: OptionsTableViewController!
/// Media Picker
///
fileprivate lazy var insertToolbarItem: UIButton = {
let insertItem = UIButton(type: .custom)
insertItem.titleLabel?.font = Fonts.mediaPickerInsert
insertItem.tintColor = WPStyleGuide.wordPressBlue()
insertItem.setTitleColor(WPStyleGuide.wordPressBlue(), for: .normal)
return insertItem
}()
fileprivate var mediaPickerInputViewController: WPInputMediaPickerViewController?
fileprivate var originalLeadingBarButtonGroup = [UIBarButtonItemGroup]()
fileprivate var originalTrailingBarButtonGroup = [UIBarButtonItemGroup]()
/// Verification Prompt Helper
///
/// - Returns: `nil` when there's no need for showing the verification prompt.
fileprivate lazy var verificationPromptHelper: AztecVerificationPromptHelper? = {
return AztecVerificationPromptHelper(account: self.post.blog.account)
}()
// MARK: - Initializers
required init(post: AbstractPost) {
self.post = post
super.init(nibName: nil, bundle: nil)
self.restorationIdentifier = Restoration.restorationIdentifier
self.restorationClass = type(of: self)
self.shouldRemovePostOnDismiss = post.shouldRemoveOnDismiss
addObservers(toPost: post)
}
required init?(coder aDecoder: NSCoder) {
preconditionFailure("Aztec Post View Controller must be initialized by code")
}
deinit {
NotificationCenter.default.removeObserver(self)
removeObservers(fromPost: post)
cancelAllPendingMediaRequests()
}
// MARK: - Lifecycle Methods
override func viewDidLoad() {
super.viewDidLoad()
// This needs to called first
configureMediaAppearance()
// TODO: Fix the warnings triggered by this one!
WPFontManager.loadNotoFontFamily()
registerAttachmentImageProviders()
createRevisionOfPost()
// Setup
configureNavigationBar()
configureView()
configureSubviews()
// Register HTML Processors for WordPress shortcodes
// UI elements might get their properties reset when the view is effectively loaded. Refresh it all!
refreshInterface()
// Setup Autolayout
view.setNeedsUpdateConstraints()
if isOpenedDirectlyForPhotoPost {
presentMediaPickerFullScreen(animated: false)
}
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
resetNavigationColors()
configureDismissButton()
startListeningToNotifications()
verificationPromptHelper?.updateVerificationStatus()
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
restoreFirstResponder()
// Handles refreshing controls with state context after options screen is dismissed
editorContentWasUpdated()
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
stopListeningToNotifications()
rememberFirstResponder()
}
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
var safeInsets = self.view.layoutMargins
safeInsets.top = richTextView.textContainerInset.top
richTextView.textContainerInset = safeInsets
htmlTextView.textContainerInset = safeInsets
}
override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) {
super.viewWillTransition(to: size, with: coordinator)
coordinator.animate(alongsideTransition: { _ in
self.resizeBlogPickerButton()
self.updateTitleHeight()
})
dismissOptionsViewControllerIfNecessary()
}
override func willMove(toParentViewController parent: UIViewController?) {
super.willMove(toParentViewController: parent)
guard let navigationController = parent as? UINavigationController else {
return
}
configureMediaProgressView(in: navigationController.navigationBar)
}
// MARK: - Title and Title placeholder position methods
func refreshTitlePosition() {
let referenceView: UITextView = mode == .richText ? richTextView : htmlTextView
titleTopConstraint.constant = -(referenceView.contentOffset.y+referenceView.contentInset.top)
var contentInset = referenceView.contentInset
contentInset.top = (titleHeightConstraint.constant + separatorView.frame.height)
referenceView.contentInset = contentInset
textPlaceholderTopConstraint.constant = referenceView.textContainerInset.top + referenceView.contentInset.top
}
func updateTitleHeight() {
let referenceView: UITextView = mode == .richText ? richTextView : htmlTextView
let layoutMargins = view.layoutMargins
let insets = titleTextField.textContainerInset
var titleWidth = titleTextField.bounds.width
if titleWidth <= 0 {
// Use the title text field's width if available, otherwise calculate it.
// View's frame minus left and right margins as well as margin between title and beta button
titleWidth = view.frame.width - (insets.left + insets.right + layoutMargins.left + layoutMargins.right) - betaButton.frame.width
}
let sizeThatShouldFitTheContent = titleTextField.sizeThatFits(CGSize(width: titleWidth, height: CGFloat.greatestFiniteMagnitude))
titleHeightConstraint.constant = max(sizeThatShouldFitTheContent.height, titleTextField.font!.lineHeight + insets.top + insets.bottom)
textPlaceholderTopConstraint.constant = referenceView.textContainerInset.top + referenceView.contentInset.top
var contentInset = referenceView.contentInset
contentInset.top = (titleHeightConstraint.constant + separatorView.frame.height)
referenceView.contentInset = contentInset
referenceView.setContentOffset(CGPoint(x: 0, y: -contentInset.top), animated: false)
}
// MARK: - Construction Helpers
/// Returns a new Editor Context for a given Post instance.
///
private func createEditorStateContext(for post: AbstractPost) -> PostEditorStateContext {
var originalPostStatus: BasePost.Status? = nil
if let originalPost = post.original, let postStatus = originalPost.status, originalPost.hasRemote() {
originalPostStatus = postStatus
}
// Self-hosted non-Jetpack blogs have no capabilities, so we'll default
// to showing Publish Now instead of Submit for Review.
//
let userCanPublish = post.blog.capabilities != nil ? post.blog.isPublishingPostsAllowed() : true
return PostEditorStateContext(originalPostStatus: originalPostStatus,
userCanPublish: userCanPublish,
publishDate: post.dateCreated,
delegate: self)
}
// MARK: - Configuration Methods
override func updateViewConstraints() {
super.updateViewConstraints()
titleHeightConstraint = titleTextField.heightAnchor.constraint(equalToConstant: titleTextField.font!.lineHeight)
titleTopConstraint = titleTextField.topAnchor.constraint(equalTo: view.topAnchor, constant: -richTextView.contentOffset.y)
textPlaceholderTopConstraint = placeholderLabel.topAnchor.constraint(equalTo: richTextView.topAnchor, constant: richTextView.textContainerInset.top + richTextView.contentInset.top)
updateTitleHeight()
let layoutGuide = view.layoutMarginsGuide
NSLayoutConstraint.activate([
titleTextField.leadingAnchor.constraint(equalTo: layoutGuide.leadingAnchor),
titleTopConstraint,
titleHeightConstraint
])
NSLayoutConstraint.activate([
betaButton.centerYAnchor.constraint(equalTo: titlePlaceholderLabel.centerYAnchor),
betaButton.trailingAnchor.constraint(equalTo: layoutGuide.trailingAnchor),
titleTextField.trailingAnchor.constraint(equalTo: betaButton.leadingAnchor, constant: -titleTextField.textContainerInset.right)
])
let insets = titleTextField.textContainerInset
NSLayoutConstraint.activate([
titlePlaceholderLabel.leftAnchor.constraint(equalTo: titleTextField.leftAnchor, constant: insets.left + titleTextField.textContainer.lineFragmentPadding),
titlePlaceholderLabel.rightAnchor.constraint(equalTo: titleTextField.rightAnchor, constant: -insets.right - titleTextField.textContainer.lineFragmentPadding),
titlePlaceholderLabel.topAnchor.constraint(equalTo: titleTextField.topAnchor, constant: insets.top),
titlePlaceholderLabel.heightAnchor.constraint(equalToConstant: titleTextField.font!.lineHeight)
])
NSLayoutConstraint.activate([
separatorView.leftAnchor.constraint(equalTo: layoutGuide.leftAnchor),
separatorView.rightAnchor.constraint(equalTo: layoutGuide.rightAnchor),
separatorView.topAnchor.constraint(equalTo: titleTextField.bottomAnchor),
separatorView.heightAnchor.constraint(equalToConstant: separatorView.frame.height)
])
NSLayoutConstraint.activate([
richTextView.leadingAnchor.constraint(equalTo: view.leadingAnchor),
richTextView.trailingAnchor.constraint(equalTo: view.trailingAnchor),
richTextView.topAnchor.constraint(equalTo: view.topAnchor),
richTextView.bottomAnchor.constraint(equalTo: view.bottomAnchor)
])
NSLayoutConstraint.activate([
htmlTextView.leftAnchor.constraint(equalTo: richTextView.leftAnchor),
htmlTextView.rightAnchor.constraint(equalTo: richTextView.rightAnchor),
htmlTextView.topAnchor.constraint(equalTo: richTextView.topAnchor),
htmlTextView.bottomAnchor.constraint(equalTo: richTextView.bottomAnchor)
])
NSLayoutConstraint.activate([
placeholderLabel.leadingAnchor.constraint(equalTo: layoutGuide.leadingAnchor, constant: Constants.placeholderPadding.left),
placeholderLabel.trailingAnchor.constraint(equalTo: layoutGuide.trailingAnchor, constant: -(Constants.placeholderPadding.right + richTextView.textContainer.lineFragmentPadding)),
textPlaceholderTopConstraint,
placeholderLabel.bottomAnchor.constraint(lessThanOrEqualTo: richTextView.bottomAnchor, constant: Constants.placeholderPadding.bottom)
])
}
private func configureDefaultProperties(for textView: UITextView, accessibilityLabel: String) {
textView.accessibilityLabel = accessibilityLabel
textView.font = Fonts.regular
textView.keyboardDismissMode = .interactive
textView.textColor = UIColor.darkText
textView.translatesAutoresizingMaskIntoConstraints = false
}
func configureNavigationBar() {
navigationController?.navigationBar.isTranslucent = false
navigationController?.navigationBar.accessibilityIdentifier = "Azctec Editor Navigation Bar"
navigationItem.leftBarButtonItems = [separatorButtonItem, closeBarButtonItem, blogPickerBarButtonItem]
navigationItem.rightBarButtonItems = [moreBarButtonItem, publishBarButtonItem, separatorButtonItem]
}
/// This is to restore the navigation bar colors after the UIDocumentPickerViewController has been dismissed,
/// either by uploading media or cancelling. Doing this in the UIDocumentPickerDelegate methods either did
/// nothing or the resetting wasn't permanent.
///
fileprivate func resetNavigationColors() {
WPStyleGuide.configureNavigationBarAppearance()
}
func configureDismissButton() {
let image = isModal() ? Assets.closeButtonModalImage : Assets.closeButtonRegularImage
closeButton.setImage(image, for: .normal)
}
func configureView() {
edgesForExtendedLayout = UIRectEdge()
view.backgroundColor = .white
}
func configureSubviews() {
view.addSubview(richTextView)
view.addSubview(htmlTextView)
view.addSubview(titleTextField)
view.addSubview(titlePlaceholderLabel)
view.addSubview(separatorView)
view.addSubview(placeholderLabel)
view.addSubview(betaButton)
}
func configureMediaProgressView(in navigationBar: UINavigationBar) {
guard mediaProgressView.superview == nil else {
return
}
navigationBar.addSubview(mediaProgressView)
NSLayoutConstraint.activate([
mediaProgressView.leadingAnchor.constraint(equalTo: navigationBar.leadingAnchor),
mediaProgressView.widthAnchor.constraint(equalTo: navigationBar.widthAnchor),
mediaProgressView.topAnchor.constraint(equalTo: navigationBar.bottomAnchor, constant: -mediaProgressView.frame.height)
])
}
func registerAttachmentImageProviders() {
let providers: [TextViewAttachmentImageProvider] = [
SpecialTagAttachmentRenderer(),
CommentAttachmentRenderer(font: Fonts.regular),
HTMLAttachmentRenderer(font: Fonts.regular)
]
for provider in providers {
richTextView.registerAttachmentImageProvider(provider)
}
}
func startListeningToNotifications() {
let nc = NotificationCenter.default
nc.addObserver(self, selector: #selector(keyboardWillShow), name: .UIKeyboardWillShow, object: nil)
nc.addObserver(self, selector: #selector(keyboardDidHide), name: .UIKeyboardDidHide, object: nil)
nc.addObserver(self, selector: #selector(applicationWillResignActive(_:)), name: .UIApplicationWillResignActive, object: nil)
}
func stopListeningToNotifications() {
let nc = NotificationCenter.default
nc.removeObserver(self, name: .UIKeyboardWillShow, object: nil)
nc.removeObserver(self, name: .UIKeyboardDidHide, object: nil)
nc.removeObserver(self, name: .UIApplicationWillResignActive, object: nil)
}
func rememberFirstResponder() {
lastFirstResponder = view.findFirstResponder()
lastFirstResponder?.resignFirstResponder()
}
func restoreFirstResponder() {
let nextFirstResponder = lastFirstResponder ?? titleTextField
nextFirstResponder.becomeFirstResponder()
}
func refreshInterface() {
reloadBlogPickerButton()
reloadEditorContents()
resizeBlogPickerButton()
reloadPublishButton()
refreshNavigationBar()
}
func refreshNavigationBar() {
if postEditorStateContext.isUploadingMedia {
navigationItem.leftBarButtonItems = [separatorButtonItem, closeBarButtonItem, mediaUploadingBarButtonItem]
} else {
navigationItem.leftBarButtonItems = [separatorButtonItem, closeBarButtonItem, blogPickerBarButtonItem]
}
}
func setHTML(_ html: String) {
setHTML(html, for: mode)
}
private func setHTML(_ html: String, for mode: EditMode) {
switch mode {
case .html:
htmlTextView.text = html
case .richText:
richTextView.setHTML(html)
self.processVideoPressAttachments()
}
}
func getHTML() -> String {
let html: String
switch mode {
case .html:
html = htmlTextView.text
case .richText:
html = richTextView.getHTML()
}
return html
}
func reloadEditorContents() {
let content = post.content ?? String()
titleTextField.text = post.postTitle
setHTML(content)
}
func reloadBlogPickerButton() {
var pickerTitle = post.blog.url ?? String()
if let blogName = post.blog.settings?.name, blogName.isEmpty == false {
pickerTitle = blogName
}
let titleText = NSAttributedString(string: pickerTitle, attributes: [NSFontAttributeName: Fonts.blogPicker])
let shouldEnable = !isSingleSiteMode
blogPickerButton.setAttributedTitle(titleText, for: .normal)
blogPickerButton.buttonMode = shouldEnable ? .multipleSite : .singleSite
blogPickerButton.isEnabled = shouldEnable
}
func reloadPublishButton() {
publishButton.setTitle(postEditorStateContext.publishButtonText, for: .normal)
publishButton.isEnabled = postEditorStateContext.isPublishButtonEnabled
}
func resizeBlogPickerButton() {
// On iOS 11 no resize is needed because the StackView on the navigation bar will do the work
if #available(iOS 11, *) {
return
}
// On iOS 10 and before we still need to manually resize the button.
// Ensure the BlogPicker gets it's maximum possible size
blogPickerButton.sizeToFit()
// Cap the size, according to the current traits
var blogPickerSize = hasHorizontallyCompactView() ? Constants.blogPickerCompactSize : Constants.blogPickerRegularSize
blogPickerSize.width = min(blogPickerSize.width, blogPickerButton.frame.width)
blogPickerButton.frame.size = blogPickerSize
}
// MARK: - Keyboard Handling
override var keyCommands: [UIKeyCommand] {
if richTextView.isFirstResponder {
return [ UIKeyCommand(input: "B", modifierFlags: .command, action: #selector(toggleBold), discoverabilityTitle: NSLocalizedString("Bold", comment: "Discoverability title for bold formatting keyboard shortcut.")),
UIKeyCommand(input: "I", modifierFlags: .command, action: #selector(toggleItalic), discoverabilityTitle: NSLocalizedString("Italic", comment: "Discoverability title for italic formatting keyboard shortcut.")),
UIKeyCommand(input: "S", modifierFlags: [.command], action: #selector(toggleStrikethrough), discoverabilityTitle: NSLocalizedString("Strikethrough", comment: "Discoverability title for strikethrough formatting keyboard shortcut.")),
UIKeyCommand(input: "U", modifierFlags: .command, action: #selector(toggleUnderline(_:)), discoverabilityTitle: NSLocalizedString("Underline", comment: "Discoverability title for underline formatting keyboard shortcut.")),
UIKeyCommand(input: "Q", modifierFlags: [.command, .alternate], action: #selector(toggleBlockquote), discoverabilityTitle: NSLocalizedString("Block Quote", comment: "Discoverability title for block quote keyboard shortcut.")),
UIKeyCommand(input: "K", modifierFlags: .command, action: #selector(toggleLink), discoverabilityTitle: NSLocalizedString("Insert Link", comment: "Discoverability title for insert link keyboard shortcut.")),
UIKeyCommand(input: "M", modifierFlags: [.command, .alternate], action: #selector(presentMediaPicker), discoverabilityTitle: NSLocalizedString("Insert Media", comment: "Discoverability title for insert media keyboard shortcut.")),
UIKeyCommand(input: "U", modifierFlags: [.command, .alternate], action: #selector(toggleUnorderedList), discoverabilityTitle: NSLocalizedString("Bullet List", comment: "Discoverability title for bullet list keyboard shortcut.")),
UIKeyCommand(input: "O", modifierFlags: [.command, .alternate], action: #selector(toggleOrderedList), discoverabilityTitle: NSLocalizedString("Numbered List", comment: "Discoverability title for numbered list keyboard shortcut.")),
UIKeyCommand(input: "H", modifierFlags: [.command, .shift], action: #selector(toggleEditingMode), discoverabilityTitle: NSLocalizedString("Toggle HTML Source ", comment: "Discoverability title for HTML keyboard shortcut."))
]
} else if htmlTextView.isFirstResponder {
return [UIKeyCommand(input: "H", modifierFlags: [.command, .shift], action: #selector(toggleEditingMode), discoverabilityTitle: NSLocalizedString("Toggle HTML Source ", comment: "Discoverability title for HTML keyboard shortcut."))
]
}
return []
}
func keyboardWillShow(_ notification: Foundation.Notification) {
guard
let userInfo = notification.userInfo as? [String: AnyObject],
let keyboardFrame = (userInfo[UIKeyboardFrameEndUserInfoKey] as? NSValue)?.cgRectValue
else {
return
}
// Convert the keyboard frame from window base coordinate
currentKeyboardFrame = view.convert(keyboardFrame, from: nil)
refreshInsets(forKeyboardFrame: keyboardFrame)
}
func keyboardDidHide(_ notification: Foundation.Notification) {
guard
let userInfo = notification.userInfo as? [String: AnyObject],
let keyboardFrame = (userInfo[UIKeyboardFrameEndUserInfoKey] as? NSValue)?.cgRectValue
else {
return
}
currentKeyboardFrame = .zero
refreshInsets(forKeyboardFrame: keyboardFrame)
}
fileprivate func refreshInsets(forKeyboardFrame keyboardFrame: CGRect) {
let referenceView: UIScrollView = mode == .richText ? richTextView : htmlTextView
let scrollInsets = UIEdgeInsets(top: referenceView.scrollIndicatorInsets.top, left: 0, bottom: view.frame.maxY - (keyboardFrame.minY + self.view.layoutMargins.bottom), right: 0)
let contentInsets = UIEdgeInsets(top: referenceView.contentInset.top, left: 0, bottom: view.frame.maxY - (keyboardFrame.minY + self.view.layoutMargins.bottom), right: 0)
htmlTextView.scrollIndicatorInsets = scrollInsets
htmlTextView.contentInset = contentInsets
richTextView.scrollIndicatorInsets = scrollInsets
richTextView.contentInset = contentInsets
}
func updateFormatBar() {
guard let toolbar = richTextView.inputAccessoryView as? Aztec.FormatBar else {
return
}
var identifiers = [FormattingIdentifier]()
if richTextView.selectedRange.length > 0 {
identifiers = richTextView.formatIdentifiersSpanningRange(richTextView.selectedRange)
} else {
identifiers = richTextView.formatIdentifiersForTypingAttributes()
}
toolbar.selectItemsMatchingIdentifiers(identifiers.map({ $0.rawValue }))
}
}
// MARK: - SDK Workarounds!
//
extension AztecPostViewController {
/// Note:
/// When presenting an UIAlertController using a navigationBarButton as a source, the entire navigationBar
/// gets set as a passthru view, allowing invalid scenarios, such as: pressing the Dismiss Button, while there's
/// an ActionSheet onscreen.
///
override func present(_ viewControllerToPresent: UIViewController, animated flag: Bool, completion: (() -> Void)? = nil) {
super.present(viewControllerToPresent, animated: flag) {
if let alert = viewControllerToPresent as? UIAlertController, alert.preferredStyle == .actionSheet {
alert.popoverPresentationController?.passthroughViews = nil
}
completion?()
}
}
}
// MARK: - Actions
//
extension AztecPostViewController {
@IBAction func publishButtonTapped(sender: UIBarButtonItem) {
trackPostSave(stat: postEditorStateContext.publishActionAnalyticsStat)
publishTapped(dismissWhenDone: postEditorStateContext.publishActionDismissesEditor)
}
@IBAction func secondaryPublishButtonTapped(dismissWhenDone: Bool = true) {
let publishPostClosure = {
if self.postEditorStateContext.secondaryPublishButtonAction == .save {
self.post.status = .draft
} else if self.postEditorStateContext.secondaryPublishButtonAction == .publish {
self.post.date_created_gmt = Date()
self.post.status = .publish
}
if let stat = self.postEditorStateContext.secondaryPublishActionAnalyticsStat {
self.trackPostSave(stat: stat)
}
self.publishTapped(dismissWhenDone: dismissWhenDone)
}
if presentedViewController != nil {
dismiss(animated: true, completion: publishPostClosure)
} else {
publishPostClosure()
}
}
func showPostHasChangesAlert() {
let title = NSLocalizedString("You have unsaved changes.", comment: "Title of message with options that shown when there are unsaved changes and the author is trying to move away from the post.")
let cancelTitle = NSLocalizedString("Keep Editing", comment: "Button shown if there are unsaved changes and the author is trying to move away from the post.")
let saveTitle = NSLocalizedString("Save Draft", comment: "Button shown if there are unsaved changes and the author is trying to move away from the post.")
let updateTitle = NSLocalizedString("Update Draft", comment: "Button shown if there are unsaved changes and the author is trying to move away from an already published/saved post.")
let discardTitle = NSLocalizedString("Discard", comment: "Button shown if there are unsaved changes and the author is trying to move away from the post.")
let alertController = UIAlertController(title: title, message: nil, preferredStyle: .actionSheet)
// Button: Keep editing
alertController.addCancelActionWithTitle(cancelTitle)
// Button: Save Draft/Update Draft
if post.hasLocalChanges() {
if !post.hasRemote() {
// The post is a local draft or an autosaved draft: Discard or Save
alertController.addDefaultActionWithTitle(saveTitle) { _ in
self.post.status = .draft
self.trackPostSave(stat: self.postEditorStateContext.publishActionAnalyticsStat)
self.publishTapped(dismissWhenDone: true)
}
} else if post.status == .draft {
// The post was already a draft
alertController.addDefaultActionWithTitle(updateTitle) { _ in
self.trackPostSave(stat: self.postEditorStateContext.publishActionAnalyticsStat)
self.publishTapped(dismissWhenDone: true)
}
}
}
// Button: Discard
alertController.addDestructiveActionWithTitle(discardTitle) { _ in
self.discardChangesAndUpdateGUI()
}
alertController.popoverPresentationController?.barButtonItem = closeBarButtonItem
present(alertController, animated: true, completion: nil)
}
private func publishTapped(dismissWhenDone: Bool) {
// Cancel publishing if media is currently being uploaded
if mediaProgressCoordinator.isRunning {
displayMediaIsUploadingAlert()
return
}
// If there is any failed media allow it to be removed or cancel publishing
if mediaProgressCoordinator.hasFailedMedia {
displayHasFailedMediaAlert(then: {
// Failed media is removed, try again.
// Note: Intentionally not tracking another analytics stat here (no appropriate one exists yet)
self.publishTapped(dismissWhenDone: dismissWhenDone)
})
return
}
// If the user is trying to publish to WP.com and they haven't verified their account, prompt them to do so.
if let verificationHelper = verificationPromptHelper, verificationHelper.neeedsVerification(before: postEditorStateContext.action) {
verificationHelper.displayVerificationPrompt(from: self) { [weak self] verifiedInBackground in
// User could've been plausibly silently verified in the background.
// If so, proceed to publishing the post as normal, otherwise save it as a draft.
if !verifiedInBackground {
self?.post.status = .draft
}
self?.publishTapped(dismissWhenDone: dismissWhenDone)
}
return
}
SVProgressHUD.setDefaultMaskType(.clear)
SVProgressHUD.show(withStatus: postEditorStateContext.publishVerbText)
postEditorStateContext.updated(isBeingPublished: true)
// Finally, publish the post.
publishPost() { uploadedPost, error in
self.postEditorStateContext.updated(isBeingPublished: false)
SVProgressHUD.dismiss()
let generator = UINotificationFeedbackGenerator()
generator.prepare()
if let error = error {
DDLogError("Error publishing post: \(error.localizedDescription)")
SVProgressHUD.showDismissibleError(withStatus: self.postEditorStateContext.publishErrorText)
generator.notificationOccurred(.error)
} else if let uploadedPost = uploadedPost {
self.post = uploadedPost
generator.notificationOccurred(.success)
}
if dismissWhenDone {
self.dismissOrPopView(didSave: true)
} else {
self.createRevisionOfPost()
}
}
}
@IBAction func closeWasPressed() {
cancelEditing()
}
@IBAction func blogPickerWasPressed() {
assert(isSingleSiteMode == false)
guard post.hasSiteSpecificChanges() else {
displayBlogSelector()
return
}
displaySwitchSiteAlert()
}
@IBAction func moreWasPressed() {
displayMoreSheet()
}
@IBAction func betaButtonTapped() {
WPAppAnalytics.track(.editorAztecBetaLink)
FancyAlertViewController.presentWhatsNewWebView(from: self)
}
private func trackPostSave(stat: WPAnalyticsStat) {
guard stat != .editorSavedDraft && stat != .editorQuickSavedDraft else {
WPAppAnalytics.track(stat, withProperties: [WPAppAnalyticsKeyEditorSource: Analytics.editorSource], with: post.blog)
return
}
let originalWordCount = post.original?.content?.wordCount() ?? 0
let wordCount = post.content?.wordCount() ?? 0
var properties: [String: Any] = ["word_count": wordCount, WPAppAnalyticsKeyEditorSource: Analytics.editorSource]
if post.hasRemote() {
properties["word_diff_count"] = originalWordCount
}
if stat == .editorPublishedPost {
properties[WPAnalyticsStatEditorPublishedPostPropertyCategory] = post.hasCategories()
properties[WPAnalyticsStatEditorPublishedPostPropertyPhoto] = post.hasPhoto()
properties[WPAnalyticsStatEditorPublishedPostPropertyTag] = post.hasTags()
properties[WPAnalyticsStatEditorPublishedPostPropertyVideo] = post.hasVideo()
}
WPAppAnalytics.track(stat, withProperties: properties, with: post)
}
}
// MARK: - Private Helpers
//
private extension AztecPostViewController {
func displayBlogSelector() {
guard let sourceView = blogPickerButton.imageView else {
fatalError()
}
// Setup Handlers
let successHandler: BlogSelectorSuccessHandler = { selectedObjectID in
self.dismiss(animated: true, completion: nil)
guard let blog = self.mainContext.object(with: selectedObjectID) as? Blog else {
return
}
self.recreatePostRevision(in: blog)
self.mediaLibraryDataSource = MediaLibraryPickerDataSource(post: self.post)
}
let dismissHandler: BlogSelectorDismissHandler = {
self.dismiss(animated: true, completion: nil)
}
// Setup Picker
let selectorViewController = BlogSelectorViewController(selectedBlogObjectID: post.blog.objectID,
successHandler: successHandler,
dismissHandler: dismissHandler)
selectorViewController.title = NSLocalizedString("Select Site", comment: "Blog Picker's Title")
selectorViewController.displaysPrimaryBlogOnTop = true
// Note:
// On iPad Devices, we'll disable the Picker's SearchController's "Autohide Navbar Feature", since
// upon dismissal, it may force the NavigationBar to show up, even when it was initially hidden.
selectorViewController.displaysNavigationBarWhenSearching = WPDeviceIdentification.isiPad()
// Setup Navigation
let navigationController = AdaptiveNavigationController(rootViewController: selectorViewController)
navigationController.configurePopoverPresentationStyle(from: sourceView)
// Done!
present(navigationController, animated: true, completion: nil)
}
func displayMoreSheet() {
let alert = UIAlertController(title: nil, message: nil, preferredStyle: .actionSheet)
if postEditorStateContext.isSecondaryPublishButtonShown,
let buttonTitle = postEditorStateContext.secondaryPublishButtonText {
let dismissWhenDone = postEditorStateContext.secondaryPublishButtonAction == .publish
alert.addActionWithTitle(buttonTitle, style: dismissWhenDone ? .destructive : .default ) { _ in
self.secondaryPublishButtonTapped(dismissWhenDone: dismissWhenDone)
}
}
alert.addDefaultActionWithTitle(MoreSheetAlert.previewTitle) { _ in
self.displayPreview()
}
alert.addDefaultActionWithTitle(MoreSheetAlert.optionsTitle) { _ in
self.displayPostOptions()
}
alert.addCancelActionWithTitle(MoreSheetAlert.cancelTitle)
alert.popoverPresentationController?.barButtonItem = moreBarButtonItem
present(alert, animated: true, completion: nil)
}
func displaySwitchSiteAlert() {
let alert = UIAlertController(title: SwitchSiteAlert.title, message: SwitchSiteAlert.message, preferredStyle: .alert)
alert.addDefaultActionWithTitle(SwitchSiteAlert.acceptTitle) { _ in
self.displayBlogSelector()
}
alert.addCancelActionWithTitle(SwitchSiteAlert.cancelTitle)
present(alert, animated: true, completion: nil)
}
func displayPostOptions() {
let settingsViewController: PostSettingsViewController
if post is Page {
settingsViewController = PageSettingsViewController(post: post)
} else {
settingsViewController = PostSettingsViewController(post: post)
}
settingsViewController.hidesBottomBarWhenPushed = true
self.navigationController?.pushViewController(settingsViewController, animated: true)
}
func displayPreview() {
let previewController = PostPreviewViewController(post: post)
previewController.hidesBottomBarWhenPushed = true
navigationController?.pushViewController(previewController, animated: true)
}
func displayMediaIsUploadingAlert() {
let alertController = UIAlertController(title: MediaUploadingAlert.title, message: MediaUploadingAlert.message, preferredStyle: .alert)
alertController.addDefaultActionWithTitle(MediaUploadingAlert.acceptTitle)
present(alertController, animated: true, completion: nil)
}
func displayHasFailedMediaAlert(then: @escaping () -> ()) {
let alertController = UIAlertController(title: FailedMediaRemovalAlert.title, message: FailedMediaRemovalAlert.message, preferredStyle: .alert)
alertController.addDefaultActionWithTitle(MediaUploadingAlert.acceptTitle) { alertAction in
self.removeFailedMedia()
then()
}
alertController.addCancelActionWithTitle(FailedMediaRemovalAlert.cancelTitle)
present(alertController, animated: true, completion: nil)
}
@IBAction func displayCancelMediaUploads() {
let alertController = UIAlertController(title: MediaUploadingCancelAlert.title, message: MediaUploadingCancelAlert.message, preferredStyle: .alert)
alertController.addDefaultActionWithTitle(MediaUploadingCancelAlert.acceptTitle) { alertAction in
self.mediaProgressCoordinator.cancelAllPendingUploads()
}
alertController.addCancelActionWithTitle(MediaUploadingCancelAlert.cancelTitle)
present(alertController, animated: true, completion: nil)
return
}
}
// MARK: - PostEditorStateContextDelegate & support methods
//
extension AztecPostViewController: PostEditorStateContextDelegate {
override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey: Any]?, context: UnsafeMutableRawPointer?) {
guard let keyPath = keyPath else {
return
}
switch keyPath {
case BasePost.statusKeyPath:
if let status = post.status {
postEditorStateContext.updated(postStatus: status)
editorContentWasUpdated()
}
case #keyPath(AbstractPost.dateCreated):
let dateCreated = post.dateCreated ?? Date()
postEditorStateContext.updated(publishDate: dateCreated)
editorContentWasUpdated()
case #keyPath(AbstractPost.content):
editorContentWasUpdated()
default:
super.observeValue(forKeyPath: keyPath, of: object, change: change, context: context)
}
}
private var editorHasContent: Bool {
let titleIsEmpty = post.postTitle?.isEmpty ?? true
let contentIsEmpty = post.content?.isEmpty ?? true
return !titleIsEmpty || !contentIsEmpty
}
private var editorHasChanges: Bool {
return post.hasUnsavedChanges()
}
internal func editorContentWasUpdated() {
postEditorStateContext.updated(hasContent: editorHasContent)
postEditorStateContext.updated(hasChanges: editorHasChanges)
}
internal func context(_ context: PostEditorStateContext, didChangeAction: PostEditorAction) {
reloadPublishButton()
}
internal func context(_ context: PostEditorStateContext, didChangeActionAllowed: Bool) {
reloadPublishButton()
}
internal func addObservers(toPost: AbstractPost) {
toPost.addObserver(self, forKeyPath: AbstractPost.statusKeyPath, options: [], context: nil)
toPost.addObserver(self, forKeyPath: #keyPath(AbstractPost.dateCreated), options: [], context: nil)
toPost.addObserver(self, forKeyPath: #keyPath(AbstractPost.content), options: [], context: nil)
}
internal func removeObservers(fromPost: AbstractPost) {
fromPost.removeObserver(self, forKeyPath: AbstractPost.statusKeyPath)
fromPost.removeObserver(self, forKeyPath: #keyPath(AbstractPost.dateCreated))
fromPost.removeObserver(self, forKeyPath: #keyPath(AbstractPost.content))
}
}
// MARK: - UITextViewDelegate methods
//
extension AztecPostViewController: UITextViewDelegate {
func textView(_ textView: UITextView, shouldChangeTextIn range: NSRange, replacementText text: String) -> Bool {
switch textView {
case titleTextField:
return shouldChangeTitleText(in: range, replacementText: text)
default:
return true
}
}
func textViewDidChangeSelection(_ textView: UITextView) {
updateFormatBar()
}
func textViewDidChange(_ textView: UITextView) {
mapUIContentToPostAndSave()
refreshPlaceholderVisibility()
switch textView {
case titleTextField:
updateTitleHeight()
case richTextView:
updateFormatBar()
default:
break
}
}
func textViewShouldBeginEditing(_ textView: UITextView) -> Bool {
textView.textAlignment = .natural
switch textView {
case titleTextField:
formatBar.enabled = false
case richTextView:
formatBar.enabled = true
case htmlTextView:
formatBar.enabled = false
// Disable the bar, except for the source code button
let htmlButton = formatBar.items.first(where: { $0.identifier == FormattingIdentifier.sourcecode.rawValue })
htmlButton?.isEnabled = true
default:
break
}
if mediaPickerInputViewController == nil {
textView.inputAccessoryView = formatBar
}
return true
}
func scrollViewDidScroll(_ scrollView: UIScrollView) {
refreshTitlePosition()
}
// MARK: - Title Input Sanitization
/// Sanitizes an input for insertion in the title text view.
///
/// - Parameters:
/// - input: the input for the title text view.
///
/// - Returns: the sanitized string
///
private func sanitizeInputForTitle(_ input: String) -> String {
var sanitizedText = input
while let range = sanitizedText.rangeOfCharacter(from: CharacterSet.newlines, options: [], range: nil) {
sanitizedText = sanitizedText.replacingCharacters(in: range, with: " ")
}
return sanitizedText
}
/// This method performs all necessary checks to verify if the title text can be changed,
/// or if some other action should be performed instead.
///
/// - Important: this method sanitizes newlines, since they're not allowed in the title.
///
/// - Parameters:
/// - range: the range that would be modified.
/// - text: the new text for the specified range.
///
/// - Returns: `true` if the modification can take place, `false` otherwise.
///
private func shouldChangeTitleText(in range: NSRange, replacementText text: String) -> Bool {
guard text.count > 1 else {
guard text.rangeOfCharacter(from: CharacterSet.newlines, options: [], range: nil) == nil else {
richTextView.becomeFirstResponder()
richTextView.selectedRange = NSRange(location: 0, length: 0)
return false
}
return true
}
let sanitizedInput = sanitizeInputForTitle(text)
let newlinesWereRemoved = sanitizedInput != text
guard !newlinesWereRemoved else {
titleTextField.insertText(sanitizedInput)
return false
}
return true
}
}
// MARK: - UITextFieldDelegate methods
//
extension AztecPostViewController {
func titleTextFieldDidChange(_ textField: UITextField) {
mapUIContentToPostAndSave()
editorContentWasUpdated()
}
}
// MARK: - TextViewFormattingDelegate methods
//
extension AztecPostViewController: Aztec.TextViewFormattingDelegate {
func textViewCommandToggledAStyle() {
updateFormatBar()
}
}
// MARK: - HTML Mode Switch methods
//
extension AztecPostViewController {
enum EditMode {
case richText
case html
mutating func toggle() {
switch self {
case .richText:
self = .html
case .html:
self = .richText
}
}
}
func refreshEditorVisibility() {
let isRichEnabled = mode == .richText
htmlTextView.isHidden = isRichEnabled
richTextView.isHidden = !isRichEnabled
}
func refreshPlaceholderVisibility() {
placeholderLabel.isHidden = richTextView.isHidden || !richTextView.text.isEmpty
titlePlaceholderLabel.isHidden = !titleTextField.text.isEmpty
}
}
// MARK: - FormatBarDelegate Conformance
//
extension AztecPostViewController: Aztec.FormatBarDelegate {
func formatBarTouchesBegan(_ formatBar: FormatBar) {
dismissOptionsViewControllerIfNecessary()
}
/// Called when the overflow items in the format bar are either shown or hidden
/// as a result of the user tapping the toggle button.
///
func formatBar(_ formatBar: FormatBar, didChangeOverflowState overflowState: FormatBarOverflowState) {
let action = overflowState == .visible ? "made_visible" : "made_hidden"
trackFormatBarAnalytics(stat: .editorTappedMoreItems, action: action)
}
}
// MARK: FormatBar Actions
//
extension AztecPostViewController {
func handleAction(for barItem: FormatBarItem) {
guard let identifier = barItem.identifier else { return }
if let formattingIdentifier = FormattingIdentifier(rawValue: identifier) {
switch formattingIdentifier {
case .bold:
toggleBold()
case .italic:
toggleItalic()
case .underline:
toggleUnderline()
case .strikethrough:
toggleStrikethrough()
case .blockquote:
toggleBlockquote()
case .unorderedlist, .orderedlist:
toggleList(fromItem: barItem)
case .link:
toggleLink()
case .media:
break
case .sourcecode:
toggleEditingMode()
case .p, .header1, .header2, .header3, .header4, .header5, .header6:
toggleHeader(fromItem: barItem)
case .horizontalruler:
insertHorizontalRuler()
case .more:
insertMore()
}
updateFormatBar()
}
else if let mediaIdentifier = FormatBarMediaIdentifier(rawValue: identifier) {
switch mediaIdentifier {
case .deviceLibrary:
trackFormatBarAnalytics(stat: .editorMediaPickerTappedDevicePhotos)
presentMediaPickerFullScreen(animated: true, dataSourceType: .device)
case .camera:
trackFormatBarAnalytics(stat: .editorMediaPickerTappedCamera)
mediaPickerInputViewController?.showCapture()
case .mediaLibrary:
trackFormatBarAnalytics(stat: .editorMediaPickerTappedMediaLibrary)
presentMediaPickerFullScreen(animated: true, dataSourceType: .mediaLibrary)
case .otherApplications:
trackFormatBarAnalytics(stat: .editorMediaPickerTappedOtherApps)
showDocumentPicker()
}
}
}
func handleFormatBarLeadingItem(_ item: UIButton) {
toggleMediaPicker(fromButton: item)
}
func handleFormatBarTrailingItem(_ item: UIButton) {
guard let mediaPicker = mediaPickerInputViewController else {
return
}
mediaPickerController(mediaPicker.mediaPicker, didFinishPicking: mediaPicker.mediaPicker.selectedAssets)
}
func toggleBold() {
trackFormatBarAnalytics(stat: .editorTappedBold)
richTextView.toggleBold(range: richTextView.selectedRange)
}
func toggleItalic() {
trackFormatBarAnalytics(stat: .editorTappedItalic)
richTextView.toggleItalic(range: richTextView.selectedRange)
}
func toggleUnderline() {
trackFormatBarAnalytics(stat: .editorTappedUnderline)
richTextView.toggleUnderline(range: richTextView.selectedRange)
}
func toggleStrikethrough() {
trackFormatBarAnalytics(stat: .editorTappedStrikethrough)
richTextView.toggleStrikethrough(range: richTextView.selectedRange)
}
func toggleOrderedList() {
trackFormatBarAnalytics(stat: .editorTappedOrderedList)
richTextView.toggleOrderedList(range: richTextView.selectedRange)
}
func toggleUnorderedList() {
trackFormatBarAnalytics(stat: .editorTappedUnorderedList)
richTextView.toggleUnorderedList(range: richTextView.selectedRange)
}
func toggleList(fromItem item: FormatBarItem) {
let listOptions = Constants.lists.map { listType -> OptionsTableViewOption in
let title = NSAttributedString(string: listType.description, attributes: [:])
return OptionsTableViewOption(image: listType.iconImage,
title: title,
accessibilityLabel: listType.accessibilityLabel)
}
var index: Int? = nil
if let listType = listTypeForSelectedText() {
index = Constants.lists.index(of: listType)
}
showOptionsTableViewControllerWithOptions(listOptions,
fromBarItem: item,
selectedRowIndex: index,
onSelect: { [weak self] selected in
let listType = Constants.lists[selected]
switch listType {
case .unordered:
self?.toggleUnorderedList()
case .ordered:
self?.toggleOrderedList()
}
})
}
func toggleBlockquote() {
trackFormatBarAnalytics(stat: .editorTappedBlockquote)
richTextView.toggleBlockquote(range: richTextView.selectedRange)
}
func listTypeForSelectedText() -> TextList.Style? {
var identifiers = [FormattingIdentifier]()
if richTextView.selectedRange.length > 0 {
identifiers = richTextView.formatIdentifiersSpanningRange(richTextView.selectedRange)
} else {
identifiers = richTextView.formatIdentifiersForTypingAttributes()
}
let mapping: [FormattingIdentifier: TextList.Style] = [
.orderedlist: .ordered,
.unorderedlist: .unordered
]
for (key, value) in mapping {
if identifiers.contains(key) {
return value
}
}
return nil
}
func toggleLink() {
trackFormatBarAnalytics(stat: .editorTappedLink)
var linkTitle = ""
var linkURL: URL? = nil
var linkRange = richTextView.selectedRange
// Let's check if the current range already has a link assigned to it.
if let expandedRange = richTextView.linkFullRange(forRange: richTextView.selectedRange) {
linkRange = expandedRange
linkURL = richTextView.linkURL(forRange: expandedRange)
}
linkTitle = richTextView.attributedText.attributedSubstring(from: linkRange).string
showLinkDialog(forURL: linkURL, title: linkTitle, range: linkRange)
}
func showLinkDialog(forURL url: URL?, title: String?, range: NSRange) {
let cancelTitle = NSLocalizedString("Cancel", comment: "Cancel button")
let removeTitle = NSLocalizedString("Remove Link", comment: "Label action for removing a link from the editor")
let insertTitle = NSLocalizedString("Insert Link", comment: "Label action for inserting a link on the editor")
let updateTitle = NSLocalizedString("Update Link", comment: "Label action for updating a link on the editor")
let isInsertingNewLink = (url == nil)
var urlToUse = url
if isInsertingNewLink {
if let pastedURL = UIPasteboard.general.value(forPasteboardType: String(kUTTypeURL)) as? URL {
urlToUse = pastedURL
}
}
let insertButtonTitle = isInsertingNewLink ? insertTitle : updateTitle
let alertController = UIAlertController(title: insertButtonTitle, message: nil, preferredStyle: .alert)
// TextField: URL
alertController.addTextField(configurationHandler: { [weak self] textField in
textField.clearButtonMode = .always
textField.placeholder = NSLocalizedString("URL", comment: "URL text field placeholder")
textField.text = urlToUse?.absoluteString
textField.addTarget(self,
action: #selector(AztecPostViewController.alertTextFieldDidChange),
for: UIControlEvents.editingChanged)
})
// TextField: Link Name
alertController.addTextField(configurationHandler: { textField in
textField.clearButtonMode = .always
textField.placeholder = NSLocalizedString("Link Name", comment: "Link name field placeholder")
textField.isSecureTextEntry = false
textField.autocapitalizationType = .sentences
textField.autocorrectionType = .default
textField.spellCheckingType = .default
textField.text = title
})
// Action: Insert
let insertAction = alertController.addDefaultActionWithTitle(insertButtonTitle) { [weak self] action in
self?.richTextView.becomeFirstResponder()
let linkURLString = alertController.textFields?.first?.text
var linkTitle = alertController.textFields?.last?.text
if linkTitle == nil || linkTitle!.isEmpty {
linkTitle = linkURLString
}
guard let urlString = linkURLString, let url = URL(string: urlString), let title = linkTitle else {
return
}
self?.richTextView.setLink(url, title: title, inRange: range)
}
// Disabled until url is entered into field
insertAction.isEnabled = urlToUse?.absoluteString.isEmpty == false
// Action: Remove
if !isInsertingNewLink {
alertController.addDestructiveActionWithTitle(removeTitle) { [weak self] action in
self?.trackFormatBarAnalytics(stat: .editorTappedUnlink)
self?.richTextView.becomeFirstResponder()
self?.richTextView.removeLink(inRange: range)
}
}
// Action: Cancel
alertController.addCancelActionWithTitle(cancelTitle) { [weak self] _ in
self?.richTextView.becomeFirstResponder()
}
present(alertController, animated: true, completion: nil)
}
func alertTextFieldDidChange(_ textField: UITextField) {
guard
let alertController = presentedViewController as? UIAlertController,
let urlFieldText = alertController.textFields?.first?.text,
let insertAction = alertController.actions.first
else {
return
}
insertAction.isEnabled = !urlFieldText.isEmpty
}
private var mediaInputToolbar: UIToolbar {
let toolbar = UIToolbar(frame: CGRect(x: 0, y: 0, width: view.frame.width, height: Constants.toolbarHeight))
toolbar.barTintColor = WPStyleGuide.aztecFormatBarBackgroundColor
toolbar.tintColor = WPStyleGuide.aztecFormatBarActiveColor
let gridButton = UIBarButtonItem(image: Gridicon.iconOfType(.grid), style: .plain, target: self, action: #selector(mediaAddShowFullScreen))
gridButton.accessibilityLabel = NSLocalizedString("Open full media picker", comment: "Editor button to swich the media picker from quick mode to full picker")
toolbar.items = [
UIBarButtonItem(barButtonSystemItem: .cancel, target: self, action: #selector(mediaAddInputCancelled)),
UIBarButtonItem(barButtonSystemItem: .flexibleSpace, target: nil, action: nil),
gridButton,
UIBarButtonItem(barButtonSystemItem: .flexibleSpace, target: nil, action: nil),
UIBarButtonItem(barButtonSystemItem: .done, target: self, action: #selector(mediaAddInputDone))
]
for item in toolbar.items! {
item.tintColor = WPStyleGuide.aztecFormatBarActiveColor
item.setTitleTextAttributes([NSForegroundColorAttributeName: WPStyleGuide.aztecFormatBarActiveColor], for: .normal)
}
return toolbar
}
// MARK: - Media Input toolbar button actions
/// Method to be called when the grid icon is pressed on the media input toolbar.
///
/// - Parameter sender: the button that was pressed.
func mediaAddShowFullScreen(_ sender: UIBarButtonItem) {
presentMediaPickerFullScreen(animated: true)
restoreInputAssistantItems()
}
/// Method to be called when canceled is pressed.
///
/// - Parameter sender: the button that was pressed.
func mediaAddInputCancelled(_ sender: UIBarButtonItem) {
guard let mediaPicker = mediaPickerInputViewController?.mediaPicker else {
return
}
mediaPickerControllerDidCancel(mediaPicker)
restoreInputAssistantItems()
}
/// Method to be called when done is pressed on the media input toolbar.
///
/// - Parameter sender: the button that was pressed.
func mediaAddInputDone(_ sender: UIBarButtonItem) {
guard let mediaPicker = mediaPickerInputViewController?.mediaPicker
else {
return
}
let selectedAssets = mediaPicker.selectedAssets
mediaPickerController(mediaPicker, didFinishPicking: selectedAssets)
restoreInputAssistantItems()
}
func restoreInputAssistantItems() {
richTextView.inputAssistantItem.leadingBarButtonGroups = originalLeadingBarButtonGroup
richTextView.inputAssistantItem.trailingBarButtonGroups = originalTrailingBarButtonGroup
richTextView.autocorrectionType = .yes
richTextView.reloadInputViews()
}
@IBAction func presentMediaPicker() {
if let item = formatBar.leadingItem {
presentMediaPicker(fromButton: item, animated: true)
}
}
fileprivate func presentMediaPickerFullScreen(animated: Bool, dataSourceType: MediaPickerDataSourceType = .device) {
let options = WPMediaPickerOptions()
options.showMostRecentFirst = true
options.filter = [.all]
options.allowCaptureOfMedia = false
let picker = WPNavigationMediaPickerViewController()
switch dataSourceType {
case .device:
picker.dataSource = devicePhotoLibraryDataSource
case .mediaLibrary:
picker.startOnGroupSelector = false
picker.showGroupSelector = false
picker.dataSource = mediaLibraryDataSource
}
picker.selectionActionTitle = Constants.mediaPickerInsertText
picker.mediaPicker.options = options
picker.delegate = self
picker.modalPresentationStyle = .currentContext
if let previousPicker = mediaPickerInputViewController?.mediaPicker {
picker.mediaPicker.selectedAssets = previousPicker.selectedAssets
}
present(picker, animated: true)
}
private func toggleMediaPicker(fromButton button: UIButton) {
if mediaPickerInputViewController != nil {
closeMediaPickerInputViewController()
trackFormatBarAnalytics(stat: .editorMediaPickerTappedDismiss)
} else {
presentMediaPicker(fromButton: button, animated: true)
}
}
private func presentMediaPicker(fromButton button: UIButton, animated: Bool = true) {
trackFormatBarAnalytics(stat: .editorTappedImage)
let options = WPMediaPickerOptions()
options.showMostRecentFirst = true
options.filter = [WPMediaType.image, WPMediaType.video]
options.allowMultipleSelection = true
options.allowCaptureOfMedia = false
options.scrollVertically = true
let picker = WPInputMediaPickerViewController(options: options)
mediaPickerInputViewController = picker
updateToolbar(formatBar, forMode: .media)
originalLeadingBarButtonGroup = richTextView.inputAssistantItem.leadingBarButtonGroups
originalTrailingBarButtonGroup = richTextView.inputAssistantItem.trailingBarButtonGroups
richTextView.inputAssistantItem.leadingBarButtonGroups = []
richTextView.inputAssistantItem.trailingBarButtonGroups = []
richTextView.autocorrectionType = .no
picker.mediaPicker.viewControllerToUseToPresent = self
picker.dataSource = WPPHAssetDataSource.sharedInstance()
picker.mediaPicker.mediaPickerDelegate = self
if currentKeyboardFrame != .zero {
// iOS is not adjusting the media picker's height to match the default keyboard's height when autoresizingMask
// is set to UIViewAutoresizingFlexibleHeight (even though the docs claim it should). Need to manually
// set the picker's frame to the current keyboard's frame.
picker.view.autoresizingMask = []
picker.view.frame = CGRect(x: 0, y: 0, width: currentKeyboardFrame.width, height: mediaKeyboardHeight)
}
presentToolbarViewControllerAsInputView(picker)
}
func toggleEditingMode() {
if mediaProgressCoordinator.isRunning {
displayMediaIsUploadingAlert()
return
}
if mediaProgressCoordinator.hasFailedMedia {
displayHasFailedMediaAlert(then: {
self.toggleEditingMode()
})
return
}
trackFormatBarAnalytics(stat: .editorTappedHTML)
formatBar.overflowToolbar(expand: true)
mode.toggle()
}
func toggleHeader(fromItem item: FormatBarItem) {
trackFormatBarAnalytics(stat: .editorTappedHeader)
let headerOptions = Constants.headers.map { headerType -> OptionsTableViewOption in
let attributes = [
NSFontAttributeName: UIFont.systemFont(ofSize: CGFloat(headerType.fontSize)),
NSForegroundColorAttributeName: WPStyleGuide.darkGrey()
]
let title = NSAttributedString(string: headerType.description, attributes: attributes)
return OptionsTableViewOption(image: headerType.iconImage,
title: title,
accessibilityLabel: headerType.accessibilityLabel)
}
let selectedIndex = Constants.headers.index(of: self.headerLevelForSelectedText())
showOptionsTableViewControllerWithOptions(headerOptions,
fromBarItem: item,
selectedRowIndex: selectedIndex,
onSelect: { [weak self] selected in
guard let range = self?.richTextView.selectedRange else { return }
let selectedStyle = Analytics.headerStyleValues[selected]
self?.trackFormatBarAnalytics(stat: .editorTappedHeaderSelection, headingStyle: selectedStyle)
self?.richTextView.toggleHeader(Constants.headers[selected], range: range)
self?.optionsViewController = nil
self?.changeRichTextInputView(to: nil)
})
}
func insertHorizontalRuler() {
trackFormatBarAnalytics(stat: .editorTappedHorizontalRule)
richTextView.replaceWithHorizontalRuler(at: richTextView.selectedRange)
}
func insertMore() {
trackFormatBarAnalytics(stat: .editorTappedMore)
richTextView.replace(richTextView.selectedRange, withComment: Constants.moreAttachmentText)
}
func headerLevelForSelectedText() -> Header.HeaderType {
var identifiers = [FormattingIdentifier]()
if richTextView.selectedRange.length > 0 {
identifiers = richTextView.formatIdentifiersSpanningRange(richTextView.selectedRange)
} else {
identifiers = richTextView.formatIdentifiersForTypingAttributes()
}
let mapping: [FormattingIdentifier: Header.HeaderType] = [
.header1: .h1,
.header2: .h2,
.header3: .h3,
.header4: .h4,
.header5: .h5,
.header6: .h6,
]
for (key, value) in mapping {
if identifiers.contains(key) {
return value
}
}
return .none
}
private func showDocumentPicker() {
let docTypes = [String(kUTTypeImage), String(kUTTypeMovie)]
let docPicker = UIDocumentPickerViewController(documentTypes: docTypes, in: .import)
docPicker.delegate = self
WPStyleGuide.configureDocumentPickerNavBarAppearance()
present(docPicker, animated: true, completion: nil)
}
// MARK: - Present Toolbar related VC
fileprivate func dismissOptionsViewControllerIfNecessary() {
guard optionsViewController != nil else {
return
}
dismissOptionsViewController()
}
func showOptionsTableViewControllerWithOptions(_ options: [OptionsTableViewOption],
fromBarItem barItem: FormatBarItem,
selectedRowIndex index: Int?,
onSelect: OptionsTableViewController.OnSelectHandler?) {
// Hide the input view if we're already showing these options
if let optionsViewController = optionsViewController ?? (presentedViewController as? OptionsTableViewController), optionsViewController.options == options {
self.optionsViewController = nil
changeRichTextInputView(to: nil)
return
}
optionsViewController = OptionsTableViewController(options: options)
optionsViewController.cellDeselectedTintColor = WPStyleGuide.aztecFormatBarInactiveColor
optionsViewController.cellBackgroundColor = WPStyleGuide.aztecFormatPickerBackgroundColor
optionsViewController.cellSelectedBackgroundColor = WPStyleGuide.aztecFormatPickerSelectedCellBackgroundColor
optionsViewController.view.tintColor = WPStyleGuide.aztecFormatBarActiveColor
optionsViewController.onSelect = { [weak self] selected in
onSelect?(selected)
self?.dismissOptionsViewController()
}
let selectRow = {
guard let index = index else {
return
}
self.optionsViewController?.selectRow(at: index)
}
if UIDevice.current.userInterfaceIdiom == .pad {
presentToolbarViewController(optionsViewController, asPopoverFromBarItem: barItem, completion: selectRow)
} else {
presentToolbarViewControllerAsInputView(optionsViewController)
selectRow()
}
}
private func presentToolbarViewController(_ viewController: UIViewController,
asPopoverFromBarItem barItem: FormatBarItem,
completion: (() -> Void)? = nil) {
viewController.modalPresentationStyle = .popover
viewController.popoverPresentationController?.permittedArrowDirections = [.down]
viewController.popoverPresentationController?.sourceView = view
let frame = barItem.superview?.convert(barItem.frame, to: UIScreen.main.coordinateSpace)
optionsViewController.popoverPresentationController?.sourceRect = view.convert(frame!, from: UIScreen.main.coordinateSpace)
optionsViewController.popoverPresentationController?.backgroundColor = WPStyleGuide.aztecFormatPickerBackgroundColor
optionsViewController.popoverPresentationController?.delegate = self
present(viewController, animated: true, completion: completion)
}
private func presentToolbarViewControllerAsInputView(_ viewController: UIViewController) {
self.addChildViewController(viewController)
changeRichTextInputView(to: viewController.view)
viewController.didMove(toParentViewController: self)
}
private func dismissOptionsViewController() {
switch UIDevice.current.userInterfaceIdiom {
case .pad:
dismiss(animated: true, completion: nil)
default:
optionsViewController?.removeFromParentViewController()
changeRichTextInputView(to: nil)
}
optionsViewController = nil
}
func changeRichTextInputView(to: UIView?) {
guard richTextView.inputView != to else {
return
}
richTextView.inputView = to
richTextView.reloadInputViews()
}
fileprivate func trackFormatBarAnalytics(stat: WPAnalyticsStat, action: String? = nil, headingStyle: String? = nil) {
var properties = [WPAppAnalyticsKeyEditorSource: Analytics.editorSource]
if let action = action {
properties["action"] = action
}
if let headingStyle = headingStyle {
properties["heading_style"] = headingStyle
}
WPAppAnalytics.track(stat, withProperties: properties, with: post)
}
// MARK: - Toolbar creation
// Used to determine which icons to show on the format bar
fileprivate enum FormatBarMode {
case text
case media
}
fileprivate func updateToolbar(_ toolbar: Aztec.FormatBar, forMode mode: FormatBarMode) {
if let leadingItem = toolbar.leadingItem {
rotateMediaToolbarItem(leadingItem, forMode: mode)
}
toolbar.trailingItem = nil
switch mode {
case .text:
toolbar.setDefaultItems(scrollableItemsForToolbar,
overflowItems: overflowItemsForToolbar)
case .media:
toolbar.setDefaultItems(mediaItemsForToolbar,
overflowItems: [])
}
}
private func rotateMediaToolbarItem(_ item: UIButton, forMode mode: FormatBarMode) {
let transform: CGAffineTransform
let accessibilityIdentifier: String
let accessibilityLabel: String
switch mode {
case .text:
accessibilityIdentifier = FormattingIdentifier.media.accessibilityIdentifier
accessibilityLabel = FormattingIdentifier.media.accessibilityLabel
transform = .identity
case .media:
accessibilityIdentifier = "format_toolbar_close_media"
accessibilityLabel = NSLocalizedString("Close Media Picker", comment: "Accessibility label for button that closes the media picker on formatting toolbar")
transform = CGAffineTransform(rotationAngle: Constants.Animations.formatBarMediaButtonRotationAngle)
}
let animator = UIViewPropertyAnimator(duration: Constants.Animations.formatBarMediaButtonRotationDuration,
curve: .easeInOut) {
item.transform = transform
}
animator.addCompletion({ position in
if position == .end {
item.accessibilityIdentifier = accessibilityIdentifier
item.accessibilityLabel = accessibilityLabel
}
})
animator.startAnimation()
}
func makeToolbarButton(identifier: FormattingIdentifier) -> FormatBarItem {
return makeToolbarButton(identifier: identifier.rawValue, provider: identifier)
}
func makeToolbarButton(identifier: FormatBarMediaIdentifier) -> FormatBarItem {
return makeToolbarButton(identifier: identifier.rawValue, provider: identifier)
}
func makeToolbarButton(identifier: String, provider: FormatBarItemProvider) -> FormatBarItem {
let button = FormatBarItem(image: provider.iconImage, identifier: identifier)
button.accessibilityLabel = provider.accessibilityLabel
button.accessibilityIdentifier = provider.accessibilityIdentifier
return button
}
func createToolbar() -> Aztec.FormatBar {
let toolbar = Aztec.FormatBar()
toolbar.tintColor = WPStyleGuide.aztecFormatBarInactiveColor
toolbar.highlightedTintColor = WPStyleGuide.aztecFormatBarActiveColor
toolbar.selectedTintColor = WPStyleGuide.aztecFormatBarActiveColor
toolbar.disabledTintColor = WPStyleGuide.aztecFormatBarDisabledColor
toolbar.dividerTintColor = WPStyleGuide.aztecFormatBarDividerColor
toolbar.overflowToggleIcon = Gridicon.iconOfType(.ellipsis)
toolbar.leadingItem = makeToolbarButton(identifier: .media)
updateToolbar(toolbar, forMode: .text)
toolbar.frame = CGRect(x: 0, y: 0, width: view.frame.width, height: Constants.toolbarHeight)
toolbar.formatter = self
toolbar.barItemHandler = { [weak self] item in
self?.handleAction(for: item)
}
toolbar.leadingItemHandler = { [weak self] item in
self?.handleFormatBarLeadingItem(item)
}
toolbar.trailingItemHandler = { [weak self] item in
self?.handleFormatBarTrailingItem(item)
}
return toolbar
}
var mediaItemsForToolbar: [FormatBarItem] {
var toolbarButtons = [makeToolbarButton(identifier: .deviceLibrary)]
if UIImagePickerController.isSourceTypeAvailable(.camera) {
toolbarButtons.append(makeToolbarButton(identifier: .camera))
}
toolbarButtons.append(makeToolbarButton(identifier: .mediaLibrary))
if #available(iOS 11, *), FeatureFlag.iCloudFilesSupport.enabled {
toolbarButtons.append(makeToolbarButton(identifier: .otherApplications))
}
return toolbarButtons
}
var scrollableItemsForToolbar: [FormatBarItem] {
let headerButton = makeToolbarButton(identifier: .p)
var alternativeIcons = [String: UIImage]()
let headings = Constants.headers.suffix(from: 1) // Remove paragraph style
for heading in headings {
alternativeIcons[heading.formattingIdentifier.rawValue] = heading.iconImage
}
headerButton.alternativeIcons = alternativeIcons
let listButton = makeToolbarButton(identifier: .unorderedlist)
var listIcons = [String: UIImage]()
for list in Constants.lists {
listIcons[list.formattingIdentifier.rawValue] = list.iconImage
}
listButton.alternativeIcons = listIcons
return [
headerButton,
listButton,
makeToolbarButton(identifier: .blockquote),
makeToolbarButton(identifier: .bold),
makeToolbarButton(identifier: .italic),
makeToolbarButton(identifier: .link)
]
}
var overflowItemsForToolbar: [FormatBarItem] {
return [
makeToolbarButton(identifier: .underline),
makeToolbarButton(identifier: .strikethrough),
makeToolbarButton(identifier: .horizontalruler),
makeToolbarButton(identifier: .more),
makeToolbarButton(identifier: .sourcecode)
]
}
}
// MARK: - UINavigationControllerDelegate Conformance
//
extension AztecPostViewController: UINavigationControllerDelegate {
}
// MARK: - UIPopoverPresentationControllerDelegate
//
extension AztecPostViewController: UIPopoverPresentationControllerDelegate {
func adaptivePresentationStyle(for controller: UIPresentationController, traitCollection: UITraitCollection) -> UIModalPresentationStyle {
return .none
}
func popoverPresentationControllerDidDismissPopover(_ popoverPresentationController: UIPopoverPresentationController) {
if optionsViewController != nil {
optionsViewController = nil
}
}
}
// MARK: - Unknown HTML
//
private extension AztecPostViewController {
func displayUnknownHtmlEditor(for attachment: HTMLAttachment) {
let targetVC = UnknownEditorViewController(attachment: attachment)
targetVC.onDidSave = { [weak self] html in
self?.richTextView.edit(attachment) { htmlAttachment in
htmlAttachment.rawHTML = html
}
self?.dismiss(animated: true, completion: nil)
}
targetVC.onDidCancel = { [weak self] in
self?.dismiss(animated: true, completion: nil)
}
let navigationController = UINavigationController(rootViewController: targetVC)
displayAsPopover(viewController: navigationController)
}
func displayAsPopover(viewController: UIViewController) {
viewController.modalPresentationStyle = .popover
viewController.preferredContentSize = view.frame.size
let presentationController = viewController.popoverPresentationController
presentationController?.sourceView = view
presentationController?.delegate = self
present(viewController, animated: true, completion: nil)
}
}
// MARK: - Cancel/Dismiss/Persistence Logic
//
private extension AztecPostViewController {
// TODO: Rip this out and put it into the PostService
func createRevisionOfPost() {
guard let context = post.managedObjectContext else {
return
}
// Using performBlock: with the AbstractPost on the main context:
// Prevents a hang on opening this view on slow and fast devices
// by deferring the cloning and UI update.
// Slower devices have the effect of the content appearing after
// a short delay
context.performAndWait {
self.post = self.post.createRevision()
ContextManager.sharedInstance().save(context)
}
}
// TODO: Rip this and put it into PostService, as well
func recreatePostRevision(in blog: Blog) {
let shouldCreatePage = post is Page
let postService = PostService(managedObjectContext: mainContext)
let newPost = shouldCreatePage ? postService.createDraftPage(for: blog) : postService.createDraftPost(for: blog)
newPost.content = contentByStrippingMediaAttachments()
newPost.postTitle = post.postTitle
newPost.password = post.password
newPost.status = post.status
newPost.dateCreated = post.dateCreated
newPost.dateModified = post.dateModified
if let source = post as? Post, let target = newPost as? Post {
target.tags = source.tags
}
discardChanges()
post = newPost
createRevisionOfPost()
RecentSitesService().touch(blog: blog)
// TODO: Add this snippet, if needed, once we've relocated this helper to PostService
//[self syncOptionsIfNecessaryForBlog:blog afterBlogChanged:YES];
}
func cancelEditing() {
stopEditing()
if post.canSave() && post.hasUnsavedChanges() {
showPostHasChangesAlert()
} else {
discardChangesAndUpdateGUI()
}
}
func stopEditing() {
view.endEditing(true)
}
func discardChanges() {
guard let context = post.managedObjectContext, let originalPost = post.original else {
return
}
WPAppAnalytics.track(.editorDiscardedChanges, withProperties: [WPAppAnalyticsKeyEditorSource: Analytics.editorSource], with: post)
post = originalPost
post.deleteRevision()
if shouldRemovePostOnDismiss {
post.remove()
}
mediaProgressCoordinator.cancelAllPendingUploads()
ContextManager.sharedInstance().save(context)
}
func discardChangesAndUpdateGUI() {
discardChanges()
dismissOrPopView(didSave: false)
}
func dismissOrPopView(didSave: Bool) {
stopEditing()
WPAppAnalytics.track(.editorClosed, withProperties: [WPAppAnalyticsKeyEditorSource: Analytics.editorSource], with: post)
if let onClose = onClose {
onClose(didSave)
} else if isModal() {
presentingViewController?.dismiss(animated: true, completion: nil)
} else {
_ = navigationController?.popViewController(animated: true)
}
}
func contentByStrippingMediaAttachments() -> String {
if mode == .html {
setHTML(htmlTextView.text)
}
richTextView.removeMediaAttachments()
let strippedHTML = getHTML()
if mode == .html {
setHTML(strippedHTML)
}
return strippedHTML
}
func mapUIContentToPostAndSave() {
post.postTitle = titleTextField.text
post.content = getHTML()
ContextManager.sharedInstance().save(post.managedObjectContext!)
}
func publishPost(completion: ((_ post: AbstractPost?, _ error: Error?) -> Void)? = nil) {
mapUIContentToPostAndSave()
let managedObjectContext = ContextManager.sharedInstance().mainContext
let postService = PostService(managedObjectContext: managedObjectContext)
postService.uploadPost(post, success: { uploadedPost in
completion?(uploadedPost, nil)
}) { error in
completion?(nil, error)
}
}
}
// MARK: - Computed Properties
//
private extension AztecPostViewController {
var mainContext: NSManagedObjectContext {
return ContextManager.sharedInstance().mainContext
}
var currentBlogCount: Int {
let service = BlogService(managedObjectContext: mainContext)
return service.blogCountForAllAccounts()
}
var isSingleSiteMode: Bool {
return currentBlogCount <= 1 || post.hasRemote()
}
/// Height to use for the inline media picker based on iOS version and screen orientation.
///
var mediaKeyboardHeight: CGFloat {
var keyboardHeight: CGFloat
// Let's assume a sensible default for the keyboard height based on orientation
let keyboardFrameRatioDefault = UIInterfaceOrientationIsPortrait(UIApplication.shared.statusBarOrientation) ? Constants.mediaPickerKeyboardHeightRatioPortrait : Constants.mediaPickerKeyboardHeightRatioLandscape
let keyboardHeightDefault = (keyboardFrameRatioDefault * UIScreen.main.bounds.height)
if #available(iOS 11, *) {
// On iOS 11, we need to make an assumption the hardware keyboard is attached based on
// the height of the current keyboard frame being less than our sensible default. If it is
// "attached", let's just use our default.
if currentKeyboardFrame.height < keyboardHeightDefault {
keyboardHeight = keyboardHeightDefault
} else {
keyboardHeight = (currentKeyboardFrame.height - Constants.toolbarHeight)
}
} else {
// On iOS 10, when the soft keyboard is visible, the keyboard's frame is within the dimensions of the screen.
// However, when an external keyboard is present, the keyboard's frame is located offscreen. Test to see if
// that is true and adjust the keyboard height as necessary.
if (currentKeyboardFrame.origin.y + currentKeyboardFrame.height) > view.frame.height {
keyboardHeight = (currentKeyboardFrame.maxY - view.frame.height)
} else {
keyboardHeight = (currentKeyboardFrame.height - Constants.toolbarHeight)
}
}
// Sanity check
keyboardHeight = max(keyboardHeight, keyboardHeightDefault)
return keyboardHeight
}
}
// MARK: - MediaProgressCoordinatorDelegate
//
extension AztecPostViewController: MediaProgressCoordinatorDelegate {
func configureMediaAppearance() {
MediaAttachment.defaultAppearance.progressBackgroundColor = Colors.mediaProgressBarBackground
MediaAttachment.defaultAppearance.progressColor = Colors.mediaProgressBarTrack
MediaAttachment.defaultAppearance.overlayColor = Colors.mediaProgressOverlay
MediaAttachment.defaultAppearance.overlayBorderWidth = Constants.mediaOverlayBorderWidth
MediaAttachment.defaultAppearance.overlayBorderColor = Colors.mediaOverlayBorderColor
}
func mediaProgressCoordinator(_ mediaProgressCoordinator: MediaProgressCoordinator, progressDidChange progress: Float) {
mediaProgressView.isHidden = !mediaProgressCoordinator.isRunning
mediaProgressView.progress = progress
for (attachmentID, progress) in self.mediaProgressCoordinator.mediaUploading {
guard let attachment = richTextView.attachment(withId: attachmentID) else {
continue
}
if progress.fractionCompleted >= 1 {
attachment.progress = nil
} else {
attachment.progress = progress.fractionCompleted
}
richTextView.refresh(attachment)
}
}
func mediaProgressCoordinatorDidStartUploading(_ mediaProgressCoordinator: MediaProgressCoordinator) {
postEditorStateContext.update(isUploadingMedia: true)
refreshNavigationBar()
}
func mediaProgressCoordinatorDidFinishUpload(_ mediaProgressCoordinator: MediaProgressCoordinator) {
postEditorStateContext.update(isUploadingMedia: false)
refreshNavigationBar()
}
}
// MARK: - Media Support
//
extension AztecPostViewController {
fileprivate func insertExternalMediaWithURL(_ url: URL) {
do {
var newAttachment: MediaAttachment?
var newStatType: WPAnalyticsStat?
let expected = try MediaURLExporter.expectedExport(with: url)
switch expected {
case .image:
newAttachment = imageAttachmentWithPlaceholder()
newStatType = .editorAddedPhotoViaOtherApps
case .video:
newAttachment = videoAttachmentWithPlaceholder()
newStatType = .editorAddedVideoViaOtherApps
default: break
}
guard let attachment = newAttachment, let statType = newStatType else { return }
let mediaService = MediaService(managedObjectContext: ContextManager.sharedInstance().mainContext)
mediaService.createMedia(url: url, forPost: post.objectID,
thumbnailCallback: { [weak self](thumbnailURL) in
self?.handleThumbnailURL(thumbnailURL, attachment: attachment)
},
completion: { [weak self](media, error) in
self?.handleNewMedia(media, error: error, attachment: attachment, statType: statType)
})
} catch {
print(MediaURLExporter().exporterErrorWith(error: error))
return
}
}
fileprivate func insertDeviceMedia(phAsset: PHAsset) {
switch phAsset.mediaType {
case .image:
insertDeviceImage(phAsset: phAsset)
case .video:
insertDeviceVideo(phAsset: phAsset)
default:
return
}
}
fileprivate func insertDeviceImage(phAsset: PHAsset) {
let attachment = imageAttachmentWithPlaceholder()
let mediaService = MediaService(managedObjectContext: ContextManager.sharedInstance().mainContext)
mediaService.createMedia(with: phAsset,
forPost: post.objectID,
thumbnailCallback: { [weak self](thumbnailURL) in
self?.handleThumbnailURL(thumbnailURL, attachment: attachment)
},
completion: { [weak self](media, error) in
self?.handleNewMedia(media, error: error, attachment: attachment, statType: .editorAddedPhotoViaLocalLibrary)
})
}
fileprivate func insertDeviceVideo(phAsset: PHAsset) {
let attachment = videoAttachmentWithPlaceholder()
let mediaService = MediaService(managedObjectContext: ContextManager.sharedInstance().mainContext)
mediaService.createMedia(with: phAsset,
forPost: post.objectID,
thumbnailCallback: { [weak self](thumbnailURL) in
self?.handleThumbnailURL(thumbnailURL, attachment: attachment)
},
completion: { [weak self](media, error) in
self?.handleNewMedia(media, error: error, attachment: attachment, statType: .editorAddedVideoViaLocalLibrary)
})
}
fileprivate func insertSiteMediaLibrary(media: Media) {
if media.hasRemote {
insertRemoteSiteMediaLibrary(media: media)
} else {
insertLocalSiteMediaLibrary(media: media)
}
}
private func imageAttachmentWithPlaceholder() -> ImageAttachment {
return richTextView.replaceWithImage(at: self.richTextView.selectedRange, sourceURL: URL(string: "placeholder://")!, placeHolderImage: Assets.defaultMissingImage)
}
private func videoAttachmentWithPlaceholder() -> VideoAttachment {
return richTextView.replaceWithVideo(at: richTextView.selectedRange, sourceURL: URL(string: "placeholder://")!, posterURL: URL(string: "placeholder://")!, placeHolderImage: Assets.defaultMissingImage)
}
private func handleThumbnailURL(_ thumbnailURL: URL, attachment: Any) {
DispatchQueue.main.async {
if let attachment = attachment as? ImageAttachment {
attachment.updateURL(thumbnailURL)
self.richTextView.refresh(attachment)
}
else if let attachment = attachment as? VideoAttachment {
attachment.posterURL = thumbnailURL
self.richTextView.refresh(attachment)
}
}
}
private func handleNewMedia(_ media: Media?, error: Error?, attachment: MediaAttachment, statType: WPAnalyticsStat) {
guard let media = media, error == nil else {
DispatchQueue.main.async {
self.handleError(error as NSError?, onAttachment: attachment)
}
return
}
WPAppAnalytics.track(statType, withProperties: WPAppAnalytics.properties(for: media, mediaOrigin: selectedMediaOrigin), with: post.blog)
upload(media: media, mediaID: attachment.identifier)
}
fileprivate func insertRemoteSiteMediaLibrary(media: Media) {
guard let remoteURLStr = media.remoteURL, let remoteURL = URL(string: remoteURLStr) else {
return
}
switch media.mediaType {
case .image:
let attachment = richTextView.replaceWithImage(at: richTextView.selectedRange, sourceURL: remoteURL, placeHolderImage: Assets.defaultMissingImage)
attachment.alt = media.alt
WPAppAnalytics.track(.editorAddedPhotoViaWPMediaLibrary, withProperties: WPAppAnalytics.properties(for: media, mediaOrigin: selectedMediaOrigin), with: post)
case .video:
var posterURL: URL?
if let posterURLString = media.remoteThumbnailURL {
posterURL = URL(string: posterURLString)
}
let attachment = richTextView.replaceWithVideo(at: richTextView.selectedRange, sourceURL: remoteURL, posterURL: posterURL, placeHolderImage: Assets.defaultMissingImage)
if let videoPressGUID = media.videopressGUID, !videoPressGUID.isEmpty {
attachment.videoPressID = videoPressGUID
richTextView.refresh(attachment)
}
WPAppAnalytics.track(.editorAddedVideoViaWPMediaLibrary, withProperties: WPAppAnalytics.properties(for: media, mediaOrigin: selectedMediaOrigin), with: post)
default:
// If we drop in here, let's just insert a link the the remote media
let linkTitle = media.title?.nonEmptyString() ?? remoteURLStr
richTextView.setLink(remoteURL, title: linkTitle, inRange: richTextView.selectedRange)
WPAppAnalytics.track(.editorAddedOtherMediaViaWPMediaLibrary, withProperties: WPAppAnalytics.properties(for: media, mediaOrigin: selectedMediaOrigin), with: post)
}
self.mediaProgressCoordinator.finishOneItem()
}
fileprivate func insertLocalSiteMediaLibrary(media: Media) {
var tempMediaURL = URL(string: "placeholder://")!
if let absoluteURL = media.absoluteLocalURL {
tempMediaURL = absoluteURL
}
var attachment: MediaAttachment?
if media.mediaType == .image {
attachment = self.richTextView.replaceWithImage(at: richTextView.selectedRange, sourceURL: tempMediaURL, placeHolderImage: Assets.defaultMissingImage)
WPAppAnalytics.track(.editorAddedPhotoViaWPMediaLibrary, withProperties: WPAppAnalytics.properties(for: media, mediaOrigin: selectedMediaOrigin), with: post)
} else if media.mediaType == .video,
let remoteURLStr = media.remoteURL,
let remoteURL = URL(string: remoteURLStr) {
attachment = richTextView.replaceWithVideo(at: richTextView.selectedRange, sourceURL: remoteURL, posterURL: media.absoluteThumbnailLocalURL, placeHolderImage: Assets.defaultMissingImage)
WPAppAnalytics.track(.editorAddedVideoViaWPMediaLibrary, withProperties: WPAppAnalytics.properties(for: media, mediaOrigin: selectedMediaOrigin), with: post)
}
if let attachment = attachment {
upload(media: media, mediaID: attachment.identifier)
}
}
fileprivate func saveToMedia(attachment: MediaAttachment) {
guard let image = attachment.image else {
return
}
mediaProgressCoordinator.track(numberOfItems: 1)
let mediaService = MediaService(managedObjectContext: ContextManager.sharedInstance().mainContext)
mediaService.createMedia(with: image, withMediaID: "CopyPasteImage", forPost: post.objectID, thumbnailCallback: { (thumbnailURL) in
DispatchQueue.main.async {
if let imageAttachment = attachment as? ImageAttachment {
imageAttachment.updateURL(thumbnailURL)
self.richTextView.refresh(imageAttachment)
}
}
}, completion: { [weak self](media, error) in
guard let strongSelf = self else {
return
}
guard let media = media, error == nil else {
DispatchQueue.main.async {
strongSelf.handleError(error as NSError?, onAttachment: attachment)
}
return
}
if media.mediaType == .image {
WPAppAnalytics.track(.editorAddedPhotoViaLocalLibrary, withProperties: WPAppAnalytics.properties(for: media, mediaOrigin: strongSelf.selectedMediaOrigin), with: strongSelf.post.blog)
} else if media.mediaType == .video {
WPAppAnalytics.track(.editorAddedVideoViaLocalLibrary, withProperties: WPAppAnalytics.properties(for: media, mediaOrigin: strongSelf.selectedMediaOrigin), with: strongSelf.post.blog)
}
strongSelf.upload(media: media, mediaID: attachment.identifier)
})
}
private func upload(media: Media, mediaID: String) {
guard let attachment = richTextView.attachment(withId: mediaID) else {
return
}
let mediaService = MediaService(managedObjectContext: ContextManager.sharedInstance().mainContext)
var uploadProgress: Progress?
mediaService.uploadMedia(media, progress: &uploadProgress, success: { _ in
guard let remoteURLStr = media.remoteURL, let remoteURL = URL(string: remoteURLStr) else {
return
}
DispatchQueue.main.async {
if let imageAttachment = attachment as? ImageAttachment {
if let width = media.width?.intValue {
imageAttachment.width = width
}
if let height = media.height?.intValue {
imageAttachment.height = height
}
if let mediaID = media.mediaID?.intValue {
imageAttachment.imageID = mediaID
}
imageAttachment.updateURL(remoteURL, refreshAsset: false)
} else if let videoAttachment = attachment as? VideoAttachment, let videoURLString = media.remoteURL {
videoAttachment.srcURL = URL(string: videoURLString)
if let videoPosterURLString = media.remoteThumbnailURL {
videoAttachment.posterURL = URL(string: videoPosterURLString)
}
if let videoPressGUID = media.videopressGUID, !videoPressGUID.isEmpty {
videoAttachment.videoPressID = videoPressGUID
}
}
}
}, failure: { [weak self] error in
guard let strongSelf = self else {
return
}
WPAppAnalytics.track(.editorUploadMediaFailed, withProperties: [WPAppAnalyticsKeyEditorSource: Analytics.editorSource], with: strongSelf.post.blog)
DispatchQueue.main.async {
strongSelf.handleError(error as NSError?, onAttachment: attachment)
}
})
if let progress = uploadProgress {
mediaProgressCoordinator.track(progress: progress, ofObject: media, withMediaID: mediaID)
}
}
private func handleError(_ error: NSError?, onAttachment attachment: Aztec.MediaAttachment) {
let message = NSLocalizedString("Failed to insert media.\n Please tap for options.", comment: "Error message to show to use when media insertion on a post fails")
if let error = error {
if error.domain == NSURLErrorDomain && error.code == NSURLErrorCancelled {
self.richTextView.remove(attachmentID: attachment.identifier)
return
}
mediaProgressCoordinator.attach(error: error, toMediaID: attachment.identifier)
}
let attributeMessage = NSAttributedString(string: message, attributes: mediaMessageAttributes)
attachment.message = attributeMessage
attachment.overlayImage = Gridicon.iconOfType(.refresh, withSize: Constants.mediaOverlayIconSize)
attachment.shouldHideBorder = true
richTextView.refresh(attachment)
}
fileprivate func removeFailedMedia() {
let failedMediaIDs = mediaProgressCoordinator.failedMediaIDs
for mediaID in failedMediaIDs {
richTextView.remove(attachmentID: mediaID)
mediaProgressCoordinator.cancelAndStopTrack(of: mediaID)
}
}
fileprivate func processVideoPressAttachments() {
richTextView.textStorage.enumerateAttachments { (attachment, range) in
if let videoAttachment = attachment as? VideoAttachment,
let videoSrcURL = videoAttachment.srcURL,
videoSrcURL.scheme == VideoShortcodeProcessor.videoPressScheme,
let videoPressID = videoSrcURL.host {
// It's videoPress video so let's fetch the information for the video
let mediaService = MediaService(managedObjectContext: ContextManager.sharedInstance().mainContext)
mediaService.getMediaURL(fromVideoPressID: videoPressID, in: self.post.blog, success: { (videoURLString, posterURLString) in
videoAttachment.srcURL = URL(string: videoURLString)
if let validPosterURLString = posterURLString, let posterURL = URL(string: validPosterURLString) {
videoAttachment.posterURL = posterURL
}
self.richTextView.refresh(videoAttachment)
}, failure: { (error) in
DDLogError("Unable to find information for VideoPress video with ID = \(videoPressID). Details: \(error.localizedDescription)")
})
} else if let videoAttachment = attachment as? VideoAttachment,
let videoSrcURL = videoAttachment.srcURL,
videoAttachment.posterURL == nil {
let asset = AVURLAsset(url: videoSrcURL as URL, options: nil)
let imgGenerator = AVAssetImageGenerator(asset: asset)
imgGenerator.maximumSize = .zero
imgGenerator.appliesPreferredTrackTransform = true
let timeToCapture = NSValue(time: CMTimeMake(0, 1))
imgGenerator.generateCGImagesAsynchronously(forTimes: [timeToCapture],
completionHandler: { (time, cgImage, actualTime, result, error) in
guard let cgImage = cgImage else {
return
}
let uiImage = UIImage(cgImage: cgImage)
let url = self.URLForTemporaryFileWithFileExtension(".jpg")
do {
try uiImage.writeJPEGToURL(url)
DispatchQueue.main.async {
videoAttachment.posterURL = url
self.richTextView.refresh(videoAttachment)
}
} catch {
DDLogError("Unable to grab frame from video = \(videoSrcURL). Details: \(error.localizedDescription)")
}
})
}
}
}
private func URLForTemporaryFileWithFileExtension(_ fileExtension: String) -> URL {
assert(!fileExtension.isEmpty, "file Extension cannot be empty")
let fileName = "\(ProcessInfo.processInfo.globallyUniqueString)_file.\(fileExtension)"
let fileURL = URL(fileURLWithPath: NSTemporaryDirectory()).appendingPathComponent(fileName)
return fileURL
}
// TODO: Extract these strings into structs like other items
fileprivate func displayActions(forAttachment attachment: MediaAttachment, position: CGPoint) {
let mediaID = attachment.identifier
let title: String = NSLocalizedString("Media Options", comment: "Title for action sheet with media options.")
var message: String?
let alertController = UIAlertController(title: title, message: nil, preferredStyle: .actionSheet)
alertController.addActionWithTitle(NSLocalizedString("Dismiss", comment: "User action to dismiss media options."),
style: .cancel,
handler: { (action) in
if attachment == self.currentSelectedAttachment {
self.currentSelectedAttachment = nil
self.resetMediaAttachmentOverlay(attachment)
self.richTextView.refresh(attachment)
}
})
if let imageAttachment = attachment as? ImageAttachment {
alertController.preferredAction = alertController.addActionWithTitle(NSLocalizedString("Edit", comment: "User action to edit media details."),
style: .default,
handler: { (action) in
self.displayDetails(forAttachment: imageAttachment)
})
} else if let videoAttachment = attachment as? VideoAttachment,
mediaProgressCoordinator.error(forMediaID: mediaID) == nil,
!mediaProgressCoordinator.isMediaUploading(mediaID: mediaID) {
alertController.preferredAction = alertController.addActionWithTitle(NSLocalizedString("Play Video", comment: "User action to play a video on the editor."),
style: .default,
handler: { (action) in
self.displayPlayerFor(videoAttachment: videoAttachment, atPosition: position)
})
}
// Is upload still going?
if let mediaProgress = mediaProgressCoordinator.progress(forMediaID: mediaID),
mediaProgress.completedUnitCount < mediaProgress.totalUnitCount {
alertController.addActionWithTitle(NSLocalizedString("Stop Upload", comment: "User action to stop upload."),
style: .destructive,
handler: { (action) in
mediaProgress.cancel()
self.richTextView.remove(attachmentID: mediaID)
})
} else {
if let error = mediaProgressCoordinator.error(forMediaID: mediaID) {
message = error.localizedDescription
alertController.addActionWithTitle(NSLocalizedString("Retry Upload", comment: "User action to retry media upload."),
style: .default,
handler: { (action) in
//retry upload
if let media = self.mediaProgressCoordinator.object(forMediaID: mediaID) as? Media,
let attachment = self.richTextView.attachment(withId: mediaID) {
self.resetMediaAttachmentOverlay(attachment)
attachment.progress = 0
self.richTextView.refresh(attachment)
self.mediaProgressCoordinator.track(numberOfItems: 1)
WPAppAnalytics.track(.editorUploadMediaRetried, withProperties: [WPAppAnalyticsKeyEditorSource: Analytics.editorSource], with: self.post.blog)
self.upload(media: media, mediaID: mediaID)
}
})
}
alertController.addActionWithTitle(NSLocalizedString("Remove", comment: "User action to remove media."),
style: .destructive,
handler: { (action) in
self.richTextView.remove(attachmentID: mediaID)
})
}
alertController.title = title
alertController.message = message
alertController.popoverPresentationController?.sourceView = richTextView
alertController.popoverPresentationController?.sourceRect = CGRect(origin: position, size: CGSize(width: 1, height: 1))
alertController.popoverPresentationController?.permittedArrowDirections = .any
present(alertController, animated: true, completion: { () in
UIMenuController.shared.setMenuVisible(false, animated: false)
})
}
func displayDetails(forAttachment attachment: ImageAttachment) {
let controller = AztecAttachmentViewController()
controller.attachment = attachment
controller.onUpdate = { [weak self] (alignment, size, alt) in
self?.richTextView.edit(attachment) { updated in
updated.alignment = alignment
updated.size = size
updated.alt = alt
}
}
controller.onCancel = { [weak self] in
if attachment == self?.currentSelectedAttachment {
self?.currentSelectedAttachment = nil
self?.resetMediaAttachmentOverlay(attachment)
self?.richTextView.refresh(attachment)
}
}
let navController = UINavigationController(rootViewController: controller)
navController.modalPresentationStyle = .formSheet
present(navController, animated: true, completion: nil)
WPAppAnalytics.track(.editorEditedImage, withProperties: [WPAppAnalyticsKeyEditorSource: Analytics.editorSource], with: post)
}
var mediaMessageAttributes: [String: Any] {
let paragraphStyle = NSMutableParagraphStyle()
paragraphStyle.alignment = .center
let attributes: [String: Any] = [NSFontAttributeName: Fonts.mediaOverlay,
NSParagraphStyleAttributeName: paragraphStyle,
NSForegroundColorAttributeName: UIColor.white]
return attributes
}
func placeholderImage(for attachment: NSTextAttachment) -> UIImage {
let imageSize = CGSize(width: 128, height: 128)
let icon: UIImage
switch attachment {
case _ as ImageAttachment:
icon = Gridicon.iconOfType(.image, withSize: imageSize)
case _ as VideoAttachment:
icon = Gridicon.iconOfType(.video, withSize: imageSize)
default:
icon = Gridicon.iconOfType(.attachment, withSize: imageSize)
}
icon.addAccessibilityForAttachment(attachment)
return icon
}
// [2017-08-30] We need to auto-close the input media picker when multitasking panes are resized - iOS
// is dropping the input picker's view from the view hierarchy. Not an ideal solution, but prevents
// the user from seeing an empty grey rect as a keyboard. Issue affects the 7.9", 9.7", and 10.5"
// iPads only...not the 12.9"
// See http://www.openradar.me/radar?id=4972612522344448 for more details.
func applicationWillResignActive(_ notification: Foundation.Notification) {
if UIDevice.isPad() {
closeMediaPickerInputViewController()
}
}
func closeMediaPickerInputViewController() {
guard mediaPickerInputViewController != nil else {
return
}
mediaPickerInputViewController = nil
changeRichTextInputView(to: nil)
updateToolbar(formatBar, forMode: .text)
restoreInputAssistantItems()
}
fileprivate func resetMediaAttachmentOverlay(_ mediaAttachment: MediaAttachment) {
if mediaAttachment is ImageAttachment {
mediaAttachment.overlayImage = nil
}
mediaAttachment.message = nil
mediaAttachment.shouldHideBorder = false
}
}
// MARK: - TextViewAttachmentDelegate Conformance
//
extension AztecPostViewController: TextViewAttachmentDelegate {
public func textView(_ textView: TextView, selected attachment: NSTextAttachment, atPosition position: CGPoint) {
if !richTextView.isFirstResponder {
richTextView.becomeFirstResponder()
}
switch attachment {
case let attachment as HTMLAttachment:
displayUnknownHtmlEditor(for: attachment)
case let attachment as MediaAttachment:
selected(textAttachment: attachment, atPosition: position)
default:
break
}
}
func selected(textAttachment attachment: MediaAttachment, atPosition position: CGPoint) {
// Check to see if this is an error
if mediaProgressCoordinator.error(forMediaID: attachment.identifier) == nil {
// If it's a new attachment tapped let's unmark the previous one...
if let selectedAttachment = currentSelectedAttachment {
self.resetMediaAttachmentOverlay(selectedAttachment)
richTextView.refresh(selectedAttachment)
}
// ...and mark the newly tapped attachment
let message = ""
attachment.message = NSAttributedString(string: message, attributes: mediaMessageAttributes)
richTextView.refresh(attachment)
currentSelectedAttachment = attachment
}
// Display the action sheet right away
displayActions(forAttachment: attachment, position: position)
}
func displayPlayerFor(videoAttachment: VideoAttachment, atPosition position: CGPoint) {
guard let videoURL = videoAttachment.srcURL else {
return
}
if let videoPressID = videoAttachment.videoPressID {
// It's videoPress video so let's fetch the information for the video
let mediaService = MediaService(managedObjectContext: ContextManager.sharedInstance().mainContext)
mediaService.getMediaURL(fromVideoPressID: videoPressID, in: self.post.blog, success: { (videoURLString, posterURLString) in
guard let videoURL = URL(string: videoURLString) else {
return
}
videoAttachment.srcURL = videoURL
if let validPosterURLString = posterURLString, let posterURL = URL(string: validPosterURLString) {
videoAttachment.posterURL = posterURL
}
self.richTextView.refresh(videoAttachment)
self.displayVideoPlayer(for: videoURL)
}, failure: { (error) in
DDLogError("Unable to find information for VideoPress video with ID = \(videoPressID). Details: \(error.localizedDescription)")
})
} else {
displayVideoPlayer(for: videoURL)
}
}
func displayVideoPlayer(for videoURL: URL) {
let asset = AVURLAsset(url: videoURL)
let controller = AVPlayerViewController()
let playerItem = AVPlayerItem(asset: asset)
let player = AVPlayer(playerItem: playerItem)
controller.showsPlaybackControls = true
controller.player = player
player.play()
present(controller, animated: true, completion: nil)
}
public func textView(_ textView: TextView, deselected attachment: NSTextAttachment, atPosition position: CGPoint) {
deselected(textAttachment: attachment, atPosition: position)
}
func deselected(textAttachment attachment: NSTextAttachment, atPosition position: CGPoint) {
currentSelectedAttachment = nil
if let mediaAttachment = attachment as? MediaAttachment {
self.resetMediaAttachmentOverlay(mediaAttachment)
richTextView.refresh(mediaAttachment)
}
}
func textView(_ textView: TextView, attachment: NSTextAttachment, imageAt url: URL, onSuccess success: @escaping (UIImage) -> Void, onFailure failure: @escaping () -> Void) {
var requestURL = url
let imageMaxDimension = max(UIScreen.main.bounds.size.width, UIScreen.main.bounds.size.height)
//use height zero to maintain the aspect ratio when fetching
var size = CGSize(width: imageMaxDimension, height: 0)
let request: URLRequest
if url.isFileURL {
request = URLRequest(url: url)
} else if self.post.blog.isPrivate() {
// private wpcom image needs special handling.
// the size that WPImageHelper expects is pixel size
size.width = size.width * UIScreen.main.scale
requestURL = WPImageURLHelper.imageURLWithSize(size, forImageURL: requestURL)
request = PrivateSiteURLProtocol.requestForPrivateSite(from: requestURL)
} else if !self.post.blog.isHostedAtWPcom && self.post.blog.isBasicAuthCredentialStored() {
size.width = size.width * UIScreen.main.scale
requestURL = WPImageURLHelper.imageURLWithSize(size, forImageURL: requestURL)
request = URLRequest(url: requestURL)
} else {
// the size that PhotonImageURLHelper expects is points size
requestURL = PhotonImageURLHelper.photonURL(with: size, forImageURL: requestURL)
request = URLRequest(url: requestURL)
}
let imageDownloader = AFImageDownloader.defaultInstance()
let receipt = imageDownloader.downloadImage(for: request, success: { [weak self](request, response, image) in
guard self != nil else {
return
}
DispatchQueue.main.async(execute: {
success(image)
})
}) { [weak self](request, response, error) in
guard self != nil else {
return
}
DispatchQueue.main.async(execute: {
failure()
})
}
if let receipt = receipt {
activeMediaRequests.append(receipt)
}
}
func textView(_ textView: TextView, urlFor imageAttachment: ImageAttachment) -> URL? {
saveToMedia(attachment: imageAttachment)
return nil
}
func cancelAllPendingMediaRequests() {
let imageDownloader = AFImageDownloader.defaultInstance()
for receipt in activeMediaRequests {
imageDownloader.cancelTask(for: receipt)
}
activeMediaRequests.removeAll()
}
func textView(_ textView: TextView, deletedAttachmentWith attachmentID: String) {
mediaProgressCoordinator.cancelAndStopTrack(of: attachmentID)
}
func textView(_ textView: TextView, placeholderFor attachment: NSTextAttachment) -> UIImage {
return placeholderImage(for: attachment)
}
}
// MARK: - MediaPickerViewController Delegate Conformance
//
extension AztecPostViewController: WPMediaPickerViewControllerDelegate {
func mediaPickerControllerDidCancel(_ picker: WPMediaPickerViewController) {
if picker != mediaPickerInputViewController?.mediaPicker {
dismiss(animated: true, completion: nil)
}
}
func mediaPickerController(_ picker: WPMediaPickerViewController, didFinishPicking assets: [WPMediaAsset]) {
if picker != mediaPickerInputViewController?.mediaPicker {
dismiss(animated: true, completion: nil)
selectedMediaOrigin = .fullScreenPicker
} else {
selectedMediaOrigin = .inlinePicker
}
closeMediaPickerInputViewController()
if assets.isEmpty {
return
}
mediaProgressCoordinator.track(numberOfItems: assets.count)
for asset in assets {
switch asset {
case let phAsset as PHAsset:
insertDeviceMedia(phAsset: phAsset)
case let media as Media:
insertSiteMediaLibrary(media: media)
default:
continue
}
}
}
func mediaPickerController(_ picker: WPMediaPickerViewController, selectionChanged assets: [WPMediaAsset]) {
updateFormatBarInsertAssetCount()
}
func mediaPickerController(_ picker: WPMediaPickerViewController, didSelect asset: WPMediaAsset) {
updateFormatBarInsertAssetCount()
}
func mediaPickerController(_ picker: WPMediaPickerViewController, didDeselect asset: WPMediaAsset) {
updateFormatBarInsertAssetCount()
}
private func updateFormatBarInsertAssetCount() {
guard let assetCount = mediaPickerInputViewController?.mediaPicker.selectedAssets.count else {
return
}
if assetCount == 0 {
formatBar.trailingItem = nil
} else {
insertToolbarItem.setTitle(String(format: Constants.mediaPickerInsertText, NSNumber(value: assetCount)), for: .normal)
if formatBar.trailingItem != insertToolbarItem {
formatBar.trailingItem = insertToolbarItem
}
}
}
}
// MARK: - Accessibility Helpers
//
extension UIImage {
func addAccessibilityForAttachment(_ attachment: NSTextAttachment) {
if let attachment = attachment as? ImageAttachment,
let accessibilityLabel = attachment.alt {
self.accessibilityLabel = accessibilityLabel
}
}
}
// MARK: - State Restoration
//
extension AztecPostViewController: UIViewControllerRestoration {
class func viewController(withRestorationIdentifierPath identifierComponents: [Any], coder: NSCoder) -> UIViewController? {
return restoreAztec(withCoder: coder)
}
override func encodeRestorableState(with coder: NSCoder) {
super.encodeRestorableState(with: coder)
coder.encode(post.objectID.uriRepresentation(), forKey: Restoration.postIdentifierKey)
coder.encode(shouldRemovePostOnDismiss, forKey: Restoration.shouldRemovePostKey)
}
class func restoreAztec(withCoder coder: NSCoder) -> AztecPostViewController? {
let context = ContextManager.sharedInstance().mainContext
guard let postURI = coder.decodeObject(forKey: Restoration.postIdentifierKey) as? URL,
let objectID = context.persistentStoreCoordinator?.managedObjectID(forURIRepresentation: postURI) else {
return nil
}
let post = try? context.existingObject(with: objectID)
guard let restoredPost = post as? AbstractPost else {
return nil
}
let aztecViewController = AztecPostViewController(post: restoredPost)
aztecViewController.shouldRemovePostOnDismiss = coder.decodeBool(forKey: Restoration.shouldRemovePostKey)
return aztecViewController
}
}
// MARK: - UIDocumentPickerDelegate
extension AztecPostViewController: UIDocumentPickerDelegate {
func documentPicker(_ controller: UIDocumentPickerViewController, didPickDocumentsAt urls: [URL]) {
selectedMediaOrigin = .documentPicker
mediaProgressCoordinator.track(numberOfItems: urls.count)
for documentURL in urls {
insertExternalMediaWithURL(documentURL)
}
}
}
// MARK: - Constants
//
extension AztecPostViewController {
struct Analytics {
static let editorSource = "aztec"
static let headerStyleValues = ["none", "h1", "h2", "h3", "h4", "h5", "h6"]
}
struct Assets {
static let closeButtonModalImage = Gridicon.iconOfType(.cross)
static let closeButtonRegularImage = UIImage(named: "icon-posts-editor-chevron")
static let defaultMissingImage = Gridicon.iconOfType(.image)
}
struct Constants {
static let defaultMargin = CGFloat(20)
static let cancelButtonPadding = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 5)
static let blogPickerCompactSize = CGSize(width: 125, height: 30)
static let blogPickerRegularSize = CGSize(width: 300, height: 30)
static let uploadingButtonSize = CGSize(width: 150, height: 30)
static let moreAttachmentText = "more"
static let placeholderPadding = UIEdgeInsets(top: 8, left: 5, bottom: 0, right: 0)
static let headers = [Header.HeaderType.none, .h1, .h2, .h3, .h4, .h5, .h6]
static let lists = [TextList.Style.unordered, .ordered]
static let toolbarHeight = CGFloat(44.0)
static let mediaPickerInsertText = NSLocalizedString("Insert %@", comment: "Button title used in media picker to insert media (photos / videos) into a post. Placeholder will be the number of items that will be inserted.")
static let mediaPickerKeyboardHeightRatioPortrait = CGFloat(0.20)
static let mediaPickerKeyboardHeightRatioLandscape = CGFloat(0.30)
static let mediaOverlayBorderWidth = CGFloat(3.0)
static let mediaOverlayIconSize = CGSize(width: 32, height: 32)
struct Animations {
static let formatBarMediaButtonRotationDuration: TimeInterval = 0.3
static let formatBarMediaButtonRotationAngle: CGFloat = .pi / 4.0
}
}
struct MoreSheetAlert {
static let htmlTitle = NSLocalizedString("Switch to HTML", comment: "Switches the Editor to HTML Mode")
static let richTitle = NSLocalizedString("Switch to Rich Text", comment: "Switches the Editor to Rich Text Mode")
static let previewTitle = NSLocalizedString("Preview", comment: "Displays the Post Preview Interface")
static let optionsTitle = NSLocalizedString("Options", comment: "Displays the Post's Options")
static let cancelTitle = NSLocalizedString("Cancel", comment: "Dismisses the Alert from Screen")
}
struct Colors {
static let aztecBackground = UIColor.clear
static let title = WPStyleGuide.grey()
static let separator = WPStyleGuide.greyLighten30()
static let placeholder = WPStyleGuide.grey()
static let progressBackground = WPStyleGuide.wordPressBlue()
static let progressTint = UIColor.white
static let progressTrack = WPStyleGuide.wordPressBlue()
static let mediaProgressOverlay = WPStyleGuide.darkGrey().withAlphaComponent(CGFloat(0.6))
static let mediaProgressBarBackground = WPStyleGuide.lightGrey()
static let mediaProgressBarTrack = WPStyleGuide.wordPressBlue()
static let aztecLinkColor = WPStyleGuide.mediumBlue()
static let mediaOverlayBorderColor = WPStyleGuide.wordPressBlue()
}
struct Fonts {
static let regular = WPFontManager.notoRegularFont(ofSize: 16)
static let semiBold = WPFontManager.systemSemiBoldFont(ofSize: 16)
static let title = WPFontManager.notoBoldFont(ofSize: 24.0)
static let blogPicker = Fonts.semiBold
static let mediaPickerInsert = WPFontManager.systemMediumFont(ofSize: 15.0)
static let mediaOverlay = WPFontManager.systemSemiBoldFont(ofSize: 15.0)
}
struct Restoration {
static let restorationIdentifier = "AztecPostViewController"
static let postIdentifierKey = AbstractPost.classNameWithoutNamespaces()
static let shouldRemovePostKey = "shouldRemovePostOnDismiss"
}
struct SwitchSiteAlert {
static let title = NSLocalizedString("Change Site", comment: "Title of an alert prompting the user that they are about to change the blog they are posting to.")
static let message = NSLocalizedString("Choosing a different site will lose edits to site specific content like media and categories. Are you sure?", comment: "And alert message warning the user they will loose blog specific edits like categories, and media if they change the blog being posted to.")
static let acceptTitle = NSLocalizedString("OK", comment: "Accept Action")
static let cancelTitle = NSLocalizedString("Cancel", comment: "Cancel Action")
}
struct MediaUploadingAlert {
static let title = NSLocalizedString("Uploading media", comment: "Title for alert when trying to save/exit a post before media upload process is complete.")
static let message = NSLocalizedString("You are currently uploading media. Please wait until this completes.", comment: "This is a notification the user receives if they are trying to save a post (or exit) before the media upload process is complete.")
static let acceptTitle = NSLocalizedString("OK", comment: "Accept Action")
}
struct FailedMediaRemovalAlert {
static let title = NSLocalizedString("Uploads failed", comment: "Title for alert when trying to save post with failed media items")
static let message = NSLocalizedString("Some media uploads failed. This action will remove all failed media from the post.\nSave anyway?", comment: "Confirms with the user if they save the post all media that failed to upload will be removed from it.")
static let acceptTitle = NSLocalizedString("Yes", comment: "Accept Action")
static let cancelTitle = NSLocalizedString("Not Now", comment: "Nicer dialog answer for \"No\".")
}
struct MediaUploadingCancelAlert {
static let title = NSLocalizedString("Cancel media uploads", comment: "Dialog box title for when the user is cancelling an upload.")
static let message = NSLocalizedString("You are currently uploading media. This action will cancel uploads in progress.\n\nAre you sure?", comment: "This prompt is displayed when the user attempts to stop media uploads in the post editor.")
static let acceptTitle = NSLocalizedString("Yes", comment: "Yes")
static let cancelTitle = NSLocalizedString("Not Now", comment: "Nicer dialog answer for \"No\".")
}
}
| gpl-2.0 |
xilosada/BitcoinFinder | BitcoinFinder/DateHelper.swift | 1 | 1220 | //
// Copyright 2015 X.I. Losada.
//
// 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
struct DateHelper {
static func fromISOString(dateString: String) -> NSDate {
let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ssZZZZ"
return dateFormatter.dateFromString(dateString)!
}
static func getISOString(date: NSDate, timeZone: NSTimeZone? = nil) -> String {
let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "HH:mm:ss"
if let timeZone = timeZone {
dateFormatter.timeZone = timeZone
}
return dateFormatter.stringFromDate(date)
}
} | apache-2.0 |
realm/SwiftLint | Source/SwiftLintFramework/Rules/Idiomatic/ToggleBoolRule.swift | 1 | 3635 | import SwiftSyntax
import SwiftSyntaxBuilder
struct ToggleBoolRule: SwiftSyntaxCorrectableRule, ConfigurationProviderRule, OptInRule {
var configuration = SeverityConfiguration(.warning)
init() {}
static var description = RuleDescription(
identifier: "toggle_bool",
name: "Toggle Bool",
description: "Prefer `someBool.toggle()` over `someBool = !someBool`.",
kind: .idiomatic,
nonTriggeringExamples: [
Example("isHidden.toggle()\n"),
Example("view.clipsToBounds.toggle()\n"),
Example("func foo() { abc.toggle() }"),
Example("view.clipsToBounds = !clipsToBounds\n"),
Example("disconnected = !connected\n"),
Example("result = !result.toggle()")
],
triggeringExamples: [
Example("↓isHidden = !isHidden\n"),
Example("↓view.clipsToBounds = !view.clipsToBounds\n"),
Example("func foo() { ↓abc = !abc }")
],
corrections: [
Example("↓isHidden = !isHidden\n"): Example("isHidden.toggle()\n"),
Example("↓view.clipsToBounds = !view.clipsToBounds\n"): Example("view.clipsToBounds.toggle()\n"),
Example("func foo() { ↓abc = !abc }"): Example("func foo() { abc.toggle() }")
]
)
func makeVisitor(file: SwiftLintFile) -> ViolationsSyntaxVisitor {
Visitor(viewMode: .sourceAccurate)
}
func makeRewriter(file: SwiftLintFile) -> ViolationsSyntaxRewriter? {
Rewriter(
locationConverter: file.locationConverter,
disabledRegions: disabledRegions(file: file)
)
}
}
private extension ToggleBoolRule {
final class Visitor: ViolationsSyntaxVisitor {
override func visitPost(_ node: ExprListSyntax) {
if node.hasToggleBoolViolation {
violations.append(node.positionAfterSkippingLeadingTrivia)
}
}
}
final class Rewriter: SyntaxRewriter, ViolationsSyntaxRewriter {
private(set) var correctionPositions: [AbsolutePosition] = []
let locationConverter: SourceLocationConverter
let disabledRegions: [SourceRange]
init(locationConverter: SourceLocationConverter, disabledRegions: [SourceRange]) {
self.locationConverter = locationConverter
self.disabledRegions = disabledRegions
}
override func visit(_ node: ExprListSyntax) -> ExprListSyntax {
guard
node.hasToggleBoolViolation,
!node.isContainedIn(regions: disabledRegions, locationConverter: locationConverter)
else {
return super.visit(node)
}
correctionPositions.append(node.positionAfterSkippingLeadingTrivia)
let newNode = node
.replacing(childAt: 0, with: "\(node.first!.withoutTrivia()).toggle()")
.removingLast()
.removingLast()
.withLeadingTrivia(node.leadingTrivia ?? .zero)
.withTrailingTrivia(node.trailingTrivia ?? .zero)
return super.visit(newNode)
}
}
}
private extension ExprListSyntax {
var hasToggleBoolViolation: Bool {
guard
count == 3,
dropFirst().first?.is(AssignmentExprSyntax.self) == true,
last?.is(PrefixOperatorExprSyntax.self) == true,
let lhs = first?.withoutTrivia().description,
let rhs = last?.withoutTrivia().description,
rhs == "!\(lhs)"
else {
return false
}
return true
}
}
| mit |
sgr-ksmt/SUSwiftSugar | SUSwiftSugar/Extensions/Foundation/NSFileManagerExtensions.swift | 1 | 1821 | //
// NSFileManagerExtensions.swift
import Foundation
private func getNSDirectory(searchPath: NSSearchPathDirectory) -> String {
return NSSearchPathForDirectoriesInDomains(searchPath, .UserDomainMask, true).first!
}
public func NSDocumentDirectory() -> String {
return getNSDirectory(.DocumentDirectory)
}
public func NSCacheDirectory() -> String {
return getNSDirectory(.CachesDirectory)
}
public extension NSFileManager {
public func fileExists(at path: FilePathConvertible) -> Bool {
return fileExistsAtPath(path.filePath)
}
public func fileExists(at path: FilePathConvertible, isDirectory: UnsafeMutablePointer<ObjCBool>) -> Bool {
return fileExistsAtPath(path.filePath, isDirectory: isDirectory)
}
public func safeRemove(path: FilePathConvertible) {
_ = try? removeItemAtPath(path.filePath)
}
public func forceMove(from: FilePathConvertible, to: FilePathConvertible) {
safeRemove(to)
_ = try? moveItemAtPath(from.filePath, toPath: to.filePath)
}
public func forceCopy(from: FilePathConvertible, to: FilePathConvertible) {
safeRemove(to)
_ = try? copyItemAtPath(from.filePath, toPath: to.filePath)
}
public func swap(path1: FilePathConvertible, and path2: FilePathConvertible) throws {
let tempPath: FilePathConvertible = NSTemporaryDirectory().stringByAppendingPathComponent(".temp")
safeRemove(tempPath)
try [(path1, tempPath), (path2, path1), (tempPath, path2)].forEach {
try moveItemAtPath($0.0.filePath, toPath: $0.1.filePath)
}
}
public func addExcludedFromBackupToItemAtURL(path: FilePathConvertible) throws {
try path.fileURL.setResourceValue(true, forKey: NSURLIsExcludedFromBackupKey)
}
} | mit |
CodeDrunkard/ARViewer | ARViewer/Core/ARView.swift | 1 | 5304 | //
// ARView.swift
// ARViewer
//
// Created by JT Ma on 11/04/2017.
// Copyright © 2017 JT Ma. All rights reserved.
//
import UIKit
import SceneKit
import CoreMotion
import AVFoundation
import SpriteKit
public enum ARControlMode: Int {
case motion
case touch
}
public class ARView: SCNView {
public var controlMode: ARControlMode! {
didSet {
switchControlMode(to: controlMode)
resetCameraAngles()
}
}
public var panoramaTexture: UIImage? {
didSet {
guard let texture = panoramaTexture else { return }
let material = SCNMaterial()
material.diffuse.contents = texture
material.diffuse.mipFilter = .nearest
material.diffuse.magnificationFilter = .nearest
material.diffuse.contentsTransform = SCNMatrix4MakeScale(-1, 1, 1)
material.diffuse.wrapS = .repeat
material.cullMode = .front
let sphere = SCNSphere()
sphere.radius = 50
sphere.segmentCount = 300
sphere.firstMaterial = material
panoramaNode.geometry = sphere
}
}
public var panoramaVideoPlayer: AVPlayer? {
didSet {
guard let videoPlayer = panoramaVideoPlayer else { return }
let videoSize = CGSize(width: 1920, height: 960)
let videoNode = SKVideoNode(avPlayer: videoPlayer)
videoNode.position = videoSize.midPoint
videoNode.xScale = -1
videoNode.yScale = -1
videoNode.size = videoSize
let videoScene = SKScene(size: videoSize)
videoScene.scaleMode = .aspectFit
videoScene.addChild(videoNode)
let material = SCNMaterial()
material.diffuse.contents = videoScene
material.cullMode = .front
let sphere = SCNSphere()
sphere.radius = 100
sphere.segmentCount = 300
sphere.firstMaterial = material
panoramaNode.geometry = sphere
}
}
public var panSpeed: (x: Float, y: Float) = (x: 0.005, y: 0.005)
public override init(frame: CGRect) {
super.init(frame: frame)
loadScene()
}
public required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
loadScene()
}
deinit {
if motionManager.isDeviceMotionActive {
motionManager.stopDeviceMotionUpdates()
}
}
public func loadScene() {
let camera = SCNCamera()
camera.zFar = 100
camera.xFov = 60
camera.yFov = 60
cameraNode.camera = camera
panoramaNode.position = SCNVector3Make(0, 0, 0)
cameraNode.position = panoramaNode.position
let scene = SCNScene()
scene.rootNode.addChildNode(cameraNode)
scene.rootNode.addChildNode(panoramaNode)
self.scene = scene
backgroundColor = UIColor.black
}
fileprivate let panoramaNode = SCNNode()
fileprivate let cameraNode = SCNNode()
fileprivate var prevLocation = CGPoint.zero
fileprivate var motionManager = CMMotionManager()
}
extension ARView {
fileprivate func resetCameraAngles() {
cameraNode.eulerAngles = SCNVector3Make(0, 0, 0)
}
public func switchControlMode(to mode: ARControlMode) {
gestureRecognizers?.removeAll()
switch mode {
case .touch:
let panGestureRec = UIPanGestureRecognizer(target: self, action: #selector(handlePan(_ :)))
addGestureRecognizer(panGestureRec)
if motionManager.isDeviceMotionActive {
motionManager.stopDeviceMotionUpdates()
}
case .motion:
guard motionManager.isAccelerometerAvailable else { return }
motionManager.deviceMotionUpdateInterval = 0.01
motionManager.startDeviceMotionUpdates(to: OperationQueue.main,
withHandler: {[unowned self] (motionData, error) in
guard let motionData = motionData else {
print("\(String(describing: error?.localizedDescription))")
self.motionManager.stopGyroUpdates()
return
}
self.cameraNode.orientation = motionData.gaze()
})
}
}
@objc private func handlePan(_ gesture: UIPanGestureRecognizer) {
if (gesture.state == .began) {
prevLocation = CGPoint.zero
} else if (gesture.state == .changed) {
let location = gesture.translation(in: self)
let orientation = cameraNode.eulerAngles
let newOrientation = SCNVector3Make(orientation.x + Float(location.y - prevLocation.y) * panSpeed.x,
orientation.y + Float(location.x - prevLocation.x) * panSpeed.y,
orientation.z)
cameraNode.eulerAngles = newOrientation
prevLocation = location
}
}
}
| mit |
dreamsxin/swift | validation-test/compiler_crashers_fixed/26824-swift-modulefile-getimportedmodules.swift | 11 | 475 | // This source file is part of the Swift.org open source project
// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
// RUN: not %target-swift-frontend %s -parse
struct S<T where g:a{func a{struct S<T where h:p}class B<b{class A{var b{class c:A
| apache-2.0 |
dreamsxin/swift | validation-test/Evolution/Inputs/class_remove_property.swift | 45 | 545 |
#if BEFORE
public final class RemoveStoredProperty {
public init(first: String, middle: String, last: String) {
self.first = first
self.middle = middle
self.last = last
}
public var first: String
public var middle: String
public var last: String
public var name: String {
return "\(first) \(middle) \(last)"
}
}
#else
public final class RemoveStoredProperty {
public init(first: String, middle: String, last: String) {
self.name = "\(first) \(middle) \(last)"
}
public var name: String
}
#endif
| apache-2.0 |
LYM-mg/MGOFO | MGOFO/MGOFO/Class/Extesion/UIViewController+Extension.swift | 1 | 10619 | //
// UIViewController+Extension.swift
// chart2
//
// Created by i-Techsys.com on 16/11/30.
// Copyright © 2016年 i-Techsys. All rights reserved.
//
import UIKit
import MBProgressHUD
import SnapKit
private let mainScreenW = UIScreen.main.bounds.size.width
private let mainScreenH = UIScreen.main.bounds.size.height
// MARK: - HUD
extension UIViewController {
// MARK:- RuntimeKey 动态绑属性
// 改进写法【推荐】
struct RuntimeKey {
static let mg_HUDKey = UnsafeRawPointer.init(bitPattern: "mg_HUDKey".hashValue)
static let mg_GIFKey = UnsafeRawPointer(bitPattern: "mg_GIFKey".hashValue)
static let mg_GIFWebView = UnsafeRawPointer(bitPattern: "mg_GIFWebView".hashValue)
/// ...其他Key声明
}
// MARK:- HUD
/** ================================= HUD蒙版提示 ====================================== **/
// 蒙版提示HUD
var MBHUD: MBProgressHUD? {
set {
objc_setAssociatedObject(self, UIViewController.RuntimeKey.mg_HUDKey, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
}
get {
return objc_getAssociatedObject(self, UIViewController.RuntimeKey.mg_HUDKey) as? MBProgressHUD
}
}
/**
* 提示信息
*
* @param view 显示在哪个view
* @param hint 提示
*/
func showHudInView(view: UIView, hint: String?, yOffset: CGFloat = 0.0) {
let hud = MBProgressHUD(view: view)
hud.label.text = hint!
view.addSubview(hud)
if yOffset != 0.0 {
hud.margin = 10.0;
hud.offset.y += yOffset;
}
hud.show(animated: true)
self.MBHUD = hud
}
/// 如果设置了图片名,mode的其他其他设置将失效
func showHudInViewWithMode(view: UIView, hint: String?, mode: MBProgressHUDMode = .text, imageName: String?) {
let hud = MBProgressHUD(view: view)
hud.label.text = hint!
view.addSubview(hud)
hud.mode = mode
if imageName != nil {
hud.mode = .customView
hud.customView = UIImageView(image: UIImage(named: imageName!))
}
hud.show(animated: true)
self.MBHUD = hud
}
/**
* 隐藏HUD
*/
func hideHud(){
self.MBHUD?.hide(animated: true)
}
/**
* 提示信息 mode: MBProgressHUDModeText
*
* @param hint 提示
*/
func showHint(hint: String?, mode: MBProgressHUDMode = .text) {
//显示提示信息
guard let view = UIApplication.shared.delegate?.window else { return }
let hud = MBProgressHUD.showAdded(to: view!, animated: true)
hud.isUserInteractionEnabled = false
hud.mode = MBProgressHUDMode.text
hud.label.text = hint!;
hud.mode = mode
hud.margin = 10.0;
hud.removeFromSuperViewOnHide = true
hud.hide(animated: true, afterDelay: 1.5)
}
func showHint(hint: String?,mode: MBProgressHUDMode? = .text,view: UIView? = (UIApplication.shared.delegate?.window!)!, yOffset: CGFloat = 0.0){
//显示提示信息
let hud = MBProgressHUD.showAdded(to: view!, animated: true)
hud.isUserInteractionEnabled = false
hud.mode = MBProgressHUDMode.text
hud.label.text = hint!
if mode == .customView {
hud.mode = .customView
hud.customView = UIImageView(image: UIImage(named: "happy_face_icon"))
}
if mode != nil {
hud.mode = mode!
}
hud.margin = 15.0
if yOffset != 0.0 {
hud.offset.y += yOffset;
}
hud.removeFromSuperViewOnHide = true
hud.hide(animated: true, afterDelay: 1.5)
}
// 带图片的提示HUD,延时2秒消失
func showHint(hint: String?,imageName: String?) {
let hud = MBProgressHUD.showAdded(to: view, animated: true)
hud.isUserInteractionEnabled = false
hud.mode = MBProgressHUDMode.text
hud.label.text = hint!
if imageName != nil {
hud.mode = .customView
hud.customView = UIImageView(image: UIImage(named: imageName!))
}else {
hud.mode = .text
}
hud.removeFromSuperViewOnHide = true
hud.hide(animated: true, afterDelay: 1.5)
}
// MARK: - 显示Gif图片
/** ============================ UIImageView显示GIF加载动画 =============================== **/
// MARK: - UIImageView显示Gif加载状态
/** 显示加载动画的UIImageView */
var mg_gifView: UIImageView? {
set {
objc_setAssociatedObject(self, UIViewController.RuntimeKey.mg_GIFKey, newValue, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN_NONATOMIC)
}
get {
return objc_getAssociatedObject(self, UIViewController.RuntimeKey.mg_GIFKey) as? UIImageView
}
}
/**
* 显示GIF加载动画
*
* @param images gif图片数组, 不传的话默认是自带的
* @param view 显示在哪个view上, 如果不传默认就是self.view
*/
func mg_showGifLoding(_ images: [UIImage]?,size: CGSize? , inView view: UIView?) {
var images = images
if images == nil {
images = [UIImage(named: "hold1_60x72")!,UIImage(named: "hold2_60x72")!,UIImage(named: "hold3_60x72")!]
}
var size = size
if size == nil {
size = CGSize(width: 60, height: 70)
}
let gifView = UIImageView()
var view = view
if view == nil {
view = self.view
}
view?.addSubview(gifView)
self.mg_gifView = gifView
gifView.snp.makeConstraints { (make) in
make.center.equalToSuperview()
make.size.equalTo(size!)
}
gifView.playGifAnimation(images: images!)
}
/**
* 取消GIF加载动画
*/
func mg_hideGifLoding() {
self.mg_gifView?.stopGifAnimation()
self.mg_gifView = nil;
}
/**
* 判断数组是否为空
*
* @param array 数组
*
* @return yes or no
*/
func isNotEmptyArray(array: [Any]) -> Bool {
if array.count >= 0 && !array.isEmpty{
return true
}else {
return false
}
}
/** ============================== UIWebView显示GIF加载动画 ================================= **/
// MARK: - UIWebView显示GIF加载动画
/** UIWebView显示Gif加载状态 */
weak var mg_GIFWebView: UIWebView? {
set {
objc_setAssociatedObject(self, UIViewController.RuntimeKey.mg_GIFWebView, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
}
get {
return objc_getAssociatedObject(self, UIViewController.RuntimeKey.mg_GIFWebView) as? UIWebView
}
}
/// 使用webView加载GIF图片
/**
* 如果view传了参数,移除的时候也要传同一个参数
*/
func mg_showWebGifLoading(frame:CGRect?, gifName: String?,view: UIView?, filter: Bool? = false) {
var gifName = gifName
if gifName == nil || gifName == "" {
gifName = "gif2"
}
var frame = frame
if frame == CGRect.zero || frame == nil {
frame = CGRect(x: 0, y: (self.navigationController != nil) ? navHeight : CGFloat(0), width: mainScreenW, height: mainScreenH)
}
/// 得先提前创建webView,不能在子线程创建webView,不然程序会崩溃
let webView = UIWebView(frame: frame!)
// 子线程加载耗时操作加载GIF图片
DispatchQueue.global().async {
// 守卫校验
guard let filePath = Bundle.main.path(forResource: gifName, ofType: "gif") else {
return
}
guard let gifData: Data = NSData(contentsOfFile: filePath) as? Data else { return }
if (frame?.size.height)! < mainScreenH - navHeight {
webView.center = CGPoint(x: (mainScreenW-webView.frame.size.width)/2, y: (mainScreenH-webView.frame.size.height)/2)
}else {
webView.center = self.view.center
}
webView.scalesPageToFit = true
webView.load(gifData, mimeType: "image/gif", textEncodingName: "UTF-8", baseURL: URL(fileURLWithPath: filePath))
webView.autoresizingMask = [.flexibleWidth,.flexibleHeight]
webView.backgroundColor = UIColor.black
webView.isOpaque = false
webView.isUserInteractionEnabled = false
webView.tag = 10000
// 回到主线程将webView加到 UIApplication.shared.delegate?.window
DispatchQueue.main.async {
var view = view
if view == nil { // 添加到窗口
view = (UIApplication.shared.delegate?.window)!
}else { // 添加到控制器
self.mg_GIFWebView = webView
}
view?.addSubview(webView)
view?.bringSubview(toFront: webView)
//创建一个灰色的蒙版,提升效果( 可选 )
if filter! { // true
let filter = UIView(frame: self.view.frame)
filter.backgroundColor = UIColor(white: 0.9, alpha: 0.3)
webView.insertSubview(filter, at: 0)
}
}
}
}
/**
* 取消GIF加载动画,隐藏webView
*/
func mg_hideWebGifLoding(view: UIView?) {
if view == nil { // 从窗口中移除
guard let view = UIApplication.shared.delegate?.window else { return }
guard let webView = view?.viewWithTag(10000) as? UIWebView else { return }
webView.removeFromSuperview()
webView.alpha = 0.0
}else { // 从控制器中移除
self.mg_GIFWebView?.removeFromSuperview()
self.mg_GIFWebView?.alpha = 0.0
}
}
}
// MARK: - 侧滑相关控制器
extension UIViewController {
func getRevealViewController() -> SWRevealViewController {
var parent: UIViewController? = self
// let revealClass: AnyClass = SWRevealViewController.classForCoder()
while (nil != (parent = parent?.parent) && !(parent is SWRevealViewController)) {
}
return (parent as! SWRevealViewController)
}
}
| mit |
CodeEagle/SSImageBrowser | Source/SSCaptionView.swift | 1 | 4067 | //
// SSCaptionView.swift
// Pods
//
// Created by LawLincoln on 15/7/10.
//
//
import UIKit
public final class SSCaptionView: UIView {
var photo: SSPhoto?
private var labelPadding: CGFloat { return 10 }
private lazy var label: UILabel = {
let label = UILabel(frame: CGRect(x: self.labelPadding, y: 0, width: self.bounds.size.width - self.labelPadding * 2, height: self.bounds.size.height))
label.autoresizingMask = [.flexibleWidth, .flexibleHeight]
label.isOpaque = false
label.backgroundColor = UIColor.clear
label.textAlignment = .center
label.lineBreakMode = NSLineBreakMode.byWordWrapping
label.numberOfLines = 3
label.textColor = UIColor.white
label.shadowColor = UIColor(white: 0, alpha: 0.5)
label.shadowOffset = CGSize(width: 0, height: 1)
label.font = UIFont.systemFont(ofSize: 17)
label.text = ""
return label
}()
convenience init(aPhoto: SSPhoto) {
let screenBound = UIScreen.main.bounds
var screenWidth = screenBound.size.width
let orientation = UIDevice.current.orientation
if orientation == .landscapeLeft ||
orientation == .landscapeRight {
screenWidth = screenBound.size.height
}
self.init(frame: CGRect(x: 0, y: 0, width: screenWidth, height: 44))
photo = aPhoto
isOpaque = false
setBackground()
setupCaption()
}
public override init(frame: CGRect) {
super.init(frame: frame)
}
public required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
open override func layoutSubviews() {
super.layoutSubviews()
if let view = viewWithTag(101) {
let len = max(UIScreen.main.bounds.width, UIScreen.main.bounds.height)
view.frame = CGRect(x: 0, y: -100, width: len, height: 130 + 100)
}
}
/**
To create your own custom caption view, subclass this view
and override the following two methods (as well as any other
UIView methods that you see fit):
Override -setupCaption so setup your subviews and customise the appearance
of your custom caption
You can access the photo's data by accessing the _photo ivar
If you need more data per photo then simply subclass IDMPhoto and return your
subclass to the photo browsers -photoBrowser:photoAtIndex: delegate method
*/
private func setupCaption() {
if let cap = photo?.caption() { label.text = cap }
addSubview(label)
}
/**
Override -sizeThatFits: and return a CGSize specifying the height of your
custom caption view. With width property is ignored and the caption is displayed
the full width of the screen
:param: size CGSize
:returns: CGSize
*/
open override func sizeThatFits(_ size: CGSize) -> CGSize {
if label.text == nil || label.text?.isEmpty == true { return .zero }
var maxHeight: CGFloat = 9999
if label.numberOfLines > 0 {
maxHeight = label.font.lineHeight * CGFloat(label.numberOfLines)
}
let text = label.text!
let width = size.width - labelPadding * 2
let font = label.font ?? UIFont.systemFont(ofSize: UIFont.systemFontSize)
let attributedText = NSAttributedString(string: text, attributes: [NSFontAttributeName: font])
let size = CGSize(width: width, height: maxHeight)
let rect = attributedText.boundingRect(with: size , options: [.usesLineFragmentOrigin, .usesFontLeading], context: nil)
let textSize = rect.size
return CGSize(width: size.width, height: textSize.height + labelPadding * 2)
}
private func setBackground() {
let len = max(UIScreen.main.bounds.width, UIScreen.main.bounds.height)
let fadeView = UIView(frame: CGRect(x: 0, y: -100, width: len, height: 130 + 100)) // Static width, autoresizingMask is not working
fadeView.tag = 101
let gradient = CAGradientLayer()
gradient.frame = fadeView.bounds
gradient.colors = [UIColor(white: 0, alpha: 0).cgColor, UIColor(white: 0, alpha: 0.8).cgColor]
fadeView.layer.insertSublayer(gradient, at: 0)
fadeView.autoresizingMask = [.flexibleWidth, .flexibleHeight]
addSubview(fadeView)
}
}
| mit |
BellAppLab/BLLogger | Package.swift | 1 | 309 | // swift-tools-version:4.1
import PackageDescription
let package = Package(
name: "BLLogger",
products: [
.library(name: "BLLogger",
targets: ["BLLogger"]),
],
targets: [
.target(name: "BLLogger"),
],
swiftLanguageVersions: [3.3, 4.1, 4.2]
)
| mit |
Mindera/Alicerce | Tests/AlicerceTests/StackOrchestrator/StackOrchestratorPerformanceMetricsTrackerTestCase.swift | 1 | 2630 | import XCTest
@testable import Alicerce
class StackOrchestratorPerformanceMetricsTrackerTestCase: XCTestCase {
private var tracker: MockStackOrchestratorPerformanceMetricsTracker!
override func setUp() {
super.setUp()
tracker = MockStackOrchestratorPerformanceMetricsTracker()
}
override func tearDown() {
tracker = nil
super.tearDown()
}
// measureDecode
func testMeasureDecode_WithSuccessfulDecode_ShouldInvokeStartAndStopOnTheTrackerAndSucceed() {
let expectation = self.expectation(description: "measure")
defer { waitForExpectations(timeout: 1) }
let testResource = "📦"
let testPayload = "🎁"
let testParsedResult = 1337
let testMetadata: PerformanceMetrics.Metadata = [tracker.modelTypeMetadataKey: "Int"]
tracker.measureSyncInvokedClosure = { identifier, metadata in
XCTAssertEqual(
identifier,
self.tracker.makeDecodeIdentifier(for: testResource, payload: testPayload, result: Int.self)
)
XCTAssertDumpsEqual(metadata, testMetadata)
expectation.fulfill()
}
XCTAssertEqual(
testParsedResult,
tracker.measureDecode(of: testResource, payload: testPayload, decode: { testParsedResult })
)
}
func testMeasureDecode_WithFailingDecode_ShouldInvokeStartAndStopOnTheTrackerAndFail() {
let expectation = self.expectation(description: "measure")
defer { waitForExpectations(timeout: 1) }
let testResource = "📦"
let testPayload = "💣"
let testMetadata: PerformanceMetrics.Metadata = [tracker.modelTypeMetadataKey: "Int"]
tracker.measureSyncInvokedClosure = { identifier, metadata in
XCTAssertEqual(
identifier,
self.tracker.makeDecodeIdentifier(for: testResource, payload: testPayload, result: Int.self)
)
XCTAssertDumpsEqual(metadata, testMetadata)
expectation.fulfill()
}
enum MockError: Error { case 💥 }
XCTAssertThrowsError(
try tracker.measureDecode(of: testResource, payload: testPayload, decode: { throw MockError.💥 }) as Int,
"unexpected success!"
) {
guard case MockError.💥 = $0 else {
XCTFail("unexpected error \($0)!")
return
}
}
}
}
final class MockStackOrchestratorPerformanceMetricsTracker:
MockPerformanceMetricsTracker, StackOrchestratorPerformanceMetricsTracker
{}
| mit |
Sephiroth87/C-swifty4 | C-swifty4 tvOS/ContextBackedView.swift | 1 | 3274 | //
// ContextBackedView.swift
// C-swifty4 iOS
//
// Created by Fabio Ritrovato on 10/01/2015.
// Copyright (c) 2015 orange in a day. All rights reserved.
//
import UIKit
private class ContextBackedLayer: CALayer {
private var size: CGSize = .zero
private var safeArea: UIEdgeInsets = .zero
private var context: CGContext?
override init() {
super.init()
actions = ["contents": NSNull()]
backgroundColor = UIColor(red: 0.0, green: 0.0, blue: 0.0, alpha: 1.0).cgColor
updateContentsRect()
}
required init?(coder aDecoder: NSCoder) {
fatalError()
}
func setTextureSize(_ size: CGSize, safeArea: UIEdgeInsets) {
let colorSpace = CGColorSpaceCreateDeviceRGB()
self.size = size
self.safeArea = safeArea
context = CGContext(data: nil, width: Int(size.width), height: Int(size.height), bitsPerComponent: 8, bytesPerRow: Int(size.width) * 4, space: colorSpace, bitmapInfo: CGImageAlphaInfo.premultipliedLast.rawValue)!
updateContentsRect()
}
override func display() {
guard let context = context else { return }
let cgImage = context.makeImage()
contents = cgImage
}
fileprivate func setData(_ data: UnsafePointer<UInt32>) {
guard let context = context else { return }
let address = context.data
memcpy(address, data, Int(size.width) * Int(size.height) * 4)
let cgImage = context.makeImage()
contents = cgImage
}
override var bounds: CGRect {
didSet {
if bounds.size != oldValue.size {
updateContentsRect()
}
}
}
private func updateContentsRect() {
let safeW = size.width - safeArea.left - safeArea.right
let safeH = size.height - safeArea.top - safeArea.bottom
var wScale = bounds.width / safeW
var hScale = bounds.height / safeH
if wScale > hScale {
wScale /= hScale
hScale = safeH / size.height
} else {
hScale /= wScale
wScale = safeW / size.width
}
if wScale >= 1.0 {
wScale *= safeW / size.width
}
if hScale >= 1.0 {
hScale *= safeH / size.height
}
let x = -wScale * 0.5 + (0.5 + ((safeArea.left + safeArea.right) / size.width) / 2.0)
let y = -hScale * 0.5 + (0.5 + ((safeArea.bottom + safeArea.top) / size.height) / 2.0)
contentsRect = CGRect(x: x, y: y, width: wScale, height: hScale)
}
}
class ContextBackedView: UIView {
override class var layerClass : AnyClass {
return ContextBackedLayer.self
}
func setTextureSize(_ size: CGSize, safeArea: (top: Int, left: Int, bottom: Int, right: Int)) {
let layer = self.layer as! ContextBackedLayer
layer.setTextureSize(size, safeArea: UIEdgeInsets(top: CGFloat(safeArea.top), left: CGFloat(safeArea.left), bottom: CGFloat(safeArea.bottom), right: CGFloat(safeArea.right)))
}
override func draw(_ rect: CGRect) {
}
internal func setData(_ data: UnsafePointer<UInt32>) {
let layer = self.layer as! ContextBackedLayer
layer.setData(data)
}
}
| mit |
MichaelJordanYang/JDYangDouYuZB | JDYDouYuZb/JDYDouYuZb/Application/Classes/Home/Controller/HomeViewController.swift | 1 | 4973 | //
// HomeViewController.swift
// JDYDouYuZb
//
// Created by xiaoyang on 2016/12/24.
// Copyright © 2016年 JDYang. All rights reserved.
//
import UIKit
fileprivate let kTitleViewHeight : CGFloat = 40
class HomeViewController: UIViewController {
// MARK:- 懒加载属性
fileprivate lazy var pageTitleView : PageTitleView = {
//设置菜单标题尺寸
let titleFrame = CGRect(x: 0, y: kStatusBarH + kNavigationBarH, width: kScreenWidth, height: kTitleViewHeight)
let titles = ["推荐", "游戏", "娱乐", "趣玩"]//设置菜单标题显示内容文字
let titleView = PageTitleView(frame: titleFrame, titles: titles)//保存到pageTitleView中
//titleView.backgroundColor = UIColor.purple
return titleView
}()
fileprivate lazy var pageContentView : PageContentView = {
//1.确定内容的frame
let contentHeight = kScreenHeight - kStatusBarH - kNavigationBarH - kTitleViewHeight
let contentFrame = CGRect(x: 0, y: kStatusBarH + kNavigationBarH + kTitleViewHeight, width: kScreenHeight, height: contentHeight)
//2.确定所有的子控制器
var childs = [UIViewController]() //创建数组子控制器
//通过for循环创建
for _ in 0..<4 {
let vc = UIViewController()
vc.view.backgroundColor = UIColor(r: CGFloat(arc4random_uniform(255)), g: CGFloat(arc4random_uniform(255)), b: CGFloat(arc4random_uniform(255)))
childs.append(vc)
}
let contentView = PageContentView(frame: contentFrame, childVcs: childs, parentViewController: self)
return contentView
}()
// MARK:- 系统回调函数
override func viewDidLoad() {
super.viewDidLoad()
//设置UI界面
setUpUI()
}
}
// MARK: -设置UI页面
extension HomeViewController {
fileprivate func setUpUI() {
//0.不需要调整UIScrollview的内边距. 系统默认会帮我们调整所以设置不调整内边距
automaticallyAdjustsScrollViewInsets = false
//1.设置导航栏
setUpNavigationBar()
//2.添加TitleView
view.addSubview(pageTitleView)
//3添加ContenView
view.addSubview(pageContentView)
pageContentView.backgroundColor = UIColor.orange
}
//设置导航栏
fileprivate func setUpNavigationBar() {
//1.设置左侧的按钮
/*
let btn = UIButton()
let image = UIImage(named: "logo")
btn.setImage(image, for: .normal)
btn.sizeToFit()//让按钮自适应图片
*/
navigationItem.leftBarButtonItem = UIBarButtonItem(imageName: "logo")
//UIBarButtonItem(customView: btn)//传一个自定义view
//2.设置右侧的item
let size = CGSize(width: 40, height: 40)//定义宽高尺寸
/*
let hisoryBtn = UIButton()
hisoryBtn.setImage(UIImage(named: "image_my_history"), for: .normal)
hisoryBtn.setImage(UIImage(named: "Image_my_history_click"), for: .highlighted)
//hisoryBtn.sizeToFit()
hisoryBtn.frame = CGRect(origin: CGPoint.zero, size: size)
*/
let historyItem = UIBarButtonItem(imageName: "image_my_history", hightImageName: "Image_my_history_click", size: size)
//UIBarButtonItem.createItem(imageName: "image_my_history", hightImageName: "Image_my_history_click", size: size)
/*
let searchBtn = UIButton()
searchBtn.setImage(UIImage(named: "btn_search"), for: .normal)
searchBtn.setImage(UIImage(named: "btn_search_clicked"), for: .highlighted)
//searchBtn.sizeToFit()
searchBtn.frame = CGRect(origin: CGPoint.zero, size: size)
*/
let searchItem = UIBarButtonItem(imageName: "btn_search", hightImageName: "btn_search_clicked", size: size)
//UIBarButtonItem.createItem.createItem(imageName: "btn_search", hightImageName: "btn_search_clicked", size: size)
/*
let qrcodeBtn = UIButton()
qrcodeBtn.setImage(UIImage(named: "Image_scan"), for: .normal)
qrcodeBtn.setImage(UIImage(named: "Image_scan_click"), for: .highlighted)
//qrcodeBtn.sizeToFit()
qrcodeBtn.frame = CGRect(origin: CGPoint.zero, size: size)
*/
let qrcodeItem = UIBarButtonItem(imageName: "Image_scan", hightImageName: "Image_scan_click", size: size)
//UIBarButtonItem.createItem(imageName: "Image_scan", hightImageName: "Image_scan_click", size: size)
navigationItem.rightBarButtonItems = [historyItem, searchItem, qrcodeItem]
}
}
| mit |
davefoxy/SwiftBomb | SwiftBomb/Classes/Requests/AuthenticationRequests.swift | 1 | 1356 | //
// AuthenticationRequests.swift
// SwiftBomb
//
// Created by David Fox on 17/04/2016.
// Copyright © 2016 David Fox. All rights reserved.
//
import Foundation
extension SwiftBomb {
static func createAuthenticationSession() -> AuthenticationSession {
let instance = SwiftBomb.framework
let authenticationSession = AuthenticationSession(requestFactory: instance.requestFactory!, networkingManager: instance.networkingManager!, authenticationStore: (instance.requestFactory?.authenticationStore)!)
return authenticationSession
}
}
extension RequestFactory {
func authenticationRegCodeRequest() -> SwiftBombRequest {
var request = SwiftBombRequest(configuration: configuration, path: "apple-tv/get-code", method: .get)
request.responseFormat = .xml
request.addURLParameter("deviceID", value: "XXX")
return request
}
func authenticationAPIKeyRequest(_ regCode: String) -> SwiftBombRequest {
var request = SwiftBombRequest(configuration: configuration, path: "apple-tv/get-result", method: .get)
request.addURLParameter("deviceID", value: "XXX")
request.addURLParameter("partner", value: "apple-tv")
request.addURLParameter("regCode", value: regCode)
return request
}
}
| mit |
simonnarang/Fandom-IOS | Fandomm/ChangePWTableViewController.swift | 1 | 2844 | //
// ChangePWTableViewController.swift
// Fandomm
//
// Created by Simon Narang on 3/30/16.
// Copyright © 2016 Simon Narang. All rights reserved.
//
import UIKit
class ChangePWTableViewController: UITableViewController {
var usernameFourTextOne = String()
override func viewDidLoad() {
super.viewDidLoad()
self.clearsSelectionOnViewWillAppear = false
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// #warning Incomplete implementation, return the number of rows
return 3
}
/*
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("reuseIdentifier", forIndexPath: indexPath)
// Configure the cell...
return cell
}
*/
/*
// Override to support conditional editing of the table view.
override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool {
// Return false if you do not want the specified item to be editable.
return true
}
*/
/*
// Override to support editing the table view.
override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
if editingStyle == .Delete {
// Delete the row from the data source
tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade)
} else if editingStyle == .Insert {
// Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
}
}
*/
/*
// Override to support rearranging the table view.
override func tableView(tableView: UITableView, moveRowAtIndexPath fromIndexPath: NSIndexPath, toIndexPath: NSIndexPath) {
}
*/
/*
// Override to support conditional rearranging of the table view.
override func tableView(tableView: UITableView, canMoveRowAtIndexPath indexPath: NSIndexPath) -> Bool {
// Return false if you do not want the item to be re-orderable.
return true
}
*/
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
| unlicense |
cuappdev/podcast-ios | old/Podcast/OnboardingButton.swift | 1 | 867 | //
// OnboardingButton.swift
// Podcast
//
// Created by Natasha Armbrust on 3/2/18.
// Copyright © 2018 Cornell App Development. All rights reserved.
//
import UIKit
/// semi-transparent buttons used in onboarding view
class OnboardingButton: UIButton {
convenience init(title: String) {
self.init(frame: .zero, title: title)
}
init(frame: CGRect, title: String) {
super.init(frame: frame)
backgroundColor = UIColor.offWhite.withAlphaComponent(0.15)
layer.cornerRadius = 2
layer.borderWidth = 1.5
layer.borderColor = UIColor.offWhite.cgColor
setTitle(title, for: .normal)
titleLabel?.font = ._14SemiboldFont()
setTitleColor(.offWhite, for: .normal)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
| mit |
odigeoteam/TableViewKit | Examples/Viper/TableViewKit+VIPER/AboutModule/MoreAboutItem.swift | 1 | 1575 | import Foundation
import TableViewKit
enum MoreAboutItemType {
case faq, contact, terms, feedback, share, rate
func title() -> String {
switch self {
case .faq:
return "FAQ"
case .contact:
return "Contact Us"
case .terms:
return "Terms and Conditions"
case .feedback:
return "Send us your feedback"
case .share:
return "Share the app"
case .rate:
return "Rate the app"
}
}
}
class MoreAboutItem: TableItem, Selectable, Editable {
public static var drawer = AnyCellDrawer(MoreAboutDrawer.self)
var type: MoreAboutItemType
var title: String?
var onSelection: (Selectable) -> Void = { _ in }
var actions: [UITableViewRowAction]?
weak var manager: TableViewManager?
let presenter: AboutPresenterProtocol?
init(type: MoreAboutItemType, presenter: AboutPresenterProtocol?, manager: TableViewManager?) {
self.presenter = presenter
self.manager = manager
self.type = type
self.title = type.title()
}
func didSelect() {
switch type {
case .faq:
presenter?.showFaq()
case .contact:
presenter?.showContactUs()
case .terms:
presenter?.showTermsAndConditions()
case .feedback:
presenter?.showFeedback()
case .share:
presenter?.showShareApp()
case .rate:
presenter?.showRateApp()
}
deselect(animated: true)
}
}
| mit |
ahoppen/swift | validation-test/stdlib/FixedPointConversion/FixedPointConversion_Release32_ToUInt32.swift | 9 | 16797 | //===----------------------------------------------------------------------===//
//
// Automatically Generated From ./Inputs/FixedPointConversion.swift.gyb
// Do Not Edit Directly!
//
//===----------------------------------------------------------------------===//
//
// REQUIRES: executable_test
// REQUIRES: PTRSIZE=32
// RUN: %target-run-simple-swift(-O)
// END.
//
//===----------------------------------------------------------------------===//
import StdlibUnittest
let FixedPointConversion_Release32_ToUInt32 = TestSuite(
"FixedPointConversion_Release32_ToUInt32"
)
//===----------------------------------------------------------------------===//
// MARK: UInt8: (+0)...(+255)
//===----------------------------------------------------------------------===//
FixedPointConversion_Release32_ToUInt32
.test("FromUInt8_NeverTraps")
.forEach(in: [
(getUInt32(+0), getUInt8(+0)),
(getUInt32(+255), getUInt8(+255)),
]) {
expectEqual($0.0, UInt32($0.1))
}
FixedPointConversion_Release32_ToUInt32
.test("FromUInt8_NeverFails")
.forEach(in: [
(getUInt32(+0), getUInt8(+0)),
(getUInt32(+255), getUInt8(+255)),
]) {
expectEqual($0.0, UInt32(exactly: $0.1))
}
//===----------------------------------------------------------------------===//
// MARK: Int8: (-128)...(+127)
//===----------------------------------------------------------------------===//
FixedPointConversion_Release32_ToUInt32
.test("FromInt8_NeverTraps")
.forEach(in: [
(getUInt32(+0), getInt8(+0)),
(getUInt32(+127), getInt8(+127)),
]) {
expectEqual($0.0, UInt32($0.1))
}
FixedPointConversion_Release32_ToUInt32
.test("FromInt8_NeverFails")
.forEach(in: [
(getUInt32(+0), getInt8(+0)),
(getUInt32(+127), getInt8(+127)),
]) {
expectEqual($0.0, UInt32(exactly: $0.1))
}
FixedPointConversion_Release32_ToUInt32
.test("FromInt8_AlwaysTraps")
.forEach(in: [
getInt8(-128),
getInt8(-1),
]) {
expectCrashLater()
_blackHole(UInt32($0))
}
FixedPointConversion_Release32_ToUInt32
.test("FromInt8_AlwaysFails")
.forEach(in: [
getInt8(-128),
getInt8(-1),
]) {
expectNil(UInt32(exactly: $0))
}
//===----------------------------------------------------------------------===//
// MARK: UInt16: (+0)...(+65535)
//===----------------------------------------------------------------------===//
FixedPointConversion_Release32_ToUInt32
.test("FromUInt16_NeverTraps")
.forEach(in: [
(getUInt32(+0), getUInt16(+0)),
(getUInt32(+65535), getUInt16(+65535)),
]) {
expectEqual($0.0, UInt32($0.1))
}
FixedPointConversion_Release32_ToUInt32
.test("FromUInt16_NeverFails")
.forEach(in: [
(getUInt32(+0), getUInt16(+0)),
(getUInt32(+65535), getUInt16(+65535)),
]) {
expectEqual($0.0, UInt32(exactly: $0.1))
}
//===----------------------------------------------------------------------===//
// MARK: Int16: (-32768)...(+32767)
//===----------------------------------------------------------------------===//
FixedPointConversion_Release32_ToUInt32
.test("FromInt16_NeverTraps")
.forEach(in: [
(getUInt32(+0), getInt16(+0)),
(getUInt32(+32767), getInt16(+32767)),
]) {
expectEqual($0.0, UInt32($0.1))
}
FixedPointConversion_Release32_ToUInt32
.test("FromInt16_NeverFails")
.forEach(in: [
(getUInt32(+0), getInt16(+0)),
(getUInt32(+32767), getInt16(+32767)),
]) {
expectEqual($0.0, UInt32(exactly: $0.1))
}
FixedPointConversion_Release32_ToUInt32
.test("FromInt16_AlwaysTraps")
.forEach(in: [
getInt16(-32768),
getInt16(-1),
]) {
expectCrashLater()
_blackHole(UInt32($0))
}
FixedPointConversion_Release32_ToUInt32
.test("FromInt16_AlwaysFails")
.forEach(in: [
getInt16(-32768),
getInt16(-1),
]) {
expectNil(UInt32(exactly: $0))
}
//===----------------------------------------------------------------------===//
// MARK: UInt32: (+0)...(+4294967295)
//===----------------------------------------------------------------------===//
FixedPointConversion_Release32_ToUInt32
.test("FromUInt32_NeverTraps")
.forEach(in: [
(getUInt32(+0), getUInt32(+0)),
(getUInt32(+4294967295), getUInt32(+4294967295)),
]) {
expectEqual($0.0, UInt32($0.1))
}
FixedPointConversion_Release32_ToUInt32
.test("FromUInt32_NeverFails")
.forEach(in: [
(getUInt32(+0), getUInt32(+0)),
(getUInt32(+4294967295), getUInt32(+4294967295)),
]) {
expectEqual($0.0, UInt32(exactly: $0.1))
}
//===----------------------------------------------------------------------===//
// MARK: Int32: (-2147483648)...(+2147483647)
//===----------------------------------------------------------------------===//
FixedPointConversion_Release32_ToUInt32
.test("FromInt32_NeverTraps")
.forEach(in: [
(getUInt32(+0), getInt32(+0)),
(getUInt32(+2147483647), getInt32(+2147483647)),
]) {
expectEqual($0.0, UInt32($0.1))
}
FixedPointConversion_Release32_ToUInt32
.test("FromInt32_NeverFails")
.forEach(in: [
(getUInt32(+0), getInt32(+0)),
(getUInt32(+2147483647), getInt32(+2147483647)),
]) {
expectEqual($0.0, UInt32(exactly: $0.1))
}
FixedPointConversion_Release32_ToUInt32
.test("FromInt32_AlwaysTraps")
.forEach(in: [
getInt32(-2147483648),
getInt32(-1),
]) {
expectCrashLater()
_blackHole(UInt32($0))
}
FixedPointConversion_Release32_ToUInt32
.test("FromInt32_AlwaysFails")
.forEach(in: [
getInt32(-2147483648),
getInt32(-1),
]) {
expectNil(UInt32(exactly: $0))
}
//===----------------------------------------------------------------------===//
// MARK: UInt64: (+0)...(+18446744073709551615)
//===----------------------------------------------------------------------===//
FixedPointConversion_Release32_ToUInt32
.test("FromUInt64_NeverTraps")
.forEach(in: [
(getUInt32(+0), getUInt64(+0)),
(getUInt32(+4294967295), getUInt64(+4294967295)),
]) {
expectEqual($0.0, UInt32($0.1))
}
FixedPointConversion_Release32_ToUInt32
.test("FromUInt64_NeverFails")
.forEach(in: [
(getUInt32(+0), getUInt64(+0)),
(getUInt32(+4294967295), getUInt64(+4294967295)),
]) {
expectEqual($0.0, UInt32(exactly: $0.1))
}
FixedPointConversion_Release32_ToUInt32
.test("FromUInt64_AlwaysTraps")
.forEach(in: [
getUInt64(+4294967296),
getUInt64(+18446744073709551615),
]) {
expectCrashLater()
_blackHole(UInt32($0))
}
FixedPointConversion_Release32_ToUInt32
.test("FromUInt64_AlwaysFails")
.forEach(in: [
getUInt64(+4294967296),
getUInt64(+18446744073709551615),
]) {
expectNil(UInt32(exactly: $0))
}
//===----------------------------------------------------------------------===//
// MARK: Int64: (-9223372036854775808)...(+9223372036854775807)
//===----------------------------------------------------------------------===//
FixedPointConversion_Release32_ToUInt32
.test("FromInt64_NeverTraps")
.forEach(in: [
(getUInt32(+0), getInt64(+0)),
(getUInt32(+4294967295), getInt64(+4294967295)),
]) {
expectEqual($0.0, UInt32($0.1))
}
FixedPointConversion_Release32_ToUInt32
.test("FromInt64_NeverFails")
.forEach(in: [
(getUInt32(+0), getInt64(+0)),
(getUInt32(+4294967295), getInt64(+4294967295)),
]) {
expectEqual($0.0, UInt32(exactly: $0.1))
}
FixedPointConversion_Release32_ToUInt32
.test("FromInt64_AlwaysTraps")
.forEach(in: [
getInt64(-9223372036854775808),
getInt64(-1),
getInt64(+4294967296),
getInt64(+9223372036854775807),
]) {
expectCrashLater()
_blackHole(UInt32($0))
}
FixedPointConversion_Release32_ToUInt32
.test("FromInt64_AlwaysFails")
.forEach(in: [
getInt64(-9223372036854775808),
getInt64(-1),
getInt64(+4294967296),
getInt64(+9223372036854775807),
]) {
expectNil(UInt32(exactly: $0))
}
//===----------------------------------------------------------------------===//
// MARK: UInt: (+0)...(+4294967295)
//===----------------------------------------------------------------------===//
FixedPointConversion_Release32_ToUInt32
.test("FromUInt_NeverTraps")
.forEach(in: [
(getUInt32(+0), getUInt(+0)),
(getUInt32(+4294967295), getUInt(+4294967295)),
]) {
expectEqual($0.0, UInt32($0.1))
}
FixedPointConversion_Release32_ToUInt32
.test("FromUInt_NeverFails")
.forEach(in: [
(getUInt32(+0), getUInt(+0)),
(getUInt32(+4294967295), getUInt(+4294967295)),
]) {
expectEqual($0.0, UInt32(exactly: $0.1))
}
//===----------------------------------------------------------------------===//
// MARK: Int: (-2147483648)...(+2147483647)
//===----------------------------------------------------------------------===//
FixedPointConversion_Release32_ToUInt32
.test("FromInt_NeverTraps")
.forEach(in: [
(getUInt32(+0), getInt(+0)),
(getUInt32(+2147483647), getInt(+2147483647)),
]) {
expectEqual($0.0, UInt32($0.1))
}
FixedPointConversion_Release32_ToUInt32
.test("FromInt_NeverFails")
.forEach(in: [
(getUInt32(+0), getInt(+0)),
(getUInt32(+2147483647), getInt(+2147483647)),
]) {
expectEqual($0.0, UInt32(exactly: $0.1))
}
FixedPointConversion_Release32_ToUInt32
.test("FromInt_AlwaysTraps")
.forEach(in: [
getInt(-2147483648),
getInt(-1),
]) {
expectCrashLater()
_blackHole(UInt32($0))
}
FixedPointConversion_Release32_ToUInt32
.test("FromInt_AlwaysFails")
.forEach(in: [
getInt(-2147483648),
getInt(-1),
]) {
expectNil(UInt32(exactly: $0))
}
//===----------------------------------------------------------------------===//
// MARK: Float16: (-2047)...(+2047)
//===----------------------------------------------------------------------===//
#if !((os(macOS) || targetEnvironment(macCatalyst)) && arch(x86_64))
if #available(SwiftStdlib 5.3, *) {
FixedPointConversion_Release32_ToUInt32
.test("FromFloat16_NeverTraps")
.forEach(in: [
(getUInt32(+0), getFloat16(-0.5)),
(getUInt32(+0), getFloat16(+0)),
(getUInt32(+0), getFloat16(-0)),
(getUInt32(+0), getFloat16(+0.5)),
(getUInt32(+127), getFloat16(+127.5)),
(getUInt32(+255), getFloat16(+255.5)),
(getUInt32(+2047), getFloat16(+2047)),
]) {
expectEqual($0.0, UInt32($0.1))
}
FixedPointConversion_Release32_ToUInt32
.test("FromFloat16_NeverFails")
.forEach(in: [
(getUInt32(+0), getFloat16(+0)),
(getUInt32(+0), getFloat16(-0)),
(getUInt32(+2047), getFloat16(+2047)),
]) {
expectEqual($0.0, UInt32(exactly: $0.1))
}
FixedPointConversion_Release32_ToUInt32
.test("FromFloat16_AlwaysTraps")
.forEach(in: [
getFloat16(-2047),
getFloat16(-128.5),
getFloat16(-1),
getFloat16(-.infinity),
getFloat16(-.nan),
getFloat16(-.signalingNaN),
getFloat16(+.infinity),
getFloat16(+.nan),
getFloat16(+.signalingNaN),
]) {
expectCrashLater()
_blackHole(UInt32($0))
}
FixedPointConversion_Release32_ToUInt32
.test("FromFloat16_AlwaysFails")
.forEach(in: [
getFloat16(-2047),
getFloat16(-128.5),
getFloat16(-1),
getFloat16(-0.5),
getFloat16(+0.5),
getFloat16(+127.5),
getFloat16(+255.5),
getFloat16(-.infinity),
getFloat16(-.nan),
getFloat16(-.signalingNaN),
getFloat16(+.infinity),
getFloat16(+.nan),
getFloat16(+.signalingNaN),
]) {
expectNil(UInt32(exactly: $0))
}
}
#endif // Float16
//===----------------------------------------------------------------------===//
// MARK: Float32: (-16777215)...(+16777215)
//===----------------------------------------------------------------------===//
FixedPointConversion_Release32_ToUInt32
.test("FromFloat32_NeverTraps")
.forEach(in: [
(getUInt32(+0), getFloat32(-0.5)),
(getUInt32(+0), getFloat32(+0)),
(getUInt32(+0), getFloat32(-0)),
(getUInt32(+0), getFloat32(+0.5)),
(getUInt32(+127), getFloat32(+127.5)),
(getUInt32(+255), getFloat32(+255.5)),
(getUInt32(+32767), getFloat32(+32767.5)),
(getUInt32(+65535), getFloat32(+65535.5)),
(getUInt32(+16777215), getFloat32(+16777215)),
]) {
expectEqual($0.0, UInt32($0.1))
}
FixedPointConversion_Release32_ToUInt32
.test("FromFloat32_NeverFails")
.forEach(in: [
(getUInt32(+0), getFloat32(+0)),
(getUInt32(+0), getFloat32(-0)),
(getUInt32(+16777215), getFloat32(+16777215)),
]) {
expectEqual($0.0, UInt32(exactly: $0.1))
}
FixedPointConversion_Release32_ToUInt32
.test("FromFloat32_AlwaysTraps")
.forEach(in: [
getFloat32(-16777215),
getFloat32(-32768.5),
getFloat32(-128.5),
getFloat32(-1),
getFloat32(-.infinity),
getFloat32(-.nan),
getFloat32(-.signalingNaN),
getFloat32(+.infinity),
getFloat32(+.nan),
getFloat32(+.signalingNaN),
]) {
expectCrashLater()
_blackHole(UInt32($0))
}
FixedPointConversion_Release32_ToUInt32
.test("FromFloat32_AlwaysFails")
.forEach(in: [
getFloat32(-16777215),
getFloat32(-32768.5),
getFloat32(-128.5),
getFloat32(-1),
getFloat32(-0.5),
getFloat32(+0.5),
getFloat32(+127.5),
getFloat32(+255.5),
getFloat32(+32767.5),
getFloat32(+65535.5),
getFloat32(-.infinity),
getFloat32(-.nan),
getFloat32(-.signalingNaN),
getFloat32(+.infinity),
getFloat32(+.nan),
getFloat32(+.signalingNaN),
]) {
expectNil(UInt32(exactly: $0))
}
//===----------------------------------------------------------------------===//
// MARK: Float64: (-9007199254740991)...(+9007199254740991)
//===----------------------------------------------------------------------===//
FixedPointConversion_Release32_ToUInt32
.test("FromFloat64_NeverTraps")
.forEach(in: [
(getUInt32(+0), getFloat64(-0.5)),
(getUInt32(+0), getFloat64(+0)),
(getUInt32(+0), getFloat64(-0)),
(getUInt32(+0), getFloat64(+0.5)),
(getUInt32(+127), getFloat64(+127.5)),
(getUInt32(+255), getFloat64(+255.5)),
(getUInt32(+32767), getFloat64(+32767.5)),
(getUInt32(+65535), getFloat64(+65535.5)),
(getUInt32(+4294967295), getFloat64(+4294967295)),
]) {
expectEqual($0.0, UInt32($0.1))
}
FixedPointConversion_Release32_ToUInt32
.test("FromFloat64_NeverFails")
.forEach(in: [
(getUInt32(+0), getFloat64(+0)),
(getUInt32(+0), getFloat64(-0)),
(getUInt32(+4294967295), getFloat64(+4294967295)),
]) {
expectEqual($0.0, UInt32(exactly: $0.1))
}
FixedPointConversion_Release32_ToUInt32
.test("FromFloat64_AlwaysTraps")
.forEach(in: [
getFloat64(-9007199254740991),
getFloat64(-32768.5),
getFloat64(-128.5),
getFloat64(-1),
getFloat64(+4294967296),
getFloat64(+9007199254740991),
getFloat64(-.infinity),
getFloat64(-.nan),
getFloat64(-.signalingNaN),
getFloat64(+.infinity),
getFloat64(+.nan),
getFloat64(+.signalingNaN),
]) {
expectCrashLater()
_blackHole(UInt32($0))
}
FixedPointConversion_Release32_ToUInt32
.test("FromFloat64_AlwaysFails")
.forEach(in: [
getFloat64(-9007199254740991),
getFloat64(-32768.5),
getFloat64(-128.5),
getFloat64(-1),
getFloat64(-0.5),
getFloat64(+0.5),
getFloat64(+127.5),
getFloat64(+255.5),
getFloat64(+32767.5),
getFloat64(+65535.5),
getFloat64(+4294967296),
getFloat64(+9007199254740991),
getFloat64(-.infinity),
getFloat64(-.nan),
getFloat64(-.signalingNaN),
getFloat64(+.infinity),
getFloat64(+.nan),
getFloat64(+.signalingNaN),
]) {
expectNil(UInt32(exactly: $0))
}
//===----------------------------------------------------------------------===//
// MARK: Float80: (-18446744073709551615)...(+18446744073709551615)
//===----------------------------------------------------------------------===//
#if !(os(Windows) || os(Android)) && (arch(i386) || arch(x86_64))
FixedPointConversion_Release32_ToUInt32
.test("FromFloat80_NeverTraps")
.forEach(in: [
(getUInt32(+0), getFloat80(-0.5)),
(getUInt32(+0), getFloat80(+0)),
(getUInt32(+0), getFloat80(-0)),
(getUInt32(+0), getFloat80(+0.5)),
(getUInt32(+127), getFloat80(+127.5)),
(getUInt32(+255), getFloat80(+255.5)),
(getUInt32(+32767), getFloat80(+32767.5)),
(getUInt32(+65535), getFloat80(+65535.5)),
(getUInt32(+4294967295), getFloat80(+4294967295)),
]) {
expectEqual($0.0, UInt32($0.1))
}
FixedPointConversion_Release32_ToUInt32
.test("FromFloat80_NeverFails")
.forEach(in: [
(getUInt32(+0), getFloat80(+0)),
(getUInt32(+0), getFloat80(-0)),
(getUInt32(+4294967295), getFloat80(+4294967295)),
]) {
expectEqual($0.0, UInt32(exactly: $0.1))
}
FixedPointConversion_Release32_ToUInt32
.test("FromFloat80_AlwaysTraps")
.forEach(in: [
getFloat80(-18446744073709551615),
getFloat80(-32768.5),
getFloat80(-128.5),
getFloat80(-1),
getFloat80(+4294967296),
getFloat80(+18446744073709551615),
getFloat80(-.infinity),
getFloat80(-.nan),
getFloat80(-.signalingNaN),
getFloat80(+.infinity),
getFloat80(+.nan),
getFloat80(+.signalingNaN),
]) {
expectCrashLater()
_blackHole(UInt32($0))
}
FixedPointConversion_Release32_ToUInt32
.test("FromFloat80_AlwaysFails")
.forEach(in: [
getFloat80(-18446744073709551615),
getFloat80(-32768.5),
getFloat80(-128.5),
getFloat80(-1),
getFloat80(-0.5),
getFloat80(+0.5),
getFloat80(+127.5),
getFloat80(+255.5),
getFloat80(+32767.5),
getFloat80(+65535.5),
getFloat80(+4294967296),
getFloat80(+18446744073709551615),
getFloat80(-.infinity),
getFloat80(-.nan),
getFloat80(-.signalingNaN),
getFloat80(+.infinity),
getFloat80(+.nan),
getFloat80(+.signalingNaN),
]) {
expectNil(UInt32(exactly: $0))
}
#endif // Float80
runAllTests()
| apache-2.0 |
Harley-xk/Chrysan | Chrysan/Sources/Responders/HUDBarProgressView.swift | 1 | 2190 | //
// HUDBarProgressView.swift
// Chrysan
//
// Created by Harley-xk on 2020/9/28.
// Copyright © 2020 Harley. All rights reserved.
//
import Foundation
import UIKit
import SnapKit
public class HUDBarProgressView: UIView, StatusIndicatorView {
public struct Options {
public init() {}
public var barSize = CGSize(width: 200, height: 15)
public var barColor = UIColor.systemBlue
public var barBackgroundColor = UIColor.darkGray
public var textColor = UIColor.white
public var textFont = UIFont.systemFont(ofSize: 11)
}
public class func makeBar(with options: Options) -> HUDBarProgressView {
let barView = HUDBarProgressView(options: options)
return barView
}
public let progressView: ProgressIndicatorView = HorizontalProgressBar()
public let textLabel = UILabel()
init(options: Options) {
super.init(frame: CGRect(origin: .zero, size: options.barSize))
self.options = options
setup()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
setup()
}
private var options: Options = Options()
private func setup() {
addSubview(progressView)
progressView.snp.makeConstraints {
// $0.center.equalToSuperview()
$0.left.right.equalToSuperview()
$0.top.bottom.equalToSuperview().inset(10)
$0.size.equalTo(options.barSize)
}
addSubview(textLabel)
textLabel.snp.makeConstraints {
$0.center.equalToSuperview()
}
updateOptions()
}
func updateOptions() {
progressView.tintColor = options.barColor
progressView.backgroundColor = options.barBackgroundColor
textLabel.font = options.textFont
textLabel.textColor = options.textColor
setNeedsDisplay()
}
public func updateStatus(from: Status, to new: Status) {
let progress = CGFloat(new.progress ?? 0)
progressView.progress = progress
textLabel.text = new.progressText ?? String(format: "%.0f%%", progress * 100)
}
}
| mit |
wangrui460/WRNavigationBar_swift | WRNavigationBar_swift/Pods/Kingfisher/Sources/CacheSerializer.swift | 5 | 3729 | //
// CacheSerializer.swift
// Kingfisher
//
// Created by Wei Wang on 2016/09/02.
//
// Copyright (c) 2017 Wei Wang <onevcat@gmail.com>
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import Foundation
/// An `CacheSerializer` would be used to convert some data to an image object for
/// retrieving from disk cache and vice versa for storing to disk cache.
public protocol CacheSerializer {
/// Get the serialized data from a provided image
/// and optional original data for caching to disk.
///
///
/// - parameter image: The image needed to be serialized.
/// - parameter original: The original data which is just downloaded.
/// If the image is retrieved from cache instead of
/// downloaded, it will be `nil`.
///
/// - returns: A data which will be stored to cache, or `nil` when no valid
/// data could be serialized.
func data(with image: Image, original: Data?) -> Data?
/// Get an image deserialized from provided data.
///
/// - parameter data: The data from which an image should be deserialized.
/// - parameter options: Options for deserialization.
///
/// - returns: An image deserialized or `nil` when no valid image
/// could be deserialized.
func image(with data: Data, options: KingfisherOptionsInfo?) -> Image?
}
/// `DefaultCacheSerializer` is a basic `CacheSerializer` used in default cache of
/// Kingfisher. It could serialize and deserialize PNG, JEPG and GIF images. For
/// image other than these formats, a normalized `pngRepresentation` will be used.
public struct DefaultCacheSerializer: CacheSerializer {
public static let `default` = DefaultCacheSerializer()
private init() {}
public func data(with image: Image, original: Data?) -> Data? {
let imageFormat = original?.kf.imageFormat ?? .unknown
let data: Data?
switch imageFormat {
case .PNG: data = image.kf.pngRepresentation()
case .JPEG: data = image.kf.jpegRepresentation(compressionQuality: 1.0)
case .GIF: data = image.kf.gifRepresentation()
case .unknown: data = original ?? image.kf.normalized.kf.pngRepresentation()
}
return data
}
public func image(with data: Data, options: KingfisherOptionsInfo?) -> Image? {
let options = options ?? KingfisherEmptyOptionsInfo
return Kingfisher<Image>.image(
data: data,
scale: options.scaleFactor,
preloadAllAnimationData: options.preloadAllAnimationData,
onlyFirstFrame: options.onlyLoadFirstFrame)
}
}
| mit |
dasdom/Swiftandpainless | SwiftAndPainless_3.playground/Pages/Generics III.xcplaygroundpage/Contents.swift | 1 | 532 | import Foundation
/*:
[⬅️](@previous) [➡️](@next)
# Generics III
*/
struct ExclusiveStack<Element where Element: Equatable>: CustomStringConvertible {
var items = [Element]()
mutating func push(item: Element) {
if !items.contains(item) {
items.append(item)
}
}
mutating func pop() -> Element {
return items.removeLast()
}
var description: String {
return "\(items)"
}
}
var stringStack = ExclusiveStack<String>()
stringStack.push("foo")
stringStack.push("bar")
stringStack.push("foo") | mit |
tuzaiz/UniformString | UniformString/UniformString/AppDelegate.swift | 1 | 2151 | //
// AppDelegate.swift
// UniformString
//
// Created by Henry Tseng on 2015/2/12.
// Copyright (c) 2015年 Cloudbay. All rights reserved.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
// Override point for customization after application launch.
return true
}
func applicationWillResignActive(application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}
func applicationDidEnterBackground(application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(application: UIApplication) {
// Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}
}
| mit |
practicalswift/swift | test/decl/ext/extensions.swift | 11 | 3642 | // RUN: %target-typecheck-verify-swift
extension extension_for_invalid_type_1 { // expected-error {{use of undeclared type 'extension_for_invalid_type_1'}}
func f() { }
}
extension extension_for_invalid_type_2 { // expected-error {{use of undeclared type 'extension_for_invalid_type_2'}}
static func f() { }
}
extension extension_for_invalid_type_3 { // expected-error {{use of undeclared type 'extension_for_invalid_type_3'}}
init() {}
}
extension extension_for_invalid_type_4 { // expected-error {{use of undeclared type 'extension_for_invalid_type_4'}}
deinit {} // expected-error {{deinitializers may only be declared within a class}}
}
extension extension_for_invalid_type_5 { // expected-error {{use of undeclared type 'extension_for_invalid_type_5'}}
typealias X = Int
}
//===--- Test that we only allow extensions at file scope.
struct Foo { }
extension NestingTest1 { // expected-error {{use of undeclared type 'NestingTest1'}}
extension Foo {} // expected-error {{declaration is only valid at file scope}}
}
struct NestingTest2 {
extension Foo {} // expected-error {{declaration is only valid at file scope}}
}
class NestingTest3 {
extension Foo {} // expected-error {{declaration is only valid at file scope}}
}
enum NestingTest4 {
extension Foo {} // expected-error {{declaration is only valid at file scope}}
}
protocol NestingTest5 {
extension Foo {} // expected-error {{declaration is only valid at file scope}}
}
func nestingTest6() {
extension Foo {} // expected-error {{declaration is only valid at file scope}}
}
//===--- Test that we only allow extensions only for nominal types.
struct S1 {
struct NestedStruct {}
}
extension S1 {} // no-error
extension S1.Type {} // expected-error {{cannot extend a metatype 'S1.Type'}}
extension S1.NestedStruct {} // no-error
struct S1_2 {
// expected-error @+2 {{type member must not be named 'Type', since it would conflict with the 'foo.Type' expression}}
// expected-note @+1 {{if this name is unavoidable, use backticks to escape it}} {{8-12=`Type`}}
enum Type {}
}
struct S1_3 {
enum `Type` {} // no-error
}
extension S1_2.Type {} // expected-error {{cannot extend a metatype 'S1_2.Type'}}
extension S1_3.`Type` {} // no-error
typealias TA_S1 = S1
extension TA_S1 {} // no-error
typealias TA_S1_NestedStruct = S1.NestedStruct
extension TA_S1_NestedStruct {} // no-error
enum U1 {
struct NestedStruct {}
}
extension U1 {} // no-error
extension U1.NestedStruct {} // no-error
class C1 {
struct NestedStruct {}
}
extension C1 {} // no-error
extension C1.NestedStruct {} // no-error
protocol P1 {}
protocol P2 {}
extension () {} // expected-error {{non-nominal type '()' cannot be extended}}
typealias TupleAlias = (x: Int, y: Int)
extension TupleAlias {} // expected-error{{non-nominal type 'TupleAlias' (aka '(x: Int, y: Int)') cannot be extended}}
// Test property accessors in extended types
class C {}
extension C {
var p1: Int {
get {return 1}
set(v) {}
}
}
var c = C()
var x = c.p1
c.p1 = 1
protocol P3 {
associatedtype Assoc
func foo() -> Assoc
}
struct X3 : P3 {
}
extension X3.Assoc { // expected-error{{'Assoc' is not a member type of 'X3'}}
}
extension X3 {
func foo() -> Int { return 0 }
}
// Make sure the test case from https://bugs.swift.org/browse/SR-3847 doesn't
// cause problems when the later extension is incorrectly nested inside another
// declaration.
extension C1.NestedStruct {
static let originalValue = 0
}
struct WrapperContext {
extension C1.NestedStruct { // expected-error {{declaration is only valid at file scope}}
static let propUsingMember = originalValue
}
}
| apache-2.0 |
zwaldowski/Lustre | Lustre/Optional.swift | 1 | 566 | //
// Optional.swift
// Lustre
//
// Created by Zachary Waldowski on 6/11/15.
// Copyright © 2014-2015. Some rights reserved.
//
extension Optional: EitherType {
public init(left: Void) {
self = .None
}
public init(right: Wrapped) {
self = .Some(right)
}
public func analysis<Result>(@noescape ifLeft ifLeft: Void -> Result, @noescape ifRight: Wrapped -> Result) -> Result {
switch self {
case .None: return ifLeft()
case .Some(let value): return ifRight(value)
}
}
}
| mit |
Zerofinancial/relay | Relay/URLSessionProtocol.swift | 1 | 478 | //
// URLSessionProtocol.swift
// Relay
//
// Created by Evan Kimia on 5/2/17.
// Copyright © 2017 zero. All rights reserved.
//
import Foundation
public protocol URLSessionProtocol {
var delegate: URLSessionDelegate? { get }
func uploadTask(with request: URLRequest, fromFile fileURL: URL) -> URLSessionUploadTask
func getAllTasks(completionHandler: @escaping ([URLSessionTask]) -> Swift.Void)
}
extension URLSession: URLSessionProtocol { }
| apache-2.0 |
kemalenver/SwiftHackerRank | Algorithms/Implementation.playground/Pages/Implementation - SockMerchant.xcplaygroundpage/Contents.swift | 1 | 505 | // number of elements
var n = 9
// read array and map the elements to integer
var readLine = "10 20 20 10 10 30 50 10 20"
var arr = readLine.split(separator: " ").map { Int(String($0))! }
var matches = [Int:Int]()
for x in arr {
if var count = matches[x] {
count += 1
matches[x] = count
} else {
matches[x] = 1
}
}
var pairs = 0
for (_, value) in matches {
let currentPair = Int(value / 2)
pairs += currentPair
}
print(pairs)
| mit |
mingsai/ColorWheel | ColorWheelTests/ColorWheelTests.swift | 1 | 927 | //
// ColorWheelTests.swift
// ColorWheelTests
//
// Created by Tommie N. Carter, Jr., MBA on 4/9/15.
// Copyright (c) 2015 MING Technology. All rights reserved.
//
import UIKit
import XCTest
class ColorWheelTests: XCTestCase {
override func setUp() {
super.setUp()
// Put setup code here. This method is called before the invocation of each test method in the class.
}
override func tearDown() {
// Put teardown code here. This method is called after the invocation of each test method in the class.
super.tearDown()
}
func testExample() {
// This is an example of a functional test case.
XCTAssert(true, "Pass")
}
func testPerformanceExample() {
// This is an example of a performance test case.
self.measureBlock() {
// Put the code you want to measure the time of here.
}
}
}
| gpl-3.0 |
jsmerola/Caffeinator | CaffeinatorTests/CaffeinatorTests.swift | 1 | 912 | //
// CaffeinatorTests.swift
// CaffeinatorTests
//
// Created by Jeff Merola on 3/21/15.
// Copyright (c) 2015 Jeff Merola. All rights reserved.
//
import Cocoa
import XCTest
class CaffeinatorTests: XCTestCase {
override func setUp() {
super.setUp()
// Put setup code here. This method is called before the invocation of each test method in the class.
}
override func tearDown() {
// Put teardown code here. This method is called after the invocation of each test method in the class.
super.tearDown()
}
func testExample() {
// This is an example of a functional test case.
XCTAssert(true, "Pass")
}
func testPerformanceExample() {
// This is an example of a performance test case.
self.measureBlock() {
// Put the code you want to measure the time of here.
}
}
}
| mit |
cnoon/swift-compiler-crashes | crashes-duplicates/05627-swift-sourcemanager-getmessage.swift | 11 | 227 | // Distributed under the terms of the MIT license
// Test case submitted to project by https://github.com/practicalswift (practicalswift)
// Test case found by fuzzing
struct d<f : P {
let t: a {
case c,
([Void{
class
case c,
| mit |
ZwxWhite/V2EX | V2EX/Pods/PagingMenuController/Pod/Classes/MenuItemView.swift | 2 | 4795 | //
// MenuItemView.swift
// PagingMenuController
//
// Created by Yusuke Kita on 5/9/15.
// Copyright (c) 2015 kitasuke. All rights reserved.
//
import UIKit
public class MenuItemView: UIView {
public private(set) var titleLabel: UILabel!
private var options: PagingMenuOptions!
private var title: String!
private var widthLabelConstraint: NSLayoutConstraint!
// MARK: - Lifecycle
internal init(title: String, options: PagingMenuOptions) {
super.init(frame: CGRectZero)
self.options = options
self.title = title
setupView()
constructLabel()
layoutLabel()
}
required public init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
override init(frame: CGRect) {
super.init(frame: frame)
}
// MARK: - Constraints manager
internal func updateLabelConstraints(size size: CGSize) {
// set width manually to support ratotaion
if case .SegmentedControl = options.menuDisplayMode {
let labelSize = calculateLableSize(size)
widthLabelConstraint.constant = labelSize.width
}
}
// MARK: - Label changer
internal func focusLabel(selected: Bool) {
if case .RoundRect = options.menuItemMode {
backgroundColor = UIColor.clearColor()
} else {
backgroundColor = selected ? options.selectedBackgroundColor : options.backgroundColor
}
titleLabel.textColor = selected ? options.selectedTextColor : options.textColor
titleLabel.font = selected ? options.selectedFont : options.font
// adjust label width if needed
let labelSize = calculateLableSize()
widthLabelConstraint.constant = labelSize.width
}
// MARK: - Constructor
private func setupView() {
if case .RoundRect = options.menuItemMode {
backgroundColor = UIColor.clearColor()
} else {
backgroundColor = options.backgroundColor
}
translatesAutoresizingMaskIntoConstraints = false
}
private func constructLabel() {
titleLabel = UILabel()
titleLabel.text = title
titleLabel.textColor = options.textColor
titleLabel.font = options.font
titleLabel.numberOfLines = 1
titleLabel.textAlignment = NSTextAlignment.Center
titleLabel.userInteractionEnabled = true
titleLabel.translatesAutoresizingMaskIntoConstraints = false
addSubview(titleLabel)
}
private func layoutLabel() {
let viewsDictionary = ["label": titleLabel]
let labelSize = calculateLableSize()
let horizontalConstraints = NSLayoutConstraint.constraintsWithVisualFormat("H:|[label]|", options: [], metrics: nil, views: viewsDictionary)
let verticalConstraints = NSLayoutConstraint.constraintsWithVisualFormat("V:|[label]|", options: [], metrics: nil, views: viewsDictionary)
NSLayoutConstraint.activateConstraints(horizontalConstraints + verticalConstraints)
widthLabelConstraint = NSLayoutConstraint(item: titleLabel, attribute: NSLayoutAttribute.Width, relatedBy: NSLayoutRelation.Equal, toItem: nil, attribute: NSLayoutAttribute.Width, multiplier: 1.0, constant: labelSize.width)
widthLabelConstraint.active = true
}
// MARK: - Size calculator
private func calculateLableSize(size: CGSize = UIScreen.mainScreen().bounds.size) -> CGSize {
let labelSize = NSString(string: title).boundingRectWithSize(CGSizeMake(CGFloat.max, CGFloat.max), options: NSStringDrawingOptions.UsesLineFragmentOrigin, attributes: [NSFontAttributeName: titleLabel.font], context: nil).size
let itemWidth: CGFloat
switch options.menuDisplayMode {
case let .Standard(widthMode, _, _):
itemWidth = labelWidth(labelSize, widthMode: widthMode)
case .SegmentedControl:
itemWidth = size.width / CGFloat(options.menuItemCount)
case let .Infinite(widthMode):
itemWidth = labelWidth(labelSize, widthMode: widthMode)
}
let itemHeight = floor(labelSize.height)
return CGSizeMake(itemWidth + calculateHorizontalMargin() * 2, itemHeight)
}
private func labelWidth(labelSize: CGSize, widthMode: PagingMenuOptions.MenuItemWidthMode) -> CGFloat {
switch widthMode {
case .Flexible: return ceil(labelSize.width)
case let .Fixed(width): return width
}
}
private func calculateHorizontalMargin() -> CGFloat {
if case .SegmentedControl = options.menuDisplayMode {
return 0.0
}
return options.menuItemMargin
}
}
| mit |
cnoon/swift-compiler-crashes | crashes-duplicates/19195-swift-typechecker-typecheckexpression.swift | 11 | 229 | // Distributed under the terms of the MIT license
// Test case submitted to project by https://github.com/practicalswift (practicalswift)
// Test case found by fuzzing
struct S {
let end = (object : A.b
struct A {
let b = Void{
| mit |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.