repo_name
stringlengths 6
91
| path
stringlengths 8
968
| copies
stringclasses 210
values | size
stringlengths 2
7
| content
stringlengths 61
1.01M
| license
stringclasses 15
values | hash
stringlengths 32
32
| line_mean
float64 6
99.8
| line_max
int64 12
1k
| alpha_frac
float64 0.3
0.91
| ratio
float64 2
9.89
| autogenerated
bool 1
class | config_or_test
bool 2
classes | has_no_keywords
bool 2
classes | has_few_assignments
bool 1
class |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
brentsimmons/Evergreen
|
Shared/Article Extractor/ExtractedArticle.swift
|
1
|
1003
|
//
// ExtractedArticle.swift
// NetNewsWire
//
// Created by Maurice Parker on 9/18/19.
// Copyright © 2019 Ranchero Software. All rights reserved.
//
import Foundation
struct ExtractedArticle: Codable, Equatable {
let title: String?
let author: String?
let datePublished: String?
let dek: String?
let leadImageURL: String?
let content: String?
let nextPageURL: String?
let url: String?
let domain: String?
let excerpt: String?
let wordCount: Int?
let direction: String?
let totalPages: Int?
let renderedPages: Int?
enum CodingKeys: String, CodingKey {
case title = "title"
case author = "author"
case datePublished = "date_published"
case dek = "dek"
case leadImageURL = "lead_image_url"
case content = "content"
case nextPageURL = "next_page_url"
case url = "url"
case domain = "domain"
case excerpt = "excerpt"
case wordCount = "word_count"
case direction = "direction"
case totalPages = "total_pages"
case renderedPages = "rendered_pages"
}
}
|
mit
|
e18407067c6eea7110d0cd407b79f1ea
| 21.266667 | 60 | 0.703593 | 3.242718 | false | false | false | false |
itsaboutcode/WordPress-iOS
|
WordPress/WordPressTest/BloggingRemindersStoreTests.swift
|
2
|
4321
|
import XCTest
@testable import WordPress
class BloggingRemindersStoreTests: XCTestCase {
func testNewlyCreatedBloggingReminderStoreHasNoScheduleForUnscheduledBlog() {
let tempFile = URL(fileURLWithPath: NSTemporaryDirectory(), isDirectory: true).appendingPathComponent("testBlogReminders_" + UUID().uuidString + ".plist")
let blogIdentifier = URL(string: "someBlog")!
let store: BloggingRemindersStore
do {
store = try BloggingRemindersStore(dataFileURL: tempFile)
} catch {
XCTFail(error.localizedDescription)
return
}
XCTAssertEqual(store.scheduledReminders(for: blogIdentifier), .none)
}
func testPreexistingBloggingReminderStoreMaintainsSchedule() {
let tempFile = URL(fileURLWithPath: NSTemporaryDirectory(), isDirectory: true).appendingPathComponent("testBlogReminders_" + UUID().uuidString + ".plist")
let configuration = [
URL(string: "someBlog")!: BloggingRemindersStore.ScheduledReminders.weekdays([
.init(weekday: .monday, notificationID: UUID().uuidString),
.init(weekday: .tuesday, notificationID: UUID().uuidString),
]),
URL(string: "someBlog2")!: BloggingRemindersStore.ScheduledReminders.weekdays([
.init(weekday: .monday, notificationID: UUID().uuidString),
.init(weekday: .wednesday, notificationID: UUID().uuidString),
]),
URL(string: "someBlog3")!: BloggingRemindersStore.ScheduledReminders.weekdays([
.init(weekday: .saturday, notificationID: UUID().uuidString),
.init(weekday: .sunday, notificationID: UUID().uuidString),
]),
]
let store: BloggingRemindersStore
do {
store = try BloggingRemindersStore(dataFileURL: tempFile)
for (blogIdentifier, scheduledReminders) in configuration {
try store.save(scheduledReminders: scheduledReminders, for: blogIdentifier)
}
} catch {
XCTFail(error.localizedDescription)
return
}
// To simulate another launch of the app, we just create another store using
// the same data file, and compare the schedules.
let secondLaunchStore: BloggingRemindersStore
do {
secondLaunchStore = try BloggingRemindersStore(dataFileURL: tempFile)
} catch {
XCTFail(error.localizedDescription)
return
}
XCTAssertEqual(secondLaunchStore.configuration, store.configuration)
}
func testUnschedulingRemindersRemovesEntryForBlog() {
let firstBlogID = URL(string: "someBlog")!
let secondBlogID = URL(string: "someBlog2")!
let tempFile = URL(fileURLWithPath: NSTemporaryDirectory(), isDirectory: true).appendingPathComponent("testBlogReminders_" + UUID().uuidString + ".plist")
let configuration = [
firstBlogID: BloggingRemindersStore.ScheduledReminders.weekdays([
.init(weekday: .monday, notificationID: UUID().uuidString),
.init(weekday: .tuesday, notificationID: UUID().uuidString),
]),
secondBlogID: BloggingRemindersStore.ScheduledReminders.weekdays([
.init(weekday: .monday, notificationID: UUID().uuidString),
.init(weekday: .wednesday, notificationID: UUID().uuidString),
])
]
let store: BloggingRemindersStore
do {
store = try BloggingRemindersStore(dataFileURL: tempFile)
for (blogIdentifier, scheduledReminders) in configuration {
try store.save(scheduledReminders: scheduledReminders, for: blogIdentifier)
}
} catch {
XCTFail(error.localizedDescription)
return
}
XCTAssertEqual(store.configuration, configuration)
try? store.save(scheduledReminders: .none, for: firstBlogID)
// There should now be no entry for the first blog
XCTAssertEqual(store.scheduledReminders(for: firstBlogID), .none)
// There should still be an entry for the second blog
XCTAssertEqual(store.scheduledReminders(for: secondBlogID), configuration[secondBlogID])
}
}
|
gpl-2.0
|
fa7e877a5e948a0987659b08e660c725
| 40.548077 | 162 | 0.647304 | 5.288862 | false | true | false | false |
fastred/IBAnalyzer
|
Pods/SourceKittenFramework/Source/SourceKittenFramework/Structure.swift
|
1
|
1690
|
//
// Structure.swift
// SourceKitten
//
// Created by JP Simard on 2015-01-06.
// Copyright (c) 2015 SourceKitten. All rights reserved.
//
import Foundation
/// Represents the structural information in a Swift source file.
public struct Structure {
/// Structural information as an [String: SourceKitRepresentable].
public let dictionary: [String: SourceKitRepresentable]
/**
Create a Structure from a SourceKit `editor.open` response.
- parameter sourceKitResponse: SourceKit `editor.open` response.
*/
public init(sourceKitResponse: [String: SourceKitRepresentable]) {
var sourceKitResponse = sourceKitResponse
_ = sourceKitResponse.removeValue(forKey: SwiftDocKey.syntaxMap.rawValue)
dictionary = sourceKitResponse
}
/**
Initialize a Structure by passing in a File.
- parameter file: File to parse for structural information.
- throws: Request.Error
*/
public init(file: File) throws {
self.init(sourceKitResponse: try Request.editorOpen(file: file).send())
}
}
// MARK: CustomStringConvertible
extension Structure: CustomStringConvertible {
/// A textual JSON representation of `Structure`.
public var description: String { return toJSON(toNSDictionary(dictionary)) }
}
// MARK: Equatable
extension Structure: Equatable {}
/**
Returns true if `lhs` Structure is equal to `rhs` Structure.
- parameter lhs: Structure to compare to `rhs`.
- parameter rhs: Structure to compare to `lhs`.
- returns: True if `lhs` Structure is equal to `rhs` Structure.
*/
public func == (lhs: Structure, rhs: Structure) -> Bool {
return lhs.dictionary.isEqualTo(rhs.dictionary)
}
|
mit
|
cd72b971746383c4b0561d21ccca8eaa
| 27.644068 | 81 | 0.708876 | 4.470899 | false | false | false | false |
austinzheng/swift
|
test/SILGen/keypath_application.swift
|
12
|
9034
|
// RUN: %target-swift-emit-silgen %s | %FileCheck %s
class A {}
class B {}
protocol P {}
protocol Q {}
// CHECK-LABEL: sil hidden [ossa] @{{.*}}loadable
func loadable(readonly: A, writable: inout A,
value: B,
kp: KeyPath<A, B>,
wkp: WritableKeyPath<A, B>,
rkp: ReferenceWritableKeyPath<A, B>) {
// CHECK: [[ROOT_COPY:%.*]] = copy_value [[READONLY:%0]] :
// CHECK: [[KP_COPY:%.*]] = copy_value [[KP:%3]]
// CHECK: [[ROOT_TMP:%.*]] = alloc_stack $A
// CHECK: store [[ROOT_COPY]] to [init] [[ROOT_TMP]]
// CHECK: [[GET:%.*]] = function_ref @swift_getAtKeyPath :
// CHECK: [[RESULT_TMP:%.*]] = alloc_stack $B
// CHECK: apply [[GET]]<A, B>([[RESULT_TMP]], [[ROOT_TMP]], [[KP_COPY]])
// CHECK: [[RESULT:%.*]] = load [take] [[RESULT_TMP]]
// CHECK: destroy_value [[RESULT]]
_ = readonly[keyPath: kp]
// CHECK: [[ACCESS:%.*]] = begin_access [read] [unknown] [[WRITABLE:%1]] :
// CHECK: [[ROOT_COPY:%.*]] = load [copy] [[ACCESS]]
// CHECK: end_access [[ACCESS]]
// CHECK: [[KP_COPY:%.*]] = copy_value [[KP]]
// CHECK: [[ROOT_TMP:%.*]] = alloc_stack $A
// CHECK: store [[ROOT_COPY]] to [init] [[ROOT_TMP]]
// CHECK: [[GET:%.*]] = function_ref @swift_getAtKeyPath :
// CHECK: [[RESULT_TMP:%.*]] = alloc_stack $B
// CHECK: apply [[GET]]<A, B>([[RESULT_TMP]], [[ROOT_TMP]], [[KP_COPY]])
// CHECK: [[RESULT:%.*]] = load [take] [[RESULT_TMP]]
// CHECK: destroy_value [[RESULT]]
_ = writable[keyPath: kp]
// CHECK: [[ROOT_COPY:%.*]] = copy_value [[READONLY]] :
// CHECK: [[KP_COPY:%.*]] = copy_value [[WKP:%4]]
// CHECK: [[KP_UPCAST:%.*]] = upcast [[KP_COPY]] : $WritableKeyPath<A, B> to $KeyPath<A, B>
// CHECK: [[ROOT_TMP:%.*]] = alloc_stack $A
// CHECK: store [[ROOT_COPY]] to [init] [[ROOT_TMP]]
// CHECK: [[GET:%.*]] = function_ref @swift_getAtKeyPath :
// CHECK: [[RESULT_TMP:%.*]] = alloc_stack $B
// CHECK: apply [[GET]]<A, B>([[RESULT_TMP]], [[ROOT_TMP]], [[KP_UPCAST]])
// CHECK: [[RESULT:%.*]] = load [take] [[RESULT_TMP]]
// CHECK: destroy_value [[RESULT]]
_ = readonly[keyPath: wkp]
// CHECK: function_ref @swift_getAtKeyPath
_ = writable[keyPath: wkp]
// CHECK: function_ref @swift_getAtKeyPath
_ = readonly[keyPath: rkp]
// CHECK: function_ref @swift_getAtKeyPath
_ = writable[keyPath: rkp]
// CHECK: [[KP_COPY:%.*]] = copy_value [[WKP]]
// CHECK-NEXT: [[VALUE_COPY:%.*]] = copy_value [[VALUE:%2]] : $B
// CHECK-NEXT: [[ACCESS:%.*]] = begin_access [modify] [unknown] [[WRITABLE]] :
// CHECK-NEXT: [[VALUE_TEMP:%.*]] = alloc_stack $B
// CHECK-NEXT: store [[VALUE_COPY]] to [init] [[VALUE_TEMP]]
// CHECK-NEXT: // function_ref
// CHECK-NEXT: [[SET:%.*]] = function_ref @swift_setAtWritableKeyPath :
// CHECK-NEXT: apply [[SET]]<A, B>([[ACCESS]], [[KP_COPY]], [[VALUE_TEMP]])
// CHECK-NEXT: end_access [[ACCESS]]
// CHECK-NEXT: dealloc_stack [[VALUE_TEMP]]
// CHECK-NEXT: destroy_value [[KP_COPY]]
writable[keyPath: wkp] = value
// CHECK-NEXT: [[ROOT_COPY:%.*]] = copy_value [[READONLY]] :
// CHECK-NEXT: [[KP_COPY:%.*]] = copy_value [[RKP:%5]]
// CHECK-NEXT: [[VALUE_COPY:%.*]] = copy_value [[VALUE]] : $B
// CHECK-NEXT: [[ROOT_TEMP:%.*]] = alloc_stack $A
// CHECK-NEXT: store [[ROOT_COPY]] to [init] [[ROOT_TEMP]]
// CHECK-NEXT: [[VALUE_TEMP:%.*]] = alloc_stack $B
// CHECK-NEXT: store [[VALUE_COPY]] to [init] [[VALUE_TEMP]]
// CHECK-NEXT: // function_ref
// CHECK-NEXT: [[SET:%.*]] = function_ref @swift_setAtReferenceWritableKeyPath :
// CHECK-NEXT: apply [[SET]]<A, B>([[ROOT_TEMP]], [[KP_COPY]], [[VALUE_TEMP]])
// CHECK-NEXT: dealloc_stack [[VALUE_TEMP]]
// CHECK-NEXT: destroy_addr [[ROOT_TEMP]]
// CHECK-NEXT: dealloc_stack [[ROOT_TEMP]]
// CHECK-NEXT: destroy_value [[KP_COPY]]
readonly[keyPath: rkp] = value
// CHECK-NEXT: [[ACCESS:%.*]] = begin_access [read] [unknown] [[WRITABLE]] :
// CHECK-NEXT: [[ROOT_COPY:%.*]] = load [copy] [[ACCESS]] :
// CHECK-NEXT: end_access [[ACCESS]]
// CHECK-NEXT: [[KP_COPY:%.*]] = copy_value [[RKP:%5]]
// CHECK-NEXT: [[VALUE_COPY:%.*]] = copy_value [[VALUE]] : $B
// CHECK-NEXT: [[ROOT_TEMP:%.*]] = alloc_stack $A
// CHECK-NEXT: store [[ROOT_COPY]] to [init] [[ROOT_TEMP]]
// CHECK-NEXT: [[VALUE_TEMP:%.*]] = alloc_stack $B
// CHECK-NEXT: store [[VALUE_COPY]] to [init] [[VALUE_TEMP]]
// CHECK-NEXT: // function_ref
// CHECK-NEXT: [[SET:%.*]] = function_ref @swift_setAtReferenceWritableKeyPath :
// CHECK-NEXT: apply [[SET]]<A, B>([[ROOT_TEMP]], [[KP_COPY]], [[VALUE_TEMP]])
// CHECK-NEXT: dealloc_stack [[VALUE_TEMP]]
// CHECK-NEXT: destroy_addr [[ROOT_TEMP]]
// CHECK-NEXT: dealloc_stack [[ROOT_TEMP]]
// CHECK-NEXT: destroy_value [[KP_COPY]]
writable[keyPath: rkp] = value
} // CHECK-LABEL: } // end sil function '{{.*}}loadable
// CHECK-LABEL: sil hidden [ossa] @{{.*}}addressOnly
func addressOnly(readonly: P, writable: inout P,
value: Q,
kp: KeyPath<P, Q>,
wkp: WritableKeyPath<P, Q>,
rkp: ReferenceWritableKeyPath<P, Q>) {
// CHECK: function_ref @swift_getAtKeyPath :
_ = readonly[keyPath: kp]
// CHECK: function_ref @swift_getAtKeyPath :
_ = writable[keyPath: kp]
// CHECK: function_ref @swift_getAtKeyPath :
_ = readonly[keyPath: wkp]
// CHECK: function_ref @swift_getAtKeyPath :
_ = writable[keyPath: wkp]
// CHECK: function_ref @swift_getAtKeyPath :
_ = readonly[keyPath: rkp]
// CHECK: function_ref @swift_getAtKeyPath :
_ = writable[keyPath: rkp]
// CHECK: function_ref @swift_setAtWritableKeyPath :
writable[keyPath: wkp] = value
// CHECK: function_ref @swift_setAtReferenceWritableKeyPath :
readonly[keyPath: rkp] = value
// CHECK: function_ref @swift_setAtReferenceWritableKeyPath :
writable[keyPath: rkp] = value
}
// CHECK-LABEL: sil hidden [ossa] @{{.*}}reabstracted
func reabstracted(readonly: @escaping () -> (),
writable: inout () -> (),
value: @escaping (A) -> B,
kp: KeyPath<() -> (), (A) -> B>,
wkp: WritableKeyPath<() -> (), (A) -> B>,
rkp: ReferenceWritableKeyPath<() -> (), (A) -> B>) {
// CHECK: function_ref @swift_getAtKeyPath :
_ = readonly[keyPath: kp]
// CHECK: function_ref @swift_getAtKeyPath :
_ = writable[keyPath: kp]
// CHECK: function_ref @swift_getAtKeyPath :
_ = readonly[keyPath: wkp]
// CHECK: function_ref @swift_getAtKeyPath :
_ = writable[keyPath: wkp]
// CHECK: function_ref @swift_getAtKeyPath :
_ = readonly[keyPath: rkp]
// CHECK: function_ref @swift_getAtKeyPath :
_ = writable[keyPath: rkp]
// CHECK: function_ref @swift_setAtWritableKeyPath :
writable[keyPath: wkp] = value
// CHECK: function_ref @swift_setAtReferenceWritableKeyPath :
readonly[keyPath: rkp] = value
// CHECK: function_ref @swift_setAtReferenceWritableKeyPath :
writable[keyPath: rkp] = value
}
// CHECK-LABEL: sil hidden [ossa] @{{.*}}partial
func partial<A>(valueA: A,
valueB: Int,
pkpA: PartialKeyPath<A>,
pkpB: PartialKeyPath<Int>,
akp: AnyKeyPath) {
// CHECK: [[PROJECT:%.*]] = function_ref @swift_getAtAnyKeyPath :
// CHECK: apply [[PROJECT]]<A>
_ = valueA[keyPath: akp]
// CHECK: [[PROJECT:%.*]] = function_ref @swift_getAtPartialKeyPath :
// CHECK: apply [[PROJECT]]<A>
_ = valueA[keyPath: pkpA]
// CHECK: [[PROJECT:%.*]] = function_ref @swift_getAtAnyKeyPath :
// CHECK: apply [[PROJECT]]<Int>
_ = valueB[keyPath: akp]
// CHECK: [[PROJECT:%.*]] = function_ref @swift_getAtPartialKeyPath :
// CHECK: apply [[PROJECT]]<Int>
_ = valueB[keyPath: pkpB]
}
extension Int {
var b: Int { get { return 0 } set { } }
var u: Int { get { return 0 } set { } }
var tt: Int { get { return 0 } set { } }
}
// CHECK-LABEL: sil hidden [ossa] @{{.*}}writebackNesting
func writebackNesting(x: inout Int,
y: WritableKeyPath<Int, Int>,
z: WritableKeyPath<Int, Int>,
w: Int) -> Int {
// -- get 'b'
// CHECK: function_ref @$sSi19keypath_applicationE1bSivg
// -- apply keypath y
// CHECK: [[PROJECT_FN:%.*]] = function_ref @swift_modifyAtWritableKeyPath :
// CHECK: ([[Y_ADDR:%.*]], [[Y_TOKEN:%.*]]) = begin_apply [[PROJECT_FN]]<Int, Int>
// -- get 'u'
// CHECK: function_ref @$sSi19keypath_applicationE1uSivg
// -- apply keypath z
// CHECK: [[PROJECT_FN:%.*]] = function_ref @swift_modifyAtWritableKeyPath :
// CHECK: ([[Z_ADDR:%.*]], [[Z_TOKEN:%.*]]) = begin_apply [[PROJECT_FN]]<Int, Int>
// -- set 'tt'
// CHECK: function_ref @$sSi19keypath_applicationE2ttSivs
// -- destroy owner for keypath projection z
// CHECK: end_apply [[Z_TOKEN]]
// -- set 'u'
// CHECK: function_ref @$sSi19keypath_applicationE1uSivs
// -- destroy owner for keypath projection y
// CHECK: end_apply [[Y_TOKEN]]
// -- set 'b'
// CHECK: function_ref @$sSi19keypath_applicationE1bSivs
x.b[keyPath: y].u[keyPath: z].tt = w
}
|
apache-2.0
|
1af3c47dff9448c20e8a1bb4ba635fe7
| 39.511211 | 93 | 0.58313 | 3.401355 | false | false | false | false |
alltheflow/copypasta
|
Carthage/Checkouts/VinceRP/vincerpTests/Common/Core/Hub+operatorsSpec.swift
|
1
|
1349
|
//
// Created by Viktor Belenyesi on 11/26/15.
// Copyright (c) 2015 Viktor Belenyesi. All rights reserved.
//
@testable import VinceRP
import Quick
import Nimble
class HubOperatorsSpec: QuickSpec {
override func spec() {
it("should negate") {
// given
let x = reactive(true)
// when
expect(x.value()) == true
// then
expect(x.not()*) == false
}
it("can skip errors") {
// given
let x = reactive(1)
let y = definedAs { x* + 1 }.skipErrors()
var count = 0
onErrorDo(y) { _ in
count++
}
// when
x <- fakeError
// then
expect(count) == 0
}
it("works with foreach") {
// given
let x = reactive(1)
var history = [Int]()
// when
x.foreach {
history.append(2 * $0)
}
// then
expect(history).toEventually(equal([2]))
// when
x <- 2
// then
expect(history).toEventually(equal([2, 4]))
}
}
}
|
mit
|
9f8b3fcacc8b4dfb096f8c2b8f2bdd9e
| 19.753846 | 60 | 0.377317 | 4.996296 | false | false | false | false |
think-dev/MadridBUS
|
MadridBUS/Source/Data/BusGeoNodeArrival.swift
|
1
|
819
|
import Foundation
import ObjectMapper
enum BusGeoPositionType: Int {
case real = 2
case estimated = 1
}
final class BusGeoNodeArrival: Mappable {
var nodeId: Int = 0
var lineId: String = ""
var busId: String = ""
var isHeader: Bool = false
var destination: String = ""
var ETA: Int = 0
var distance: Int = 0
var latitude: Double = 0.0
var longitude: Double = 0.0
init() {}
required init?(map: Map) {}
func mapping(map: Map) {
nodeId <- map["stopId"]
lineId <- map["lineId"]
busId <- map["busId"]
isHeader <- map["isHead"]
destination <- map["destination"]
ETA <- map["busTimeLeft"]
distance <- map["busDistance"]
latitude <- map["latitude"]
longitude <- map["longitude"]
}
}
|
mit
|
2371abbacd49ca66805522490f2e3c79
| 23.088235 | 41 | 0.568987 | 3.956522 | false | false | false | false |
dvl/imagefy-ios
|
imagefy/Modules/WishOffers/WishOffersViewController.swift
|
1
|
5413
|
//
// WishOffersViewController.swift
// imagefy
//
// Created by Guilherme Augusto on 22/05/16.
// Copyright © 2016 Alan M. Lira. All rights reserved.
//
import UIKit
import Buy
import DZNEmptyDataSet
import RNActivityView
private let reuseIdentifier = "WishOfferCell"
class WishOffersViewController: UICollectionViewController, UICollectionViewDelegateFlowLayout {
var offers: [Offer] = []
let refreshControl = UIRefreshControl()
override func viewDidLoad() {
super.viewDidLoad()
self.clearsSelectionOnViewWillAppear = false
self.collectionView?.emptyDataSetSource = self
self.collectionView?.emptyDataSetDelegate = self
self.title = "Offers"
self.refreshControl.tintColor = kAccentColor
self.refreshControl.addTarget(self, action: #selector(WishOffersViewController.reloadData), forControlEvents: .ValueChanged)
self.collectionView?.addSubview(self.refreshControl)
self.collectionView?.alwaysBounceVertical = true
}
override func viewDidAppear(animated: Bool) {
let tabbar = self.tabBarController as! TabbarController
tabbar.showButton()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func reloadData() {
self.collectionView?.reloadData()
if self.refreshControl.refreshing {
self.refreshControl.endRefreshing()
}
}
// MARK: UICollectionViewDataSource
override func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int {
return 1
}
override func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return offers.count
}
override func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCellWithReuseIdentifier(reuseIdentifier, forIndexPath: indexPath) as! WishOfferCell
let offer = offers[indexPath.row]
cell.setupWithProductId(offer.productId!, price: offer.price ?? "100")
UIDesign.viewShadowPath(cell.layer, bounds: cell.bounds, radius: 3.5, shadowOffset: CGSize(width: 1, height: 4), masksToBounds: true)
cell.imgOffer.layer.cornerRadius = 3.5
return cell
}
override func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
let offer = offers[indexPath.row]
self.view.showActivityView()
myAppDelegate.client.getProductById(offer.productId) { (product, error) in
let vc = self.productViewController()
vc.loadWithProduct(product) { (success, error) in
self.view.hideActivityViewWithAfterDelay(2)
guard error == nil else {
return
}
if let tabbar = self.tabBarController as? TabbarController {
tabbar.hideButton()
}
self.navigationController?.pushViewController(vc, animated: true)
}
}
}
// MARK: - UICollectionViewDelegateFlowLayout
func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize {
let width:CGFloat = self.view.frame.width * 0.94
let height:CGFloat = width * 0.6
return CGSizeMake(width, height)
}
// Margens
func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAtIndex section: Int) -> UIEdgeInsets {
return UIEdgeInsetsMake(10, 5, 2, 5)
}
func productViewController() -> BUYProductViewController {
let theme = BUYTheme()
theme.style = .Light
theme.tintColor = kAccentColor
theme.showsProductImageBackground = true
return BUYProductViewController(client: myAppDelegate.client, theme: theme)
}
}
extension WishOffersViewController: DZNEmptyDataSetSource, DZNEmptyDataSetDelegate {
func emptyDataSetDidTapView(scrollView: UIScrollView!) {
}
func imageForEmptyDataSet(scrollView: UIScrollView!) -> UIImage! {
return UIImage(named: "offer")
}
func titleForEmptyDataSet(scrollView: UIScrollView!) -> NSAttributedString! {
let text = "Imagefy"
let attributes = [NSFontAttributeName: UIFont(name: "Comfortaa", size: 18)!, NSForegroundColorAttributeName: UIColor.darkGrayColor()]
return NSAttributedString(string: text, attributes: attributes)
}
func descriptionForEmptyDataSet(scrollView: UIScrollView!) -> NSAttributedString! {
let text = "We have not found offers for you yet"
let paragraph = NSMutableParagraphStyle()
paragraph.lineBreakMode = .ByWordWrapping
paragraph.alignment = .Center
let attributes = [NSFontAttributeName: UIFont(name: "Comfortaa", size: 15)!, NSForegroundColorAttributeName: UIColor.lightGrayColor(), NSParagraphStyleAttributeName: paragraph]
return NSAttributedString(string: text, attributes: attributes)
}
}
|
mit
|
8e00df12cb58972ae76f24bb873ca774
| 36.583333 | 184 | 0.68071 | 5.643379 | false | false | false | false |
colbylwilliams/bugtrap
|
iOS/Code/Swift/bugTrap/bugTrapKit/Trackers/JIRA/Domain/JiraIssueTypeFieldSchema.swift
|
1
|
1060
|
//
// JiraIssueTypeFieldSchema.swift
// bugTrap
//
// Created by Colby L Williams on 1/26/15.
// Copyright (c) 2015 bugTrap. All rights reserved.
//
import Foundation
class JiraIssueTypeFieldSchema : JsonSerializable {
var type = ""
var system = ""
init() {
}
init(type: String, system: String) {
self.type = type
self.system = system
}
class func deserialize (json: JSON) -> JiraIssueTypeFieldSchema? {
let type = json["type"].stringValue
let system = json["system"].stringValue
return JiraIssueTypeFieldSchema(type: type, system: system)
}
class func deserializeAll(json: JSON) -> [JiraIssueTypeFieldSchema] {
var items = [JiraIssueTypeFieldSchema]()
if let jsonArray = json.array {
for item: JSON in jsonArray {
if let si = deserialize(item) {
items.append(si)
}
}
}
return items
}
func serialize () -> NSMutableDictionary {
let dict = NSMutableDictionary()
dict.setObject(type, forKey: "type")
dict.setObject(system, forKey: "system")
return dict
}
}
|
mit
|
a36f0ee14c466402130ee2071dfae735
| 16.983051 | 70 | 0.661321 | 3.452769 | false | false | false | false |
linhaosunny/smallGifts
|
小礼品/小礼品/Classes/Module/Classify/Views/ClassifySingleListCellViewModel.swift
|
1
|
881
|
//
// ClassifySingleListCellViewModel.swift
// 小礼品
//
// Created by 李莎鑫 on 2017/4/23.
// Copyright © 2017年 李莎鑫. All rights reserved.
//
import UIKit
class ClassifySingleListCellDataModel: NSObject {
}
class ClassifySingleListCellViewModel: NSObject {
var dataModel:ClassifySingleListCellDataModel?
var photoImage:UIImage?
var titleLabelText:String?
var tagLabelText:String?
var tagNameLabelText:String?
var priceButtonTitle:String?
init(withModel model:ClassifySingleListCellDataModel) {
self.dataModel = model
photoImage = UIImage(named: "strategy_\(Int(arc4random() % 17) + 1).jpg")
titleLabelText = "第68期|讲真,不规矩穿衣让你衣品开挂!"
tagLabelText = "17-05"
tagNameLabelText = "穿衣大队长"
priceButtonTitle = "1789"
}
}
|
mit
|
439138f5ea50bfc4741c0bba3c8db00e
| 23.727273 | 81 | 0.678922 | 3.642857 | false | false | false | false |
sandsmedia/SS_Authentication
|
SS_Authentication/Classes/ViewControllers/SSAuthenticationRegisterViewController.swift
|
1
|
11123
|
//
// SSAuthenticationRegisterViewController.swift
// SS_Authentication
//
// Created by Eddie Li on 25/05/16.
// Copyright © 2016 Software and Support Media GmbH. All rights reserved.
//
import UIKit
public protocol SSAuthenticationRegisterDelegate: class {
func registerSuccess(_ user: SSUser)
}
open class SSAuthenticationRegisterViewController: SSAuthenticationBaseViewController {
open weak var delegate: SSAuthenticationRegisterDelegate?
fileprivate var registerButton: UIButton?
fileprivate var hasLoadedConstraints = false
// MARK: - Initialisation
convenience init() {
self.init(nibName: nil, bundle: nil)
}
override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: Bundle?) {
super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil)
self.setup()
}
required public init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
self.setup()
}
deinit {
self.delegate = nil
}
// MARK: - Accessors
fileprivate(set) lazy var emailAlreadyExistAlertController: UIAlertController = {
let _emailAlreadyExistAlertController = UIAlertController(title: nil, message: self.localizedString(key: "email_exist_error.message"), preferredStyle: .alert)
let cancelAction = UIAlertAction(title: self.localizedString(key: "ok.title"), style: .cancel, handler: { (action) in
self.emailTextField.becomeFirstResponder()
})
_emailAlreadyExistAlertController.addAction(cancelAction)
return _emailAlreadyExistAlertController
}()
fileprivate(set) lazy var registerFailedAlertController: UIAlertController = {
let _registerFailedAlertController = UIAlertController(title: nil, message: self.localizedString(key: "user_register_fail.message"), preferredStyle: .alert)
let cancelAction = UIAlertAction(title: self.localizedString(key: "ok.title"), style: .cancel, handler: { (action) in
self.emailTextField.becomeFirstResponder()
})
_registerFailedAlertController.addAction(cancelAction)
return _registerFailedAlertController
}()
// MARK: - Events
func tapAction() {
for textField in (self.textFieldsStackView?.arrangedSubviews)! {
textField.resignFirstResponder()
}
}
func registerButtonAction() {
self.tapAction()
guard (self.isEmailValid && self.isPasswordValid && self.isConfirmPasswordValid) else {
if (!self.isEmailValid) {
if (!self.emailFailureAlertController.isBeingPresented) {
self.emailTextField.layer.borderColor = UIColor.red.cgColor
self.present(self.emailFailureAlertController, animated: true, completion: nil)
}
} else if (!self.isPasswordValid) {
if (!self.passwordValidFailAlertController.isBeingPresented) {
self.passwordTextField.layer.borderColor = UIColor.red.cgColor
self.present(self.passwordValidFailAlertController, animated: true, completion: nil)
}
} else {
if (!self.confirmPasswordValidFailAlertController.isBeingPresented) {
self.confirmPasswordTextField.layer.borderColor = UIColor.red.cgColor
self.present(self.confirmPasswordValidFailAlertController, animated: true, completion: nil)
}
}
return
}
if let email = self.emailTextField.text, let password = self.passwordTextField.text {
self.registerButton?.isUserInteractionEnabled = false
self.showLoadingView()
let userDict = [EMAIL_KEY: email,
PASSWORD_KEY: password]
SSAuthenticationManager.sharedInstance.emailValidate(email: email) { (bool: Bool, statusCode: Int, error: Error?) in
if (bool) {
SSAuthenticationManager.sharedInstance.register(userDictionary: userDict) { (user: SSUser?, statusCode: Int, error: Error?) in
if (user != nil) {
self.delegate?.registerSuccess(user!)
} else {
if (statusCode == INVALID_STATUS_CODE) {
self.present(self.emailAlreadyExistAlertController, animated: true, completion: nil)
} else {
self.present(self.registerFailedAlertController, animated: true, completion: nil)
}
}
self.hideLoadingView()
self.registerButton?.isUserInteractionEnabled = true
}
} else {
if (error != nil) {
self.present(self.registerFailedAlertController, animated: true, completion: nil)
} else {
self.present(self.emailFailureAlertController, animated: true, completion: nil)
}
self.hideLoadingView()
self.registerButton?.isUserInteractionEnabled = true
}
}
}
}
// MARK: - Public Methods
override open func forceUpdateStatusBarStyle(_ style: UIStatusBarStyle) {
super.forceUpdateStatusBarStyle(style)
}
override open func textFieldShouldReturn(_ textField: UITextField) -> Bool {
if (textField == self.confirmPasswordTextField) {
self.registerButtonAction()
} else if (textField == self.passwordTextField) {
self.confirmPasswordTextField.becomeFirstResponder()
} else {
self.passwordTextField.becomeFirstResponder()
}
return super.textFieldShouldReturn(textField)
}
// MARK: - Subviews
fileprivate func setupRegisterButton() {
self.registerButton = UIButton(type: .system)
self.registerButton?.backgroundColor = SSAuthenticationManager.sharedInstance.buttonBackgroundColour
self.registerButton?.setAttributedTitle(NSAttributedString.init(string: self.localizedString(key: "user.register"), attributes: SSAuthenticationManager.sharedInstance.buttonFontAttribute), for: UIControlState())
self.registerButton?.addTarget(self, action: .registerButtonAction, for: .touchUpInside)
self.registerButton?.layer.cornerRadius = GENERAL_ITEM_RADIUS
}
override func setupSubviews() {
super.setupSubviews()
self.emailTextField.translatesAutoresizingMaskIntoConstraints = false
self.textFieldsStackView?.addArrangedSubview(self.emailTextField)
self.passwordTextField.translatesAutoresizingMaskIntoConstraints = false
self.textFieldsStackView?.addArrangedSubview(self.passwordTextField)
self.confirmPasswordTextField.translatesAutoresizingMaskIntoConstraints = false
self.textFieldsStackView?.addArrangedSubview(self.confirmPasswordTextField)
self.setupRegisterButton()
self.registerButton?.translatesAutoresizingMaskIntoConstraints = false
self.buttonsStackView?.addArrangedSubview(self.registerButton!)
let tapGesture = UITapGestureRecognizer.init(target: self, action: .tapAction)
self.view.addGestureRecognizer(tapGesture)
}
override open func updateViewConstraints() {
if (!self.hasLoadedConstraints) {
let views: [String: Any] = ["email": self.emailTextField,
"password": self.passwordTextField,
"confirm": self.confirmPasswordTextField,
"register": self.registerButton!]
let metrics = ["SPACING": GENERAL_SPACING,
"LARGE_SPACING": LARGE_SPACING,
"WIDTH": GENERAL_ITEM_WIDTH,
"HEIGHT": ((IS_IPHONE_4S) ? (GENERAL_ITEM_HEIGHT - 10.0) : GENERAL_ITEM_HEIGHT),
"BUTTON_HEIGHT": GENERAL_ITEM_HEIGHT]
self.textFieldsStackView!.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "|-(LARGE_SPACING)-[email]-(LARGE_SPACING)-|", options: .directionMask, metrics: metrics, views: views))
self.textFieldsStackView!.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "|-(LARGE_SPACING)-[password]-(LARGE_SPACING)-|", options: .directionMask, metrics: metrics, views: views))
self.textFieldsStackView!.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "|-(LARGE_SPACING)-[confirm]-(LARGE_SPACING)-|", options: .directionMask, metrics: metrics, views: views))
self.textFieldsStackView!.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "V:[email(HEIGHT)]", options: .directionMask, metrics: metrics, views: views))
self.textFieldsStackView!.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "V:[password(HEIGHT)]", options: .directionMask, metrics: metrics, views: views))
self.textFieldsStackView!.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "V:[confirm(HEIGHT)]", options: .directionMask, metrics: metrics, views: views))
self.buttonsStackView!.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "|-(LARGE_SPACING)-[register]-(LARGE_SPACING)-|", options: .directionMask, metrics: metrics, views: views))
self.buttonsStackView!.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "V:[register(BUTTON_HEIGHT)]", options: .directionMask, metrics: metrics, views: views))
self.hasLoadedConstraints = true
}
super.updateViewConstraints()
}
override open func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
let top = self.topLayoutGuide.length
let bottom = self.bottomLayoutGuide.length
self.baseScrollView?.contentInset = UIEdgeInsetsMake(top, 0.0, bottom, 0.0)
}
// MARK: - View lifecycle
override open func loadView() {
super.loadView()
}
override open func viewDidLoad() {
super.viewDidLoad()
self.title = self.localizedString(key: "user.register")
self.emailTextField.returnKeyType = .next
self.passwordTextField.returnKeyType = .next
self.confirmPasswordTextField.returnKeyType = .go
}
override open func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
self.emailTextField.becomeFirstResponder()
}
}
private extension Selector {
static let registerButtonAction = #selector(SSAuthenticationRegisterViewController.registerButtonAction)
static let tapAction = #selector(SSAuthenticationRegisterViewController.tapAction)
}
|
mit
|
d14792bd3ff14628fcfe8b815e2bfbad
| 44.958678 | 219 | 0.642331 | 5.792708 | false | false | false | false |
jvesala/teknappi
|
teknappi/teknappi/UserDataRepository.swift
|
1
|
1529
|
//
// UserDataRepository.swift
// teknappi
//
// Created by Jussi Vesala on 11.1.2016.
// Copyright © 2016 Jussi Vesala. All rights reserved.
//
import Foundation
class UserDataRepository {
static let LoginName = "loginToken"
static func getLoginToken() -> String? {
let defaults = NSUserDefaults.standardUserDefaults()
return defaults.stringForKey(LoginName)
}
static func setLoginToken(loginToken: String) {
let defaults = NSUserDefaults.standardUserDefaults()
defaults.setObject(loginToken, forKey: LoginName)
}
static func reset() {
print("Remove existing tokens for debug")
let defaults = NSUserDefaults.standardUserDefaults()
defaults.removeObjectForKey(LoginName)
}
static func setUserData(userData: UserData) {
let defaults = NSUserDefaults.standardUserDefaults()
defaults.setObject(userData.firstName, forKey: "firstName")
defaults.setObject(userData.lastName, forKey: "lastName")
defaults.setObject(userData.email, forKey: "email")
defaults.setObject(userData.phoneNumber, forKey: "phoneNumber")
}
static func getUserData() -> UserData? {
let defaults = NSUserDefaults.standardUserDefaults()
return UserData(firstName: defaults.stringForKey("firstName")!,
lastName: defaults.stringForKey("lastName")!,
email: defaults.stringForKey("email")!,
phoneNumber: defaults.stringForKey("phoneNumber")!)
}
}
|
gpl-3.0
|
47f166af8fb000bd29691b492d60386c
| 32.217391 | 71 | 0.678665 | 4.977199 | false | false | false | false |
ultimecia7/BestGameEver
|
Stick-Hero/SpeedModeViewController.swift
|
1
|
2217
|
//
// SpeedModeViewController.swift
// Stick-Hero
//
// Created by 刘嘉诚 on 11/12/15.
// Copyright © 2015 koofrank. All rights reserved.
//
import UIKit
import SpriteKit
import AVFoundation
class SpeedModeViewController: UIViewController {
@IBAction func timeback(sender: AnyObject) {
//TODO: send a request to sever
self.performSegueWithIdentifier("speedback", sender: self)
}
@IBOutlet weak var display: UILabel!
var musicPlayer:AVAudioPlayer!
var character:String!
override func viewDidLoad() {
super.viewDidLoad()
print(character)
let scene = SpeedModeScene(size:CGSizeMake(DefinedScreenWidth, DefinedScreenHeight))
scene.Character = character
// Configure the view.
let skView = self.view as! SKView
// skView.showsFPS = true
// skView.showsNodeCount = true
/* Sprite Kit applies additional optimizations to improve rendering performance */
skView.ignoresSiblingOrder = true
/* Set the scale mode to scale to fit the window */
scene.scaleMode = .AspectFill
skView.presentScene(scene)
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
musicPlayer = setupAudioPlayerWithFile("bg_country", type: "mp3")
musicPlayer.numberOfLoops = -1
musicPlayer.play()
}
func setupAudioPlayerWithFile(file:NSString, type:NSString) -> AVAudioPlayer {
let url = NSBundle.mainBundle().URLForResource(file as String, withExtension: type as String)
var audioPlayer:AVAudioPlayer?
do {
try audioPlayer = AVAudioPlayer(contentsOfURL: url!)
} catch {
print("NO AUDIO PLAYER")
}
return audioPlayer!
}
override func shouldAutorotate() -> Bool {
return true
}
override func supportedInterfaceOrientations() -> UIInterfaceOrientationMask {
return .Portrait
}
override func prefersStatusBarHidden() -> Bool {
return true
}
}
|
mit
|
93ec79ab105cc1b66c737896b2688033
| 25.011765 | 101 | 0.613575 | 5.364078 | false | false | false | false |
marcelmueller/MyWeight
|
MyWeight/Screens/AuthorizationRequest/AuthorizationRequestViewController.swift
|
1
|
2101
|
//
// AuthorizationRequestViewController.swift
// MyWeight
//
// Created by Diogo on 18/10/16.
// Copyright © 2016 Diogo Tridapalli. All rights reserved.
//
import UIKit
public protocol AuthorizationRequestViewControllerDelegate {
func didFinish(on controller: AuthorizationRequestViewController,
with authorized: Bool)
}
public class AuthorizationRequestViewController: UIViewController {
let massService: MassService
public var delegate: AuthorizationRequestViewControllerDelegate?
var theView: AuthorizationRequestView {
// I don't like this `!` but it's a framework limitation
return self.view as! AuthorizationRequestView
}
public required init(with massService: MassService)
{
self.massService = massService
super.init(nibName: nil, bundle: nil)
}
@available(*, unavailable)
public required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override public func loadView()
{
let view = AuthorizationRequestView()
self.view = view
}
override public func viewDidLoad()
{
let viewModel = AuthorizationRequestViewModel(didTapOkAction:
{ [weak self] in
self?.tapOk()
}, didTapCancelAction: { [weak self] in
self?.tapCancel()
})
theView.viewModel = viewModel
}
override public func viewDidLayoutSubviews()
{
theView.topOffset = topLayoutGuide.length
}
func tapOk()
{
massService.requestAuthorization { [weak self] error in
if let error = error {
Log.debug(error)
}
print("start")
let authorized = self?.massService.authorizationStatus == .authorized
print("finish")
self?.didFinish(with: authorized)
}
}
func tapCancel()
{
didFinish(with: false)
}
func didFinish(with authorized: Bool)
{
self.delegate?.didFinish(on: self, with: authorized)
}
}
|
mit
|
046d3257af631d490b99be76d8e777fd
| 24.301205 | 81 | 0.626667 | 5.023923 | false | false | false | false |
castillejoale/Bluefruit_LE_Connect_v2_Minimized_UART
|
bluefruitconnect/Platform/iOS/Controllers/Info/InfoModuleViewController.swift
|
1
|
20334
|
//
// InfoViewController.swift
// Bluefruit Connect
//
// Created by Antonio García on 05/02/16.
// Copyright © 2016 Adafruit. All rights reserved.
//
import UIKit
class InfoModuleViewController: ModuleViewController {
// Config
private static let kReadForbiddenCCCD = false // Added to avoid generating a didModifyServices callback when reading Uart/DFU CCCD (bug??)
// UI
@IBOutlet weak var baseTableView: UITableView!
@IBOutlet weak var waitView: UIActivityIndicatorView!
// Delegates
var onServicesDiscovered: (() -> ())?
// var onInfoScanFinished: (() ->())?
// Data
private var blePeripheral: BlePeripheral?
private var services: [CBService]?
private var itemDisplayMode = [String : DisplayMode]()
private var shouldDiscoverCharacteristics = Preferences.infoIsRefreshOnLoadEnabled
private var isDiscoveringServices = false
private var elementsToDiscover = 0
private var elementsDiscovered = 0
private var valuesToRead = 0
private var valuesRead = 0
override func viewDidLoad() {
super.viewDidLoad()
// Peripheral should be connected
blePeripheral = BleManager.sharedInstance.blePeripheralConnected
guard blePeripheral != nil else {
DLog("Error: Info: blePeripheral is nil")
return
}
// Setup table
baseTableView.contentInset = UIEdgeInsetsMake(44, 0, 0, 0) // extend below navigation inset fix
baseTableView.estimatedRowHeight = 60
baseTableView.rowHeight = UITableViewAutomaticDimension
// Discover services
shouldDiscoverCharacteristics = Preferences.infoIsRefreshOnLoadEnabled
services = nil
discoverServices()
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
// Title
let localizationManager = LocalizationManager.sharedInstance
let name = blePeripheral!.name != nil ? blePeripheral!.name! : LocalizationManager.sharedInstance.localizedString("peripherallist_unnamed")
let title = String(format: localizationManager.localizedString("info_navigation_title_format"), arguments: [name])
//tabBarController?.navigationItem.title = title
navigationController?.navigationItem.title = title
// Refresh data
baseTableView.reloadData()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func discoverServices() {
guard isDiscoveringServices == false else {
DLog("warning: call to discoverServices while services discovery in process")
return;
}
isDiscoveringServices = true
elementsToDiscover = 0
elementsDiscovered = 0
valuesToRead = 0
valuesRead = 0
services = nil
showWait(true)
BleManager.sharedInstance.discover(blePeripheral!, serviceUUIDs: nil)
}
func showWait(show: Bool) {
baseTableView.hidden = show
waitView.hidden = !show
}
// MARK: - Actions
@IBAction func onClickHelp(sender: UIBarButtonItem) {
let localizationManager = LocalizationManager.sharedInstance
let helpViewController = storyboard!.instantiateViewControllerWithIdentifier("HelpViewController") as! HelpViewController
helpViewController.setHelp(localizationManager.localizedString("info_help_text"), title: localizationManager.localizedString("info_help_title"))
let helpNavigationController = UINavigationController(rootViewController: helpViewController)
helpNavigationController.modalPresentationStyle = .Popover
helpNavigationController.popoverPresentationController?.barButtonItem = sender
presentViewController(helpNavigationController, animated: true, completion: nil)
}
}
extension InfoModuleViewController : UITableViewDataSource {
enum DisplayMode : Int {
case Auto = 0
case Text = 1
case Hex = 2
}
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
// Services
if let services = services {
return services.count
}
else {
return 0
}
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
let service = services![section]
if let characteristics = service.characteristics {
let numCharacteristics = characteristics.count
var numDescriptors = 0
for characteristic in characteristics {
numDescriptors += characteristic.descriptors?.count ?? 0
}
//DLog("section:\(section) - numCharacteristics: \(numCharacteristics), numDescriptors:\(numDescriptors), service: \(service.UUID.UUIDString)")
return numCharacteristics + numDescriptors
}
else {
return 0
}
}
func tableView(tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
guard let service = services?[section] else {
DLog("warning: titleForHeaderInSection service is nil")
return nil
}
var identifier = service.UUID.UUIDString
if let name = BleUUIDNames.sharedInstance.nameForUUID(identifier) {
identifier = name
}
return identifier
}
func tableView(tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
return 60
}
private func itemForIndexPath(indexPath: NSIndexPath) -> (Int, CBAttribute?, Bool) {
let service = services![indexPath.section]
// The same table view section is used for characteristics and descriptors. So first calculate if the current indexPath.row is for a characteristic or descriptor
var currentItem: CBAttribute?
var currentCharacteristicIndex = 0
var currentRow = 0
var isDescriptor = false
// DLog("section:\(indexPath.section) - service: \(service.UUID.UUIDString)")
while currentRow <= indexPath.row && currentCharacteristicIndex < service.characteristics!.count && service.characteristics != nil {
let characteristic = service.characteristics![currentCharacteristicIndex]
if currentRow == indexPath.row {
currentItem = characteristic
currentRow += 1 // same as break
}
else {
currentRow += 1 // + 1 characteristic
let numDescriptors = characteristic.descriptors?.count ?? 0
if numDescriptors > 0 {
let remaining = indexPath.row-currentRow
if remaining < numDescriptors {
currentItem = characteristic.descriptors![remaining]
isDescriptor = true
}
currentRow += numDescriptors
}
}
if currentItem == nil {
currentCharacteristicIndex += 1
}
}
if currentItem == nil {
DLog("Error populating tableview")
}
return (currentCharacteristicIndex, currentItem, isDescriptor)
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
guard let service = services?[indexPath.section] where service.characteristics != nil else {
DLog("warning: cellForRowAtIndexPath characteristics is nil")
return tableView.dequeueReusableCellWithIdentifier("CharacteristicCell", forIndexPath:indexPath)
}
let (currentCharacteristicIndex, currentItemOptional, isDescriptor) = itemForIndexPath(indexPath)
guard let currentItem = currentItemOptional else {
DLog("warning: current item is nil")
return tableView.dequeueReusableCellWithIdentifier("CharacteristicCell", forIndexPath:indexPath)
}
//DLog("secrow: \(indexPath.section)/\(indexPath.row): ci: \(currentCharacteristicIndex) isD: \(isDescriptor))")
// Intanciate cell
let reuseIdentifier = isDescriptor ? "DescriptorCell":"CharacteristicCell"
let cell = tableView.dequeueReusableCellWithIdentifier(reuseIdentifier, forIndexPath:indexPath)
var identifier = ""
var value = " "
var valueData: NSData?
if let characteristic = service.characteristics?[currentCharacteristicIndex] {
identifier = currentItem.UUID.UUIDString
let displayModeIdentifier = "\(currentCharacteristicIndex)_\(identifier)" // Descriptors in different characteristics could have the same CBUUID
var currentDisplayMode = DisplayMode.Auto
if let displayMode = itemDisplayMode[displayModeIdentifier] {
currentDisplayMode = displayMode
}
else {
itemDisplayMode[displayModeIdentifier] = .Auto
}
if let name = BleUUIDNames.sharedInstance.nameForUUID(identifier) {
identifier = name
}
if isDescriptor {
let descriptor = currentItem as! CBDescriptor
valueData = InfoModuleManager.parseDescriptorValue(descriptor)
}
else {
valueData = characteristic.value
}
if valueData != nil {
switch currentDisplayMode {
case .Auto:
if let characteristicString = NSString(data: valueData!, encoding: NSUTF8StringEncoding) as String? {
if isStringPrintable(characteristicString) {
value = characteristicString
}
else { // print as hex
value = hexString(valueData!)
}
}
case .Text:
if let text = NSString(data:valueData!, encoding: NSUTF8StringEncoding) as? String {
value = text
}
case .Hex:
value = hexString(valueData!)
}
}
}
let characteristicCell = cell as! InfoCharacteristicTableViewCell
characteristicCell.titleLabel.text = identifier
characteristicCell.subtitleLabel.text = valueData != nil ? value : LocalizationManager.sharedInstance.localizedString(isDescriptor ? "info_type_descriptor":"info_type_characteristic")
characteristicCell.subtitleLabel.textColor = valueData != nil ? UIColor.blackColor() : UIColor.lightGrayColor()
return cell
}
private func isStringPrintable(text: String) -> Bool {
//NSCharacterSet
//let printableCharacterSet:NSCharacterSet = NSCharacterSet(charactersInString: "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLKMNOPQRSTUVWXYZ0123456789")
let printableCharacterSet = NSCharacterSet.alphanumericCharacterSet()
let isPrintable = text.rangeOfCharacterFromSet(printableCharacterSet) != nil
return isPrintable
}
}
extension InfoModuleViewController: UITableViewDelegate {
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
guard let service = services?[indexPath.section] where service.characteristics != nil else {
DLog("warning: didSelectRowAtIndexPath characteristics is nil")
tableView.deselectRowAtIndexPath(indexPath, animated: true)
return
}
let (currentCharacteristicIndex, currentItemOptional, isDescriptor) = itemForIndexPath(indexPath)
guard let currentItem = currentItemOptional else {
DLog("warning: current item is nil")
tableView.deselectRowAtIndexPath(indexPath, animated: true)
return
}
if let characteristic = service.characteristics?[currentCharacteristicIndex] {
let identifier = currentItem.UUID.UUIDString
let displayModeIdentifier = "\(currentCharacteristicIndex)_\(identifier)" // Descriptors in different characteristics could have the same CBUUID
if let displayMode = itemDisplayMode[displayModeIdentifier] {
switch displayMode {
case .Text:
itemDisplayMode[displayModeIdentifier] = .Hex
case .Hex:
itemDisplayMode[displayModeIdentifier] = .Text
default:
// Check if is printable
var isPrintable = false
var valueData: NSData?
if isDescriptor {
let descriptor = currentItem as! CBDescriptor
valueData = InfoModuleManager.parseDescriptorValue(descriptor)
}
else {
valueData = characteristic.value
}
if let value = valueData {
if let characteristicString = NSString(data:value, encoding: NSUTF8StringEncoding) as String? {
isPrintable = isStringPrintable(characteristicString)
}
}
itemDisplayMode[displayModeIdentifier] = isPrintable ? .Hex: .Text
}
}
tableView.reloadData()
//tableView.reloadRowsAtIndexPaths([indexPath], withRowAnimation: .None)
}
tableView.deselectRowAtIndexPath(indexPath, animated: true)
}
}
// MARK: - CBPeripheralDelegate
extension InfoModuleViewController : CBPeripheralDelegate {
func peripheralDidUpdateName(peripheral: CBPeripheral) {
DLog("centralManager peripheralDidUpdateName: \(peripheral.name != nil ? peripheral.name! : "")")
/*
dispatch_async(dispatch_get_main_queue(),{ [weak self] in
self?.discoverServices()
})
*/
}
func peripheral(peripheral: CBPeripheral, didModifyServices invalidatedServices: [CBService]) {
DLog("centralManager didModifyServices: \(peripheral.name != nil ? peripheral.name! : "")")
dispatch_async(dispatch_get_main_queue(),{ [weak self] in
self?.discoverServices()
})
}
func peripheral(peripheral: CBPeripheral, didDiscoverServices error: NSError?) {
isDiscoveringServices = false
if services == nil {
//DLog("centralManager didDiscoverServices: \(peripheral.name != nil ? peripheral.name! : "")")
services = blePeripheral?.peripheral.services
elementsToDiscover = 0
elementsDiscovered = 0
// Order services so "DIS" is at the top (if present)
let kDisServiceUUID = "180A" // DIS service UUID
if let unorderedServices = services {
services = unorderedServices.sort({ (serviceA, serviceB) -> Bool in
let isServiceBDis = serviceB.UUID.isEqual(CBUUID(string: kDisServiceUUID))
return !isServiceBDis
})
}
// Discover characteristics
if shouldDiscoverCharacteristics {
if let services = services {
for service in services {
elementsToDiscover += 1
blePeripheral?.peripheral.discoverCharacteristics(nil, forService: service)
}
}
}
/*
else {
onInfoScanFinished?()
}*/
// Update UI
dispatch_async(dispatch_get_main_queue(),{ [unowned self] in
//self.updateDiscoveringStatusLabel()
self.baseTableView.reloadData()
self.showWait(false)
self.onServicesDiscovered?()
})
}
}
func peripheral(peripheral: CBPeripheral, didDiscoverCharacteristicsForService service: CBService, error: NSError?) {
//DLog("centralManager didDiscoverCharacteristicsForService: \(service.UUID.UUIDString)")
elementsDiscovered += 1
if let characteristics = service.characteristics {
for characteristic in characteristics {
if (characteristic.properties.rawValue & CBCharacteristicProperties.Read.rawValue != 0) {
valuesToRead += 1
peripheral.readValueForCharacteristic(characteristic)
}
//elementsToDiscover += 1 // Dont add descriptors to elementsToDiscover because the number of descriptors found is unknown
blePeripheral?.peripheral.discoverDescriptorsForCharacteristic(characteristic)
}
}
dispatch_async(dispatch_get_main_queue(),{ [unowned self] in
self.baseTableView.reloadData()
})
}
func peripheral(peripheral: CBPeripheral, didDiscoverDescriptorsForCharacteristic characteristic: CBCharacteristic, error: NSError?) {
//DLog("centralManager didDiscoverDescriptorsForCharacteristic: \(characteristic.UUID.UUIDString)")
//elementsDiscovered += 1
if let descriptors = characteristic.descriptors {
for descriptor in descriptors {
let isAForbiddenCCCD = descriptor.UUID.UUIDString.caseInsensitiveCompare("2902") == .OrderedSame && (characteristic.UUID.UUIDString.caseInsensitiveCompare(UartManager.RxCharacteristicUUID) == .OrderedSame || characteristic.UUID.UUIDString.caseInsensitiveCompare(dfuControlPointCharacteristicUUIDString) == .OrderedSame)
if InfoModuleViewController.kReadForbiddenCCCD || !isAForbiddenCCCD {
valuesToRead += 1
peripheral.readValueForDescriptor(descriptor)
}
}
}
if (self.elementsDiscovered == self.elementsToDiscover) {
dispatch_async(dispatch_get_main_queue(),{ [unowned self] in
self.baseTableView.reloadData()
})
}
/*
if (self.valuesRead == self.valuesToRead) {
dispatch_async(dispatch_get_main_queue(),{ [unowned self] in
self.onInfoScanFinished?()
})
}
*/
}
func peripheral(peripheral: CBPeripheral, didUpdateValueForCharacteristic characteristic: CBCharacteristic, error: NSError?) {
//DLog("centralManager didUpdateValueForCharacteristic: \(characteristic.UUID.UUIDString)")
valuesRead += 1
if (self.elementsDiscovered >= self.elementsToDiscover) {
dispatch_async(dispatch_get_main_queue(),{ [unowned self] in
//self.updateDiscoveringStatusLabel()
self.baseTableView.reloadData()
})
}
}
func peripheral(peripheral: CBPeripheral, didUpdateValueForDescriptor descriptor: CBDescriptor, error: NSError?) {
//DLog("centralManager didUpdateValueForDescriptor: \(descriptor.UUID.UUIDString)")
valuesRead += 1
DLog("didUpdateValueForDescriptor: \(descriptor.UUID.UUIDString) characteristic: \(descriptor.characteristic.UUID.UUIDString)")
// DLog("disco \(self.elementsDiscovered)/\(self.elementsToDiscover)")
if (self.elementsDiscovered >= self.elementsToDiscover) {
dispatch_async(dispatch_get_main_queue(),{ [unowned self] in
//self.updateDiscoveringStatusLabel()
self.baseTableView.reloadData()
})
}
}
}
|
mit
|
d0e571fb0f526caba974925c90de0b33
| 39.664 | 335 | 0.606138 | 6.103873 | false | false | false | false |
c1moore/deckstravaganza
|
Deckstravaganza/AppDelegate.swift
|
1
|
2803
|
//
// AppDelegate.swift
// Deckstravaganza
//
// Created by Calvin Moore on 9/19/15.
// Copyright © 2015 University of Florida. All rights reserved.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
GCHelper.sharedInstance.authenticateLocalUser()
// Override point for customization after application launch.
let splitViewController = self.window!.rootViewController as! UISplitViewController
let leftNavController = splitViewController.viewControllers.first as! UINavigationController
let masterViewController = leftNavController.topViewController as! MasterViewController
let detailViewController = splitViewController.viewControllers.last as! DetailViewController
let firstMenu = masterViewController.menus.first?.first
detailViewController.selectedMenuOption = firstMenu!
masterViewController.delegate = detailViewController
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
|
0e5385568d18f6e549082612799c7679
| 49.035714 | 285 | 0.761599 | 5.849687 | false | false | false | false |
LuizZak/TaskMan
|
TaskMan/AppDelegate.swift
|
1
|
1306
|
//
// AppDelegate.swift
// TaskMan
//
// Created by Luiz Fernando Silva on 16/09/16.
// Copyright © 2016 Luiz Fernando Silva. All rights reserved.
//
import Cocoa
@NSApplicationMain
class AppDelegate: NSObject, NSApplicationDelegate {
override init() {
_ = TaskDocumentController()
super.init()
}
func applicationDidFinishLaunching(_ aNotification: Notification) {
// Insert code here to initialize your application
}
func applicationWillTerminate(_ aNotification: Notification) {
// Insert code here to tear down your application
}
func applicationShouldOpenUntitledFile(_ sender: NSApplication) -> Bool {
return true
}
func application(_ application: NSApplication, willPresentError error: Error) -> Error {
let nsError: NSError = error as NSError
if (nsError.domain == (TaskManDocument.ReadError.InvalidVersion as NSError).domain) {
let description = "\(nsError.localizedDescription)\nThe file was created with a future/unsuported version of TaskMan."
let newError = NSError(domain: "TaskManError", code: 1001, userInfo: [NSLocalizedDescriptionKey: description])
return newError
}
return error
}
}
|
mit
|
cb66f020549f0ebc2bcd58ea77b2b3a7
| 28 | 130 | 0.658238 | 5.158103 | false | false | false | false |
wikimedia/wikipedia-ios
|
Wikipedia/Code/NSNumberFormatter+WMFExtras.swift
|
1
|
3382
|
import Foundation
let thousandsFormatter = { () -> NumberFormatter in
let formatter = NumberFormatter()
formatter.numberStyle = .decimal
formatter.maximumFractionDigits = 1
formatter.roundingMode = .halfUp
return formatter
}()
let threeSignificantDigitWholeNumberFormatterGlobal = { () -> NumberFormatter in
let formatter = NumberFormatter()
formatter.numberStyle = .decimal
formatter.maximumFractionDigits = 0
formatter.usesSignificantDigits = true
formatter.maximumSignificantDigits = 3
formatter.roundingMode = .halfUp
return formatter
}()
extension NumberFormatter {
public class var threeSignificantDigitWholeNumberFormatter: NumberFormatter {
return threeSignificantDigitWholeNumberFormatterGlobal
}
public class func localizedThousandsStringFromNumber(_ number: NSNumber) -> String {
let doubleValue = number.doubleValue
let absDoubleValue = abs(doubleValue)
var adjustedDoubleValue: Double = doubleValue
var formatString: String = "%1$@"
if absDoubleValue > 1000000000 {
adjustedDoubleValue = doubleValue/1000000000.0
formatString = WMFLocalizedString("number-billions", value:"%1$@B", comment:"%1$@B - %1$@ is replaced with a number represented in billions. In English 'B' is commonly used after a number to indicate that number is in 'billions'. So the 'B' should be changed to a character or short string indicating billions. For example 5,100,000,000 would become 5.1B. If there is no simple translation for this in the target language, make the translation %1$@ with no other characters and the full number will be shown.")
} else if absDoubleValue > 1000000 {
adjustedDoubleValue = doubleValue/1000000.0
formatString = WMFLocalizedString("number-millions", value:"%1$@M", comment:"%1$@M - %1$@ is replaced with a number represented in millions. In English 'M' is commonly used after a number to indicate that number is in 'millions'. So the 'M' should be changed to a character or short string indicating millions. For example 500,000,000 would become 500M. If there is no simple translation for this in the target language, make the translation %1$@ with no other characters and the full number will be shown.")
} else if absDoubleValue > 1000 {
adjustedDoubleValue = doubleValue/1000.0
formatString = WMFLocalizedString("number-thousands", value:"%1$@K", comment:"%1$@K - %1$@ is replaced with a number represented in thousands. In English the letter 'K' is commonly used after a number to indicate that number is in 'thousands'. So the letter 'K' should be changed to a character or short string indicating thousands. For example 500,000 would become 500K. If there is no simple translation for this in the target language, make the translation %1$@ with no other characters and the full number will be shown. {{Identical|%1$@k}}")
}
if formatString == "%1$@" { // check for opt-out translations
adjustedDoubleValue = doubleValue
}
if let numberString = thousandsFormatter.string(from: NSNumber(value:adjustedDoubleValue)) {
return String.localizedStringWithFormat(formatString, numberString)
} else {
return ""
}
}
}
|
mit
|
55f9f74e0c954a8455e6c365c0e3eb4e
| 58.333333 | 558 | 0.706387 | 5.093373 | false | false | false | false |
superk589/DereGuide
|
DereGuide/Unit/Simulation/View/UnitSimulationLiveSelectCell.swift
|
2
|
5093
|
//
// UnitSimulationLiveSelectCell.swift
// DereGuide
//
// Created by zzk on 2017/5/16.
// Copyright © 2017 zzk. All rights reserved.
//
import UIKit
import SnapKit
class UnitSimulationLiveView: UIView {
let jacketImageView = BannerView()
let typeIcon = UIImageView()
let nameLabel = UILabel()
let descriptionLabel = UILabel()
let backgroundLabel = UILabel()
let noteDistributionLabel = UILabel()
override init(frame: CGRect) {
super.init(frame: frame)
addSubview(jacketImageView)
jacketImageView.snp.makeConstraints { (make) in
make.left.top.equalToSuperview()
make.width.height.equalTo(64)
make.bottom.equalToSuperview()
}
addSubview(typeIcon)
typeIcon.snp.makeConstraints { (make) in
make.left.equalTo(jacketImageView.snp.right).offset(10)
make.top.equalTo(jacketImageView)
make.width.height.equalTo(20)
}
nameLabel.font = .boldSystemFont(ofSize: 18)
nameLabel.adjustsFontSizeToFitWidth = true
nameLabel.baselineAdjustment = .alignCenters
addSubview(nameLabel)
nameLabel.snp.makeConstraints { (make) in
make.left.equalTo(typeIcon.snp.right).offset(5)
make.centerY.equalTo(typeIcon)
make.right.lessThanOrEqualToSuperview()
}
descriptionLabel.font = .systemFont(ofSize: 12)
descriptionLabel.textColor = .darkGray
descriptionLabel.adjustsFontSizeToFitWidth = true
descriptionLabel.baselineAdjustment = .alignCenters
descriptionLabel.textAlignment = .left
addSubview(descriptionLabel)
addSubview(noteDistributionLabel)
noteDistributionLabel.font = .systemFont(ofSize: 12)
noteDistributionLabel.textColor = .darkGray
noteDistributionLabel.adjustsFontSizeToFitWidth = true
noteDistributionLabel.baselineAdjustment = .alignCenters
noteDistributionLabel.snp.makeConstraints { (make) in
make.left.equalTo(typeIcon)
make.right.lessThanOrEqualTo(-10)
make.bottom.equalTo(jacketImageView)
}
descriptionLabel.snp.makeConstraints { (make) in
make.left.equalTo(typeIcon)
make.right.lessThanOrEqualTo(-10)
make.bottom.equalTo(noteDistributionLabel.snp.top).offset(-5)
}
addSubview(backgroundLabel)
backgroundLabel.font = .systemFont(ofSize: 18)
backgroundLabel.textColor = .lightGray
backgroundLabel.text = NSLocalizedString("请选择歌曲", comment: "队伍详情页面")
backgroundLabel.snp.makeConstraints { (make) in
make.center.equalToSuperview()
}
}
func setup(with scene: CGSSLiveScene?) {
guard let scene = scene, let beatmap = scene.beatmap else {
backgroundLabel.text = NSLocalizedString("请选择歌曲", comment: "队伍详情页面")
descriptionLabel.text = ""
jacketImageView.image = nil
nameLabel.text = ""
typeIcon.image = nil
return
}
backgroundLabel.text = ""
descriptionLabel.text = "\(scene.stars)☆ \(scene.difficulty.description) bpm: \(scene.live.bpm) notes: \(beatmap.numberOfNotes) \(NSLocalizedString("时长", comment: "队伍详情页面")): \(Int(beatmap.totalSeconds))\(NSLocalizedString("秒", comment: "队伍详情页面"))"
nameLabel.text = scene.live.name
nameLabel.textColor = scene.live.color
typeIcon.image = scene.live.icon
jacketImageView.sd_setImage(with: scene.live.jacketURL)
let format = "normal: %.0f%% hold: %.0f%% flick: %.0f%% slide: %.0f%%"
noteDistributionLabel.text = String(
format: format,
beatmap.noteTypeDistribution.percentOfClick,
beatmap.noteTypeDistribution.percentOfHold,
beatmap.noteTypeDistribution.percentOfFlick,
beatmap.noteTypeDistribution.percentOfSlide
)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
class UnitSimulationLiveSelectCell: UITableViewCell {
let liveView = UnitSimulationLiveView()
override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
contentView.addSubview(liveView)
liveView.snp.makeConstraints { (make) in
make.top.equalTo(10)
make.left.equalTo(10)
make.right.equalToSuperview()
make.bottom.equalToSuperview().offset(-10)
}
selectionStyle = .none
accessoryType = .disclosureIndicator
}
func setup(with scene: CGSSLiveScene?) {
liveView.setup(with: scene)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
|
mit
|
042c7e58fcd3931c60910bf04cb30c33
| 34.323944 | 256 | 0.635965 | 4.790831 | false | false | false | false |
minio/swift-photo-app
|
SwiftPhotoApp/ViewController.swift
|
1
|
3886
|
//
// SwiftPhotoApp, (C) 2017 Minio, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
import UIKit
class ViewController: UIViewController {
@IBAction func refButton(sender: UIButton) {
// Set up the URL Object.
let url = URL(string: "http://play.minio.io:8080/PhotoAPIService-0.0.1-SNAPSHOT/minio/photoservice/list")
// Task fetches the url contents asynchronously.
let task = URLSession.shared.dataTask(with: url! as URL) {(data, response, error) in
let httpResponse = response as! HTTPURLResponse
let statusCode = httpResponse.statusCode
// Process the response.
if (statusCode == 200) {
do{
// Get the json response.
let json = try JSONSerialization.jsonObject(with: data!, options:.allowFragments) as! [String:AnyObject]
// Extract the Album json into the albums array.
if let albums = json["Album"] as? [[String: AnyObject]]{
// Pick a random index from the albums array.
let randomIndex = Int(arc4random_uniform(UInt32(albums.count)))
// Extract the url from the albums array using this random index we generated.
let loadImageUrl:String = albums[randomIndex]["url"] as! String
// Prepare the imageView.
self.imageView.contentMode = .scaleAspectFit
// Download and place the image in the image view with a helper function.
if let checkedUrl = URL(string: loadImageUrl) {
self.imageView.contentMode = .scaleAspectFit
self.downloadImage(url: checkedUrl)
}
}
}
catch {
print("Error with Json: \(error)")
}
}
}
task.resume()
}
@IBOutlet weak var imageView: UIImageView!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// Asynchronous helper function that fetches data from the PhotoAPIService.
func getDataFromUrl(url:URL, completion: @escaping ((_ data: Data?, _ response: URLResponse?, _ error: Error? ) -> Void)) {
URLSession.shared.dataTask(with: url as URL) { (data, response, error) in
completion(data, response, error)
}.resume()
}
// Helper function that download asynchronously an image from a given url.
func downloadImage(url: URL){
getDataFromUrl(url: url) { (data, response, error) in
DispatchQueue.main.async() { () -> Void in
guard let data = data, error == nil else { return }
self.imageView.image = UIImage(data: data as Data)
}
}
}
}
|
apache-2.0
|
bf9502bdef3449f07b81b99680ceaf4c
| 38.653061 | 127 | 0.552753 | 5.195187 | false | false | false | false |
matrix-org/matrix-ios-sdk
|
MatrixSDK/Data/RoomList/MXStore/MXStoreRoomListDataFetcher.swift
|
1
|
11212
|
//
// Copyright 2021 The Matrix.org Foundation C.I.C
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
import Foundation
@objcMembers
internal class MXStoreRoomListDataFetcher: NSObject, MXRoomListDataFetcher {
internal private(set) var data: MXRoomListData? {
didSet {
guard let data = data else {
// do not notify when stopped
return
}
if data != oldValue {
let totalCountsChanged: Bool
if fetchOptions.paginationOptions == .none {
// pagination disabled, we don't need to track number of rooms in this case
totalCountsChanged = true
} else {
totalCountsChanged = oldValue?.counts.total?.numberOfRooms != data.counts.total?.numberOfRooms
}
notifyDataChange(totalCountsChanged: totalCountsChanged)
}
}
}
internal let fetchOptions: MXRoomListDataFetchOptions
private let store: MXRoomSummaryStore
private let multicastDelegate: MXMulticastDelegate<MXRoomListDataFetcherDelegate> = MXMulticastDelegate()
private var roomSummaries: [String: MXRoomSummaryProtocol] = [:]
private let executionQueue: DispatchQueue = DispatchQueue(label: "MXStoreRoomListDataFetcherQueue-" + MXTools.generateSecret())
internal init(fetchOptions: MXRoomListDataFetchOptions,
store: MXRoomSummaryStore) {
self.fetchOptions = fetchOptions
self.store = store
super.init()
self.fetchOptions.fetcher = self
addDataObservers()
}
// MARK: - Delegate
internal func addDelegate(_ delegate: MXRoomListDataFetcherDelegate) {
multicastDelegate.addDelegate(delegate)
}
internal func removeDelegate(_ delegate: MXRoomListDataFetcherDelegate) {
multicastDelegate.removeDelegate(delegate)
}
internal func removeAllDelegates() {
multicastDelegate.removeAllDelegates()
}
// MARK: - Data
internal func paginate() {
if fetchOptions.async {
executionQueue.async { [weak self] in
guard let self = self else { return }
self.innerPaginate()
}
} else {
executionQueue.sync { [weak self] in
guard let self = self else { return }
self.innerPaginate()
}
}
}
internal func resetPagination() {
if fetchOptions.async {
executionQueue.async { [weak self] in
guard let self = self else { return }
self.innerResetPagination()
}
} else {
executionQueue.sync { [weak self] in
guard let self = self else { return }
self.innerResetPagination()
}
}
}
internal func refresh() {
guard let oldData = data else {
return
}
data = nil
recomputeData(using: oldData)
}
internal func stop() {
removeAllDelegates()
removeDataObservers()
data = nil
}
// MARK: - Private
private func innerPaginate() {
let numberOfItems: Int
if let data = data {
// load next page
guard data.hasMoreRooms else {
// there is no more rooms to paginate
return
}
// MXStore implementation does not provide any pagination options.
// We'll try to change total number of items we fetched when paginating further.
// Case: we've loaded our nth page of data with pagination size P.
// To further paginate, we'll try to fetch (n+2)*P items in total.
numberOfItems = (data.currentPage + 2) * data.paginationOptions.rawValue
} else {
// load first page
for roomId in store.rooms {
if let summary = store.summary(ofRoom: roomId) {
self.roomSummaries[roomId] = summary
}
}
numberOfItems = fetchOptions.paginationOptions.rawValue
}
data = computeData(upto: numberOfItems)
}
/// Load first page again
private func innerResetPagination() {
data = computeData(upto: fetchOptions.paginationOptions.rawValue)
}
/// Recompute data with the same number of rooms of the given `data`
private func recomputeData(using data: MXRoomListData) {
let numberOfItems = (data.currentPage + 1) * data.paginationOptions.rawValue
self.data = computeData(upto: numberOfItems)
}
/// Compute data up to a numberOfItems
private func computeData(upto numberOfItems: Int) -> MXRoomListData {
var rooms = Array(roomSummaries.values)
rooms = filterRooms(rooms)
rooms = sortRooms(rooms)
var total: MXRoomListDataCounts?
if numberOfItems > 0 && rooms.count > numberOfItems {
// compute total counts just before cutting the rooms array
total = MXStoreRoomListDataCounts(withRooms: rooms, total: nil)
rooms = Array(rooms[0..<numberOfItems])
}
return MXRoomListData(rooms: rooms,
counts: MXStoreRoomListDataCounts(withRooms: rooms,
total: total),
paginationOptions: fetchOptions.paginationOptions)
}
private func notifyDataChange(totalCountsChanged: Bool) {
multicastDelegate.invoke({ $0.fetcherDidChangeData(self, totalCountsChanged: totalCountsChanged) })
}
// MARK: - Data Observers
private func addDataObservers() {
NotificationCenter.default.addObserver(self,
selector: #selector(roomAdded(_:)),
name: .mxSessionNewRoom,
object: nil)
NotificationCenter.default.addObserver(self,
selector: #selector(roomRemoved(_:)),
name: .mxSessionDidLeaveRoom,
object: nil)
NotificationCenter.default.addObserver(self,
selector: #selector(roomSummaryUpdated(_:)),
name: .mxRoomSummaryDidChange,
object: nil)
NotificationCenter.default.addObserver(self,
selector: #selector(directRoomsUpdated(_:)),
name: .mxSessionDirectRoomsDidChange,
object: nil)
}
private func removeDataObservers() {
NotificationCenter.default.removeObserver(self,
name: .mxSessionNewRoom,
object: nil)
NotificationCenter.default.removeObserver(self,
name: .mxSessionDidLeaveRoom,
object: nil)
NotificationCenter.default.removeObserver(self,
name: .mxRoomSummaryDidChange,
object: nil)
NotificationCenter.default.removeObserver(self,
name: .mxSessionDirectRoomsDidChange,
object: nil)
}
@objc
private func roomAdded(_ notification: Notification) {
executionQueue.async { [weak self] in
guard let self = self else { return }
guard let data = self.data else {
// ignore this change if we never computed data yet
return
}
guard let roomId = notification.userInfo?[kMXSessionNotificationRoomIdKey] as? String else {
return
}
guard let summary = self.store.summary(ofRoom: roomId) else {
MXLog.error("[MXStoreRoomListDataManager] roomAdded: room not found in the store", context: [
"room_id": roomId
])
return
}
self.roomSummaries[roomId] = summary
self.recomputeData(using: data)
}
}
@objc
private func roomRemoved(_ notification: Notification) {
executionQueue.async { [weak self] in
guard let self = self else { return }
guard let data = self.data else {
// ignore this change if we never computed data yet
return
}
guard let roomId = notification.userInfo?[kMXSessionNotificationRoomIdKey] as? String else {
return
}
self.roomSummaries.removeValue(forKey: roomId)
self.recomputeData(using: data)
}
}
@objc
private func roomSummaryUpdated(_ notification: Notification) {
executionQueue.async { [weak self] in
guard let self = self else { return }
guard let data = self.data else {
// ignore this change if we never computed data yet
return
}
guard let summary = notification.object as? MXRoomSummary else {
return
}
self.roomSummaries[summary.roomId] = summary
self.recomputeData(using: data)
}
}
@objc
private func directRoomsUpdated(_ notification: Notification) {
executionQueue.async { [weak self] in
guard let self = self else { return }
guard let data = self.data else {
// ignore this change if we never computed data yet
return
}
self.recomputeData(using: data)
}
}
deinit {
stop()
}
}
// MARK: MXRoomListDataSortable
extension MXStoreRoomListDataFetcher: MXRoomListDataSortable {
var sortOptions: MXRoomListDataSortOptions {
return fetchOptions.sortOptions
}
}
// MARK: MXRoomListDataFilterable
extension MXStoreRoomListDataFetcher: MXRoomListDataFilterable {
var filterOptions: MXRoomListDataFilterOptions {
return fetchOptions.filterOptions
}
}
|
apache-2.0
|
d06fbf1b09695299503b24118ce90998
| 36.0033 | 131 | 0.550482 | 5.545005 | false | false | false | false |
bitjammer/swift
|
test/stdlib/UnsafeRawPointer.swift
|
22
|
7554
|
// RUN: %target-run-simple-swiftgyb
// REQUIRES: executable_test
import StdlibUnittest
var UnsafeMutableRawPointerExtraTestSuite =
TestSuite("UnsafeMutableRawPointerExtra")
class Missile {
static var missilesLaunched = 0
let number: Int
init(_ number: Int) { self.number = number }
deinit { Missile.missilesLaunched += 1 }
}
UnsafeMutableRawPointerExtraTestSuite.test("initializeMemory") {
Missile.missilesLaunched = 0
do {
let sizeInBytes = 3 * MemoryLayout<Missile>.stride
var p1 = UnsafeMutableRawPointer.allocate(
bytes: sizeInBytes, alignedTo: MemoryLayout<Missile>.alignment)
defer {
p1.deallocate(bytes: sizeInBytes, alignedTo: MemoryLayout<Missile>.alignment)
}
var ptrM = p1.initializeMemory(as: Missile.self, to: Missile(1))
p1.initializeMemory(as: Missile.self, at: 1, count: 2, to: Missile(2))
expectEqual(1, ptrM[0].number)
expectEqual(2, ptrM[1].number)
expectEqual(2, ptrM[2].number)
var p2 = UnsafeMutableRawPointer.allocate(
bytes: sizeInBytes, alignedTo: MemoryLayout<Missile>.alignment)
defer {
p2.deallocate(bytes: sizeInBytes, alignedTo: MemoryLayout<Missile>.alignment)
}
let ptrM2 = p2.moveInitializeMemory(as: Missile.self, from: ptrM, count: 3)
defer {
ptrM2.deinitialize(count: 3)
}
// p1 is now deinitialized.
expectEqual(1, ptrM2[0].number)
expectEqual(2, ptrM2[1].number)
expectEqual(2, ptrM2[2].number)
ptrM = p1.initializeMemory(
as: Missile.self, from: (1...3).map(Missile.init))
defer {
ptrM.deinitialize(count: 3)
}
expectEqual(1, ptrM[0].number)
expectEqual(2, ptrM[1].number)
expectEqual(3, ptrM[2].number)
}
expectEqual(5, Missile.missilesLaunched)
}
UnsafeMutableRawPointerExtraTestSuite.test("bindMemory") {
let sizeInBytes = 3 * MemoryLayout<Int>.stride
var p1 = UnsafeMutableRawPointer.allocate(
bytes: sizeInBytes, alignedTo: MemoryLayout<Int>.alignment)
defer {
p1.deallocate(bytes: sizeInBytes, alignedTo: MemoryLayout<Int>.alignment)
}
let ptrI = p1.bindMemory(to: Int.self, capacity: 3)
let bufI = UnsafeMutableBufferPointer(start: ptrI, count: 3)
bufI.initialize(from: 1...3)
let ptrU = p1.bindMemory(to: UInt.self, capacity: 3)
expectEqual(1, ptrU[0])
expectEqual(2, ptrU[1])
expectEqual(3, ptrU[2])
let ptrU2 = p1.assumingMemoryBound(to: UInt.self)
expectEqual(1, ptrU[0])
}
UnsafeMutableRawPointerExtraTestSuite.test("load/store") {
let sizeInBytes = 3 * MemoryLayout<Int>.stride
var p1 = UnsafeMutableRawPointer.allocate(
bytes: sizeInBytes, alignedTo: MemoryLayout<Int>.alignment)
defer {
p1.deallocate(bytes: sizeInBytes, alignedTo: MemoryLayout<Int>.alignment)
}
let ptrI = p1.initializeMemory(as: Int.self, from: 1...3)
defer {
ptrI.deinitialize(count: 3)
}
expectEqual(1, p1.load(as: Int.self))
expectEqual(2, p1.load(fromByteOffset: MemoryLayout<Int>.stride, as: Int.self))
expectEqual(3, p1.load(fromByteOffset: 2*MemoryLayout<Int>.stride, as: Int.self))
p1.storeBytes(of: 4, as: Int.self)
p1.storeBytes(of: 5, toByteOffset: MemoryLayout<Int>.stride, as: Int.self)
p1.storeBytes(of: 6, toByteOffset: 2 * MemoryLayout<Int>.stride, as: Int.self)
expectEqual(4, p1.load(as: Int.self))
expectEqual(5, p1.load(fromByteOffset: MemoryLayout<Int>.stride, as: Int.self))
expectEqual(6, p1.load(fromByteOffset: 2 * MemoryLayout<Int>.stride, as: Int.self))
}
UnsafeMutableRawPointerExtraTestSuite.test("copyBytes") {
let sizeInBytes = 4 * MemoryLayout<Int>.stride
var rawPtr = UnsafeMutableRawPointer.allocate(
bytes: sizeInBytes, alignedTo: MemoryLayout<Int>.alignment)
defer {
rawPtr.deallocate(bytes: sizeInBytes, alignedTo: MemoryLayout<Int>.alignment)
}
let ptrI = rawPtr.initializeMemory(as: Int.self, count: 4, to: 42)
defer {
ptrI.deinitialize(count: 4)
}
let roPtr = UnsafeRawPointer(rawPtr)
// Right overlap
ptrI[0] = 1
ptrI[1] = 2
(rawPtr + MemoryLayout<Int>.stride).copyBytes(
from: roPtr, count: 2 * MemoryLayout<Int>.stride)
expectEqual(1, ptrI[1])
expectEqual(2, ptrI[2])
// Left overlap
ptrI[1] = 2
ptrI[2] = 3
rawPtr.copyBytes(
from: roPtr + MemoryLayout<Int>.stride, count: 2 * MemoryLayout<Int>.stride)
expectEqual(2, ptrI[0])
expectEqual(3, ptrI[1])
// Disjoint:
ptrI[2] = 2
ptrI[3] = 3
rawPtr.copyBytes(
from: roPtr + 2 * MemoryLayout<Int>.stride, count: 2 * MemoryLayout<Int>.stride)
expectEqual(2, ptrI[0])
expectEqual(3, ptrI[1])
// Backwards
ptrI[0] = 0
ptrI[1] = 1
(rawPtr + 2 * MemoryLayout<Int>.stride).copyBytes(
from: roPtr, count: 2 * MemoryLayout<Int>.stride)
expectEqual(0, ptrI[2])
expectEqual(1, ptrI[3])
}
// --------------------------------------------
// Test bulk initialization from UnsafePointer.
enum Check {
case LeftOverlap
case RightOverlap
case Disjoint
}
func checkRawPointerCorrectness(_ check: Check,
_ f: (UnsafeMutableRawPointer) -> (_ as: Int.Type, _ from: UnsafeMutablePointer<Int>, _ count: Int) -> UnsafeMutablePointer<Int>) {
let ptr = UnsafeMutablePointer<Int>.allocate(capacity: 4)
switch check {
case .RightOverlap:
ptr.initialize(to: 1)
(ptr + 1).initialize(to: 2)
_ = f(UnsafeMutableRawPointer(ptr + 1))(Int.self, ptr, 2)
expectEqual(1, ptr[1])
expectEqual(2, ptr[2])
case .LeftOverlap:
(ptr + 1).initialize(to: 2)
(ptr + 2).initialize(to: 3)
_ = f(UnsafeMutableRawPointer(ptr))(Int.self, ptr + 1, 2)
expectEqual(2, ptr[0])
expectEqual(3, ptr[1])
case .Disjoint:
(ptr + 2).initialize(to: 2)
(ptr + 3).initialize(to: 3)
_ = f(UnsafeMutableRawPointer(ptr))(Int.self, ptr + 2, 2)
expectEqual(2, ptr[0])
expectEqual(3, ptr[1])
// backwards
let ptr2 = UnsafeMutablePointer<Int>.allocate(capacity: 4)
ptr2.initialize(to: 0)
(ptr2 + 1).initialize(to: 1)
_ = f(UnsafeMutableRawPointer(ptr2 + 2))(Int.self, ptr2, 2)
expectEqual(0, ptr2[2])
expectEqual(1, ptr2[3])
}
}
func checkPtr(
_ f: @escaping ((UnsafeMutableRawPointer)
-> (_ as: Int.Type, _ from: UnsafeMutablePointer<Int>, _ count: Int)
-> UnsafeMutablePointer<Int>)
) -> (Check) -> Void {
return { checkRawPointerCorrectness($0, f) }
}
func checkPtr(
_ f: @escaping ((UnsafeMutableRawPointer)
-> (_ as: Int.Type, _ from: UnsafePointer<Int>, _ count: Int)
-> UnsafeMutablePointer<Int>)
) -> (Check) -> Void {
return {
checkRawPointerCorrectness($0) { destPtr in
return { f(destPtr)($0, UnsafeMutablePointer($1), $2) }
}
}
}
UnsafeMutableRawPointerExtraTestSuite.test("initializeMemory:as:from:count:") {
let check = checkPtr(UnsafeMutableRawPointer.initializeMemory(as:from:count:))
check(Check.Disjoint)
// This check relies on _debugPrecondition() so will only trigger in
// -Onone mode.
if _isDebugAssertConfiguration() {
expectCrashLater()
check(Check.LeftOverlap)
}
}
UnsafeMutableRawPointerExtraTestSuite.test("initializeMemory:as:from:count:.Right") {
let check = checkPtr(UnsafeMutableRawPointer.initializeMemory(as:from:count:))
// This check relies on _debugPrecondition() so will only trigger in
// -Onone mode.
if _isDebugAssertConfiguration() {
expectCrashLater()
check(Check.RightOverlap)
}
}
UnsafeMutableRawPointerExtraTestSuite.test("moveInitialize:from:") {
let check =
checkPtr(UnsafeMutableRawPointer.moveInitializeMemory(as:from:count:))
check(Check.LeftOverlap)
check(Check.Disjoint)
check(Check.RightOverlap)
}
runAllTests()
|
apache-2.0
|
d945b61594d505fcb05e74079a11bf05
| 31.560345 | 133 | 0.690892 | 3.548145 | false | true | false | false |
lovehhf/edx-app-ios
|
Source/CutomePlayer/OEXVideoPlayerSettings.swift
|
1
|
5200
|
//
// OEXVideoPlayerSettings.swift
// edX
//
// Created by Michael Katz on 9/9/15.
// Copyright (c) 2015 edX. All rights reserved.
//
import Foundation
private let cellId = "CustomCell"
private typealias RowType = (title: String, value: Any)
private struct OEXVideoPlayerSetting {
let title: String
let rows: [RowType]
let isSelected: (row: Int) -> Bool
let callback: (value: Any)->()
}
@objc protocol OEXVideoPlayerSettingsDelegate {
func showSubSettings(chooser: PSTAlertController)
func setCaption(language: String)
func setPlaybackSpeed(speed: Float)
func videoInfo() -> OEXVideoSummary
}
private func setupTable(table: UITableView) {
table.layer.cornerRadius = 10
table.layer.shadowColor = UIColor.blackColor().CGColor
table.layer.shadowRadius = 1.0
table.layer.shadowOffset = CGSize(width: 1, height: 1)
table.layer.shadowOpacity = 0.8
table.separatorInset = UIEdgeInsetsZero
table.registerNib(UINib(nibName: "OEXClosedCaptionTableViewCell", bundle: nil), forCellReuseIdentifier: cellId)
}
@objc class OEXVideoPlayerSettings : NSObject {
let optionsTable: UITableView = UITableView(frame: CGRectZero, style: .Plain)
private lazy var settings: [OEXVideoPlayerSetting] = {
self.updateMargins() //needs to be done here because the table loads the data too soon otherwise and it's nil
let speeds = OEXVideoPlayerSetting(title: "Video Speed", rows: [("0.5x", 0.5), ("1.0x", 1.0), ("1.5x", 1.5), ("2.0x", 2.0)], isSelected: { (row) -> Bool in
return false
}) { value in
let fltValue = Float(value as! Double)
self.delegate?.setPlaybackSpeed(fltValue)
}
if let transcripts: [String: String] = self.delegate?.videoInfo().transcripts as? [String: String] {
var rows = [RowType]()
for lang: String in transcripts.keys {
let locale = NSLocale(localeIdentifier: lang)
let displayLang: String = locale.displayNameForKey(NSLocaleLanguageCode, value: lang)!
let item: RowType = (title: displayLang, value: lang)
rows.append(item)
}
let cc = OEXVideoPlayerSetting(title: "Closed Captions", rows: rows, isSelected: { (row) -> Bool in
var selected = false
if let selectedLanguage:String = OEXInterface.getCCSelectedLanguage() {
let lang = rows[row].value as! String
selected = selectedLanguage == lang
}
return selected
}) { value in
self.delegate?.setCaption(value as! String)
}
return [cc, speeds]
} else {
return [speeds]
}
}()
weak var delegate: OEXVideoPlayerSettingsDelegate?
func updateMargins() {
if UIDevice.isOSVersionAtLeast8() {
optionsTable.layoutMargins = UIEdgeInsetsZero
}
}
init(delegate: OEXVideoPlayerSettingsDelegate, videoInfo: OEXVideoSummary) {
self.delegate = delegate
super.init()
optionsTable.dataSource = self
optionsTable.delegate = self
setupTable(optionsTable)
}
}
extension OEXVideoPlayerSettings: UITableViewDataSource, UITableViewDelegate {
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return settings.count
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier(cellId, forIndexPath: indexPath) as! OEXClosedCaptionTableViewCell
cell.selectionStyle = .None
cell.lbl_Title.font = UIFont(name: "OpenSans", size: 12)
cell.viewDisable.backgroundColor = UIColor.whiteColor()
if UIDevice.isOSVersionAtLeast8() {
cell.layoutMargins = UIEdgeInsetsZero
}
cell.backgroundColor = UIColor.whiteColor()
let setting = settings[indexPath.row]
cell.lbl_Title.text = setting.title
return cell
}
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
let selectedSetting = settings[indexPath.row]
let alert = PSTAlertController(title: selectedSetting.title, message: nil, preferredStyle: PSTAlertControllerStyle.ActionSheet)
for (i, row) in enumerate(selectedSetting.rows) {
var title = row.title
if selectedSetting.isSelected(row: i) {
//Can't use font awesome here
title = NSString(format: OEXLocalizedString("VIDEO_SETTING_SELECTED", nil), row.title) as String
}
alert.addAction(PSTAlertAction(title: title, handler: { _ in
selectedSetting.callback(value: row.value)
}))
}
alert.addCancelActionWithHandler(nil)
delegate?.showSubSettings(alert)
}
}
|
apache-2.0
|
72665f34bc80e5e09acf4069068830c8
| 35.111111 | 164 | 0.631346 | 4.805915 | false | false | false | false |
FandyLiu/FDDemoCollection
|
Swift/Apply/Apply/ApplyTableViewCell.swift
|
1
|
4257
|
//
// ApplyTableViewCell.swift
// Apply
//
// Created by QianTuFD on 2017/3/31.
// Copyright © 2017年 fandy. All rights reserved.
//
import UIKit
protocol ApplyTableViewCellProtocol {
associatedtype TableViewCellType
static var indentifier: String { get }
var myType: TableViewCellType { get set }
}
@objc protocol CommonTableViewCellDelegate: NSObjectProtocol {
@objc optional func commonCell(_ commonCell: CommonTableViewCell, textFieldDidEndEditing textField: UITextField)
@objc optional func commonCell(_ commonCell: CommonTableViewCell, textFieldShouldBeginEditing textField: UITextField)
@objc optional func commonCell(_ commonCell: CommonTableViewCell, verificationButtonClick verificationButton: UIButton)
@objc optional func commonCell(_ commonCell: CommonTableViewCell, arrowCellClick textField: UITextField)
}
@objc protocol ImageTableViewCellDelegate: NSObjectProtocol {
@objc optional func imageCell(_ imageCell: ImageTableViewCell, imageButtonClick imageButton: UIImageView)
}
@objc protocol ButtonTableViewCellDelegate: NSObjectProtocol {
@objc optional func buttonCell(_ buttonCell: ButtonTableViewCell, nextButtonClick nextButton: UIButton)
}
protocol ApplyTableViewCellDelegate: CommonTableViewCellDelegate, ImageTableViewCellDelegate, ButtonTableViewCellDelegate {
}
class ApplyTableViewCell: UITableViewCell {
var cellType: ApplyTableViewCellType?
weak var delegate: ApplyTableViewCellDelegate?
var myCellContent: Any? {
get {
guard let cellType = cellType else {
print("没有初始化cellType")
return nil
}
switch cellType {
case .common:
return textFieldText
case .image:
return images
default:
return nil
}
}
set {
guard let cellType = cellType else {
print("没有初始化cellType")
return
}
switch cellType {
case .common:
textFieldText = newValue as? String
case .image:
guard let aimages = newValue as? [UIImage?] else {
return
}
assert(images.count == aimages.count, "不相等")
for (index, image) in aimages.enumerated() {
if let image = image {
images[index] = image
}
}
default:
break
}
}
}
// textField 内部
var textFieldText: String?
var images: [UIImage?] = [UIImage]()
var mycontentViewTopConstraint: NSLayoutConstraint?
/// 最外层view
let mycontentView: UIView = {
let mycontentView = UIView()
return mycontentView
}()
override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
selectionStyle = .none
contentView.addSubview(mycontentView)
// mycontentView
({
mycontentView.translatesAutoresizingMaskIntoConstraints = false
contentView.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "H:|-25-[mycontentView]-25-|", options: NSLayoutFormatOptions.alignAllCenterY, metrics: nil, views: ["mycontentView" : mycontentView]))
let bottomConstraint = NSLayoutConstraint(item: mycontentView, attribute: NSLayoutAttribute.bottom, relatedBy: NSLayoutRelation.equal, toItem: contentView, attribute: NSLayoutAttribute.bottom, multiplier: 1.0, constant: 0.0)
let topConstraint = NSLayoutConstraint(item: mycontentView, attribute: NSLayoutAttribute.top, relatedBy: NSLayoutRelation.equal, toItem: contentView, attribute: NSLayoutAttribute.top, multiplier: 1.0, constant: 0.0)
mycontentViewTopConstraint = topConstraint
contentView.addConstraints([bottomConstraint, topConstraint])
}())
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
|
mit
|
8b5a7be970a242dd1bea1da4c8f61ae8
| 34.15 | 236 | 0.643907 | 5.723202 | false | false | false | false |
haoking/SwiftyUI
|
Sources/SwiftyTimer.swift
|
1
|
1258
|
//
// SwiftyTimer.swift
// WHCWSIFT
//
// Created by Haochen Wang on 9/24/17.
// Copyright © 2017 Haochen Wang. All rights reserved.
//
import Foundation
public extension Timer
{
@discardableResult
final class func after(_ interval: TimeInterval, _ wrapper: ClosureWrapper<Timer>) -> Timer
{
var timer: Timer!
timer = CFRunLoopTimerCreateWithHandler(kCFAllocatorDefault, CFAbsoluteTimeGetCurrent() + interval, 0, 0, 0) {_ in
if let block = wrapper.closure
{
block(timer)
}
}
return timer
}
@discardableResult
final class func every(_ interval: TimeInterval, _ wrapper: ClosureWrapper<Timer>) -> Timer
{
var timer: Timer!
timer = CFRunLoopTimerCreateWithHandler(kCFAllocatorDefault, CFAbsoluteTimeGetCurrent() + interval, interval, 0, 0) { _ in
if let block = wrapper.closure
{
block(timer)
}
}
return timer
}
final func start(runLoop: RunLoop = .current, modes: [RunLoop.Mode] = [RunLoop.Mode.default])
{
for (_, mode) in modes.enumerated().reversed()
{
runLoop.add(self, forMode: mode)
}
}
}
|
mit
|
629bd71c1058b97200be085e31b630a7
| 26.326087 | 130 | 0.584726 | 4.672862 | false | false | false | false |
i-schuetz/SwiftCharts
|
Examples/UIColor.swift
|
1
|
912
|
//
// UIColor.swift
// SwiftCharts
//
// Created by Ivan Schuetz on 17/02/2017.
// Copyright © 2017 ivanschuetz. All rights reserved.
//
import UIKit
extension UIColor {
public convenience init(hexString: String) {
let hexString = hexString.trimmingCharacters(in: CharacterSet.whitespacesAndNewlines) as String
let scanner = Scanner(string: hexString)
if (hexString.hasPrefix("#")) {
scanner.scanLocation = 1
}
var color: UInt32 = 0
scanner.scanHexInt32(&color)
let mask = 0x000000FF
let r = Int(color >> 16) & mask
let g = Int(color >> 8) & mask
let b = Int(color) & mask
let red = CGFloat(r) / 255.0
let green = CGFloat(g) / 255.0
let blue = CGFloat(b) / 255.0
self.init(red:red, green:green, blue:blue, alpha:1)
}
}
|
apache-2.0
|
f4bedb6140b4ee017c8e84a41e74b260
| 24.305556 | 103 | 0.564215 | 4.048889 | false | false | false | false |
hejunbinlan/Operations
|
Operations/Operations/GroupOperation.swift
|
1
|
4139
|
//
// GroupOperation.swift
// Operations
//
// Created by Daniel Thorpe on 18/07/2015.
// Copyright © 2015 Daniel Thorpe. All rights reserved.
//
import Foundation
/**
An `Operation` subclass which enables the grouping
of other operations. Use `GroupOperation`s to associate
related operations together, thereby creating higher
levels of abstractions.
Additionally, `GroupOperation`s are useful as a way
of creating Operations which may repeat themselves before
subsequent operations can run. For example, authentication
operations.
*/
public class GroupOperation: Operation {
private let queue = OperationQueue()
private let operations: [NSOperation]
private let finishingOperation = NSBlockOperation(block: {})
private var aggregateErrors = Array<ErrorType>()
/**
Designated initializer.
:park: operations, an array of `NSOperation`s.
*/
public init(operations ops: [NSOperation]) {
operations = ops
super.init()
queue.suspended = true
queue.delegate = self
}
public convenience init(operations: NSOperation...) {
self.init(operations: operations)
}
/**
Cancels all the groups operations.
*/
public override func cancel() {
queue.cancelAllOperations()
super.cancel()
}
public override func execute() {
for operation in operations {
queue.addOperation(operation)
}
queue.suspended = false
queue.addOperation(finishingOperation)
}
/**
Add an `NSOperation` to the group's queue.
:param: operation, an `NSOperation`
*/
public func addOperation(operation: NSOperation) {
queue.addOperation(operation)
}
public func addOperations(operations: [NSOperation]) {
queue.addOperations(operations, waitUntilFinished: false)
}
final func aggregateError(error: ErrorType) {
aggregateErrors.append(error)
}
/**
This method is called every time one of the groups child operations
finish.
Over-ride this method to enable the following sort of behavior:
## Error handling.
Typically you will want to have code like this:
if !errors.isEmpty {
if operation is MyOperation, let error = errors.first as? MyOperation.Error {
switch error {
case .AnError:
println("Handle the error case")
}
}
}
So, if the errors array is not empty, it is important to know which kind of
errors the operation may have encountered, and then implement handling of
any that are necessary.
Note that if an operation has conditions, which fail, they will be returned
as the first errors.
## Move results between operations.
Typically we use `GroupOperation` to
compose and manage multiple operations into a single unit. This might
often need to move the results of one operation into the next one. So this
can be done here.
:param: operation, an `NSOperation`
:param:, errors, an array of `ErrorType`s.
*/
public func operationDidFinish(operation: NSOperation, withErrors errors: [ErrorType]) {
// no-op, subclasses can override for their own functionality.
}
}
extension GroupOperation: OperationQueueDelegate {
public func operationQueue(queue: OperationQueue, willAddOperation operation: NSOperation) {
assert(!finishingOperation.finished && !finishingOperation.executing, "Cannot add new operations to a group after the group has completed.")
if operation !== finishingOperation {
finishingOperation.addDependency(operation)
}
}
public func operationQueue(queue: OperationQueue, operationDidFinish operation: NSOperation, withErrors errors: [ErrorType]) {
aggregateErrors.appendContentsOf(errors)
if operation === finishingOperation {
queue.suspended = true
finish(aggregateErrors)
}
else {
operationDidFinish(operation, withErrors: errors)
}
}
}
|
mit
|
af9a0861ae10227ccf13647ff785212e
| 28.140845 | 148 | 0.666989 | 5.089791 | false | false | false | false |
cyrilchandelier/TodoSwift
|
Code/TodoSwiftKit/Task.swift
|
1
|
956
|
//
// Task.swift
// TodoSwift
//
// Created by Cyril Chandelier on 01/11/15.
// Copyright © 2015 Cyril Chandelier. All rights reserved.
//
import Foundation
import CoreData
public let TaskEntityName = "Task"
public let TaskCompletedAttribute = "completed"
public let TaskCreatedAtAttribute = "createdAt"
public let TaskLabelAttribute = "label"
public class Task: NSManagedObject
{
// MARK: - Sort descriptors
public class func sortDescriptors() -> [NSSortDescriptor] {
return [
NSSortDescriptor(key: TaskCreatedAtAttribute, ascending: false)
]
}
// MARK: - Predicates
public class func activePredicate() -> NSPredicate
{
return NSPredicate(format: "%K == %@", TaskCompletedAttribute, false)
}
public class func completedPredicate() -> NSPredicate
{
return NSPredicate(format: "%K == %@", TaskCompletedAttribute, true)
}
}
|
mit
|
97ee4bf89100d5e26df293a36db49386
| 22.875 | 77 | 0.649215 | 4.462617 | false | false | false | false |
juheon0615/GhostHandongSwift
|
HandongAppSwift/MyDeliveryViewController.swift
|
3
|
9497
|
//
// MyDeliveryViewController.swift
// HandongAppSwift
//
// Created by csee on 2015. 2. 23..
// Copyright (c) 2015년 GHOST. All rights reserved.
//
import Foundation
import UIKit
class MyDeliveryViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {
@IBOutlet weak var recentTableView: UITableView!
@IBOutlet weak var favoriteTableView: UITableView!
@IBOutlet weak var clearButton: UIButton!
var selectedStore: StoreModel?
let storeList = StoreListModel.sharedInstance
var userDefaults = NSUserDefaults.standardUserDefaults()
var favoriteList = Array<StoreModel>()
var recentList = Array<StoreModel>()
var timeList = Array<String>()
override func viewDidLoad() {
StoreListDAO.beginParsing(&storeList.storeList)
// RECENT
recentTableView.registerClass(UITableViewCell.self, forCellReuseIdentifier: "rCell")
recentTableView.dataSource = self
recentTableView.delegate = self
recentTableView.rowHeight = 44
self.getRecentIDs()
self.recentTableView.reloadData()
// FAVORITE
favoriteTableView.registerClass(UITableViewCell.self, forCellReuseIdentifier: "fCell")
favoriteTableView.dataSource = self
favoriteTableView.delegate = self
favoriteTableView.rowHeight = 44
self.getFavoriteIDs()
self.favoriteTableView.reloadData()
clearButton.addTarget(self, action: "clerButtonClick:", forControlEvents: .TouchUpInside)
}
func getFavoriteIDs() {
for store in storeList.storeList {
let isFav = self.userDefaults.boolForKey(store.id)
// case for Favorite Store ALREADY Checked
if isFav == true {
self.favoriteList.append(store)
}
}
}
func getRecentIDs() {
let list = userDefaults.stringArrayForKey(Util.RecentCallKey) as! Array<String>?
if list == nil {
return
}
// init list
recentList.removeAll(keepCapacity: false)
timeList.removeAll(keepCapacity: false)
// add DATA
for row in list! {
let id = row.componentsSeparatedByString(Util.recentCallSpliter)[0]
let time = row.componentsSeparatedByString(Util.recentCallSpliter)[1]
for shop in storeList.storeList {
if shop.id == id {
recentList.append(shop)
timeList.append(time)
break
}
}
}
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if tableView == self.favoriteTableView {
return self.favoriteList.count
} else {
return self.recentList.count
}
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
if tableView == self.favoriteTableView {
var cell:UITableViewCell! = self.favoriteTableView.dequeueReusableCellWithIdentifier("fCell") as! UITableViewCell
if cell == nil {
cell = NSBundle.mainBundle().loadNibNamed("fCell", owner: self, options: nil)[0] as! UITableViewCell
}
// remove previous labels
for view in cell.subviews {
view.removeFromSuperview()
}
// make cell content
let tableWidth = tableView.frame.width
let labelWidth = (tableWidth-60)
// name Text Label
let nameLabel = UILabel(frame: CGRect(x: 5.0, y: 0.0, width: labelWidth, height: 30.0))
nameLabel.text = self.favoriteList[indexPath.row].name
nameLabel.lineBreakMode = NSLineBreakMode.ByTruncatingTail
nameLabel.textAlignment = NSTextAlignment.Left
cell.addSubview(nameLabel)
let phoneLabel = UILabel(frame: CGRect(x: 5.0, y: 30.0, width: labelWidth/2, height: 10.0))
phoneLabel.text = self.favoriteList[indexPath.row].phone
phoneLabel.lineBreakMode = NSLineBreakMode.ByCharWrapping
phoneLabel.textAlignment = NSTextAlignment.Left
phoneLabel.font = UIFont(name: phoneLabel.font.fontName, size: 11)
cell.addSubview(phoneLabel)
let rtLabel = UILabel(frame: CGRect(x: labelWidth/2, y: 30.0, width: labelWidth/2, height: 10.0))
rtLabel.text = self.favoriteList[indexPath.row].runTime
rtLabel.lineBreakMode = NSLineBreakMode.ByCharWrapping
rtLabel.textAlignment = NSTextAlignment.Right
rtLabel.font = UIFont(name: rtLabel.font.fontName, size: 11)
cell.addSubview(rtLabel)
let phoneButton = UIButton(frame: CGRect(x: labelWidth + 10, y: 5, width: 40, height: 40))
phoneButton.setImage(UIImage(named: "phone_icon.png"), forState: .Normal)
phoneButton.tag = indexPath.row
phoneButton.addTarget(self, action: "callButtonClick:", forControlEvents: .TouchUpInside)
cell.addSubview(phoneButton)
cell.separatorInset.bottom = 1.0
return cell
} else {
var cell:UITableViewCell! = self.recentTableView.dequeueReusableCellWithIdentifier("rCell") as! UITableViewCell
if cell == nil {
cell = NSBundle.mainBundle().loadNibNamed("rCell", owner: self, options: nil)[0] as! UITableViewCell
}
// remove previous labels
for view in cell.subviews {
view.removeFromSuperview()
}
// make cell content
let tableWidth = tableView.frame.width
let labelWidth = (tableWidth-60)
// name Text Label
let nameLabel = UILabel(frame: CGRect(x: 5.0, y: 0.0, width: labelWidth, height: 30.0))
nameLabel.text = self.recentList[indexPath.row].name
nameLabel.lineBreakMode = NSLineBreakMode.ByTruncatingTail
nameLabel.textAlignment = NSTextAlignment.Left
cell.addSubview(nameLabel)
let phoneLabel = UILabel(frame: CGRect(x: 5.0, y: 30.0, width: labelWidth/2, height: 10.0))
phoneLabel.text = self.recentList[indexPath.row].phone
phoneLabel.lineBreakMode = NSLineBreakMode.ByCharWrapping
phoneLabel.textAlignment = NSTextAlignment.Left
phoneLabel.font = UIFont(name: phoneLabel.font.fontName, size: 11)
cell.addSubview(phoneLabel)
let timestampLabel = UILabel(frame: CGRect(x: labelWidth/2, y: 30.0, width: labelWidth/2, height: 10.0))
timestampLabel.text = self.timeList[indexPath.row]
timestampLabel.lineBreakMode = NSLineBreakMode.ByCharWrapping
timestampLabel.textAlignment = NSTextAlignment.Right
timestampLabel.font = UIFont(name: timestampLabel.font.fontName, size: 11)
cell.addSubview(timestampLabel)
let phoneButton = UIButton(frame: CGRect(x: labelWidth + 10, y: 5, width: 40, height: 40))
phoneButton.setImage(UIImage(named: "phone_icon.png"), forState: .Normal)
phoneButton.tag = indexPath.row
phoneButton.addTarget(self, action: "callButtonClick:", forControlEvents: .TouchUpInside)
cell.addSubview(phoneButton)
cell.separatorInset.bottom = 1.0
return cell
}
}
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
if tableView == self.favoriteTableView {
self.selectedStore = self.favoriteList[indexPath.row]
} else {
self.selectedStore = self.recentList[indexPath.row]
}
self.performSegueWithIdentifier("deliveryDetailSegue", sender: self)
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if segue.identifier == "deliveryDetailSegue" {
var dstView = segue.destinationViewController as! DeliveryDetailViewController
dstView.store = self.selectedStore
}
}
// call Button event handler
func callButtonClick(sender: UIButton!) {
let selectedView = sender.superview as! UITableViewCell
var number: String
var id: String
if selectedView.reuseIdentifier == "fCell" {
number = self.favoriteList[sender.tag].phone
id = self.favoriteList[sender.tag].id
} else {
number = self.recentList[sender.tag].phone
id = self.recentList[sender.tag].id
}
Util.makePhoneCall(number, storeID: id)
self.getRecentIDs()
recentTableView.reloadData()
}
func clerButtonClick(sender: UIButton!) {
let list = userDefaults.stringArrayForKey(Util.RecentCallKey) as! Array<String>?
if list == nil {
return
}
for row in list! {
userDefaults.removeObjectForKey(Util.RecentCallKey)
}
recentList.removeAll(keepCapacity: false)
recentTableView.reloadData()
}
}
|
mit
|
746af77623afc639bcfc2eedaa6d7027
| 38.566667 | 125 | 0.609268 | 5.118598 | false | false | false | false |
bingoogolapple/SwiftNote-PartOne
|
静态单元格-Storyboard/静态单元格-Storyboard/ViewController.swift
|
1
|
1161
|
//
// ViewController.swift
// 静态单元格-Storyboard
//
// Created by bingoogol on 14/9/25.
// Copyright (c) 2014年 bingoogol. All rights reserved.
//
import UIKit
class ViewController: UITableViewController {
@IBOutlet weak var title1: UILabel!
@IBOutlet weak var detail1: UILabel!
@IBOutlet weak var title2: UILabel!
@IBOutlet weak var title3: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
self.title1.text = "蓝牙"
self.title2.text = "通用"
self.title3.text = "隐私"
self.detail1.text = "关于"
}
override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
if indexPath.section == 0 && indexPath.row == 0 {
// 1.取出用户点击的表格行
var cell = tableView.cellForRowAtIndexPath(indexPath)
// 2.利用表格行的tag表示打开和关闭状态
cell?.tag = cell?.tag == 0 ? 1 : 0
var str = cell?.tag == 1 ? "打开" : "关闭"
// 3.根据状态设置单元格的内容
self.detail1.text = str
}
}
}
|
apache-2.0
|
07bd8e372aa721c8492bb019967612e2
| 25.974359 | 101 | 0.595623 | 3.807971 | false | false | false | false |
ontouchstart/swift3-playground
|
Learn to Code 2.playgroundbook/Contents/Sources/WorldActionComponent.swift
|
2
|
5504
|
//
// WorldActionComponent.swift
//
// Copyright (c) 2016 Apple Inc. All Rights Reserved.
//
import SceneKit
class WorldActionComponent: ActorComponent {
// MARK: Properties
unowned let actor: Actor
weak var world: GridWorld?
private var animationDuration: TimeInterval {
let animationComponent = actor.componentForType(AnimationComponent.self)
return animationComponent?.currentAnimationDuration ?? 1.0
}
// MARK: Initializers
required init(actor: Actor) {
self.actor = actor
}
// MARK: Performer
func applyStateChange(for action: Action) {
guard let world = world else { return }
switch action {
case let .move(start, end):
moveItemsBetween(start: start, end: end, animated: false)
case let .jump(start, end):
moveItemsBetween(start: start, end: end, animated: false)
case .place(_), .remove(_):
world.applyStateChange(for: action)
case let .toggle(id, on):
guard let switchItem = world.item(forID: id) as? Switch else { break }
switchItem.setActive(on, animated: false)
case let .control(lock, isMovingUp):
isMovingUp ? lock.raisePlatforms() : lock.lowerPlatforms()
default:
break
}
}
func perform(_ action: Action) {
// Unpack action.
switch action {
case let .move(start, end):
moveItemsBetween(start: start, end: end, animated: true)
case let .jump(start, end):
moveItemsBetween(start: start, end: end, animated: true)
case let .teleport(from: start, end):
teleportActorFrom(start, to: end)
case let .toggle(id, on):
guard let switchItem = world?.item(forID: id) as? Switch, switchItem.isInWorld else {
fatalError("Instructed to `toogleSwitch`, but no switch was found for id: \(id).")
}
#if DEBUG
assert(switchItem.coordinate == actor.coordinate, "The actor can only toggle switches it's currently on.")
#endif
switchItem.setActive(on, animated: true)
case let .remove(indices):
guard let index = indices.first else { fatalError("Attempting to remove, but no indices were found") }
guard let gem = world?.item(forID: index) as? Gem else {
fatalError("Actor cannot remove nodes other than gems. <\(index)> \(world?.item(forID: index))")
}
gem.collect(withDuration: animationDuration)
case let .control(lock, isMovingUp):
let movementDuration = animationDuration / 2
let wait = SCNAction.wait(forDuration: animationDuration / 2)
let movePlatforms = SCNAction.run { _ in
SCNTransaction.begin()
SCNTransaction.animationDuration = movementDuration
SCNTransaction.animationTimingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseInEaseOut)
isMovingUp ? lock.raisePlatforms() : lock.lowerPlatforms()
SCNTransaction.commit()
}
lock.scnNode.run(.sequence([wait, movePlatforms]))
default:
break
}
// Mark the action as complete.
actor.performerFinished(self)
}
func cancel(_ action: Action) {
switch action {
case let .remove(indices):
for index in indices {
let item = world?.item(forID: index)
item?.scnNode.removeAllActions()
}
default:
node.removeAction(forKey: action.key.rawValue)
}
}
// MARK: Convenience
func moveItemsBetween(start: SCNVector3, end destination: SCNVector3, animated: Bool) {
guard let world = world else { return }
func moveGems(at coordinate: Coordinate, up: Bool) {
let items = world.existingNodes(ofType: Gem.self, at: [coordinate])
let duration = animated ? animationDuration : 0.0
for item in items {
item.move(up: up, withDuration: duration)
}
}
// Raise upcoming gems.
let incomingCoordinate = Coordinate(destination)
moveGems(at: incomingCoordinate, up: true)
// Lower passed gems.
let leavingCoordinate = Coordinate(start)
moveGems(at: leavingCoordinate, up: false)
}
// MARK: Teleportation
func teleportActorFrom(_ position: SCNVector3, to newPosition: SCNVector3) {
guard let world = world,
let startingPortal = world.existingNode(ofType: Portal.self, at: Coordinate(position)),
let endingPortal = world.existingNode(ofType: Portal.self, at: Coordinate(newPosition)) else { return }
startingPortal.enter(atSpeed: Actor.commandSpeed)
endingPortal.exit(atSpeed: Actor.commandSpeed)
let halfWait = SCNAction.wait(forDuration: animationDuration / 2.0)
let moveActor = SCNAction.move(to: newPosition, duration: 0.0)
node.run(.sequence([halfWait, moveActor]), forKey: CommandKey.teleport.rawValue)
}
}
|
mit
|
96758cfed89bc2042b92637b4c02669f
| 34.057325 | 121 | 0.576853 | 4.9319 | false | false | false | false |
Cin316/X-Schedule
|
X Schedule Watch Extension/ComplicationController.swift
|
1
|
8412
|
//
// ComplicationController.swift
// X Schedule Watch Extension
//
// Created by Nicholas Reichert on 4/19/16.
// Copyright © 2016 Nicholas Reichert.
//
import ClockKit
import XScheduleKitWatch
class ComplicationController: NSObject, CLKComplicationDataSource {
// TODO Stop using deprecated methods here.
var schedule: Schedule!
var scheduleTimes: [(blockName: String, time: Date)] = []
override init() {
super.init()
XScheduleManager.getScheduleForToday( { (schedule: Schedule) in
self.schedule = schedule
self.scheduleTimes = self.scheduleToArray(schedule)
})
}
private func scheduleToArray(_ schedule: Schedule) -> [(blockName: String, time: Date)] {
var array: [(blockName: String, time: Date)] = []
for item in schedule.items {
if let spanItem = item as? TimeSpanScheduleItem {
if let time = spanItem.startTime {
array.append((blockName: spanItem.blockName, time: time))
}
if let time = spanItem.endTime {
array.append((blockName: spanItem.blockName, time: time))
}
} else if let pointItem = item as? TimePointScheduleItem {
if let time = pointItem.time {
array.append((blockName: pointItem.blockName, time: time))
}
}
}
array.sort {
$0.time < $1.time
}
return array
}
// MARK: - Timeline Configuration
func getSupportedTimeTravelDirections(for complication: CLKComplication, withHandler handler: @escaping (CLKComplicationTimeTravelDirections) -> Void) {
handler([.forward, .backward])
}
func getTimelineStartDate(for complication: CLKComplication, withHandler handler: @escaping (Date?) -> Void) {
if (scheduleTimes.count > 0) {
handler(scheduleTimes.first?.time)
} else {
handler(nil)
}
}
func getTimelineEndDate(for complication: CLKComplication, withHandler handler: @escaping (Date?) -> Void) {
if (scheduleTimes.count > 0) {
handler(scheduleTimes.last?.time)
} else {
handler(nil)
}
}
func getPrivacyBehavior(for complication: CLKComplication, withHandler handler: @escaping (CLKComplicationPrivacyBehavior) -> Void) {
handler(.showOnLockScreen)
}
// MARK: - Timeline Population
// TODO Support ALL the edge cases.
func getCurrentTimelineEntry(for complication: CLKComplication, withHandler handler: @escaping (CLKComplicationTimelineEntry?) -> Void) {
// Call the handler with the current timeline entry
handler(getTimelineEntryForDate(complication, date: Date()))
}
func getTimelineEntries(for complication: CLKComplication, before date: Date, limit: Int, withHandler handler: @escaping ([CLKComplicationTimelineEntry]?) -> Void) {
// Call the handler with the timeline entries prior to the given date
var templates: [CLKComplicationTimelineEntry] = []
let array = scheduleToArray(schedule)
var index: Int = 0;
while templates.count <= limit && date <= array[index].time && index < array.count { // `date <= array[index].time` may be causing incorrect behavior.
templates.append(getTimelineEntryForDate(complication, date: array[index].time)!)
index += 1
}
handler(templates)
}
func getTimelineEntries(for complication: CLKComplication, after date: Date, limit: Int, withHandler handler: @escaping ([CLKComplicationTimelineEntry]?) -> Void) {
// Call the handler with the timeline entries after to the given date
var templates: [CLKComplicationTimelineEntry] = []
let array = scheduleToArray(schedule)
var index: Int = 0;
//Find first item.
for item in array {
if (item.time < date) {
break;
}
index += 1
}
while templates.count <= limit && index < array.count {
templates.append(getTimelineEntryForDate(complication, date: array[index].time)!)
index += 1
}
handler(templates)
}
private func getTimelineEntryForDate(_ complication: CLKComplication, date: Date) -> CLKComplicationTimelineEntry? {
let template = getComplicationTemplateForDate(complication, date: date)
let startTime = getStartTimeForTime(date)
if template != nil && startTime != nil {
return CLKComplicationTimelineEntry(date: startTime!, complicationTemplate: template!)
} else {
return nil
}
}
private func getStartTimeForTime(_ date: Date) -> Date? {
if scheduleTimes.count > 0 {
if date < scheduleTimes.first!.time {
return date
}
for i in 1..<scheduleTimes.count {
let precedingItem = scheduleTimes[i-1]
let nextItem = scheduleTimes[i]
if (precedingItem.time <= date && date < nextItem.time) { // If date is between two times...
return precedingItem.time
}
}
}
//If the date is after the schedule ends...
// Return nil if the time is after the schedule is finished.
return nil
}
private func getComplicationTemplateForDate(_ complication: CLKComplication, date: Date) -> CLKComplicationTemplate? {
var bell: String
var time: Date
let timeAndBell = getTimeAndBellForDate(date)
if timeAndBell != nil {
if (complication.family == .modularSmall) {
(bell, time) = timeAndBell!
let template = CLKComplicationTemplateModularSmallStackText()
let bellProvider = CLKSimpleTextProvider(text: bell)
let timeProvider = CLKTimeTextProvider(date: time)
template.line1TextProvider = bellProvider
template.highlightLine2 = false //Highlight line 1.
template.line2TextProvider = timeProvider
return template
} else {
return nil
}
} else {
return nil
}
}
private func getTimeAndBellForDate(_ date: Date) -> (bell: String, time: Date)? {
if scheduleTimes.count > 0 {
if date < scheduleTimes.first!.time {
return (scheduleTimes.first!.blockName, scheduleTimes.first!.time)
}
for i in 1..<scheduleTimes.count {
let precedingItem = scheduleTimes[i-1]
let nextItem = scheduleTimes[i]
if (precedingItem.time <= date && date < nextItem.time) { // If date is between two times...
return (nextItem.blockName, nextItem.time)
}
}
}
// Return nil if the time is after the schedule is finished.
return nil
}
// MARK: - Update Scheduling
func requestedUpdateDidBegin() {
XScheduleManager.getScheduleForToday( { (schedule: Schedule) in
if (schedule.date != self.schedule.date) {
self.schedule = schedule
if let complications = CLKComplicationServer.sharedInstance().activeComplications {
for complication in complications {
CLKComplicationServer.sharedInstance().reloadTimeline(for: complication)
}
}
}
})
}
func getNextRequestedUpdateDate(handler: @escaping (Date?) -> Void) {
// Call the handler with the date when you would next like to be given the opportunity to update your complication content
// Update content every 8 hours.
handler(Date().addingTimeInterval(8*60*60))
}
// MARK: - Placeholder Templates
func getPlaceholderTemplate(for complication: CLKComplication, withHandler handler: @escaping (CLKComplicationTemplate?) -> Void) {
// This method will be called once per supported complication, and the results will be cached
handler(nil)
}
}
|
mit
|
677a68b04b92f5dab8a3e6772748f40c
| 37.760369 | 169 | 0.592438 | 5.237235 | false | false | false | false |
tus/TUSKit
|
Tests/TUSKitTests/TUSAPITests.swift
|
1
|
8545
|
//
// TUSAPITests.swift
//
//
// Created by Tjeerd in ‘t Veen on 16/09/2021.
//
import Foundation
import XCTest
@testable import TUSKit
final class TUSAPITests: XCTestCase {
var api: TUSAPI!
var uploadURL: URL!
override func setUp() {
super.setUp()
let configuration = URLSessionConfiguration.default
configuration.protocolClasses = [MockURLProtocol.self]
let session = URLSession.init(configuration: configuration)
uploadURL = URL(string: "www.tus.io")!
api = TUSAPI(session: session)
}
override func tearDown() {
super.tearDown()
MockURLProtocol.receivedRequests = []
}
func testStatus() throws {
let length = 3000
let offset = 20
MockURLProtocol.prepareResponse(for: "HEAD") { _ in
MockURLProtocol.Response(status: 200, headers: ["Upload-Length": String(length), "Upload-Offset": String(offset)], data: nil)
}
let statusExpectation = expectation(description: "Call api.status()")
let remoteFileURL = URL(string: "https://tus.io/myfile")!
let metaData = UploadMetadata(id: UUID(),
filePath: URL(string: "file://whatever/abc")!,
uploadURL: URL(string: "io.tus")!,
size: length)
api.status(remoteDestination: remoteFileURL, headers: metaData.customHeaders, completion: { result in
do {
let values = try result.get()
XCTAssertEqual(length, values.length)
XCTAssertEqual(offset, values.offset)
statusExpectation.fulfill()
} catch {
XCTFail("Expected this call to succeed")
}
})
waitForExpectations(timeout: 3, handler: nil)
}
func testCreationWithAbsolutePath() throws {
let remoteFileURL = URL(string: "https://tus.io/myfile")!
MockURLProtocol.prepareResponse(for: "POST") { _ in
MockURLProtocol.Response(status: 200, headers: ["Location": remoteFileURL.absoluteString], data: nil)
}
let size = 300
let creationExpectation = expectation(description: "Call api.create()")
let metaData = UploadMetadata(id: UUID(),
filePath: URL(string: "file://whatever/abc")!,
uploadURL: URL(string: "https://io.tus")!,
size: size)
api.create(metaData: metaData) { result in
do {
let url = try result.get()
XCTAssertEqual(url, remoteFileURL)
creationExpectation.fulfill()
} catch {
XCTFail("Expected to retrieve a URL for this test")
}
}
waitForExpectations(timeout: 3, handler: nil)
let headerFields = try XCTUnwrap(MockURLProtocol.receivedRequests.first?.allHTTPHeaderFields)
let expectedFileName = metaData.filePath.lastPathComponent.toBase64()
let expectedHeaders: [String: String] =
[
"TUS-Resumable": "1.0.0",
"Upload-Extension": "creation",
"Upload-Length": String(size),
"Upload-Metadata": "filename \(expectedFileName)"
]
XCTAssertEqual(expectedHeaders, headerFields)
}
func testCreationWithRelativePath() throws {
let uploadURL = URL(string: "https://tus.example.org/files")!
let relativePath = "files/24e533e02ec3bc40c387f1a0e460e216"
let expectedURL = URL(string: "https://tus.example.org/files/24e533e02ec3bc40c387f1a0e460e216")!
MockURLProtocol.prepareResponse(for: "POST") { _ in
MockURLProtocol.Response(status: 200, headers: ["Location": relativePath], data: nil)
}
let size = 300
let creationExpectation = expectation(description: "Call api.create()")
let metaData = UploadMetadata(id: UUID(),
filePath: URL(string: "file://whatever/abc")!,
uploadURL: uploadURL,
size: size)
api.create(metaData: metaData) { result in
do {
let url = try result.get()
XCTAssertEqual(url.absoluteURL, expectedURL)
creationExpectation.fulfill()
} catch {
XCTFail("Expected to retrieve a URL for this test")
}
}
waitForExpectations(timeout: 3, handler: nil)
let headerFields = try XCTUnwrap(MockURLProtocol.receivedRequests.first?.allHTTPHeaderFields)
let expectedFileName = metaData.filePath.lastPathComponent.toBase64()
let expectedHeaders: [String: String] =
[
"TUS-Resumable": "1.0.0",
"Upload-Extension": "creation",
"Upload-Length": String(size),
"Upload-Metadata": "filename \(expectedFileName)"
]
XCTAssertEqual(expectedHeaders, headerFields)
}
func testUpload() throws {
let data = Data("Hello how are you".utf8)
MockURLProtocol.prepareResponse(for: "PATCH") { _ in
MockURLProtocol.Response(status: 200, headers: ["Upload-Offset": String(data.count)], data: nil)
}
let offset = 2
let length = data.count
let range = offset..<data.count
let uploadExpectation = expectation(description: "Call api.upload()")
let metaData = UploadMetadata(id: UUID(),
filePath: URL(string: "file://whatever/abc")!,
uploadURL: URL(string: "io.tus")!,
size: length)
let task = api.upload(data: Data(), range: range, location: uploadURL, metaData: metaData) { _ in
uploadExpectation.fulfill()
}
XCTAssertEqual(task.originalRequest?.url, uploadURL)
waitForExpectations(timeout: 3, handler: nil)
let headerFields = try XCTUnwrap(MockURLProtocol.receivedRequests.first?.allHTTPHeaderFields)
let expectedHeaders: [String: String] =
[
"TUS-Resumable": "1.0.0",
"Content-Type": "application/offset+octet-stream",
"Upload-Offset": String(offset),
"Content-Length": String(length)
]
XCTAssertEqual(headerFields, expectedHeaders)
}
func testUploadWithRelativePath() throws {
let data = Data("Hello how are you".utf8)
let baseURL = URL(string: "https://tus.example.org/files")!
let relativePath = "files/24e533e02ec3bc40c387f1a0e460e216"
let uploadURL = URL(string: relativePath, relativeTo: baseURL)!
let expectedURL = URL(string: "https://tus.example.org/files/24e533e02ec3bc40c387f1a0e460e216")!
MockURLProtocol.prepareResponse(for: "PATCH") { _ in
MockURLProtocol.Response(status: 200, headers: ["Upload-Offset": String(data.count)], data: nil)
}
let offset = 2
let length = data.count
let range = offset..<data.count
let uploadExpectation = expectation(description: "Call api.upload()")
let metaData = UploadMetadata(id: UUID(),
filePath: URL(string: "file://whatever/abc")!,
uploadURL: URL(string: "io.tus")!,
size: length)
let task = api.upload(data: Data(), range: range, location: uploadURL, metaData: metaData) { _ in
uploadExpectation.fulfill()
}
XCTAssertEqual(task.originalRequest?.url, expectedURL)
waitForExpectations(timeout: 3, handler: nil)
let headerFields = try XCTUnwrap(MockURLProtocol.receivedRequests.first?.allHTTPHeaderFields)
let expectedHeaders: [String: String] =
[
"TUS-Resumable": "1.0.0",
"Content-Type": "application/offset+octet-stream",
"Upload-Offset": String(offset),
"Content-Length": String(length)
]
XCTAssertEqual(headerFields, expectedHeaders)
}
}
|
mit
|
74a5835a885bba0f336dad8d61acd439
| 39.680952 | 137 | 0.55683 | 4.876142 | false | true | false | false |
notbenoit/SCCollectionViewController
|
Source/SCNavigationBar.swift
|
1
|
2464
|
// Copyright (c) 2015 Benoit Layer
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import UIKit
/**
* I did not override drawRect: to draw the background with a custom alpha, because
* the rect passed as a paramterer to drawRect: does not
* cover the status bar space
*
* Use this navigation bar as a standard navigation bar. The only thing
* is that setting its alpha will only set the alpha of the bar background.
* It takes the current barTintColor and creates a background with
* corresponding alpha.
**/
class SCNavigationBar: UINavigationBar {
// Setting the alpha of the status bar only changes the background.
override var alpha: CGFloat {
get {
return 1.0
}
set {
self.setBackgroundImage(createImageBackgroundWithAlpha(newValue), forBarMetrics: UIBarMetrics.Default)
self.shadowImage = UIImage()
}
}
private func createImageBackgroundWithAlpha(alpha: CGFloat) -> UIImage {
let rect = CGRectMake(0, 0, 1, 1);
UIGraphicsBeginImageContext(rect.size);
let context = UIGraphicsGetCurrentContext();
let color = CGColorCreateCopyWithAlpha(self.barTintColor?.CGColor, alpha)
CGContextSetFillColorWithColor(context, color)
CGContextFillRect(context, rect);
let img = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext()
return img
}
}
|
mit
|
71ea0243d2ae90b419cfd057db8c3231
| 41.482759 | 114 | 0.72362 | 4.977778 | false | false | false | false |
Wolkabout/WolkSense-Hexiwear-
|
iOS/Hexiwear/Util.swift
|
1
|
4932
|
//
// Hexiwear application is used to pair with Hexiwear BLE devices
// and send sensor readings to WolkSense sensor data cloud
//
// Copyright (C) 2016 WolkAbout Technology s.r.o.
//
// Hexiwear is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Hexiwear is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
//
//
// Util.swift
//
import UIKit
import MapKit
// HEXIWEAR CONSTANTS
let signUpURL = "https://wolksense.com"
let privacyPolicyURL = "https://wolksense.com/documents/privacypolicy.html"
let termsAndConditionsURL = "https://wolksense.com/documents/termsofservice.html"
let BAD_REQUEST = 400
let NOT_AUTHORIZED = 401
let FORBIDDEN = 403
let NOT_FOUND = 404
let CONFLICT = 409
let applicationTitle = "Hexiwear"
let demoAccount = "demo"
let wolkaboutBlueColor = UIColor(red: 0.0, green: 128.0/255.0, blue: 1.0, alpha: 1.0)
// NOTIFICATIONS
let HexiwearDidSignOut = "HexiwearDidSignOut"
// TopMostViewController extensions
extension UIViewController {
func topMostViewController() -> UIViewController {
// Handling Modal views
if let presentedViewController = self.presentedViewController {
return presentedViewController.topMostViewController()
}
// Handling UIViewController's added as subviews to some other views.
for view in self.view.subviews
{
// Key property which most of us are unaware of / rarely use.
if let subViewController = view.next {
if subViewController is UIViewController {
let viewController = subViewController as! UIViewController
return viewController.topMostViewController()
}
}
}
return self
}
}
extension UITabBarController {
override func topMostViewController() -> UIViewController {
return self.selectedViewController!.topMostViewController()
}
}
extension UINavigationController {
override func topMostViewController() -> UIViewController {
return self.visibleViewController!.topMostViewController()
}
}
// Global misc functions
func isValidEmailAddress(_ email: String) -> Bool {
let regExPattern = "[A-Z0-9a-z\\._%+-]+@([A-Za-z0-9-]+\\.)+[A-Za-z]{2,4}"
do {
let regEx = try NSRegularExpression(pattern: regExPattern, options: .caseInsensitive)
let regExMatches = regEx.numberOfMatches(in: email, options: [], range: NSMakeRange(0, email.characters.count))
return regExMatches == 0 ? false : true
}
catch {
return false
}
}
func getPrivateDocumentsDirectory() -> String? {
let paths = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)
if paths.count == 0 { print("No private directory"); return nil }
var documentsDirectory = paths[0]
documentsDirectory = (documentsDirectory as NSString).appendingPathComponent("Private Documents")
if let _ = try? FileManager.default.createDirectory(atPath: documentsDirectory, withIntermediateDirectories: true, attributes: nil) {
return documentsDirectory
}
return nil
}
func delay(_ delay:Double, closure:@escaping ()->()) {
DispatchQueue.main.asyncAfter(
deadline: DispatchTime.now() + Double(Int64(delay * Double(NSEC_PER_SEC))) / Double(NSEC_PER_SEC), execute: closure)
}
func showSimpleAlertWithTitle(_ title: String!, message: String, viewController: UIViewController, OKhandler: ((UIAlertAction?) -> Void)? = nil) {
DispatchQueue.main.async {
let alert = UIAlertController(title: title, message: message, preferredStyle: .alert)
let action = UIAlertAction(title: "OK", style: .cancel, handler: OKhandler)
alert.addAction(action)
viewController.present(alert, animated: true, completion: nil)
}
}
func showOKAndCancelAlertWithTitle(_ title: String!, message: String, viewController: UIViewController, OKhandler: ((UIAlertAction?) -> Void)? = nil) {
DispatchQueue.main.async {
let alert = UIAlertController(title: title, message: message, preferredStyle: .alert)
let OKaction = UIAlertAction(title: "OK", style: .default, handler: OKhandler)
alert.addAction(OKaction)
let CancelAction = UIAlertAction(title: "Cancel", style: .cancel, handler: nil)
alert.addAction(CancelAction)
viewController.present(alert, animated: true, completion: nil)
}
}
|
gpl-3.0
|
a6b206e2d2f60ff7b219b4d5f4de0a3f
| 36.648855 | 151 | 0.697689 | 4.455285 | false | false | false | false |
motylevm/skstylekit
|
Sources/SKStyleUIView.swift
|
1
|
3712
|
//
// Copyright (c) 2016 Mikhail Motylev https://twitter.com/mikhail_motylev
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of
// this software and associated documentation files (the "Software"), to deal in
// the Software without restriction, including without limitation the rights to
// use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
// the Software, and to permit persons to whom the Software is furnished to do so,
// subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
// FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
// COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
// IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
// CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
import UIKit
public extension SKStyle {
// MARK: - UIView -
/**
Applies style to a view
- parameter view: View to apply style to
*/
func apply(view: UIView?) {
if !checkFlag(flagViewWasSet) {
setViewFlags()
}
guard checkFlag(flagViewAny) else { return }
// Common
if checkFlag(flagViewCommon) {
if let alpha = alpha {
view?.alpha = alpha
}
if let cornerRadius = cornerRadius {
view?.layer.cornerRadius = cornerRadius
}
}
// Border
if checkFlag(flagViewBorder) {
if let borderWidth = borderWidth {
view?.layer.borderWidth = borderWidth
}
if let borderColor = borderColor {
view?.layer.borderColor = borderColor.cgColor
}
}
// Colors
if checkFlag(flagViewColor) {
if let backgroundColor = backgroundColor {
view?.backgroundColor = backgroundColor
}
if let tintColor = tintColor {
view?.tintColor = tintColor
}
}
// Shadow
if checkFlag(flagViewShadow) {
if let shadowRadius = shadowRadius {
view?.layer.shadowRadius = shadowRadius
}
if let shadowOffset = shadowOffset {
view?.layer.shadowOffset = shadowOffset
}
if let shadowColor = shadowColor {
view?.layer.shadowColor = shadowColor.cgColor
}
if let shadowOpacity = shadowOpacity {
view?.layer.shadowOpacity = Float(shadowOpacity)
}
}
}
// MARK: - Set flags -
func setViewFlags() {
if alpha != nil || cornerRadius != nil {
setFlag(flagViewCommon)
}
if borderWidth != nil || borderColor != nil {
setFlag(flagViewBorder)
}
if backgroundColor != nil || tintColor != nil {
setFlag(flagViewColor)
}
if shadowRadius != nil || shadowOffset != nil || shadowColor != nil || shadowOpacity != nil {
setFlag(flagViewShadow)
}
setFlag(flagViewWasSet)
}
}
|
mit
|
8caf100936e9634048a8d248b5404e46
| 30.726496 | 101 | 0.554688 | 5.387518 | false | false | false | false |
avito-tech/Paparazzo
|
Paparazzo/Core/VIPER/NewCamera/View/NewCameraView.swift
|
1
|
18532
|
import AVFoundation
import ImageSource
import UIKit
enum SelectedPhotosBarState {
case hidden
case placeholder
case visible(SelectedPhotosBarData)
}
struct SelectedPhotosBarData { // TODO: make final class
let lastPhoto: ImageSource?
let penultimatePhoto: ImageSource?
let countString: String
}
final class NewCameraView: UIView {
// MARK: - Subviews
var cameraOutputLayer: AVCaptureVideoPreviewLayer?
private let closeButton = UIButton()
private let photoLibraryButton = UIButton()
private let captureButton = UIButton()
private let flashButton = UIButton()
private let toggleCameraButton = UIButton()
private let hintLabel = UILabel()
private let selectedPhotosBarView = SelectedPhotosBarView()
private let flashView = UIView()
private let snapshotView = UIImageView()
private let photoView = UIImageView()
private let accessDeniedView = AccessDeniedView()
// TODO: extract to separate view
private let previewView = UIView()
private let viewfinderBorderView = CameraViewfinderBorderView()
// MARK: - Specs
private let navigationBarHeight = CGFloat(52)
private let captureButtonSize = CGFloat(64)
private var captureButtonBorderColorEnabled = UIColor(red: 0, green: 0.67, blue: 1, alpha: 1)
private var captureButtonBackgroundColorEnabled = UIColor.white
private var captureButtonBorderColorDisabled = UIColor(red: 0.85, green: 0.85, blue: 0.85, alpha: 1)
private var captureButtonBackgroundColorDisabled = UIColor(red: 0.97, green: 0.97, blue: 0.97, alpha: 1)
// MARK: - Init
init() {
super.init(frame: .zero)
backgroundColor = .white
addSubview(previewView)
addSubview(closeButton)
addSubview(photoLibraryButton)
addSubview(captureButton)
addSubview(photoView)
addSubview(flashButton)
addSubview(toggleCameraButton)
addSubview(hintLabel)
addSubview(selectedPhotosBarView)
addSubview(snapshotView)
addSubview(flashView)
addSubview(accessDeniedView)
accessDeniedView.isHidden = true
photoView.backgroundColor = .lightGray
photoView.contentMode = .scaleAspectFill
photoView.layer.cornerRadius = 18.5
photoView.clipsToBounds = true
photoView.isUserInteractionEnabled = true
photoView.addGestureRecognizer(UITapGestureRecognizer(
target: self,
action: #selector(onPhotoViewTap(_:))
))
snapshotView.contentMode = .scaleAspectFill
snapshotView.layer.cornerRadius = 10
snapshotView.layer.masksToBounds = true
snapshotView.isHidden = true
flashView.backgroundColor = .white
flashView.alpha = 0
closeButton.addTarget(self, action: #selector(handleCloseButtonTap), for: .touchUpInside)
captureButton.layer.cornerRadius = captureButtonSize / 2
captureButton.layer.borderWidth = 6
captureButton.addTarget(self, action: #selector(handleCaptureButtonTap), for: .touchUpInside)
setCaptureButtonState(.enabled)
previewView.layer.masksToBounds = true
flashButton.addTarget(self, action: #selector(handleFlashButtonTap), for: .touchUpInside)
toggleCameraButton.setImage(
UIImage(named: "back_front_new", in: Resources.bundle, compatibleWith: nil),
for: .normal
)
toggleCameraButton.addTarget(self, action: #selector(handleToggleCameraButtonTap), for: .touchUpInside)
toggleCameraButton.sizeToFit()
hintLabel.textColor = .gray
hintLabel.textAlignment = .center
hintLabel.numberOfLines = 0
selectedPhotosBarView.isHidden = true
previewView.addSubview(viewfinderBorderView)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
// MARK: - NewCameraView
var onCaptureButtonTap: (() -> ())?
var onCloseButtonTap: (() -> ())?
var onToggleCameraButtonTap: (() -> ())?
var onFlashToggle: ((Bool) -> ())?
var onDoneButtonTap: (() -> ())? {
get { return selectedPhotosBarView.onButtonTap }
set { selectedPhotosBarView.onButtonTap = newValue }
}
var onLastPhotoThumbnailTap: (() -> ())? {
get { return selectedPhotosBarView.onLastPhotoThumbnailTap }
set { selectedPhotosBarView.onLastPhotoThumbnailTap = newValue }
}
var onAccessDeniedButtonTap: (() -> ())? {
get { return accessDeniedView.onButtonTap }
set { accessDeniedView.onButtonTap = newValue }
}
func setTheme(_ theme: NewCameraUITheme) {
backgroundColor = theme.newCameraViewBackgroundColor
flashView.backgroundColor = theme.newCameraFlashBackgroundColor
captureButtonBorderColorEnabled = theme.newCameraCaptureButtonBorderColorEnabled
captureButtonBorderColorDisabled = theme.newCameraCaptureButtonBorderColorDisabled
captureButtonBackgroundColorEnabled = theme.newCameraCaptureButtonBackgroundColorEnabled
captureButtonBackgroundColorDisabled = theme.newCameraCaptureButtonBackgroundColorDisabled
closeButton.setImage(theme.newCameraCloseIcon, for: .normal)
flashButton.setImage(theme.newCameraFlashOffIcon, for: .normal)
flashButton.setImage(theme.newCameraFlashOnIcon, for: .selected)
hintLabel.font = theme.newCameraHintFont
hintLabel.textColor = theme.newCameraHintTextColor
selectedPhotosBarView.setTheme(theme)
accessDeniedView.setTheme(theme)
}
func setSelectedPhotosBarState(_ state: SelectedPhotosBarState, completion: @escaping () -> ()) {
switch state {
case .hidden:
selectedPhotosBarView.isHidden = true
completion()
case .placeholder:
selectedPhotosBarView.isHidden = false
selectedPhotosBarView.setPlaceholderHidden(false)
case .visible(let data):
selectedPhotosBarView.isHidden = false
selectedPhotosBarView.setPlaceholderHidden(true)
selectedPhotosBarView.label.text = data.countString
let dispatchGroup = DispatchGroup()
if let lastPhoto = data.lastPhoto {
var didLeaveGroup = false
dispatchGroup.enter()
selectedPhotosBarView.setLastImage(lastPhoto) { result in
if !result.degraded && !didLeaveGroup {
dispatchGroup.leave()
didLeaveGroup = true // prevent leaving dispatch group more times than entering
}
}
}
if let penultimatePhoto = data.penultimatePhoto {
var didLeaveGroup = false
dispatchGroup.enter()
selectedPhotosBarView.setPenultimateImage(penultimatePhoto) { result in
if !result.degraded && !didLeaveGroup {
dispatchGroup.leave()
didLeaveGroup = true // prevent leaving dispatch group more times than entering
}
}
}
dispatchGroup.notify(queue: .main, execute: completion)
}
}
func setHintText(_ hintText: String) {
hintLabel.text = hintText
}
func setDoneButtonTitle(_ title: String) {
selectedPhotosBarView.setDoneButtonTitle(title)
}
func setPlaceholderText(_ text: String) {
selectedPhotosBarView.setPlaceholderText(text)
}
func setLatestPhotoLibraryItemImage(_ imageSource: ImageSource?) {
photoView.setImage(
fromSource: imageSource,
size: CGSize(width: 32, height: 32),
placeholder: nil,
placeholderDeferred: false
)
}
func animateFlash() {
UIView.animate(
withDuration: 0.1,
animations: {
self.flashView.alpha = 1
},
completion: { _ in
UIView.animate(
withDuration: 0.3,
delay: 0.1,
options: [.curveEaseOut],
animations: {
self.flashView.alpha = 0
},
completion: nil
)
}
)
}
func animateCapturedPhoto(
_ image: ImageSource,
completion: @escaping (_ finalizeAnimation: @escaping () -> ()) -> ())
{
let sideInsets = CGFloat(18)
let snapshotWidthToHeightRatio = CGFloat(4) / 3
let snapshotInitialWidth = previewView.width - 2 * sideInsets
let snapshotInitialHeight = snapshotInitialWidth / snapshotWidthToHeightRatio
let snapshotFinalFrame = convert(
selectedPhotosBarView.lastPhotoThumbnailView.frame,
from: selectedPhotosBarView.lastPhotoThumbnailView.superview
)
snapshotView.frame = CGRect(
x: previewView.left + sideInsets,
y: previewView.top + (previewView.height - snapshotInitialHeight) / 2,
width: snapshotInitialWidth,
height: snapshotInitialHeight
)
snapshotView.layer.cornerRadius = 10
snapshotView.isHidden = false
snapshotView.setImage(
fromSource: image,
resultHandler: { result in
guard !result.degraded else { return }
UIView.animate(
withDuration: 0.3,
delay: 0.5,
options: [],
animations: {
self.snapshotView.frame = snapshotFinalFrame
self.layer.cornerRadius = self.selectedPhotosBarView.lastPhotoThumbnailView.layer.cornerRadius
},
completion: { _ in
completion {
self.snapshotView.isHidden = true
}
}
)
}
)
}
func setFlashButtonVisible(_ visible: Bool) {
flashButton.isHidden = !visible
}
func setFlashButtonOn(_ isOn: Bool) {
flashButton.isSelected = isOn
layOutFlashButton()
}
func setCaptureButtonState(_ state: CaptureButtonState) {
captureButton.isEnabled = (state == .enabled)
switch state {
case .enabled, .nonInteractive:
captureButton.layer.borderColor = captureButtonBorderColorEnabled.cgColor
captureButton.layer.backgroundColor = captureButtonBackgroundColorEnabled.cgColor
case .disabled:
captureButton.layer.borderColor = captureButtonBorderColorDisabled.cgColor
captureButton.layer.backgroundColor = captureButtonBackgroundColorDisabled.cgColor
}
}
func setPreviewLayer(_ previewLayer: AVCaptureVideoPreviewLayer?) {
self.cameraOutputLayer = previewLayer
if let previewLayer = previewLayer {
previewView.layer.insertSublayer(previewLayer, below: viewfinderBorderView.layer)
layOutPreview()
}
}
func previewFrame(forBounds bounds: CGRect) -> CGRect {
return layout(for: bounds).previewViewFrame
}
func setAccessDeniedViewVisible(_ visible: Bool) {
accessDeniedView.isHidden = !visible
}
func setAccessDeniedTitle(_ title: String) {
accessDeniedView.title = title
}
func setAccessDeniedMessage(_ message: String) {
accessDeniedView.message = message
}
func setAccessDeniedButtonTitle(_ title: String) {
accessDeniedView.buttonTitle = title
}
// MARK: - UIView
override func layoutSubviews() {
super.layoutSubviews()
let layout = self.layout(for: bounds)
closeButton.frame = layout.closeButtonFrame
selectedPhotosBarView.frame = layout.selectedPhotosBarFrame
captureButton.frame = layout.captureButtonFrame
hintLabel.frame = layout.hintLabelFrame
previewView.frame = layout.previewViewFrame
flashView.frame = layout.flashViewFrame
toggleCameraButton.frame = layout.toggleCameraButtonFrame
photoView.frame = layout.photoViewFrame
accessDeniedView.frame = layout.accessDeniedViewFrame
viewfinderBorderView.frame = previewView.bounds
layOutPreview()
layOutFlashButton()
}
// MARK: - Private - Layout
private struct Layout {
let closeButtonFrame: CGRect
let selectedPhotosBarFrame: CGRect
let captureButtonFrame: CGRect
let hintLabelFrame: CGRect
let previewViewFrame: CGRect
let flashViewFrame: CGRect
let toggleCameraButtonFrame: CGRect
let photoViewFrame: CGRect
let accessDeniedViewFrame: CGRect
}
private func layout(for bounds: CGRect) -> Layout {
let paparazzoSafeAreaInsets = window?.paparazzoSafeAreaInsets ?? self.paparazzoSafeAreaInsets
let closeButtonFrame = CGRect(
x: bounds.left + 8,
y: max(8, paparazzoSafeAreaInsets.top),
width: 38,
height: 38
)
let selectedPhotosBarViewSize = selectedPhotosBarSize(for: bounds)
let selectedPhotosBarBottom = bounds.bottom - max(16, paparazzoSafeAreaInsets.bottom)
let selectedPhotosBarViewFrame = CGRect(
x: bounds.left + floor((bounds.width - selectedPhotosBarViewSize.width) / 2),
y: selectedPhotosBarBottom - selectedPhotosBarViewSize.height,
width: selectedPhotosBarViewSize.width,
height: selectedPhotosBarViewSize.height
)
let freeHeight = selectedPhotosBarViewFrame.top - closeButtonFrame.bottom
let previewAspectRatio = CGFloat(3) / 4
let previewHeight = floor(bounds.width * previewAspectRatio)
let contentHeight = captureButtonSize + previewHeight
let spacing = floor((freeHeight - contentHeight) / 3)
let captureButtonBottom = selectedPhotosBarViewFrame.top - spacing
let captureButtonFrame = CGRect(
x: floor(bounds.centerX - captureButtonSize / 2),
y: captureButtonBottom - captureButtonSize,
width: captureButtonSize,
height: captureButtonSize
)
let hintLabelWidth = bounds.width - 2 * 16
let hintLabelHeight = hintLabel.sizeForWidth(hintLabelWidth).height
let hintLabelBottom = bounds.bottom - max(23, paparazzoSafeAreaInsets.bottom)
let hintLabelFrame = CGRect(
x: bounds.left + 16,
y: hintLabelBottom - hintLabelHeight,
width: hintLabelWidth,
height: hintLabelHeight
)
let previewViewBottom = captureButtonFrame.top - spacing
let previewViewFrame = CGRect(
x: bounds.left,
y: previewViewBottom - previewHeight,
width: bounds.width,
height: previewHeight
)
let toggleCameraButtonSize = toggleCameraButton.sizeThatFits()
let toggleCameraButtonRight = bounds.right - 23
let toggleCameraButtonFrame = CGRect(
x: toggleCameraButtonRight - toggleCameraButtonSize.width,
y: floor(captureButtonFrame.centerY - toggleCameraButtonSize.height / 2),
width: toggleCameraButtonSize.width,
height: toggleCameraButtonSize.height
)
let photoViewSize = CGSize(width: 37, height: 37)
let photoViewFrame = CGRect(
centerX: bounds.left + floor((captureButtonFrame.left - bounds.left) / 2),
centerY: captureButtonFrame.centerY,
width: photoViewSize.width,
height: photoViewSize.height
)
let accessDeniedViewMaxSize = CGSize(
width: bounds.width,
height: captureButtonFrame.top - closeButtonFrame.bottom
)
let accessDeniedViewSize = accessDeniedView.sizeThatFits(accessDeniedViewMaxSize)
let accessDeniedViewFrame = CGRect(
centerX: previewViewFrame.centerX,
centerY: previewViewFrame.centerY,
width: accessDeniedViewSize.width,
height: accessDeniedViewSize.height
)
return Layout(
closeButtonFrame: closeButtonFrame,
selectedPhotosBarFrame: selectedPhotosBarViewFrame,
captureButtonFrame: captureButtonFrame,
hintLabelFrame: hintLabelFrame,
previewViewFrame: previewViewFrame,
flashViewFrame: bounds,
toggleCameraButtonFrame: toggleCameraButtonFrame,
photoViewFrame: photoViewFrame,
accessDeniedViewFrame: accessDeniedViewFrame
)
}
private func layOutFlashButton() {
flashButton.sizeToFit()
flashButton.right = toggleCameraButton.left - 20
flashButton.centerY = toggleCameraButton.centerY
}
private func selectedPhotosBarSize(for bounds: CGRect) -> CGSize {
let maxSize = CGSize(width: bounds.width - 32, height: .greatestFiniteMagnitude)
return selectedPhotosBarView.sizeThatFits(maxSize)
}
private func layOutPreview() {
CATransaction.begin()
CATransaction.setDisableActions(true)
cameraOutputLayer?.frame = previewView.layer.bounds
CATransaction.commit()
}
// MARK: - Private - Event handling
@objc private func handleCaptureButtonTap() {
onCaptureButtonTap?()
}
@objc private func handleCloseButtonTap() {
onCloseButtonTap?()
}
@objc private func handleFlashButtonTap() {
flashButton.isSelected = !flashButton.isSelected
onFlashToggle?(flashButton.isSelected)
}
@objc private func handleToggleCameraButtonTap() {
onToggleCameraButtonTap?()
}
@objc private func onPhotoViewTap(_ tapRecognizer: UITapGestureRecognizer) {
onCloseButtonTap?()
}
}
|
mit
|
8b1f72339eb2d9afcce68a5d810d877b
| 35.769841 | 118 | 0.62643 | 5.565165 | false | false | false | false |
abema/NavigationNotice
|
NavigationNoticeExample/NavigationNoticeExample/ViewController.swift
|
1
|
3583
|
//
// ViewController.swift
// NavigationNoticeExample
//
// Created by Kyohei Ito on 2015/02/08.
// Copyright (c) 2015年 kyohei_ito. All rights reserved.
//
import UIKit
import NavigationNotice
class ViewController: UIViewController {
var tableSourceList: [[String]] = [[Int](0..<20).map({ "section 0, cell \($0)" })]
fileprivate func contentView(_ text: String) -> UIView {
let view = UIView(frame: CGRect(x: 0, y: 0, width: 375, height: 64))
view.autoresizingMask = [.flexibleWidth, .flexibleHeight]
let label = UILabel(frame: view.bounds)
label.frame.origin.x = 10
label.frame.origin.y = 10
label.frame.size.width -= label.frame.origin.x
label.frame.size.height -= label.frame.origin.y
label.autoresizingMask = [.flexibleWidth, .flexibleHeight]
label.text = text
label.numberOfLines = 2
label.textColor = UIColor.white
view.addSubview(label)
return view
}
override func viewDidLoad() {
super.viewDidLoad()
title = "Notification"
DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + Double(Int64(1 * Double(NSEC_PER_SEC))) / Double(NSEC_PER_SEC)) {
let content1 = self.contentView("Interactive Notification.\nYour original contents.")
content1.backgroundColor = UIColor.red.withAlphaComponent(0.9)
NavigationNotice.onStatusBar(false).addContent(content1).showOn(self.view).showAnimations { animations, completion in
UIView.animate(withDuration: 0.6, delay: 0, usingSpringWithDamping: 0.8, initialSpringVelocity: 0.1, options: .beginFromCurrentState, animations: animations, completion: completion)
} .hideAnimations { animations, completion in
UIView.animate(withDuration: 0.8, animations: animations, completion: completion)
}
NavigationNotice.defaultShowAnimations = { animations, completion in
UIView.animate(withDuration: 0.5, delay: 0, usingSpringWithDamping: 0.5, initialSpringVelocity: 0, options: .beginFromCurrentState, animations: animations, completion: completion)
}
NavigationNotice.defaultHideAnimations = { animations, completion in
UIView.animate(withDuration: 0.5, delay: 0, usingSpringWithDamping: 0.5, initialSpringVelocity: 0, options: .beginFromCurrentState, animations: animations, completion: completion)
}
let content2 = self.contentView("Timer Notification.\nCustomize your animation.")
content2.backgroundColor = UIColor.blue.withAlphaComponent(0.9)
NavigationNotice.addContent(content2).showOn(self.view).hide(2)
}
}
@IBAction func topButtonWasTapped(_ sender: UIButton) {
let content = self.contentView("Create your content.")
content.frame.size.height = 50
content.backgroundColor = UIColor.black.withAlphaComponent(0.9)
NavigationNotice.onStatusBar(false).addContent(content).showOn(self.view).position(.top).topInset(30).hide(5)
}
@IBAction func bottomButtonWasTapped(_ sender: UIButton) {
let content = self.contentView("Create your content.")
content.frame.size.height = 50
content.backgroundColor = UIColor.black.withAlphaComponent(0.9)
NavigationNotice.onStatusBar(false).addContent(content).showOn(self.view).position(.bottom).bottomInset(30).hide(5)
}
@IBAction func hideBUttonWasTapped(_ sender: UIButton) {
NavigationNotice.currentNotice()?.hide(0)
}
}
|
mit
|
661b4e77083d9b169656292d56db06ae
| 43.7625 | 197 | 0.680536 | 4.481852 | false | false | false | false |
codebreaker01/Currency-Converter
|
CurrencyConverter/Constants.swift
|
1
|
569
|
//
// Constants.swift
// CurrencyConverter
//
// Created by Jaikumar Bhambhwani on 4/25/15.
// Copyright (c) 2015 Jaikumar Bhambhwani. All rights reserved.
//
import Foundation
let kJSONRatesAPIKey = "jr-6cca58fac0b91d06472a60ec74035c9e"
let kURLForCurrencySymbols = "http://www.freecurrencyconverterapi.com/api/v3/currencies"
let kURLForCurrencies = "http://jsonrates.com/currencies.json"
let kURLForLocale = "http://jsonrates.com/locales.json"
let kURLForExchangeRate = "http://jsonrates.com/get/"
let kURLForHistoricalData = "http://jsonrates.com/historical/"
|
mit
|
3ce0bbb2511f86320b35b55378650bdf
| 32.529412 | 88 | 0.775044 | 2.994737 | false | false | false | false |
shohei/firefox-ios
|
ReadingListTests/ReadingListFetchSpecTestCase.swift
|
9
|
1624
|
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
import Foundation
import XCTest
class ReadingListFetchSpecTestCase: XCTestCase {
let serviceURLString = "https://readinglist.dev.mozaws.net/v0/"
private func compareSpec(spec: ReadingListFetchSpec, expectedURL: String) {
XCTAssertNotNil(spec)
let serviceURL = NSURL(string: serviceURLString)
XCTAssertNotNil(serviceURL)
let url = spec.getURL(serviceURL: serviceURL!)
XCTAssertNotNil(url)
let absoluteString = url?.absoluteString
XCTAssertNotNil(absoluteString)
XCTAssertEqual(absoluteString!, expectedURL)
}
func testFetchSpecBuilder() {
compareSpec(ReadingListFetchSpec.Builder().setStatus("0", not: false).build(),
expectedURL: "\(serviceURLString)?status=0")
compareSpec(ReadingListFetchSpec.Builder().setStatus("0", not: false).setUnread(true).build(),
expectedURL: "\(serviceURLString)?status=0&unread=true")
compareSpec(ReadingListFetchSpec.Builder().setStatus("0", not: false).setUnread(true).setMinAttribute("date", value: "1234567890").build(),
expectedURL: "\(serviceURLString)?status=0&unread=true&min_date=1234567890")
compareSpec(ReadingListFetchSpec.Builder().setStatus("0", not: false).setUnread(true).setMaxAttribute("cheese", value: "31337").build(),
expectedURL: "\(serviceURLString)?status=0&unread=true&max_cheese=31337")
}
}
|
mpl-2.0
|
97130fa02bb71ba716f594a0d17cd960
| 42.891892 | 147 | 0.700123 | 4.486188 | false | true | false | false |
mikina/SwiftNews
|
SwiftNews/SwiftNews/Modules/CustomTabBar/Controller/CustomTabBarController.swift
|
1
|
2332
|
//
// CustomTabBarController.swift
// SwiftNews
//
// Created by Mike Mikina on 10/31/16.
// Copyright © 2016 SwiftCookies.com. All rights reserved.
//
import UIKit
class CustomTabBarController: UIViewController, TabBarItemDelegate {
var tabBarContainerView: TabBarContainerView?
var tabBarView: TabBarView?
var activeViewController: UIViewController?
var viewControllers: [CustomTabBar] = []
override func viewDidLoad() {
super.viewDidLoad()
self.setupView()
self.tabBarSelected(position: 0)
}
func setupView() {
self.tabBarContainerView = TabBarContainerView(parentView: self.view)
self.tabBarView = TabBarView(parentView: self.view, viewControllers: self.viewControllers)
self.tabBarView?.delegate = self
}
func showViewController(viewController: UIViewController) {
if(self.activeViewController != nil) {
self.removeActiveViewController()
}
self.addChildViewController(viewController)
if let container = self.tabBarContainerView {
viewController.view.frame = container.bounds
container.addSubview(viewController.view)
}
self.activeViewController = viewController
viewController.didMove(toParentViewController: self)
}
func removeActiveViewController() {
self.activeViewController?.willMove(toParentViewController: nil)
self.activeViewController?.view.removeFromSuperview()
self.activeViewController?.removeFromParentViewController()
}
func tabBarSelected(position: Int) {
if(position <= self.viewControllers.count && !self.viewControllers.isEmpty) {
if let coordinator = self.viewControllers[position] as? TabItemCoordinator {
self.checkForActiveElement(viewController: coordinator.rootController)
self.prepareForShowViewController(viewController: coordinator.rootController)
self.tabBarView?.setSelectedTab(index: position)
}
}
}
func prepareForShowViewController(viewController: UIViewController) {
if(viewController != self.activeViewController) {
self.showViewController(viewController: viewController)
}
}
func checkForActiveElement(viewController: UIViewController) {
if let nav = self.activeViewController as? UINavigationController,
nav == viewController {
nav.popToRootViewController(animated: true)
}
}
}
|
mit
|
560fafba868608911f0307ad103cd67e
| 30.931507 | 94 | 0.750322 | 5.078431 | false | false | false | false |
LYM-mg/MGDS_Swift
|
MGDS_Swift/MGDS_Swift/Class/Music/PlayMusic/Tools/MGImageTool.swift
|
1
|
1357
|
//
// MGImageTool.swift
// MGDS_Swift
//
// Created by i-Techsys.com on 17/3/6.
// Copyright © 2017年 i-Techsys. All rights reserved.
//
import UIKit
class MGImageTool: NSObject {
static func creatImageWithText(text: String,InImage image: UIImage) -> UIImage? {
// 开启位图上下文
UIGraphicsBeginImageContextWithOptions(image.size, false, 0.0)
image.draw(in: CGRect(origin: .zero, size: image.size))
// 将文字绘制到图片上面
let rect = CGRect(origin: CGPoint(x: 0, y: image.size.height*0.4), size: image.size)
// 设置文字样式
let style = NSMutableParagraphStyle()
style.alignment = .center
let dict: [NSAttributedString.Key: Any] = [
NSAttributedString.Key.font:UIFont.systemFont(ofSize: 20),
NSAttributedString.Key.foregroundColor: UIColor.green,
NSAttributedString.Key.paragraphStyle : style
]
(text as NSString).draw(in: rect, withAttributes: dict)
// 获取最新的图片
let resultImage = UIGraphicsGetImageFromCurrentImageContext()
// 关闭上下文
UIGraphicsEndImageContext();
return resultImage
}
}
|
mit
|
c1a2655f0e14b55f94bd42a0eda5765a
| 31.923077 | 94 | 0.57243 | 4.703297 | false | false | false | false |
Raizlabs/ios-template
|
{{ cookiecutter.project_name | replace(' ', '') }}/app/{{ cookiecutter.project_name | replace(' ', '') }}/Screens/Onboarding/OnboardingPageViewController.swift
|
1
|
6540
|
//
// OnboardingPageViewController.swift
// {{ cookiecutter.project_name | replace(' ', '') }}
//
// Created by {{ cookiecutter.lead_dev }} on {% now 'utc', '%D' %}.
// Copyright © {% now 'utc', '%Y' %} {{ cookiecutter.company_name }}. All rights reserved.
//
import Anchorage
import Swiftilities
// MARK: OnboardingPageViewController
class OnboardingPageViewController: UIViewController {
fileprivate let viewControllers: [UIViewController]
fileprivate let skipButton: UIButton = {
let button = UIButton()
button.bonMotStyle = .body
button.bonMotStyle?.color = Color.darkGray
button.setTitleColor(Color.darkGray.highlighted, for: .highlighted)
button.styledText = L10n.Onboarding.Buttons.skip
return button
}()
fileprivate let pageController = UIPageViewController(
transitionStyle: .scroll, navigationOrientation: .horizontal, options: nil)
fileprivate let firstHairline = HairlineView(axis: .horizontal)
fileprivate let joinButton: UIButton = {
let button = UIButton()
button.bonMotStyle = .body
button.bonMotStyle?.color = Color.green
button.setTitleColor(Color.green.highlighted, for: .highlighted)
button.styledText = L10n.Onboarding.Buttons.join
return button
}()
fileprivate let secondHairline = HairlineView(axis: .horizontal)
fileprivate let signInButton: UIButton = {
let button = UIButton()
button.bonMotStyle = .body
button.bonMotStyle?.color = Color.darkGray
button.styledText = L10n.Onboarding.Buttons.signIn
button.setTitleColor(Color.darkGray.highlighted, for: .highlighted)
return button
}()
weak var delegate: Delegate?
init(viewModels: [OnboardingSamplePageViewModel]) {
self.viewControllers = viewModels.map {
OnboardingSamplePageViewController(viewModel: $0)
}
super.init(nibName: nil, bundle: nil)
}
@available(*, unavailable) required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func viewDidLoad() {
super.viewDidLoad()
configureView()
configureLayout()
}
}
// MARK: Actionable
extension OnboardingPageViewController: Actionable {
enum Action {
case skipTapped
case joinTapped
case signInTapped
}
}
// MARK: Private
private extension OnboardingPageViewController {
func configureView() {
view.backgroundColor = .white
view.addSubview(skipButton)
skipButton.addTarget(self, action: #selector(skipTapped), for: .touchUpInside)
pageController.setViewControllers(
[viewControllers[0]], direction: .forward, animated: false, completion: nil)
pageController.dataSource = self
addChild(pageController)
view.addSubview(pageController.view)
pageController.didMove(toParent: self)
let pageControlAppearance = UIPageControl.appearance(
whenContainedInInstancesOf: [OnboardingPageViewController.self])
pageControlAppearance.pageIndicatorTintColor = Color.lightGray
pageControlAppearance.currentPageIndicatorTintColor = Color.darkGray
view.addSubview(firstHairline)
joinButton.addTarget(self, action: #selector(joinTapped), for: .touchUpInside)
view.addSubview(joinButton)
view.addSubview(secondHairline)
signInButton.addTarget(self, action: #selector(signInTapped), for: .touchUpInside)
view.addSubview(signInButton)
}
struct Layout {
static let skipButtonTrailingInset = CGFloat(20)
static let skipButtonTopInset = CGFloat(22)
static let pageViewTopSpace = CGFloat(20)
static let joinVerticalSpace = CGFloat(8)
static let signInVerticalSpace = CGFloat(18)
}
func configureLayout() {
skipButton.topAnchor == view.safeAreaLayoutGuide.topAnchor + Layout.skipButtonTopInset
skipButton.trailingAnchor == view.safeAreaLayoutGuide.trailingAnchor - Layout.skipButtonTrailingInset
pageController.view.topAnchor == skipButton.bottomAnchor + Layout.pageViewTopSpace
pageController.view.horizontalAnchors == view.safeAreaLayoutGuide.horizontalAnchors
firstHairline.topAnchor == pageController.view.bottomAnchor
firstHairline.horizontalAnchors == view.safeAreaLayoutGuide.horizontalAnchors
joinButton.horizontalAnchors == view.safeAreaLayoutGuide.horizontalAnchors
joinButton.topAnchor == firstHairline.bottomAnchor + Layout.joinVerticalSpace
joinButton.bottomAnchor == secondHairline.topAnchor - Layout.joinVerticalSpace
secondHairline.horizontalAnchors == view.safeAreaLayoutGuide.horizontalAnchors
signInButton.horizontalAnchors == view.safeAreaLayoutGuide.horizontalAnchors
signInButton.topAnchor == secondHairline.bottomAnchor + Layout.signInVerticalSpace
signInButton.bottomAnchor == view.safeAreaLayoutGuide.bottomAnchor - Layout.signInVerticalSpace
}
}
// MARK: Actions
private extension OnboardingPageViewController {
@objc func skipTapped() {
notify(.skipTapped)
}
@objc func joinTapped() {
notify(.joinTapped)
}
@objc func signInTapped() {
notify(.signInTapped)
}
}
// MARK: UIPageViewControllerDataSource
extension OnboardingPageViewController: UIPageViewControllerDataSource {
func pageViewController(_ pageViewController: UIPageViewController, viewControllerBefore viewController: UIViewController) -> UIViewController? {
guard let index = viewControllers.firstIndex(of: viewController), index > 0 else {
return nil
}
return viewControllers[index - 1]
}
func pageViewController(_ pageViewController: UIPageViewController, viewControllerAfter viewController: UIViewController) -> UIViewController? {
guard let index = viewControllers.firstIndex(of: viewController),
index < viewControllers.count - 1 else {
return nil
}
return viewControllers[index + 1]
}
func presentationCount(for pageViewController: UIPageViewController) -> Int {
return viewControllers.count
}
func presentationIndex(for pageViewController: UIPageViewController) -> Int {
guard let current = pageViewController.viewControllers?.first else {
return 0
}
return viewControllers.firstIndex(of: current) ?? 0
}
}
|
mit
|
d39e4d4112716ee109baf4190b6949c0
| 34.928571 | 149 | 0.704236 | 5.444629 | false | false | false | false |
eugeneego/utilities-ios
|
Sources/UI/ShadowView.swift
|
1
|
1838
|
//
// ShadowView
// Legacy
//
// Copyright (c) 2015 Eugene Egorov.
// License: MIT, https://github.com/eugeneego/legacy/blob/master/LICENSE
//
#if canImport(UIKit)
#if !os(watchOS)
import UIKit
open class ShadowView: UIView {
@IBInspectable open var shadowColor: UIColor = .black {
didSet {
layer.shadowColor = shadowColor.cgColor
}
}
@IBInspectable open var shadowOffset: CGSize = CGSize(width: 3, height: 3) {
didSet {
layer.shadowOffset = shadowOffset
}
}
@IBInspectable open var shadowOpacity: Float = 0.5 {
didSet {
layer.shadowOpacity = shadowOpacity
}
}
@IBInspectable open var shadowRadius: CGFloat = 5 {
didSet {
layer.shadowRadius = shadowRadius
}
}
@IBInspectable open var shadowCornerRadius: CGFloat = 0 {
didSet {
updatePath()
}
}
open var shadowPath: UIBezierPath? {
didSet {
updatePath()
}
}
public override required init(frame: CGRect) {
super.init(frame: frame)
setup()
}
public required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
open override func awakeFromNib() {
super.awakeFromNib()
setup()
}
private func setup() {
layer.shadowColor = shadowColor.cgColor
layer.shadowOffset = shadowOffset
layer.shadowOpacity = shadowOpacity
layer.shadowRadius = shadowRadius
}
open override func layoutSubviews() {
super.layoutSubviews()
updatePath()
}
private func updatePath() {
let path = shadowPath ?? UIBezierPath(roundedRect: bounds, cornerRadius: shadowCornerRadius)
layer.shadowPath = path.cgPath
}
}
#endif
#endif
|
mit
|
202e57ce423373534c678c0b54e2b1c2
| 19.651685 | 100 | 0.5963 | 4.811518 | false | false | false | false |
dvor/Antidote
|
Antidote/LoginLogoController.swift
|
2
|
2712
|
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at http://mozilla.org/MPL/2.0/.
import UIKit
import SnapKit
private struct PrivateConstants {
static let LogoTopOffset = -200.0
static let LogoHeight = 100.0
}
class LoginLogoController: LoginBaseController {
/**
* Main view, which is used as container for all subviews.
*/
var mainContainerView: UIView!
var mainContainerViewTopConstraint: Constraint?
var logoImageView: UIImageView!
/**
* Use this container to add subviews in subclasses.
* Is placed under logo.
*/
var contentContainerView: UIView!
override func loadView() {
super.loadView()
createMainContainerView()
createLogoImageView()
createContainerView()
installConstraints()
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
navigationController?.setNavigationBarHidden(true, animated:animated)
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
navigationController?.setNavigationBarHidden(false, animated:animated)
}
}
private extension LoginLogoController {
func createMainContainerView() {
mainContainerView = UIView()
mainContainerView.backgroundColor = .clear
view.addSubview(mainContainerView)
}
func createLogoImageView() {
let image = UIImage(named: "login-logo")
logoImageView = UIImageView(image: image)
logoImageView.contentMode = .scaleAspectFit
mainContainerView.addSubview(logoImageView)
}
func createContainerView() {
contentContainerView = UIView()
contentContainerView.backgroundColor = .clear
mainContainerView.addSubview(contentContainerView)
}
func installConstraints() {
mainContainerView.snp.makeConstraints {
mainContainerViewTopConstraint = $0.top.equalTo(view).constraint
$0.leading.trailing.equalTo(view)
$0.height.equalTo(view)
}
logoImageView.snp.makeConstraints {
$0.centerX.equalTo(mainContainerView)
$0.top.equalTo(mainContainerView.snp.centerY).offset(PrivateConstants.LogoTopOffset)
$0.height.equalTo(PrivateConstants.LogoHeight)
}
contentContainerView.snp.makeConstraints {
$0.top.equalTo(logoImageView.snp.bottom).offset(Constants.VerticalOffset)
$0.bottom.equalTo(mainContainerView)
$0.leading.trailing.equalTo(mainContainerView)
}
}
}
|
mit
|
7af5a0cc802935e4ecdc5bcd30071e24
| 29.47191 | 96 | 0.681047 | 5.175573 | false | false | false | false |
sudeepunnikrishnan/ios-sdk
|
Instamojo/UPISubmissionResponse.swift
|
1
|
1208
|
//
// UPISubmissionResponse.swift
// Instamojo
//
// Created by Sukanya Raj on 15/02/17.
// Copyright © 2017 Sukanya Raj. All rights reserved.
//
import UIKit
public class UPISubmissionResponse: NSObject {
public var paymentID: String
public var statusCode: Int
public var payerVirtualAddress: String
public var payeeVirtualAddress: String
public var statusCheckURL: String
public var upiBank: String
public var statusMessage: String
override init() {
self.paymentID = ""
self.statusCode = 0
self.payeeVirtualAddress = ""
self.payerVirtualAddress = ""
self.statusCheckURL = ""
self.upiBank = ""
self.statusMessage = ""
}
public init(paymentID: String, statusCode: Int, payerVirtualAddress: String, payeeVirtualAddress: String, statusCheckURL: String, upiBank: String, statusMessage: String) {
self.paymentID = paymentID
self.statusCode = statusCode
self.payerVirtualAddress = payerVirtualAddress
self.payeeVirtualAddress = payeeVirtualAddress
self.statusCheckURL = statusCheckURL
self.upiBank = upiBank
self.statusMessage = statusMessage
}
}
|
lgpl-3.0
|
f145b82277f9d41d8f8d79cef22b435b
| 29.175 | 175 | 0.685998 | 4.866935 | false | false | false | false |
alvarozizou/Noticias-Leganes-iOS
|
NoticiasLeganes/ViewControllers/ListViewController.swift
|
1
|
1923
|
//
// ListViewController.swift
// NoticiasLeganes
//
// Created by Alvaro Blazquez Montero on 7/10/17.
// Copyright © 2017 Alvaro Blazquez Montero. All rights reserved.
//
import UIKit
protocol ListViewController{
var activityIndicator: UIActivityIndicatorView {get set}
var refreshControl: UIRefreshControl {get set}
func initTableView()
func prepareTableView()
func prepareActivityIndicator()
func reloadData()
func reloadTableView()
func stopAnimation()
func showError()
func showNewData()
}
extension ListViewController where Self: UIViewController {
func initTableView() {
prepareActivityIndicator()
prepareTableView()
reloadData()
}
func prepareActivityIndicator() {
activityIndicator.center = self.view.center
activityIndicator.color = K.mainColor
activityIndicator.hidesWhenStopped = true
self.view.addSubview(activityIndicator)
activityIndicator.startAnimating()
}
func prepareRefreshControl() {
refreshControl.tintColor = K.mainColor
}
func showNewData() {
stopAnimation()
reloadTableView()
}
func stopAnimation() {
activityIndicator.stopAnimating()
refreshControl.endRefreshing()
}
func showError() {
stopAnimation()
let alertController = UIAlertController(title: "¡Vaya!", message: "Parece que hemos tenido un problema. Vuelve a intentarlo.", preferredStyle: UIAlertController.Style.alert)
let okAction = UIAlertAction(title: "Vuelve a intentarlo", style: UIAlertAction.Style.default) {
(result : UIAlertAction) -> Void in
self.reloadData()
}
alertController.addAction(okAction)
self.present(alertController, animated: true, completion: nil)
}
}
|
mit
|
dc7df1f69760cbd22d835bf2ac9f2226
| 24.959459 | 181 | 0.651223 | 5.365922 | false | false | false | false |
y0ke/actor-platform
|
actor-sdk/sdk-core-ios/ActorSDK/Sources/SwiftExtensions/AALocalized.swift
|
2
|
1468
|
//
// Copyright (c) 2014-2016 Actor LLC. <https://actor.im>
//
import Foundation
// Shorter helper for localized strings
public func AALocalized(text: String!) -> String! {
if text == nil {
return nil
}
let appRes = NSLocalizedString(text, comment: "")
if (appRes != text) {
return appRes
}
for t in tables {
let res = NSLocalizedString(text, tableName: t.table, bundle: t.bundle, value: text, comment: "")
if (res != text) {
return res
}
}
return NSLocalizedString(text, tableName: nil, bundle: NSBundle.framework, value: text, comment: "")
}
// Registration localization table
public func AARegisterLocalizedBundle(table: String, bundle: NSBundle) {
tables.append(LocTable(table: table, bundle: bundle))
}
private var tables = [LocTable]()
private class LocTable {
let table: String
let bundle: NSBundle
init(table: String, bundle: NSBundle) {
self.table = table
self.bundle = bundle
}
}
// Extensions on various UIView
public extension UILabel {
public var textLocalized: String? {
get {
return self.text
}
set (value) {
if value != nil {
self.text = AALocalized(value!).replace("{appname}", dest: ActorSDK.sharedActor().appName)
} else {
self.text = nil
}
}
}
}
|
agpl-3.0
|
869a9bbe811e539a10f56db5d60dcf52
| 20.925373 | 106 | 0.571526 | 4.292398 | false | false | false | false |
Urinx/SublimeCode
|
Sublime/Sublime/Utils/Device.swift
|
1
|
4168
|
//
// Device.swift
// Sublime
//
// Created by Eular on 5/6/16.
// Copyright © 2016 Eular. All rights reserved.
//
import Foundation
struct Device {
static func appSize(process: ((Double) -> Void)? = nil, completion: ((Double, Double) -> Void)? = nil) {
// 后台执行
let priority = DISPATCH_QUEUE_PRIORITY_DEFAULT
dispatch_async(dispatch_get_global_queue(priority, 0)) {
let fileMgr = NSFileManager.defaultManager()
let homePath = NSHomeDirectory()
let appPath = NSBundle.mainBundle().bundlePath
let fileArray:[AnyObject] = fileMgr.subpathsAtPath(homePath)!
let fileArray2:[AnyObject] = fileMgr.subpathsAtPath(appPath)!
let total = fileArray.count + fileArray2.count
var count = 0
var allSize = 0.0
var cacheSize = 0.0
for fn in fileArray {
count += 1
let attr = try! fileMgr.attributesOfItemAtPath(homePath + "/\(fn)")
let size = attr["NSFileSize"] as! Double
allSize += size
if fn.hasPrefix("Library/Caches") { cacheSize += size }
process?(Double(count) / Double(total))
}
for fn in fileArray2 {
count += 1
let attr = try! fileMgr.attributesOfItemAtPath(appPath + "/\(fn)")
let size = attr["NSFileSize"] as! Double
allSize += size
process?(Double(count) / Double(total))
}
completion?(allSize, cacheSize)
}
}
static var cache: Double {
get {
let fileMgr = NSFileManager.defaultManager()
let path = NSHomeDirectory() + "/Library/Caches/"
let fileArray:[AnyObject] = fileMgr.subpathsAtPath(path)!
var allSize = 0.0
for fn in fileArray {
let attr = try! fileMgr.attributesOfItemAtPath(path + "/\(fn)")
let size = attr["NSFileSize"] as! Double
allSize += size
}
return allSize
}
set {
let fileMgr = NSFileManager.defaultManager()
let path = NSHomeDirectory() + "/Library/Caches/"
do {
try fileMgr.removeItemAtPath(path)
try fileMgr.createDirectoryAtPath(path, withIntermediateDirectories: true, attributes: nil)
} catch {
Log("Error: clean cache failed.")
}
}
}
static var systemFreeSize: Double {
let fm = NSFileManager.defaultManager()
let fattributes = try! fm.attributesOfFileSystemForPath(NSHomeDirectory())
return fattributes["NSFileSystemFreeSize"] as! Double
}
static var systemSize: Double {
let fm = NSFileManager.defaultManager()
let fattributes = try! fm.attributesOfFileSystemForPath(NSHomeDirectory())
return fattributes["NSFileSystemSize"] as! Double
}
static var batteryLevel: Float {
return UIDevice.currentDevice().batteryLevel
}
static var batteryState: UIDeviceBatteryState {
return UIDevice.currentDevice().batteryState
}
static var UUID: String {
return UIDevice.currentDevice().identifierForVendor!.UUIDString
}
static var name: String {
return UIDevice.currentDevice().name
}
static var systemVersion: String {
return UIDevice.currentDevice().systemVersion
}
static var app: Array<String> {
var appList = [String]()
for app in ObjC.getAppList() {
let BundleID = String(app).split(" ")[2]
if !BundleID.hasPrefix("com.apple") {
appList.append(BundleID)
}
}
return appList
}
static var appNum: Int {
return app.count
}
static var SSID: String {
return ObjC.SSID()
}
static var BSSID: String {
return ObjC.BSSID()
}
}
|
gpl-3.0
|
efe2c17eddc28fae214528c7bf00e6ee
| 30.044776 | 108 | 0.545804 | 5.134568 | false | false | false | false |
belatrix/iOSAllStars
|
AllStarsV2/AllStarsV2/iPhone/Classes/Animations/AchievementToDetailTransition.swift
|
1
|
7048
|
//
// AchievementToDetailTransition.swift
// AllStarsV2
//
// Created by Kenyi Rodriguez Vergara on 14/08/17.
// Copyright © 2017 Kenyi Rodriguez Vergara. All rights reserved.
//
import UIKit
class AchievementToDetailInteractiveTransition : InteractiveTransition{
var initialScale : CGFloat = 0
@objc func gestureTransitionMethod(_ gesture : UIPanGestureRecognizer){
let view = self.navigationController.view!
if gesture.state == .began {
self.interactiveTransition = UIPercentDrivenInteractiveTransition()
self.navigationController.popViewController(animated: true)
}else if gesture.state == .changed{
let translation = gesture.translation(in: view)
let delta = fabs(translation.y / view.bounds.height)
self.interactiveTransition?.update(delta)
}else{
self.interactiveTransition?.finish()
self.interactiveTransition = nil
}
}
}
class AchievementToDetailTransition: ControllerTransition {
override func createInteractiveTransition(navigationController: UINavigationController) -> InteractiveTransition? {
let interactiveTransition = AchievementToDetailInteractiveTransition()
interactiveTransition.navigationController = navigationController
interactiveTransition.gestureTransition = UIPanGestureRecognizer(target: interactiveTransition, action: #selector(interactiveTransition.gestureTransitionMethod(_:)))
interactiveTransition.navigationController.view.addGestureRecognizer(interactiveTransition.gestureTransition!)
return interactiveTransition
}
override func animatePush(toContext context : UIViewControllerContextTransitioning) {
let fromVC = self.controllerOrigin as! UserProfileViewController
let toVC = self.controllerDestination as! AchievementDetailViewController
let containerView = context.containerView
containerView.backgroundColor = .white
let fromView = context.view(forKey: .from)!
let toView = context.view(forKey: .to)!
let duration = self.transitionDuration(using: context)
fromView.frame = UIScreen.main.bounds
containerView.addSubview(fromView)
toView.frame = UIScreen.main.bounds
containerView.addSubview(toView)
let cell = fromVC.controllerAchievements.achievementCellSelected
let cellFrame = fromVC.controllerAchievements.clvAchievements.convert(cell!.frame, to: containerView)
let imageFrame = cell!.imgIcon.frame
let imageIcon = UIImageView(image: cell!.imgIcon.image)
containerView.addSubview(imageIcon)
imageIcon.frame = CGRect(x: cellFrame.origin.x + imageFrame.origin.x , y: cellFrame.origin.y + imageFrame.origin.y, width: imageFrame.width, height: imageFrame.height)
cell!.imgIcon.alpha = 0
toVC.constraintLeftBtnCerrar.constant = -44
toVC.constraintTopContent.constant = UIScreen.main.bounds.size.height - toVC.viewContent.frame.origin.y + toVC.initialContraintTopContent
toVC.constraintBottomShare.constant = -60
toView.backgroundColor = .clear
toVC.imgIcon.alpha = 0
containerView.layoutIfNeeded()
UIView.animate(withDuration: duration*0.5, delay: 0, usingSpringWithDamping: 0.8, initialSpringVelocity: 0.1, options: .curveEaseIn, animations: {
imageIcon.frame = toVC.imgIcon.frame
imageIcon.center.x = UIScreen.main.bounds.size.width / 2
toView.backgroundColor = .white
toVC.constraintLeftBtnCerrar.constant = 0
containerView.layoutIfNeeded()
}) { (_) in
}
UIView.animate(withDuration: duration*0.7, delay: 0.3, usingSpringWithDamping: 0.8, initialSpringVelocity: 0.1, options: .curveEaseIn, animations: {
toVC.constraintTopContent.constant = toVC.initialContraintTopContent
toVC.constraintBottomShare.constant = toVC.initialCOnstraintBottomShare
containerView.layoutIfNeeded()
}) { (_) in
cell!.imgIcon.alpha = 1
imageIcon.removeFromSuperview()
toVC.imgIcon.alpha = 1
context.completeTransition(true)
}
}
override func animatePop(toContext context : UIViewControllerContextTransitioning) {
let fromVC = self.controllerOrigin as! AchievementDetailViewController
let toVC = self.controllerDestination as! UserProfileViewController
let containerView = context.containerView
containerView.backgroundColor = .white
let fromView = context.view(forKey: .from)!
let toView = context.view(forKey: .to)!
let duration = self.transitionDuration(using: context)
toView.frame = UIScreen.main.bounds
containerView.addSubview(toView)
fromView.frame = UIScreen.main.bounds
containerView.addSubview(fromView)
let imageIcon = UIImageView(image: fromVC.imgIcon.image)
containerView.addSubview(imageIcon)
imageIcon.frame = fromVC.imgIcon.frame
fromVC.imgIcon.alpha = 0
toVC.controllerAchievements.achievementCellSelected.imgIcon.alpha = 0
UIView.animate(withDuration: duration, delay: 0, usingSpringWithDamping: 0.8, initialSpringVelocity: 0.1, options: .curveEaseIn, animations: {
let cell = toVC.controllerAchievements.achievementCellSelected
let cellFrame = toVC.controllerAchievements.clvAchievements.convert(cell!.frame, to: containerView)
let imageFrame = cell!.imgIcon.frame
imageIcon.frame = CGRect(x: cellFrame.origin.x + imageFrame.origin.x , y: cellFrame.origin.y + imageFrame.origin.y, width: imageFrame.width, height: imageFrame.height)
fromView.backgroundColor = .clear
fromVC.constraintLeftBtnCerrar.constant = -44
fromVC.viewContent.alpha = 0
fromVC.constraintTopContent.constant = UIScreen.main.bounds.size.height - fromVC.viewContent.frame.origin.y + fromVC.initialContraintTopContent
fromVC.constraintBottomShare.constant = -60
containerView.layoutIfNeeded()
}) { (_) in
toVC.controllerAchievements.achievementCellSelected.imgIcon.alpha = 1
imageIcon.removeFromSuperview()
fromVC.imgIcon.alpha = 1
context.completeTransition(true)
}
}
override func transitionDuration(using transitionContext: UIViewControllerContextTransitioning?) -> TimeInterval {
return 0.8
}
}
|
apache-2.0
|
d7a5b71882cadb87f04974f1eaf91039
| 40.210526 | 180 | 0.656591 | 5.488318 | false | false | false | false |
doronkatz/firefox-ios
|
Client/Frontend/Browser/BrowserViewController.swift
|
1
|
156211
|
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
import Foundation
import Photos
import UIKit
import WebKit
import Shared
import Storage
import SnapKit
import XCGLogger
import Alamofire
import Account
import ReadingList
import MobileCoreServices
import WebImage
import SwiftyJSON
import Telemetry
import Sentry
private let log = Logger.browserLogger
private let KVOLoading = "loading"
private let KVOEstimatedProgress = "estimatedProgress"
private let KVOURL = "URL"
private let KVOTitle = "title"
private let KVOCanGoBack = "canGoBack"
private let KVOCanGoForward = "canGoForward"
private let KVOContentSize = "contentSize"
private let ActionSheetTitleMaxLength = 120
private struct BrowserViewControllerUX {
fileprivate static let BackgroundColor = UIConstants.AppBackgroundColor
fileprivate static let ShowHeaderTapAreaHeight: CGFloat = 32
fileprivate static let BookmarkStarAnimationDuration: Double = 0.5
fileprivate static let BookmarkStarAnimationOffset: CGFloat = 80
}
class BrowserViewController: UIViewController {
var homePanelController: HomePanelViewController?
var webViewContainer: UIView!
var menuViewController: MenuViewController?
var urlBar: URLBarView!
var clipboardBarDisplayHandler: ClipboardBarDisplayHandler!
var readerModeBar: ReaderModeBarView?
var readerModeCache: ReaderModeCache
fileprivate var statusBarOverlay: UIView!
fileprivate(set) var toolbar: TabToolbar?
fileprivate var searchController: SearchViewController?
fileprivate var screenshotHelper: ScreenshotHelper!
fileprivate var homePanelIsInline = false
fileprivate var searchLoader: SearchLoader!
fileprivate let snackBars = UIView()
fileprivate let webViewContainerToolbar = UIView()
fileprivate var findInPageBar: FindInPageBar?
fileprivate let findInPageContainer = UIView()
fileprivate lazy var mailtoLinkHandler: MailtoLinkHandler = MailtoLinkHandler()
lazy fileprivate var customSearchEngineButton: UIButton = {
let searchButton = UIButton()
searchButton.setImage(UIImage(named: "AddSearch")?.withRenderingMode(.alwaysTemplate), for: UIControlState())
searchButton.addTarget(self, action: #selector(BrowserViewController.addCustomSearchEngineForFocusedElement), for: .touchUpInside)
searchButton.accessibilityIdentifier = "BrowserViewController.customSearchEngineButton"
return searchButton
}()
fileprivate var customSearchBarButton: UIBarButtonItem?
// popover rotation handling
fileprivate var displayedPopoverController: UIViewController?
fileprivate var updateDisplayedPopoverProperties: (() -> Void)?
fileprivate var openInHelper: OpenInHelper?
// location label actions
fileprivate var pasteGoAction: AccessibleAction!
fileprivate var pasteAction: AccessibleAction!
fileprivate var copyAddressAction: AccessibleAction!
fileprivate weak var tabTrayController: TabTrayController!
fileprivate let profile: Profile
let tabManager: TabManager
// These views wrap the urlbar and toolbar to provide background effects on them
var header: BlurWrapper!
var headerBackdrop: UIView!
var footer: UIView!
var footerBackdrop: UIView!
fileprivate var footerBackground: BlurWrapper?
fileprivate var topTouchArea: UIButton!
let urlBarTopTabsContainer = UIView(frame: CGRect.zero)
// Backdrop used for displaying greyed background for private tabs
var webViewContainerBackdrop: UIView!
fileprivate var scrollController = TabScrollingController()
fileprivate var keyboardState: KeyboardState?
var didRemoveAllTabs: Bool = false
var pendingToast: ButtonToast? // A toast that might be waiting for BVC to appear before displaying
let WhiteListedUrls = ["\\/\\/itunes\\.apple\\.com\\/"]
// Tracking navigation items to record history types.
// TODO: weak references?
var ignoredNavigation = Set<WKNavigation>()
var typedNavigation = [WKNavigation: VisitType]()
var navigationToolbar: TabToolbarProtocol {
return toolbar ?? urlBar
}
var topTabsViewController: TopTabsViewController?
let topTabsContainer = UIView(frame: CGRect.zero)
init(profile: Profile, tabManager: TabManager) {
self.profile = profile
self.tabManager = tabManager
self.readerModeCache = DiskReaderModeCache.sharedInstance
super.init(nibName: nil, bundle: nil)
didInit()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override var supportedInterfaceOrientations: UIInterfaceOrientationMask {
if UIDevice.current.userInterfaceIdiom == .phone {
return UIInterfaceOrientationMask.allButUpsideDown
} else {
return UIInterfaceOrientationMask.all
}
}
override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) {
super.viewWillTransition(to: size, with: coordinator)
displayedPopoverController?.dismiss(animated: true) {
self.displayedPopoverController = nil
}
coordinator.animate(alongsideTransition: { context in
self.scrollController.updateMinimumZoom()
self.topTabsViewController?.scrollToCurrentTab(false, centerCell: false)
if let popover = self.displayedPopoverController {
self.updateDisplayedPopoverProperties?()
self.present(popover, animated: true, completion: nil)
}
}, completion: { _ in
self.scrollController.setMinimumZoom()
})
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
log.debug("BVC received memory warning")
}
fileprivate func didInit() {
screenshotHelper = ScreenshotHelper(controller: self)
tabManager.addDelegate(self)
tabManager.addNavigationDelegate(self)
}
override var preferredStatusBarStyle: UIStatusBarStyle {
return UIStatusBarStyle.lightContent
}
func shouldShowFooterForTraitCollection(_ previousTraitCollection: UITraitCollection) -> Bool {
return previousTraitCollection.verticalSizeClass != .compact &&
previousTraitCollection.horizontalSizeClass != .regular
}
func shouldShowTopTabsForTraitCollection(_ newTraitCollection: UITraitCollection) -> Bool {
guard AppConstants.MOZ_TOP_TABS else {
return false
}
return newTraitCollection.verticalSizeClass == .regular &&
newTraitCollection.horizontalSizeClass == .regular
}
func toggleSnackBarVisibility(show: Bool) {
if show {
UIView.animate(withDuration: 0.1, animations: { self.snackBars.isHidden = false })
} else {
snackBars.isHidden = true
}
}
fileprivate func updateToolbarStateForTraitCollection(_ newCollection: UITraitCollection, withTransitionCoordinator coordinator: UIViewControllerTransitionCoordinator? = nil) {
let showToolbar = shouldShowFooterForTraitCollection(newCollection)
let showTopTabs = shouldShowTopTabsForTraitCollection(newCollection)
if UI_USER_INTERFACE_IDIOM() == .pad,
let mvc = menuViewController, showToolbar != (toolbar != nil) {
// Hide the menu, and then re-open it so that the menu is always the correct one for the given traits
mvc.dismiss(animated: true, completion: nil)
coordinator?.animate(alongsideTransition: nil, completion: { _ in
self.tabToolbarDidPressMenu(self.navigationToolbar, button: self.navigationToolbar.menuButton)
})
}
urlBar.topTabsIsShowing = showTopTabs
urlBar.setShowToolbar(!showToolbar)
toolbar?.removeFromSuperview()
toolbar?.tabToolbarDelegate = nil
footerBackground?.removeFromSuperview()
footerBackground = nil
toolbar = nil
if showToolbar {
toolbar = TabToolbar()
toolbar?.tabToolbarDelegate = self
footerBackground = BlurWrapper(view: toolbar!)
footerBackground?.translatesAutoresizingMaskIntoConstraints = false
// Need to reset the proper blur style
if let selectedTab = tabManager.selectedTab, selectedTab.isPrivate {
footerBackground!.blurStyle = .dark
toolbar?.applyTheme(Theme.PrivateMode)
}
footer.addSubview(footerBackground!)
}
if showTopTabs {
if topTabsViewController == nil {
let topTabsViewController = TopTabsViewController(tabManager: tabManager)
topTabsViewController.delegate = self
addChildViewController(topTabsViewController)
topTabsViewController.view.frame = topTabsContainer.frame
topTabsContainer.addSubview(topTabsViewController.view)
topTabsViewController.view.snp.makeConstraints { make in
make.edges.equalTo(topTabsContainer)
make.height.equalTo(TopTabsUX.TopTabsViewHeight)
}
self.topTabsViewController = topTabsViewController
}
topTabsContainer.snp.updateConstraints { make in
make.height.equalTo(TopTabsUX.TopTabsViewHeight)
}
header.disableBlur = true
} else {
topTabsContainer.snp.updateConstraints { make in
make.height.equalTo(0)
}
topTabsViewController?.view.removeFromSuperview()
topTabsViewController?.removeFromParentViewController()
topTabsViewController = nil
header.disableBlur = false
}
view.setNeedsUpdateConstraints()
if let home = homePanelController {
home.view.setNeedsUpdateConstraints()
}
if let tab = tabManager.selectedTab,
let webView = tab.webView {
updateURLBarDisplayURL(tab)
navigationToolbar.updateBackStatus(webView.canGoBack)
navigationToolbar.updateForwardStatus(webView.canGoForward)
navigationToolbar.updateReloadStatus(tab.loading)
}
}
override func willTransition(to newCollection: UITraitCollection, with coordinator: UIViewControllerTransitionCoordinator) {
super.willTransition(to: newCollection, with: coordinator)
// During split screen launching on iPad, this callback gets fired before viewDidLoad gets a chance to
// set things up. Make sure to only update the toolbar state if the view is ready for it.
if isViewLoaded {
updateToolbarStateForTraitCollection(newCollection, withTransitionCoordinator: coordinator)
}
displayedPopoverController?.dismiss(animated: true, completion: nil)
coordinator.animate(alongsideTransition: { context in
self.scrollController.showToolbars(animated: false)
}, completion: nil)
}
func SELappDidEnterBackgroundNotification() {
displayedPopoverController?.dismiss(animated: false) {
self.displayedPopoverController = nil
}
}
func SELtappedTopArea() {
scrollController.showToolbars(animated: true)
}
func SELappWillResignActiveNotification() {
// Dismiss any popovers that might be visible
displayedPopoverController?.dismiss(animated: false) {
self.displayedPopoverController = nil
}
// Dismiss menu if presenting
menuViewController?.dismiss(animated: true, completion: nil)
// If we are displying a private tab, hide any elements in the tab that we wouldn't want shown
// when the app is in the home switcher
guard let privateTab = tabManager.selectedTab, privateTab.isPrivate else {
return
}
webViewContainerBackdrop.alpha = 1
webViewContainer.alpha = 0
urlBar.locationContainer.alpha = 0
topTabsViewController?.switchForegroundStatus(isInForeground: false)
presentedViewController?.popoverPresentationController?.containerView?.alpha = 0
presentedViewController?.view.alpha = 0
}
func SELappDidBecomeActiveNotification() {
// Re-show any components that might have been hidden because they were being displayed
// as part of a private mode tab
UIView.animate(withDuration: 0.2, delay: 0, options: UIViewAnimationOptions(), animations: {
self.webViewContainer.alpha = 1
self.urlBar.locationContainer.alpha = 1
self.topTabsViewController?.switchForegroundStatus(isInForeground: true)
self.presentedViewController?.popoverPresentationController?.containerView?.alpha = 1
self.presentedViewController?.view.alpha = 1
self.view.backgroundColor = UIColor.clear
}, completion: { _ in
self.webViewContainerBackdrop.alpha = 0
})
// Re-show toolbar which might have been hidden during scrolling (prior to app moving into the background)
scrollController.showToolbars(animated: false)
}
deinit {
NotificationCenter.default.removeObserver(self, name: NSNotification.Name(rawValue: BookmarkStatusChangedNotification), object: nil)
NotificationCenter.default.removeObserver(self, name: NSNotification.Name.UIApplicationWillResignActive, object: nil)
NotificationCenter.default.removeObserver(self, name: NSNotification.Name.UIApplicationWillEnterForeground, object: nil)
NotificationCenter.default.removeObserver(self, name: NSNotification.Name.UIApplicationDidEnterBackground, object: nil)
}
override func viewDidLoad() {
log.debug("BVC viewDidLoad…")
super.viewDidLoad()
log.debug("BVC super viewDidLoad called.")
NotificationCenter.default.addObserver(self, selector: #selector(BrowserViewController.SELBookmarkStatusDidChange(_:)), name: NSNotification.Name(rawValue: BookmarkStatusChangedNotification), object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(BrowserViewController.SELappWillResignActiveNotification), name: NSNotification.Name.UIApplicationWillResignActive, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(BrowserViewController.SELappDidBecomeActiveNotification), name: NSNotification.Name.UIApplicationDidBecomeActive, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(BrowserViewController.SELappDidEnterBackgroundNotification), name: NSNotification.Name.UIApplicationDidEnterBackground, object: nil)
KeyboardHelper.defaultHelper.addDelegate(self)
log.debug("BVC adding footer and header…")
footerBackdrop = UIView()
footerBackdrop.backgroundColor = UIColor.white
view.addSubview(footerBackdrop)
headerBackdrop = UIView()
headerBackdrop.backgroundColor = UIColor.white
view.addSubview(headerBackdrop)
log.debug("BVC setting up webViewContainer…")
webViewContainerBackdrop = UIView()
webViewContainerBackdrop.backgroundColor = UIColor.gray
webViewContainerBackdrop.alpha = 0
view.addSubview(webViewContainerBackdrop)
webViewContainer = UIView()
webViewContainer.addSubview(webViewContainerToolbar)
view.addSubview(webViewContainer)
log.debug("BVC setting up status bar…")
// Temporary work around for covering the non-clipped web view content
statusBarOverlay = UIView()
statusBarOverlay.backgroundColor = BrowserViewControllerUX.BackgroundColor
view.addSubview(statusBarOverlay)
log.debug("BVC setting up top touch area…")
topTouchArea = UIButton()
topTouchArea.isAccessibilityElement = false
topTouchArea.addTarget(self, action: #selector(BrowserViewController.SELtappedTopArea), for: UIControlEvents.touchUpInside)
view.addSubview(topTouchArea)
log.debug("BVC setting up URL bar…")
// Setup the URL bar, wrapped in a view to get transparency effect
urlBar = URLBarView()
urlBar.translatesAutoresizingMaskIntoConstraints = false
urlBar.delegate = self
urlBar.tabToolbarDelegate = self
header = BlurWrapper(view: urlBarTopTabsContainer)
urlBarTopTabsContainer.addSubview(urlBar)
urlBarTopTabsContainer.addSubview(topTabsContainer)
view.addSubview(header)
// UIAccessibilityCustomAction subclass holding an AccessibleAction instance does not work, thus unable to generate AccessibleActions and UIAccessibilityCustomActions "on-demand" and need to make them "persistent" e.g. by being stored in BVC
pasteGoAction = AccessibleAction(name: NSLocalizedString("Paste & Go", comment: "Paste the URL into the location bar and visit"), handler: { () -> Bool in
if let pasteboardContents = UIPasteboard.general.string {
self.urlBar(self.urlBar, didSubmitText: pasteboardContents)
return true
}
return false
})
pasteAction = AccessibleAction(name: NSLocalizedString("Paste", comment: "Paste the URL into the location bar"), handler: { () -> Bool in
if let pasteboardContents = UIPasteboard.general.string {
// Enter overlay mode and fire the text entered callback to make the search controller appear.
self.urlBar.enterOverlayMode(pasteboardContents, pasted: true)
self.urlBar(self.urlBar, didEnterText: pasteboardContents)
return true
}
return false
})
copyAddressAction = AccessibleAction(name: NSLocalizedString("Copy Address", comment: "Copy the URL from the location bar"), handler: { () -> Bool in
if let url = self.urlBar.currentURL {
UIPasteboard.general.url = url as URL
}
return true
})
log.debug("BVC setting up search loader…")
searchLoader = SearchLoader(profile: profile, urlBar: urlBar)
footer = UIView()
self.view.addSubview(footer)
self.view.addSubview(snackBars)
snackBars.backgroundColor = UIColor.clear
self.view.addSubview(findInPageContainer)
clipboardBarDisplayHandler = ClipboardBarDisplayHandler(prefs: profile.prefs)
clipboardBarDisplayHandler.delegate = self
scrollController.urlBar = urlBar
scrollController.header = header
scrollController.footer = footer
scrollController.snackBars = snackBars
scrollController.webViewContainerToolbar = webViewContainerToolbar
log.debug("BVC updating toolbar state…")
self.updateToolbarStateForTraitCollection(self.traitCollection)
log.debug("BVC setting up constraints…")
setupConstraints()
log.debug("BVC done.")
}
fileprivate func setupConstraints() {
topTabsContainer.snp.makeConstraints { make in
make.leading.trailing.equalTo(self.header)
make.top.equalTo(urlBarTopTabsContainer)
}
urlBar.snp.makeConstraints { make in
make.leading.trailing.bottom.equalTo(urlBarTopTabsContainer)
make.height.equalTo(UIConstants.ToolbarHeight)
make.top.equalTo(topTabsContainer.snp.bottom)
}
header.snp.makeConstraints { make in
scrollController.headerTopConstraint = make.top.equalTo(self.topLayoutGuide.snp.bottom).constraint
make.left.right.equalTo(self.view)
}
headerBackdrop.snp.makeConstraints { make in
make.edges.equalTo(self.header)
}
webViewContainerBackdrop.snp.makeConstraints { make in
make.edges.equalTo(webViewContainer)
}
webViewContainerToolbar.snp.makeConstraints { make in
make.left.right.top.equalTo(webViewContainer)
make.height.equalTo(0)
}
}
override func viewDidLayoutSubviews() {
log.debug("BVC viewDidLayoutSubviews…")
super.viewDidLayoutSubviews()
statusBarOverlay.snp.remakeConstraints { make in
make.top.left.right.equalTo(self.view)
make.height.equalTo(self.topLayoutGuide.length)
}
self.appDidUpdateState(getCurrentAppState())
log.debug("BVC done.")
}
func loadQueuedTabs() {
log.debug("Loading queued tabs in the background.")
// Chain off of a trivial deferred in order to run on the background queue.
succeed().upon() { res in
self.dequeueQueuedTabs()
}
}
fileprivate func dequeueQueuedTabs() {
assert(!Thread.current.isMainThread, "This must be called in the background.")
self.profile.queue.getQueuedTabs() >>== { cursor in
// This assumes that the DB returns rows in some kind of sane order.
// It does in practice, so WFM.
log.debug("Queue. Count: \(cursor.count).")
if cursor.count <= 0 {
return
}
let urls = cursor.flatMap { $0?.url.asURL }
if !urls.isEmpty {
DispatchQueue.main.async {
self.tabManager.addTabsForURLs(urls, zombie: false)
}
}
// Clear *after* making an attempt to open. We're making a bet that
// it's better to run the risk of perhaps opening twice on a crash,
// rather than losing data.
self.profile.queue.clearQueuedTabs()
}
}
// Because crashedLastLaunch is sticky, it does not get reset, we need to remember its
// value so that we do not keep asking the user to restore their tabs.
var displayedRestoreTabsAlert = false
override func viewWillAppear(_ animated: Bool) {
log.debug("BVC viewWillAppear.")
super.viewWillAppear(animated)
log.debug("BVC super.viewWillAppear done.")
// On iPhone, if we are about to show the On-Boarding, blank out the tab so that it does
// not flash before we present. This change of alpha also participates in the animation when
// the intro view is dismissed.
if UIDevice.current.userInterfaceIdiom == .phone {
self.view.alpha = (profile.prefs.intForKey(IntroViewControllerSeenProfileKey) != nil) ? 1.0 : 0.0
}
if !displayedRestoreTabsAlert && hasPendingCrashReport() {
displayedRestoreTabsAlert = true
showRestoreTabsAlert()
} else {
log.debug("Restoring tabs.")
tabManager.restoreTabs()
log.debug("Done restoring tabs.")
}
log.debug("Updating tab count.")
updateTabCountUsingTabManager(tabManager, animated: false)
clipboardBarDisplayHandler.checkIfShouldDisplayBar()
log.debug("BVC done.")
NotificationCenter.default.addObserver(self,
selector: #selector(BrowserViewController.openSettings),
name: NSNotification.Name(rawValue: NotificationStatusNotificationTapped),
object: nil)
}
fileprivate func hasPendingCrashReport() -> Bool {
return Client.shared?.crashedLastLaunch() ?? false
}
fileprivate func showRestoreTabsAlert() {
if !canRestoreTabs() {
self.tabManager.addTabAndSelect()
return
}
let alert = UIAlertController.restoreTabsAlert(
okayCallback: { _ in
self.tabManager.restoreTabs()
self.updateTabCountUsingTabManager(self.tabManager, animated: false)
},
noCallback: { _ in
self.tabManager.addTabAndSelect()
self.updateTabCountUsingTabManager(self.tabManager, animated: false)
}
)
self.present(alert, animated: true, completion: nil)
}
fileprivate func canRestoreTabs() -> Bool {
guard let tabsToRestore = TabManager.tabsToRestore() else { return false }
return tabsToRestore.count > 0
}
override func viewDidAppear(_ animated: Bool) {
log.debug("BVC viewDidAppear.")
presentIntroViewController()
log.debug("BVC intro presented.")
self.webViewContainerToolbar.isHidden = false
screenshotHelper.viewIsVisible = true
log.debug("BVC taking pending screenshots….")
screenshotHelper.takePendingScreenshots(tabManager.tabs)
log.debug("BVC done taking screenshots.")
log.debug("BVC calling super.viewDidAppear.")
super.viewDidAppear(animated)
log.debug("BVC done.")
if shouldShowWhatsNewTab() {
// Only display if the SUMO topic has been configured in the Info.plist (present and not empty)
if let whatsNewTopic = AppInfo.whatsNewTopic, whatsNewTopic != "" {
if let whatsNewURL = SupportUtils.URLForTopic(whatsNewTopic) {
self.openURLInNewTab(whatsNewURL, isPrivileged: false)
profile.prefs.setString(AppInfo.appVersion, forKey: LatestAppVersionProfileKey)
}
}
}
if let toast = self.pendingToast {
self.pendingToast = nil
show(buttonToast: toast, afterWaiting: ButtonToastUX.ToastDelay)
}
showQueuedAlertIfAvailable()
}
fileprivate func shouldShowWhatsNewTab() -> Bool {
guard let latestMajorAppVersion = profile.prefs.stringForKey(LatestAppVersionProfileKey)?.components(separatedBy: ".").first else {
return DeviceInfo.hasConnectivity()
}
return latestMajorAppVersion != AppInfo.majorAppVersion && DeviceInfo.hasConnectivity()
}
fileprivate func showQueuedAlertIfAvailable() {
if let queuedAlertInfo = tabManager.selectedTab?.dequeueJavascriptAlertPrompt() {
let alertController = queuedAlertInfo.alertController()
alertController.delegate = self
present(alertController, animated: true, completion: nil)
}
}
override func viewWillDisappear(_ animated: Bool) {
screenshotHelper.viewIsVisible = false
super.viewWillDisappear(animated)
}
override func viewDidDisappear(_ animated: Bool) {
super.viewDidDisappear(animated)
NotificationCenter.default.removeObserver(self, name: NSNotification.Name(rawValue: NotificationStatusNotificationTapped), object: nil)
}
func resetBrowserChrome() {
// animate and reset transform for tab chrome
urlBar.updateAlphaForSubviews(1)
footer.alpha = 1
[header,
footer,
readerModeBar,
footerBackdrop,
headerBackdrop].forEach { view in
view?.transform = CGAffineTransform.identity
}
}
override func updateViewConstraints() {
super.updateViewConstraints()
topTouchArea.snp.remakeConstraints { make in
make.top.left.right.equalTo(self.view)
make.height.equalTo(BrowserViewControllerUX.ShowHeaderTapAreaHeight)
}
readerModeBar?.snp.remakeConstraints { make in
make.top.equalTo(self.header.snp.bottom)
make.height.equalTo(UIConstants.ToolbarHeight)
make.leading.trailing.equalTo(self.view)
}
webViewContainer.snp.remakeConstraints { make in
make.left.right.equalTo(self.view)
if let readerModeBarBottom = readerModeBar?.snp.bottom {
make.top.equalTo(readerModeBarBottom)
} else {
make.top.equalTo(self.header.snp.bottom)
}
let findInPageHeight = (findInPageBar == nil) ? 0 : UIConstants.ToolbarHeight
if let toolbar = self.toolbar {
make.bottom.equalTo(toolbar.snp.top).offset(-findInPageHeight)
} else {
make.bottom.equalTo(self.view).offset(-findInPageHeight)
}
}
// Setup the bottom toolbar
toolbar?.snp.remakeConstraints { make in
make.edges.equalTo(self.footerBackground!)
make.height.equalTo(UIConstants.ToolbarHeight)
}
footer.snp.remakeConstraints { make in
scrollController.footerBottomConstraint = make.bottom.equalTo(self.view.snp.bottom).constraint
make.top.equalTo(self.snackBars.snp.top)
make.leading.trailing.equalTo(self.view)
}
footerBackdrop.snp.remakeConstraints { make in
make.edges.equalTo(self.footer)
}
updateSnackBarConstraints()
footerBackground?.snp.remakeConstraints { make in
make.bottom.left.right.equalTo(self.footer)
make.height.equalTo(UIConstants.ToolbarHeight)
}
urlBar.setNeedsUpdateConstraints()
// Remake constraints even if we're already showing the home controller.
// The home controller may change sizes if we tap the URL bar while on about:home.
homePanelController?.view.snp.remakeConstraints { make in
make.top.equalTo(self.urlBar.snp.bottom)
make.left.right.equalTo(self.view)
if self.homePanelIsInline {
make.bottom.equalTo(self.toolbar?.snp.top ?? self.view.snp.bottom)
} else {
make.bottom.equalTo(self.view.snp.bottom)
}
}
findInPageContainer.snp.remakeConstraints { make in
make.left.right.equalTo(self.view)
if let keyboardHeight = keyboardState?.intersectionHeightForView(self.view), keyboardHeight > 0 {
make.bottom.equalTo(self.view).offset(-keyboardHeight)
} else if let toolbar = self.toolbar {
make.bottom.equalTo(toolbar.snp.top)
} else {
make.bottom.equalTo(self.view)
}
}
}
fileprivate func showHomePanelController(inline: Bool) {
log.debug("BVC showHomePanelController.")
homePanelIsInline = inline
if homePanelController == nil {
let homePanelController = HomePanelViewController()
homePanelController.profile = profile
homePanelController.delegate = self
homePanelController.appStateDelegate = self
homePanelController.url = tabManager.selectedTab?.url?.displayURL
homePanelController.view.alpha = 0
self.homePanelController = homePanelController
addChildViewController(homePanelController)
view.addSubview(homePanelController.view)
homePanelController.didMove(toParentViewController: self)
}
guard let homePanelController = self.homePanelController else {
assertionFailure("homePanelController is still nil after assignment.")
return
}
let panelNumber = tabManager.selectedTab?.url?.fragment
// splitting this out to see if we can get better crash reports when this has a problem
var newSelectedButtonIndex = 0
if let numberArray = panelNumber?.components(separatedBy: "=") {
if let last = numberArray.last, let lastInt = Int(last) {
newSelectedButtonIndex = lastInt
}
}
homePanelController.selectedPanel = HomePanelType(rawValue: newSelectedButtonIndex)
homePanelController.isPrivateMode = tabManager.selectedTab?.isPrivate ?? false
// We have to run this animation, even if the view is already showing because there may be a hide animation running
// and we want to be sure to override its results.
UIView.animate(withDuration: 0.2, animations: { () -> Void in
homePanelController.view.alpha = 1
}, completion: { finished in
if finished {
self.webViewContainer.accessibilityElementsHidden = true
UIAccessibilityPostNotification(UIAccessibilityScreenChangedNotification, nil)
}
})
view.setNeedsUpdateConstraints()
log.debug("BVC done with showHomePanelController.")
}
fileprivate func hideHomePanelController() {
if let controller = homePanelController {
self.homePanelController = nil
UIView.animate(withDuration: 0.2, delay: 0, options: .beginFromCurrentState, animations: { () -> Void in
controller.view.alpha = 0
}, completion: { _ in
controller.willMove(toParentViewController: nil)
controller.view.removeFromSuperview()
controller.removeFromParentViewController()
self.webViewContainer.accessibilityElementsHidden = false
UIAccessibilityPostNotification(UIAccessibilityScreenChangedNotification, nil)
// Refresh the reading view toolbar since the article record may have changed
if let readerMode = self.tabManager.selectedTab?.getHelper(name: ReaderMode.name()) as? ReaderMode, readerMode.state == .active {
self.showReaderModeBar(animated: false)
}
})
}
}
fileprivate func updateInContentHomePanel(_ url: URL?) {
if !urlBar.inOverlayMode {
if let url = url, url.isAboutHomeURL {
showHomePanelController(inline: true)
} else {
hideHomePanelController()
}
}
}
fileprivate func showSearchController() {
if searchController != nil {
return
}
let isPrivate = tabManager.selectedTab?.isPrivate ?? false
searchController = SearchViewController(isPrivate: isPrivate)
searchController!.searchEngines = profile.searchEngines
searchController!.searchDelegate = self
searchController!.profile = self.profile
searchLoader.addListener(searchController!)
addChildViewController(searchController!)
view.addSubview(searchController!.view)
searchController!.view.snp.makeConstraints { make in
make.top.equalTo(self.urlBar.snp.bottom)
make.left.right.bottom.equalTo(self.view)
return
}
homePanelController?.view?.isHidden = true
searchController!.didMove(toParentViewController: self)
}
fileprivate func hideSearchController() {
if let searchController = searchController {
searchController.willMove(toParentViewController: nil)
searchController.view.removeFromSuperview()
searchController.removeFromParentViewController()
self.searchController = nil
homePanelController?.view?.isHidden = false
}
}
fileprivate func finishEditingAndSubmit(_ url: URL, visitType: VisitType) {
urlBar.currentURL = url
urlBar.leaveOverlayMode()
guard let tab = tabManager.selectedTab else {
return
}
if let webView = tab.webView {
resetSpoofedUserAgentIfRequired(webView, newURL: url)
}
if let nav = tab.loadRequest(PrivilegedRequest(url: url) as URLRequest) {
self.recordNavigationInTab(tab, navigation: nav, visitType: visitType)
}
}
func addBookmark(_ tabState: TabState) {
guard let url = tabState.url else { return }
let absoluteString = url.absoluteString
let shareItem = ShareItem(url: absoluteString, title: tabState.title, favicon: tabState.favicon)
profile.bookmarks.shareItem(shareItem)
var userData = [QuickActions.TabURLKey: shareItem.url]
if let title = shareItem.title {
userData[QuickActions.TabTitleKey] = title
}
QuickActions.sharedInstance.addDynamicApplicationShortcutItemOfType(.openLastBookmark,
withUserData: userData,
toApplication: UIApplication.shared)
if let tab = tabManager.getTabForURL(url) {
tab.isBookmarked = true
}
}
fileprivate func animateBookmarkStar() {
let offset: CGFloat
let button: UIButton!
if let toolbar: TabToolbar = self.toolbar {
offset = BrowserViewControllerUX.BookmarkStarAnimationOffset * -1
button = toolbar.bookmarkButton
} else {
offset = BrowserViewControllerUX.BookmarkStarAnimationOffset
button = self.urlBar.bookmarkButton
}
JumpAndSpinAnimator.animateFromView(button.imageView ?? button, offset: offset, completion: nil)
}
fileprivate func removeBookmark(_ tabState: TabState) {
guard let url = tabState.url else { return }
let absoluteString = url.absoluteString
profile.bookmarks.modelFactory >>== {
$0.removeByURL(absoluteString)
.uponQueue(DispatchQueue.main) { res in
if res.isSuccess {
if let tab = self.tabManager.getTabForURL(url) {
tab.isBookmarked = false
}
}
}
}
}
func SELBookmarkStatusDidChange(_ notification: Notification) {
if let bookmark = notification.object as? BookmarkItem {
if bookmark.url == urlBar.currentURL?.absoluteString {
if let userInfo = notification.userInfo as? Dictionary<String, Bool> {
if userInfo["added"] != nil {
if let tab = self.tabManager.getTabForURL(urlBar.currentURL!) {
tab.isBookmarked = false
}
}
}
}
}
}
override func accessibilityPerformEscape() -> Bool {
if urlBar.inOverlayMode {
urlBar.SELdidClickCancel()
return true
} else if let selectedTab = tabManager.selectedTab, selectedTab.canGoBack {
selectedTab.goBack()
return true
}
return false
}
override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey: Any]?, context: UnsafeMutableRawPointer?) {
let webView = object as! WKWebView
guard let path = keyPath else { assertionFailure("Unhandled KVO key: \(keyPath ?? "nil")"); return }
switch path {
case KVOEstimatedProgress:
guard webView == tabManager.selectedTab?.webView,
let progress = change?[NSKeyValueChangeKey.newKey] as? Float else { break }
urlBar.updateProgressBar(progress)
case KVOLoading:
guard let loading = change?[NSKeyValueChangeKey.newKey] as? Bool else { break }
if webView == tabManager.selectedTab?.webView {
navigationToolbar.updateReloadStatus(loading)
}
if !loading {
runScriptsOnWebView(webView)
}
case KVOURL:
guard let tab = tabManager[webView] else { break }
// To prevent spoofing, only change the URL immediately if the new URL is on
// the same origin as the current URL. Otherwise, do nothing and wait for
// didCommitNavigation to confirm the page load.
if tab.url?.origin == webView.url?.origin {
tab.url = webView.url
if tab === tabManager.selectedTab && !tab.restoring {
updateUIForReaderHomeStateForTab(tab)
}
}
case KVOTitle:
guard let tab = tabManager[webView] else { break }
// Ensure that the tab title *actually* changed to prevent repeated calls
// to navigateInTab(tab:).
guard let title = tab.title else { break }
if !title.isEmpty && title != tab.lastTitle {
navigateInTab(tab: tab)
}
case KVOCanGoBack:
guard webView == tabManager.selectedTab?.webView,
let canGoBack = change?[NSKeyValueChangeKey.newKey] as? Bool else { break }
navigationToolbar.updateBackStatus(canGoBack)
case KVOCanGoForward:
guard webView == tabManager.selectedTab?.webView,
let canGoForward = change?[NSKeyValueChangeKey.newKey] as? Bool else { break }
navigationToolbar.updateForwardStatus(canGoForward)
default:
assertionFailure("Unhandled KVO key: \(keyPath ?? "nil")")
}
}
fileprivate func runScriptsOnWebView(_ webView: WKWebView) {
webView.evaluateJavaScript("__firefox__.favicons.getFavicons()", completionHandler: nil)
if AppConstants.MOZ_CONTENT_METADATA_PARSING {
webView.evaluateJavaScript("__firefox__.metadata.extractMetadata()", completionHandler: nil)
}
}
fileprivate func updateUIForReaderHomeStateForTab(_ tab: Tab) {
updateURLBarDisplayURL(tab)
scrollController.showToolbars(animated: false)
if let url = tab.url {
if url.isReaderModeURL {
showReaderModeBar(animated: false)
NotificationCenter.default.addObserver(self, selector: #selector(BrowserViewController.SELDynamicFontChanged(_:)), name: NotificationDynamicFontChanged, object: nil)
} else {
hideReaderModeBar(animated: false)
NotificationCenter.default.removeObserver(self, name: NotificationDynamicFontChanged, object: nil)
}
updateInContentHomePanel(url as URL)
}
}
fileprivate func isWhitelistedUrl(_ url: URL) -> Bool {
for entry in WhiteListedUrls {
if let _ = url.absoluteString.range(of: entry, options: .regularExpression) {
return UIApplication.shared.canOpenURL(url)
}
}
return false
}
/// Updates the URL bar text and button states.
/// Call this whenever the page URL changes.
fileprivate func updateURLBarDisplayURL(_ tab: Tab) {
urlBar.currentURL = tab.url?.displayURL
let isPage = tab.url?.displayURL?.isWebPage() ?? false
navigationToolbar.updatePageStatus(isPage)
guard let url = tab.url?.displayURL?.absoluteString else {
return
}
profile.bookmarks.modelFactory >>== {
$0.isBookmarked(url).uponQueue(DispatchQueue.main) { [weak tab] result in
guard let bookmarked = result.successValue else {
log.error("Error getting bookmark status: \(result.failureValue ??? "nil").")
return
}
tab?.isBookmarked = bookmarked
}
}
}
// Mark: Opening New Tabs
func switchToPrivacyMode(isPrivate: Bool ) {
applyTheme(isPrivate ? Theme.PrivateMode : Theme.NormalMode)
let tabTrayController = self.tabTrayController ?? TabTrayController(tabManager: tabManager, profile: profile, tabTrayDelegate: self)
if tabTrayController.privateMode != isPrivate {
tabTrayController.changePrivacyMode(isPrivate)
}
self.tabTrayController = tabTrayController
}
func switchToTabForURLOrOpen(_ url: URL, isPrivate: Bool = false, isPrivileged: Bool) {
popToBVC()
if let tab = tabManager.getTabForURL(url) {
tabManager.selectTab(tab)
} else {
openURLInNewTab(url, isPrivate: isPrivate, isPrivileged: isPrivileged)
}
}
func openURLInNewTab(_ url: URL?, isPrivate: Bool = false, isPrivileged: Bool) {
if let selectedTab = tabManager.selectedTab {
screenshotHelper.takeScreenshot(selectedTab)
}
let request: URLRequest?
if let url = url {
request = isPrivileged ? PrivilegedRequest(url: url) as URLRequest : URLRequest(url: url)
} else {
request = nil
}
switchToPrivacyMode(isPrivate: isPrivate)
_ = tabManager.addTabAndSelect(request, isPrivate: isPrivate)
if url == nil && NewTabAccessors.getNewTabPage(profile.prefs) == .blankPage {
urlBar.tabLocationViewDidTapLocation(urlBar.locationView)
}
}
func openBlankNewTab(isPrivate: Bool = false) {
popToBVC()
openURLInNewTab(nil, isPrivate: isPrivate, isPrivileged: true)
}
fileprivate func popToBVC() {
guard let currentViewController = navigationController?.topViewController else {
return
}
currentViewController.dismiss(animated: true, completion: nil)
if currentViewController != self {
_ = self.navigationController?.popViewController(animated: true)
} else if urlBar.inOverlayMode {
urlBar.SELdidClickCancel()
}
}
// Mark: User Agent Spoofing
fileprivate func resetSpoofedUserAgentIfRequired(_ webView: WKWebView, newURL: URL) {
// Reset the UA when a different domain is being loaded
if webView.url?.host != newURL.host {
webView.customUserAgent = nil
}
}
fileprivate func restoreSpoofedUserAgentIfRequired(_ webView: WKWebView, newRequest: URLRequest) {
// Restore any non-default UA from the request's header
let ua = newRequest.value(forHTTPHeaderField: "User-Agent")
webView.customUserAgent = ua != UserAgent.defaultUserAgent() ? ua : nil
}
fileprivate func presentActivityViewController(_ url: URL, tab: Tab? = nil, sourceView: UIView?, sourceRect: CGRect, arrowDirection: UIPopoverArrowDirection) {
var activities = [UIActivity]()
let findInPageActivity = FindInPageActivity() { [unowned self] in
self.updateFindInPageVisibility(visible: true)
}
activities.append(findInPageActivity)
if let tab = tab, (tab.getHelper(name: ReaderMode.name()) as? ReaderMode)?.state != .active {
let requestDesktopSiteActivity = RequestDesktopSiteActivity(requestMobileSite: tab.desktopSite) { [unowned tab] in
tab.toggleDesktopSite()
}
activities.append(requestDesktopSiteActivity)
}
let helper = ShareExtensionHelper(url: url, tab: tab, activities: activities)
let controller = helper.createActivityViewController({ [unowned self] completed, _ in
// After dismissing, check to see if there were any prompts we queued up
self.showQueuedAlertIfAvailable()
// Usually the popover delegate would handle nil'ing out the references we have to it
// on the BVC when displaying as a popover but the delegate method doesn't seem to be
// invoked on iOS 10. See Bug 1297768 for additional details.
self.displayedPopoverController = nil
self.updateDisplayedPopoverProperties = nil
if completed {
// We don't know what share action the user has chosen so we simply always
// update the toolbar and reader mode bar to reflect the latest status.
if let tab = tab {
self.updateURLBarDisplayURL(tab)
}
self.updateReaderModeBar()
}
})
if let popoverPresentationController = controller.popoverPresentationController {
popoverPresentationController.sourceView = sourceView
popoverPresentationController.sourceRect = sourceRect
popoverPresentationController.permittedArrowDirections = arrowDirection
popoverPresentationController.delegate = self
}
self.present(controller, animated: true, completion: nil)
}
fileprivate func updateFindInPageVisibility(visible: Bool) {
if visible {
if findInPageBar == nil {
let findInPageBar = FindInPageBar()
self.findInPageBar = findInPageBar
findInPageBar.delegate = self
findInPageContainer.addSubview(findInPageBar)
findInPageBar.snp.makeConstraints { make in
make.edges.equalTo(findInPageContainer)
make.height.equalTo(UIConstants.ToolbarHeight)
}
updateViewConstraints()
// We make the find-in-page bar the first responder below, causing the keyboard delegates
// to fire. This, in turn, will animate the Find in Page container since we use the same
// delegate to slide the bar up and down with the keyboard. We don't want to animate the
// constraints added above, however, so force a layout now to prevent these constraints
// from being lumped in with the keyboard animation.
findInPageBar.layoutIfNeeded()
}
self.findInPageBar?.becomeFirstResponder()
} else if let findInPageBar = self.findInPageBar {
findInPageBar.endEditing(true)
guard let webView = tabManager.selectedTab?.webView else { return }
webView.evaluateJavaScript("__firefox__.findDone()", completionHandler: nil)
findInPageBar.removeFromSuperview()
self.findInPageBar = nil
updateViewConstraints()
}
}
override var canBecomeFirstResponder: Bool {
return true
}
override func becomeFirstResponder() -> Bool {
// Make the web view the first responder so that it can show the selection menu.
return tabManager.selectedTab?.webView?.becomeFirstResponder() ?? false
}
func reloadTab() {
if homePanelController == nil {
tabManager.selectedTab?.reload()
}
}
func goBack() {
if tabManager.selectedTab?.canGoBack == true && homePanelController == nil {
tabManager.selectedTab?.goBack()
}
}
func goForward() {
if tabManager.selectedTab?.canGoForward == true && homePanelController == nil {
tabManager.selectedTab?.goForward()
}
}
func findOnPage() {
if homePanelController == nil {
tab( (tabManager.selectedTab)!, didSelectFindInPageForSelection: "")
}
}
func selectLocationBar() {
scrollController.showToolbars(animated: true)
urlBar.tabLocationViewDidTapLocation(urlBar.locationView)
}
func newTab() {
openBlankNewTab(isPrivate: false)
}
func newPrivateTab() {
openBlankNewTab(isPrivate: true)
}
func closeTab() {
guard let currentTab = tabManager.selectedTab else {
return
}
tabManager.removeTab(currentTab)
}
func nextTab() {
guard let currentTab = tabManager.selectedTab else {
return
}
let tabs = currentTab.isPrivate ? tabManager.privateTabs : tabManager.normalTabs
if let index = tabs.index(of: currentTab), index + 1 < tabs.count {
tabManager.selectTab(tabs[index + 1])
} else if let firstTab = tabs.first {
tabManager.selectTab(firstTab)
}
}
func previousTab() {
guard let currentTab = tabManager.selectedTab else {
return
}
let tabs = currentTab.isPrivate ? tabManager.privateTabs : tabManager.normalTabs
if let index = tabs.index(of: currentTab), index - 1 < tabs.count && index != 0 {
tabManager.selectTab(tabs[index - 1])
} else if let lastTab = tabs.last {
tabManager.selectTab(lastTab)
}
}
override var keyCommands: [UIKeyCommand]? {
return [
UIKeyCommand(input: "r", modifierFlags: .command, action: #selector(BrowserViewController.reloadTab), discoverabilityTitle: Strings.ReloadPageTitle),
UIKeyCommand(input: "[", modifierFlags: .command, action: #selector(BrowserViewController.goBack), discoverabilityTitle: Strings.BackTitle),
UIKeyCommand(input: UIKeyInputLeftArrow, modifierFlags: .command, action: #selector(BrowserViewController.goBack), discoverabilityTitle: Strings.BackTitle),
UIKeyCommand(input: "]", modifierFlags: .command, action: #selector(BrowserViewController.goForward), discoverabilityTitle: Strings.ForwardTitle),
UIKeyCommand(input: UIKeyInputRightArrow, modifierFlags: .command, action: #selector(BrowserViewController.goForward), discoverabilityTitle: Strings.ForwardTitle),
UIKeyCommand(input: "f", modifierFlags: .command, action: #selector(BrowserViewController.findOnPage), discoverabilityTitle: Strings.FindTitle),
UIKeyCommand(input: "l", modifierFlags: .command, action: #selector(BrowserViewController.selectLocationBar), discoverabilityTitle: Strings.SelectLocationBarTitle),
UIKeyCommand(input: "t", modifierFlags: .command, action: #selector(BrowserViewController.newTab), discoverabilityTitle: Strings.NewTabTitle),
UIKeyCommand(input: "p", modifierFlags: [.command, .shift], action: #selector(BrowserViewController.newPrivateTab), discoverabilityTitle: Strings.NewPrivateTabTitle),
UIKeyCommand(input: "w", modifierFlags: .command, action: #selector(BrowserViewController.closeTab), discoverabilityTitle: Strings.CloseTabTitle),
UIKeyCommand(input: "\t", modifierFlags: .control, action: #selector(BrowserViewController.nextTab), discoverabilityTitle: Strings.ShowNextTabTitle),
UIKeyCommand(input: UIKeyInputRightArrow, modifierFlags: [.command, .shift], action: #selector(BrowserViewController.nextTab), discoverabilityTitle: Strings.ShowNextTabTitle),
UIKeyCommand(input: "\t", modifierFlags: [.control, .shift], action: #selector(BrowserViewController.previousTab), discoverabilityTitle: Strings.ShowPreviousTabTitle),
UIKeyCommand(input: UIKeyInputLeftArrow, modifierFlags: [.command, .shift], action: #selector(BrowserViewController.previousTab), discoverabilityTitle: Strings.ShowPreviousTabTitle),
]
}
fileprivate func getCurrentAppState() -> AppState {
return mainStore.updateState(getCurrentUIState())
}
fileprivate func getCurrentUIState() -> UIState {
if let homePanelController = homePanelController {
return .homePanels(homePanelState: homePanelController.homePanelState)
}
guard let tab = tabManager.selectedTab else {
return .loading
}
if tab.url == nil {
return .emptyTab
}
return .tab(tabState: tab.tabState)
}
@objc fileprivate func openSettings() {
assert(Thread.isMainThread, "Opening settings requires being invoked on the main thread")
let settingsTableViewController = AppSettingsTableViewController()
settingsTableViewController.profile = profile
settingsTableViewController.tabManager = tabManager
settingsTableViewController.settingsDelegate = self
let controller = SettingsNavigationController(rootViewController: settingsTableViewController)
controller.popoverDelegate = self
controller.modalPresentationStyle = UIModalPresentationStyle.formSheet
self.present(controller, animated: true, completion: nil)
}
fileprivate func navigateInTab(tab: Tab, to navigation: WKNavigation? = nil) {
tabManager.expireSnackbars()
guard let webView = tab.webView else {
log.warning("Cannot navigate in tab without a webView")
return
}
if let url = webView.url, !url.isErrorPageURL && !url.isAboutHomeURL {
tab.lastExecutedTime = Date.now()
if navigation == nil {
log.warning("Implicitly unwrapped optional navigation was nil.")
}
postLocationChangeNotificationForTab(tab, navigation: navigation)
// Fire the readability check. This is here and not in the pageShow event handler in ReaderMode.js anymore
// because that event wil not always fire due to unreliable page caching. This will either let us know that
// the currently loaded page can be turned into reading mode or if the page already is in reading mode. We
// ignore the result because we are being called back asynchronous when the readermode status changes.
webView.evaluateJavaScript("\(ReaderModeNamespace).checkReadability()", completionHandler: nil)
// Re-run additional scripts in webView to extract updated favicons and metadata.
runScriptsOnWebView(webView)
}
if tab === tabManager.selectedTab {
UIAccessibilityPostNotification(UIAccessibilityScreenChangedNotification, nil)
// must be followed by LayoutChanged, as ScreenChanged will make VoiceOver
// cursor land on the correct initial element, but if not followed by LayoutChanged,
// VoiceOver will sometimes be stuck on the element, not allowing user to move
// forward/backward. Strange, but LayoutChanged fixes that.
UIAccessibilityPostNotification(UIAccessibilityLayoutChangedNotification, nil)
} else {
// To Screenshot a tab that is hidden we must add the webView,
// then wait enough time for the webview to render.
if let webView = tab.webView {
view.insertSubview(webView, at: 0)
let time = DispatchTime.now() + Double(Int64(500 * NSEC_PER_MSEC)) / Double(NSEC_PER_SEC)
DispatchQueue.main.asyncAfter(deadline: time) {
self.screenshotHelper.takeScreenshot(tab)
if webView.superview == self.view {
webView.removeFromSuperview()
}
}
}
}
// Remember whether or not a desktop site was requested
tab.desktopSite = webView.customUserAgent?.isEmpty == false
}
}
extension BrowserViewController: ClipboardBarDisplayHandlerDelegate {
func shouldDisplay(clipboardBar bar: ButtonToast) {
show(buttonToast: bar, duration: ClipboardBarToastUX.ToastDelay)
}
}
extension BrowserViewController: AppStateDelegate {
func appDidUpdateState(_ appState: AppState) {
menuViewController?.appState = appState
toolbar?.appDidUpdateState(appState)
urlBar?.appDidUpdateState(appState)
}
}
extension BrowserViewController: MenuActionDelegate {
func performMenuAction(_ action: MenuAction, withAppState appState: AppState) {
if let menuAction = AppMenuAction(rawValue: action.action) {
switch menuAction {
case .openNewNormalTab:
self.openURLInNewTab(nil, isPrivate: false, isPrivileged: true)
//LeanplumIntegration.sharedInstance.track(eventName: .openedNewTab, withParameters: ["Source": "Menu" as AnyObject])
// this is a case that is only available in iOS9
case .openNewPrivateTab:
self.openURLInNewTab(nil, isPrivate: true, isPrivileged: true)
case .findInPage:
self.updateFindInPageVisibility(visible: true)
case .toggleBrowsingMode:
guard let tab = tabManager.selectedTab else { break }
tab.toggleDesktopSite()
case .toggleBookmarkStatus:
switch appState.ui {
case .tab(let tabState):
self.toggleBookmarkForTabState(tabState)
default: break
}
case .showImageMode:
self.setNoImageMode(false)
case .hideImageMode:
self.setNoImageMode(true)
case .showNightMode:
NightModeHelper.setNightMode(self.profile.prefs, tabManager: self.tabManager, enabled: false)
case .hideNightMode:
NightModeHelper.setNightMode(self.profile.prefs, tabManager: self.tabManager, enabled: true)
case .scanQRCode:
self.scanQRCode()
case .openSettings:
self.openSettings()
case .openTopSites:
openHomePanel(.topSites, forAppState: appState)
case .openBookmarks:
openHomePanel(.bookmarks, forAppState: appState)
case .openHistory:
openHomePanel(.history, forAppState: appState)
case .openReadingList:
openHomePanel(.readingList, forAppState: appState)
case .setHomePage:
guard let tab = tabManager.selectedTab else { break }
HomePageHelper(prefs: profile.prefs).setHomePage(toTab: tab, withNavigationController: navigationController)
case .openHomePage:
guard let tab = tabManager.selectedTab else { break }
HomePageHelper(prefs: profile.prefs).openHomePage(inTab: tab, withNavigationController: navigationController)
case .sharePage:
guard let url = tabManager.selectedTab?.url else { break }
let sourceView = self.navigationToolbar.menuButton
let tab = tabManager.selectedTab
presentActivityViewController(url as URL, tab: tab, sourceView: sourceView.superview, sourceRect: sourceView.frame, arrowDirection: .up)
default: break
}
}
}
fileprivate func openHomePanel(_ panel: HomePanelType, forAppState appState: AppState) {
switch appState.ui {
case .tab(_):
self.openURLInNewTab(panel.localhostURL as URL, isPrivate: appState.ui.isPrivate(), isPrivileged: true)
case .homePanels(_):
self.homePanelController?.selectedPanel = panel
default: break
}
}
fileprivate func scanQRCode() {
let qrCodeViewController = QRCodeViewController()
qrCodeViewController.qrCodeDelegate = self
let controller = UINavigationController(rootViewController: qrCodeViewController)
self.present(controller, animated: true, completion: nil)
}
}
extension BrowserViewController: QRCodeViewControllerDelegate {
func scanSuccessOpenNewTabWithData(data: String) {
self.openBlankNewTab()
self.urlBar(self.urlBar, didSubmitText: data)
}
}
extension BrowserViewController: SettingsDelegate {
func settingsOpenURLInNewTab(_ url: URL) {
self.openURLInNewTab(url, isPrivileged: false)
}
}
extension BrowserViewController: PresentingModalViewControllerDelegate {
func dismissPresentedModalViewController(_ modalViewController: UIViewController, animated: Bool) {
self.appDidUpdateState(getCurrentAppState())
self.dismiss(animated: animated, completion: nil)
}
}
/**
* History visit management.
* TODO: this should be expanded to track various visit types; see Bug 1166084.
*/
extension BrowserViewController {
func ignoreNavigationInTab(_ tab: Tab, navigation: WKNavigation) {
self.ignoredNavigation.insert(navigation)
}
func recordNavigationInTab(_ tab: Tab, navigation: WKNavigation, visitType: VisitType) {
self.typedNavigation[navigation] = visitType
}
/**
* Untrack and do the right thing.
*/
func getVisitTypeForTab(_ tab: Tab, navigation: WKNavigation?) -> VisitType? {
guard let navigation = navigation else {
// See https://github.com/WebKit/webkit/blob/master/Source/WebKit2/UIProcess/Cocoa/NavigationState.mm#L390
return VisitType.link
}
if let _ = self.ignoredNavigation.remove(navigation) {
return nil
}
return self.typedNavigation.removeValue(forKey: navigation) ?? VisitType.link
}
}
extension BrowserViewController: URLBarDelegate {
func urlBarDidPressReload(_ urlBar: URLBarView) {
tabManager.selectedTab?.reload()
}
func urlBarDidPressStop(_ urlBar: URLBarView) {
tabManager.selectedTab?.stop()
}
func urlBarDidPressTabs(_ urlBar: URLBarView) {
self.webViewContainerToolbar.isHidden = true
updateFindInPageVisibility(visible: false)
let tabTrayController = TabTrayController(tabManager: tabManager, profile: profile, tabTrayDelegate: self)
if let tab = tabManager.selectedTab {
screenshotHelper.takeScreenshot(tab)
}
self.navigationController?.pushViewController(tabTrayController, animated: true)
self.tabTrayController = tabTrayController
}
func urlBarDidPressReaderMode(_ urlBar: URLBarView) {
if let tab = tabManager.selectedTab {
if let readerMode = tab.getHelper(name: "ReaderMode") as? ReaderMode {
switch readerMode.state {
case .available:
enableReaderMode()
case .active:
disableReaderMode()
case .unavailable:
break
}
}
}
}
func urlBarDidLongPressReaderMode(_ urlBar: URLBarView) -> Bool {
guard let tab = tabManager.selectedTab,
let url = tab.url?.displayURL,
let result = profile.readingList?.createRecordWithURL(url.absoluteString, title: tab.title ?? "", addedBy: UIDevice.current.name)
else {
UIAccessibilityPostNotification(UIAccessibilityAnnouncementNotification, NSLocalizedString("Could not add page to Reading list", comment: "Accessibility message e.g. spoken by VoiceOver after adding current webpage to the Reading List failed."))
return false
}
switch result {
case .success:
UIAccessibilityPostNotification(UIAccessibilityAnnouncementNotification, NSLocalizedString("Added page to Reading List", comment: "Accessibility message e.g. spoken by VoiceOver after the current page gets added to the Reading List using the Reader View button, e.g. by long-pressing it or by its accessibility custom action."))
// TODO: https://bugzilla.mozilla.org/show_bug.cgi?id=1158503 provide some form of 'this has been added' visual feedback?
case .failure(let error):
UIAccessibilityPostNotification(UIAccessibilityAnnouncementNotification, NSLocalizedString("Could not add page to Reading List. Maybe it's already there?", comment: "Accessibility message e.g. spoken by VoiceOver after the user wanted to add current page to the Reading List and this was not done, likely because it already was in the Reading List, but perhaps also because of real failures."))
log.error("readingList.createRecordWithURL(url: \"\(url.absoluteString)\", ...) failed with error: \(error)")
}
return true
}
func locationActionsForURLBar(_ urlBar: URLBarView) -> [AccessibleAction] {
if UIPasteboard.general.string != nil {
return [pasteGoAction, pasteAction, copyAddressAction]
} else {
return [copyAddressAction]
}
}
func urlBarDisplayTextForURL(_ url: URL?) -> String? {
// use the initial value for the URL so we can do proper pattern matching with search URLs
var searchURL = self.tabManager.selectedTab?.currentInitialURL
if searchURL?.isErrorPageURL ?? true {
searchURL = url
}
return profile.searchEngines.queryForSearchURL(searchURL as URL?) ?? url?.absoluteString
}
func urlBarDidLongPressLocation(_ urlBar: URLBarView) {
let longPressAlertController = UIAlertController(title: nil, message: nil, preferredStyle: .actionSheet)
for action in locationActionsForURLBar(urlBar) {
longPressAlertController.addAction(action.alertAction(style: .default))
}
let cancelAction = UIAlertAction(title: NSLocalizedString("Cancel", comment: "Label for Cancel button"), style: .cancel, handler: { (alert: UIAlertAction) -> Void in
})
longPressAlertController.addAction(cancelAction)
let setupPopover = { [unowned self] in
if let popoverPresentationController = longPressAlertController.popoverPresentationController {
popoverPresentationController.sourceView = urlBar
popoverPresentationController.sourceRect = urlBar.frame
popoverPresentationController.permittedArrowDirections = .any
popoverPresentationController.delegate = self
}
}
setupPopover()
if longPressAlertController.popoverPresentationController != nil {
displayedPopoverController = longPressAlertController
updateDisplayedPopoverProperties = setupPopover
}
self.present(longPressAlertController, animated: true, completion: nil)
}
func urlBarDidPressScrollToTop(_ urlBar: URLBarView) {
if let selectedTab = tabManager.selectedTab {
// Only scroll to top if we are not showing the home view controller
if homePanelController == nil {
selectedTab.webView?.scrollView.setContentOffset(CGPoint.zero, animated: true)
}
}
}
func urlBarLocationAccessibilityActions(_ urlBar: URLBarView) -> [UIAccessibilityCustomAction]? {
return locationActionsForURLBar(urlBar).map { $0.accessibilityCustomAction }
}
func urlBar(_ urlBar: URLBarView, didEnterText text: String) {
searchLoader.query = text
if text.isEmpty {
hideSearchController()
} else {
showSearchController()
searchController!.searchQuery = text
}
}
func urlBar(_ urlBar: URLBarView, didSubmitText text: String) {
if let fixupURL = URIFixup.getURL(text) {
// The user entered a URL, so use it.
finishEditingAndSubmit(fixupURL, visitType: VisitType.typed)
return
}
// We couldn't build a URL, so check for a matching search keyword.
let trimmedText = text.trimmingCharacters(in: CharacterSet.whitespaces)
guard let possibleKeywordQuerySeparatorSpace = trimmedText.characters.index(of: " ") else {
submitSearchText(text)
return
}
let possibleKeyword = trimmedText.substring(to: possibleKeywordQuerySeparatorSpace)
let possibleQuery = trimmedText.substring(from: trimmedText.index(after: possibleKeywordQuerySeparatorSpace))
profile.bookmarks.getURLForKeywordSearch(possibleKeyword).uponQueue(DispatchQueue.main) { result in
if var urlString = result.successValue,
let escapedQuery = possibleQuery.addingPercentEncoding(withAllowedCharacters:NSCharacterSet.urlQueryAllowed),
let range = urlString.range(of: "%s") {
urlString.replaceSubrange(range, with: escapedQuery)
if let url = URL(string: urlString) {
self.finishEditingAndSubmit(url, visitType: VisitType.typed)
return
}
}
self.submitSearchText(text)
}
}
fileprivate func submitSearchText(_ text: String) {
let engine = profile.searchEngines.defaultEngine
if let searchURL = engine.searchURLForQuery(text) {
// We couldn't find a matching search keyword, so do a search query.
Telemetry.recordEvent(SearchTelemetry.makeEvent(engine, source: .URLBar))
finishEditingAndSubmit(searchURL, visitType: VisitType.typed)
} else {
// We still don't have a valid URL, so something is broken. Give up.
log.error("Error handling URL entry: \"\(text)\".")
assertionFailure("Couldn't generate search URL: \(text)")
}
}
func urlBarDidEnterOverlayMode(_ urlBar: URLBarView) {
if .blankPage == NewTabAccessors.getNewTabPage(profile.prefs) {
UIAccessibilityPostNotification(UIAccessibilityScreenChangedNotification, nil)
} else {
if let toast = clipboardBarDisplayHandler.clipboardToast {
toast.removeFromSuperview()
}
showHomePanelController(inline: false)
}
//LeanplumIntegration.sharedInstance.track(eventName: .interactWithURLBar)
}
func urlBarDidLeaveOverlayMode(_ urlBar: URLBarView) {
hideSearchController()
updateInContentHomePanel(tabManager.selectedTab?.url as URL?)
}
}
extension BrowserViewController: TabToolbarDelegate {
func tabToolbarDidPressBack(_ tabToolbar: TabToolbarProtocol, button: UIButton) {
tabManager.selectedTab?.goBack()
}
func tabToolbarDidLongPressBack(_ tabToolbar: TabToolbarProtocol, button: UIButton) {
showBackForwardList()
}
func tabToolbarDidPressReload(_ tabToolbar: TabToolbarProtocol, button: UIButton) {
tabManager.selectedTab?.reload()
}
func tabToolbarDidLongPressReload(_ tabToolbar: TabToolbarProtocol, button: UIButton) {
guard let tab = tabManager.selectedTab, tab.webView?.url != nil && (tab.getHelper(name: ReaderMode.name()) as? ReaderMode)?.state != .active else {
return
}
let toggleActionTitle: String
if tab.desktopSite {
toggleActionTitle = NSLocalizedString("Request Mobile Site", comment: "Action Sheet Button for Requesting the Mobile Site")
} else {
toggleActionTitle = NSLocalizedString("Request Desktop Site", comment: "Action Sheet Button for Requesting the Desktop Site")
}
let controller = UIAlertController(title: nil, message: nil, preferredStyle: .actionSheet)
controller.addAction(UIAlertAction(title: toggleActionTitle, style: .default, handler: { _ in tab.toggleDesktopSite() }))
controller.addAction(UIAlertAction(title: NSLocalizedString("Cancel", comment:"Label for Cancel button"), style: .cancel, handler: nil))
controller.popoverPresentationController?.sourceView = toolbar ?? urlBar
controller.popoverPresentationController?.sourceRect = button.frame
present(controller, animated: true, completion: nil)
}
func tabToolbarDidPressStop(_ tabToolbar: TabToolbarProtocol, button: UIButton) {
tabManager.selectedTab?.stop()
}
func tabToolbarDidPressForward(_ tabToolbar: TabToolbarProtocol, button: UIButton) {
tabManager.selectedTab?.goForward()
}
func tabToolbarDidLongPressForward(_ tabToolbar: TabToolbarProtocol, button: UIButton) {
showBackForwardList()
}
func tabToolbarDidPressMenu(_ tabToolbar: TabToolbarProtocol, button: UIButton) {
// ensure that any keyboards or spinners are dismissed before presenting the menu
UIApplication.shared.sendAction(#selector(UIResponder.resignFirstResponder), to:nil, from:nil, for:nil)
// check the trait collection
// open as modal if portrait\
let presentationStyle: MenuViewPresentationStyle = (self.traitCollection.horizontalSizeClass == .compact && traitCollection.verticalSizeClass == .regular) ? .modal : .popover
let mvc = MenuViewController(withAppState: getCurrentAppState(), presentationStyle: presentationStyle)
mvc.delegate = self
mvc.actionDelegate = self
mvc.menuTransitionDelegate = MenuPresentationAnimator()
mvc.modalPresentationStyle = presentationStyle == .modal ? .overCurrentContext : .popover
if let popoverPresentationController = mvc.popoverPresentationController {
popoverPresentationController.backgroundColor = UIColor.clear
popoverPresentationController.delegate = self
popoverPresentationController.sourceView = button
popoverPresentationController.sourceRect = CGRect(x: button.frame.width/2, y: button.frame.size.height * 0.75, width: 1, height: 1)
popoverPresentationController.permittedArrowDirections = UIPopoverArrowDirection.up
}
self.present(mvc, animated: true, completion: nil)
menuViewController = mvc
}
fileprivate func setNoImageMode(_ enabled: Bool) {
self.profile.prefs.setBool(enabled, forKey: PrefsKeys.KeyNoImageModeStatus)
for tab in self.tabManager.tabs {
tab.setNoImageMode(enabled, force: true)
}
self.tabManager.selectedTab?.reload()
}
func toggleBookmarkForTabState(_ tabState: TabState) {
if tabState.isBookmarked {
self.removeBookmark(tabState)
} else {
self.addBookmark(tabState)
//LeanplumIntegration.sharedInstance.track(eventName: .savedBookmark)
}
}
func tabToolbarDidPressBookmark(_ tabToolbar: TabToolbarProtocol, button: UIButton) {
guard let tab = tabManager.selectedTab,
let _ = tab.url?.displayURL?.absoluteString else {
log.error("Bookmark error: No tab is selected, or no URL in tab.")
return
}
toggleBookmarkForTabState(tab.tabState)
}
func tabToolbarDidLongPressBookmark(_ tabToolbar: TabToolbarProtocol, button: UIButton) {
}
func tabToolbarDidPressShare(_ tabToolbar: TabToolbarProtocol, button: UIButton) {
if let tab = tabManager.selectedTab, let url = tab.url?.displayURL {
let sourceView = self.navigationToolbar.shareButton
presentActivityViewController(url, tab: tab, sourceView: sourceView.superview, sourceRect: sourceView.frame, arrowDirection: .up)
}
}
func tabToolbarDidPressHomePage(_ tabToolbar: TabToolbarProtocol, button: UIButton) {
guard let tab = tabManager.selectedTab else { return }
HomePageHelper(prefs: profile.prefs).openHomePage(inTab: tab, withNavigationController: navigationController)
}
func showBackForwardList() {
if let backForwardList = tabManager.selectedTab?.webView?.backForwardList {
let backForwardViewController = BackForwardListViewController(profile: profile, backForwardList: backForwardList, isPrivate: tabManager.selectedTab?.isPrivate ?? false)
backForwardViewController.tabManager = tabManager
backForwardViewController.bvc = self
backForwardViewController.modalPresentationStyle = UIModalPresentationStyle.overCurrentContext
backForwardViewController.backForwardTransitionDelegate = BackForwardListAnimator()
self.present(backForwardViewController, animated: true, completion: nil)
}
}
}
extension BrowserViewController: MenuViewControllerDelegate {
func menuViewControllerDidDismiss(_ menuViewController: MenuViewController) {
self.menuViewController = nil
displayedPopoverController = nil
updateDisplayedPopoverProperties = nil
}
func shouldCloseMenu(_ menuViewController: MenuViewController, forRotationToNewSize size: CGSize, forTraitCollection traitCollection: UITraitCollection) -> Bool {
// if we're presenting in popover but we haven't got a preferred content size yet, don't dismiss, otherwise we might dismiss before we've presented
if (traitCollection.horizontalSizeClass == .compact && traitCollection.verticalSizeClass == .compact) && menuViewController.preferredContentSize == CGSize.zero {
return false
}
// Dismiss the menu if we are going into the background.
let state = UIApplication.shared.applicationState
if state != .active {
return true
}
func orientationForSize(_ size: CGSize) -> UIInterfaceOrientation {
return size.height < size.width ? .landscapeLeft : .portrait
}
let currentOrientation = orientationForSize(self.view.bounds.size)
let newOrientation = orientationForSize(size)
let isiPhone = UI_USER_INTERFACE_IDIOM() == .phone
// we only want to dismiss when rotating on iPhone
// if we're rotating from landscape to portrait then we are rotating from popover to modal
return isiPhone && currentOrientation != newOrientation
}
}
extension BrowserViewController: WindowCloseHelperDelegate {
func windowCloseHelper(_ helper: WindowCloseHelper, didRequestToCloseTab tab: Tab) {
tabManager.removeTab(tab)
}
}
extension BrowserViewController: TabDelegate {
func tab(_ tab: Tab, didCreateWebView webView: WKWebView) {
webView.frame = webViewContainer.frame
// Observers that live as long as the tab. Make sure these are all cleared
// in willDeleteWebView below!
webView.addObserver(self, forKeyPath: KVOEstimatedProgress, options: .new, context: nil)
webView.addObserver(self, forKeyPath: KVOLoading, options: .new, context: nil)
webView.addObserver(self, forKeyPath: KVOCanGoBack, options: .new, context: nil)
webView.addObserver(self, forKeyPath: KVOCanGoForward, options: .new, context: nil)
tab.webView?.addObserver(self, forKeyPath: KVOURL, options: .new, context: nil)
tab.webView?.addObserver(self, forKeyPath: KVOTitle, options: .new, context: nil)
webView.scrollView.addObserver(self.scrollController, forKeyPath: KVOContentSize, options: .new, context: nil)
webView.uiDelegate = self
let readerMode = ReaderMode(tab: tab)
readerMode.delegate = self
tab.addHelper(readerMode, name: ReaderMode.name())
let favicons = FaviconManager(tab: tab, profile: profile)
tab.addHelper(favicons, name: FaviconManager.name())
// only add the logins helper if the tab is not a private browsing tab
if !tab.isPrivate {
let logins = LoginsHelper(tab: tab, profile: profile)
tab.addHelper(logins, name: LoginsHelper.name())
}
let contextMenuHelper = ContextMenuHelper(tab: tab)
contextMenuHelper.delegate = self
tab.addHelper(contextMenuHelper, name: ContextMenuHelper.name())
let errorHelper = ErrorPageHelper()
tab.addHelper(errorHelper, name: ErrorPageHelper.name())
let windowCloseHelper = WindowCloseHelper(tab: tab)
windowCloseHelper.delegate = self
tab.addHelper(windowCloseHelper, name: WindowCloseHelper.name())
let sessionRestoreHelper = SessionRestoreHelper(tab: tab)
sessionRestoreHelper.delegate = self
tab.addHelper(sessionRestoreHelper, name: SessionRestoreHelper.name())
let findInPageHelper = FindInPageHelper(tab: tab)
findInPageHelper.delegate = self
tab.addHelper(findInPageHelper, name: FindInPageHelper.name())
let noImageModeHelper = NoImageModeHelper(tab: tab)
tab.addHelper(noImageModeHelper, name: NoImageModeHelper.name())
let printHelper = PrintHelper(tab: tab)
tab.addHelper(printHelper, name: PrintHelper.name())
let customSearchHelper = CustomSearchHelper(tab: tab)
tab.addHelper(customSearchHelper, name: CustomSearchHelper.name())
let openURL = {(url: URL) -> Void in
self.switchToTabForURLOrOpen(url, isPrivileged: true)
}
let nightModeHelper = NightModeHelper(tab: tab)
tab.addHelper(nightModeHelper, name: NightModeHelper.name())
let spotlightHelper = SpotlightHelper(tab: tab, openURL: openURL)
tab.addHelper(spotlightHelper, name: SpotlightHelper.name())
tab.addHelper(LocalRequestHelper(), name: LocalRequestHelper.name())
let historyStateHelper = HistoryStateHelper(tab: tab)
historyStateHelper.delegate = self
tab.addHelper(historyStateHelper, name: HistoryStateHelper.name())
if AppConstants.MOZ_CONTENT_METADATA_PARSING {
let metadataHelper = MetadataParserHelper(tab: tab, profile: profile)
tab.addHelper(metadataHelper, name: MetadataParserHelper.name())
}
}
func tab(_ tab: Tab, willDeleteWebView webView: WKWebView) {
tab.cancelQueuedAlerts()
webView.removeObserver(self, forKeyPath: KVOEstimatedProgress)
webView.removeObserver(self, forKeyPath: KVOLoading)
webView.removeObserver(self, forKeyPath: KVOCanGoBack)
webView.removeObserver(self, forKeyPath: KVOCanGoForward)
webView.scrollView.removeObserver(self.scrollController, forKeyPath: KVOContentSize)
webView.removeObserver(self, forKeyPath: KVOURL)
webView.removeObserver(self, forKeyPath: KVOTitle)
webView.uiDelegate = nil
webView.scrollView.delegate = nil
webView.removeFromSuperview()
}
fileprivate func findSnackbar(_ barToFind: SnackBar) -> Int? {
let bars = snackBars.subviews
for (index, bar) in bars.enumerated() where bar === barToFind {
return index
}
return nil
}
fileprivate func updateSnackBarConstraints() {
snackBars.snp.remakeConstraints { make in
make.bottom.equalTo(findInPageContainer.snp.top)
let bars = self.snackBars.subviews
if bars.count > 0 {
let view = bars[bars.count-1]
make.top.equalTo(view.snp.top)
} else {
make.height.equalTo(0)
}
if traitCollection.horizontalSizeClass != .regular {
make.leading.trailing.equalTo(self.footer)
self.snackBars.layer.borderWidth = 0
} else {
make.centerX.equalTo(self.footer)
make.width.equalTo(SnackBarUX.MaxWidth)
self.snackBars.layer.borderColor = UIConstants.BorderColor.cgColor
self.snackBars.layer.borderWidth = 1
}
}
}
// This removes the bar from its superview and updates constraints appropriately
fileprivate func finishRemovingBar(_ bar: SnackBar) {
// If there was a bar above this one, we need to remake its constraints.
if let index = findSnackbar(bar) {
// If the bar being removed isn't on the top of the list
let bars = snackBars.subviews
if index < bars.count-1 {
// Move the bar above this one
let nextbar = bars[index+1] as! SnackBar
nextbar.snp.makeConstraints { make in
// If this wasn't the bottom bar, attach to the bar below it
if index > 0 {
let bar = bars[index-1] as! SnackBar
nextbar.bottom = make.bottom.equalTo(bar.snp.top).constraint
} else {
// Otherwise, we attach it to the bottom of the snackbars
nextbar.bottom = make.bottom.equalTo(self.snackBars.snp.bottom).constraint
}
}
}
}
// Really remove the bar
bar.removeFromSuperview()
}
fileprivate func finishAddingBar(_ bar: SnackBar) {
snackBars.addSubview(bar)
bar.snp.makeConstraints { make in
// If there are already bars showing, add this on top of them
let bars = self.snackBars.subviews
// Add the bar on top of the stack
// We're the new top bar in the stack, so make sure we ignore ourself
if bars.count > 1 {
let view = bars[bars.count - 2]
bar.bottom = make.bottom.equalTo(view.snp.top).offset(0).constraint
} else {
bar.bottom = make.bottom.equalTo(self.snackBars.snp.bottom).offset(0).constraint
}
make.leading.trailing.equalTo(self.snackBars)
}
}
func showBar(_ bar: SnackBar, animated: Bool) {
finishAddingBar(bar)
updateSnackBarConstraints()
bar.hide()
view.layoutIfNeeded()
UIView.animate(withDuration: animated ? 0.25 : 0, animations: { () -> Void in
bar.show()
self.view.layoutIfNeeded()
})
}
func removeBar(_ bar: SnackBar, animated: Bool) {
if let _ = findSnackbar(bar) {
UIView.animate(withDuration: animated ? 0.25 : 0, animations: { () -> Void in
bar.hide()
self.view.layoutIfNeeded()
}, completion: { success in
// Really remove the bar
self.finishRemovingBar(bar)
self.updateSnackBarConstraints()
})
}
}
func removeAllBars() {
let bars = snackBars.subviews
for bar in bars {
if let bar = bar as? SnackBar {
bar.removeFromSuperview()
}
}
self.updateSnackBarConstraints()
}
func tab(_ tab: Tab, didAddSnackbar bar: SnackBar) {
showBar(bar, animated: true)
}
func tab(_ tab: Tab, didRemoveSnackbar bar: SnackBar) {
removeBar(bar, animated: true)
}
func tab(_ tab: Tab, didSelectFindInPageForSelection selection: String) {
updateFindInPageVisibility(visible: true)
findInPageBar?.text = selection
}
}
extension BrowserViewController: HomePanelViewControllerDelegate {
func homePanelViewController(_ homePanelViewController: HomePanelViewController, didSelectURL url: URL, visitType: VisitType) {
finishEditingAndSubmit(url, visitType: visitType)
}
func homePanelViewController(_ homePanelViewController: HomePanelViewController, didSelectPanel panel: Int) {
if let url = tabManager.selectedTab?.url, url.isAboutHomeURL {
tabManager.selectedTab?.webView?.evaluateJavaScript("history.replaceState({}, '', '#panel=\(panel)')", completionHandler: nil)
}
}
func homePanelViewControllerDidRequestToCreateAccount(_ homePanelViewController: HomePanelViewController) {
presentSignInViewController() // TODO UX Right now the flow for sign in and create account is the same
}
func homePanelViewControllerDidRequestToSignIn(_ homePanelViewController: HomePanelViewController) {
presentSignInViewController() // TODO UX Right now the flow for sign in and create account is the same
}
func homePanelViewControllerDidRequestToOpenInNewTab(_ url: URL, isPrivate: Bool) {
let tab = self.tabManager.addTab(PrivilegedRequest(url: url) as URLRequest, afterTab: self.tabManager.selectedTab, isPrivate: isPrivate)
// If we are showing toptabs a user can just use the top tab bar
// If in overlay mode switching doesnt correctly dismiss the homepanels
guard self.topTabsViewController == nil, !self.urlBar.inOverlayMode else {
return
}
// We're not showing the top tabs; show a toast to quick switch to the fresh new tab.
let toast = ButtonToast(labelText: Strings.ContextMenuButtonToastNewTabOpenedLabelText, buttonText: Strings.ContextMenuButtonToastNewTabOpenedButtonText, completion: { buttonPressed in
if buttonPressed {
self.tabManager.selectTab(tab)
}
})
self.show(buttonToast: toast)
}
}
extension BrowserViewController: SearchViewControllerDelegate {
func searchViewController(_ searchViewController: SearchViewController, didSelectURL url: URL) {
finishEditingAndSubmit(url, visitType: VisitType.typed)
}
func presentSearchSettingsController() {
let settingsNavigationController = SearchSettingsTableViewController()
settingsNavigationController.model = self.profile.searchEngines
settingsNavigationController.profile = self.profile
let navController = UINavigationController(rootViewController: settingsNavigationController)
self.present(navController, animated: true, completion: nil)
}
}
extension BrowserViewController: TabManagerDelegate {
func tabManager(_ tabManager: TabManager, didSelectedTabChange selected: Tab?, previous: Tab?) {
// Remove the old accessibilityLabel. Since this webview shouldn't be visible, it doesn't need it
// and having multiple views with the same label confuses tests.
if let wv = previous?.webView {
removeOpenInView()
wv.endEditing(true)
wv.accessibilityLabel = nil
wv.accessibilityElementsHidden = true
wv.accessibilityIdentifier = nil
wv.removeFromSuperview()
}
if let tab = selected, let webView = tab.webView {
updateURLBarDisplayURL(tab)
if tab.isPrivate {
readerModeCache = MemoryReaderModeCache.sharedInstance
applyTheme(Theme.PrivateMode)
} else {
readerModeCache = DiskReaderModeCache.sharedInstance
applyTheme(Theme.NormalMode)
}
if let privateModeButton = topTabsViewController?.privateModeButton, previous != nil && previous?.isPrivate != tab.isPrivate {
privateModeButton.setSelected(tab.isPrivate, animated: true)
}
ReaderModeHandlers.readerModeCache = readerModeCache
scrollController.tab = selected
webViewContainer.addSubview(webView)
webView.snp.makeConstraints { make in
make.top.equalTo(webViewContainerToolbar.snp.bottom)
make.left.right.bottom.equalTo(self.webViewContainer)
}
webView.accessibilityLabel = NSLocalizedString("Web content", comment: "Accessibility label for the main web content view")
webView.accessibilityIdentifier = "contentView"
webView.accessibilityElementsHidden = false
if let url = webView.url {
let absoluteString = url.absoluteString
// Don't bother fetching bookmark state for about/sessionrestore and about/home.
if url.isAboutURL {
// Indeed, because we don't show the toolbar at all, don't even blank the star.
} else {
profile.bookmarks.modelFactory >>== { [weak tab] in
$0.isBookmarked(absoluteString)
.uponQueue(DispatchQueue.main) {
guard let isBookmarked = $0.successValue else {
log.error("Error getting bookmark status: \($0.failureValue ??? "nil").")
return
}
tab?.isBookmarked = isBookmarked
}
}
}
} else {
// The web view can go gray if it was zombified due to memory pressure.
// When this happens, the URL is nil, so try restoring the page upon selection.
tab.reload()
}
}
if let selected = selected, let previous = previous, selected.isPrivate != previous.isPrivate {
updateTabCountUsingTabManager(tabManager)
}
removeAllBars()
if let bars = selected?.bars {
for bar in bars {
showBar(bar, animated: true)
}
}
updateFindInPageVisibility(visible: false)
navigationToolbar.updateReloadStatus(selected?.loading ?? false)
navigationToolbar.updateBackStatus(selected?.canGoBack ?? false)
navigationToolbar.updateForwardStatus(selected?.canGoForward ?? false)
self.urlBar.updateProgressBar(Float(selected?.estimatedProgress ?? 0))
if let readerMode = selected?.getHelper(name: ReaderMode.name()) as? ReaderMode {
urlBar.updateReaderModeState(readerMode.state)
if readerMode.state == .active {
showReaderModeBar(animated: false)
} else {
hideReaderModeBar(animated: false)
}
} else {
urlBar.updateReaderModeState(ReaderModeState.unavailable)
}
updateInContentHomePanel(selected?.url as URL?)
}
func tabManager(_ tabManager: TabManager, willAddTab tab: Tab) {
}
func tabManager(_ tabManager: TabManager, didAddTab tab: Tab) {
// If we are restoring tabs then we update the count once at the end
if !tabManager.isRestoring {
updateTabCountUsingTabManager(tabManager)
}
tab.tabDelegate = self
tab.appStateDelegate = self
}
func tabManager(_ tabManager: TabManager, willRemoveTab tab: Tab) {
}
func tabManager(_ tabManager: TabManager, didRemoveTab tab: Tab) {
updateTabCountUsingTabManager(tabManager)
// tabDelegate is a weak ref (and the tab's webView may not be destroyed yet)
// so we don't expcitly unset it.
if let url = tab.url, !url.isAboutURL && !tab.isPrivate {
profile.recentlyClosedTabs.addTab(url as URL, title: tab.title, faviconURL: tab.displayFavicon?.url)
}
}
func tabManagerDidAddTabs(_ tabManager: TabManager) {
updateTabCountUsingTabManager(tabManager)
}
func tabManagerDidRestoreTabs(_ tabManager: TabManager) {
updateTabCountUsingTabManager(tabManager)
}
func show(buttonToast: ButtonToast, afterWaiting delay: Double = 0, duration: Double = SimpleToastUX.ToastDismissAfter) {
// If BVC isnt visible hold on to this toast until viewDidAppear
if self.view.window == nil {
self.pendingToast = buttonToast
return
}
let time = DispatchTime(uptimeNanoseconds: DispatchTime.now().uptimeNanoseconds) + Double(Int64(delay * Double(NSEC_PER_SEC))) / Double(NSEC_PER_SEC)
DispatchQueue.main.asyncAfter(deadline: time) {
self.view.addSubview(buttonToast)
buttonToast.snp.makeConstraints { make in
make.left.right.equalTo(self.view)
make.bottom.equalTo(self.webViewContainer)
}
buttonToast.showToast(duration: duration)
}
}
func tabManagerDidRemoveAllTabs(_ tabManager: TabManager, toast: ButtonToast?) {
guard let toast = toast, !tabTrayController.privateMode else {
return
}
show(buttonToast: toast, afterWaiting: ButtonToastUX.ToastDelay)
}
fileprivate func updateTabCountUsingTabManager(_ tabManager: TabManager, animated: Bool = true) {
if let selectedTab = tabManager.selectedTab {
let count = selectedTab.isPrivate ? tabManager.privateTabs.count : tabManager.normalTabs.count
urlBar.updateTabCount(max(count, 1), animated: !urlBar.inOverlayMode)
topTabsViewController?.updateTabCount(max(count, 1), animated: animated)
}
}
}
extension BrowserViewController: WKNavigationDelegate {
func webView(_ webView: WKWebView, didStartProvisionalNavigation navigation: WKNavigation!) {
if tabManager.selectedTab?.webView !== webView {
return
}
updateFindInPageVisibility(visible: false)
// If we are going to navigate to a new page, hide the reader mode button. Unless we
// are going to a about:reader page. Then we keep it on screen: it will change status
// (orange color) as soon as the page has loaded.
if let url = webView.url {
if !url.isReaderModeURL {
urlBar.updateReaderModeState(ReaderModeState.unavailable)
hideReaderModeBar(animated: false)
}
// remove the open in overlay view if it is present
removeOpenInView()
}
}
// Recognize an Apple Maps URL. This will trigger the native app. But only if a search query is present. Otherwise
// it could just be a visit to a regular page on maps.apple.com.
fileprivate func isAppleMapsURL(_ url: URL) -> Bool {
if url.scheme == "http" || url.scheme == "https" {
if url.host == "maps.apple.com" && url.query != nil {
return true
}
}
return false
}
// Recognize a iTunes Store URL. These all trigger the native apps. Note that appstore.com and phobos.apple.com
// used to be in this list. I have removed them because they now redirect to itunes.apple.com. If we special case
// them then iOS will actually first open Safari, which then redirects to the app store. This works but it will
// leave a 'Back to Safari' button in the status bar, which we do not want.
fileprivate func isStoreURL(_ url: URL) -> Bool {
if url.scheme == "http" || url.scheme == "https" {
if url.host == "itunes.apple.com" {
return true
}
}
return false
}
// This is the place where we decide what to do with a new navigation action. There are a number of special schemes
// and http(s) urls that need to be handled in a different way. All the logic for that is inside this delegate
// method.
func webView(_ webView: WKWebView, decidePolicyFor navigationAction: WKNavigationAction, decisionHandler: @escaping (WKNavigationActionPolicy) -> Void) {
guard let url = navigationAction.request.url else {
decisionHandler(WKNavigationActionPolicy.cancel)
return
}
if url.scheme == "about" {
decisionHandler(WKNavigationActionPolicy.allow)
return
}
if !navigationAction.isAllowed && navigationAction.navigationType != .backForward {
log.warning("Denying unprivileged request: \(navigationAction.request)")
decisionHandler(WKNavigationActionPolicy.cancel)
return
}
// First special case are some schemes that are about Calling. We prompt the user to confirm this action. This
// gives us the exact same behaviour as Safari.
if url.scheme == "tel" || url.scheme == "facetime" || url.scheme == "facetime-audio" {
if let components = NSURLComponents(url: url, resolvingAgainstBaseURL: false), let phoneNumber = components.path, !phoneNumber.isEmpty {
let formatter = PhoneNumberFormatter()
let formattedPhoneNumber = formatter.formatPhoneNumber(phoneNumber)
let alert = UIAlertController(title: formattedPhoneNumber, message: nil, preferredStyle: UIAlertControllerStyle.alert)
alert.addAction(UIAlertAction(title: NSLocalizedString("Cancel", comment:"Label for Cancel button"), style: UIAlertActionStyle.cancel, handler: nil))
alert.addAction(UIAlertAction(title: NSLocalizedString("Call", comment:"Alert Call Button"), style: UIAlertActionStyle.default, handler: { (action: UIAlertAction!) in
UIApplication.shared.openURL(url)
}))
present(alert, animated: true, completion: nil)
}
decisionHandler(WKNavigationActionPolicy.cancel)
return
}
// Second special case are a set of URLs that look like regular http links, but should be handed over to iOS
// instead of being loaded in the webview. Note that there is no point in calling canOpenURL() here, because
// iOS will always say yes. TODO Is this the same as isWhitelisted?
if isAppleMapsURL(url) || isStoreURL(url) {
UIApplication.shared.openURL(url)
decisionHandler(WKNavigationActionPolicy.cancel)
return
}
// Handles custom mailto URL schemes.
if url.scheme == "mailto" {
if let mailToMetadata = url.mailToMetadata(), let mailScheme = self.profile.prefs.stringForKey(PrefsKeys.KeyMailToOption), mailScheme != "mailto" {
self.mailtoLinkHandler.launchMailClientForScheme(mailScheme, metadata: mailToMetadata, defaultMailtoURL: url)
} else {
UIApplication.shared.openURL(url)
}
//LeanplumIntegration.sharedInstance.track(eventName: .openedMailtoLink)
decisionHandler(WKNavigationActionPolicy.cancel)
return
}
// This is the normal case, opening a http or https url, which we handle by loading them in this WKWebView. We
// always allow this. Additionally, data URIs are also handled just like normal web pages.
if url.scheme == "http" || url.scheme == "https" || url.scheme == "data" || url.scheme == "blob" {
if navigationAction.navigationType == .linkActivated {
resetSpoofedUserAgentIfRequired(webView, newURL: url)
} else if navigationAction.navigationType == .backForward {
restoreSpoofedUserAgentIfRequired(webView, newRequest: navigationAction.request)
}
decisionHandler(WKNavigationActionPolicy.allow)
return
}
// Default to calling openURL(). What this does depends on the iOS version. On iOS 8, it will just work without
// prompting. On iOS9, depending on the scheme, iOS will prompt: "Firefox" wants to open "Twitter". It will ask
// every time. There is no way around this prompt. (TODO Confirm this is true by adding them to the Info.plist)
let openedURL = UIApplication.shared.openURL(url)
if !openedURL {
let alert = UIAlertController(title: Strings.UnableToOpenURLErrorTitle, message: Strings.UnableToOpenURLError, preferredStyle: .alert)
alert.addAction(UIAlertAction(title: UIConstants.OKString, style: UIAlertActionStyle.default, handler: nil))
self.present(alert, animated: true, completion: nil)
}
decisionHandler(WKNavigationActionPolicy.cancel)
}
func webView(_ webView: WKWebView, didReceive challenge: URLAuthenticationChallenge, completionHandler: @escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Void) {
// If this is a certificate challenge, see if the certificate has previously been
// accepted by the user.
let origin = "\(challenge.protectionSpace.host):\(challenge.protectionSpace.port)"
if challenge.protectionSpace.authenticationMethod == NSURLAuthenticationMethodServerTrust,
let trust = challenge.protectionSpace.serverTrust,
let cert = SecTrustGetCertificateAtIndex(trust, 0), profile.certStore.containsCertificate(cert, forOrigin: origin) {
completionHandler(URLSession.AuthChallengeDisposition.useCredential, URLCredential(trust: trust))
return
}
guard challenge.protectionSpace.authenticationMethod == NSURLAuthenticationMethodHTTPBasic ||
challenge.protectionSpace.authenticationMethod == NSURLAuthenticationMethodHTTPDigest ||
challenge.protectionSpace.authenticationMethod == NSURLAuthenticationMethodNTLM,
let tab = tabManager[webView] else {
completionHandler(URLSession.AuthChallengeDisposition.performDefaultHandling, nil)
return
}
// If this is a request to our local web server, use our private credentials.
if challenge.protectionSpace.host == "localhost" && challenge.protectionSpace.port == Int(WebServer.sharedInstance.server.port) {
completionHandler(.useCredential, WebServer.sharedInstance.credentials)
return
}
// The challenge may come from a background tab, so ensure it's the one visible.
tabManager.selectTab(tab)
let loginsHelper = tab.getHelper(name: LoginsHelper.name()) as? LoginsHelper
Authenticator.handleAuthRequest(self, challenge: challenge, loginsHelper: loginsHelper).uponQueue(DispatchQueue.main) { res in
if let credentials = res.successValue {
completionHandler(.useCredential, credentials.credentials)
} else {
completionHandler(URLSession.AuthChallengeDisposition.rejectProtectionSpace, nil)
}
}
}
func webView(_ webView: WKWebView, didCommit navigation: WKNavigation!) {
guard let tab = tabManager[webView] else { return }
tab.url = webView.url
self.scrollController.resetZoomState()
if tabManager.selectedTab === tab {
updateUIForReaderHomeStateForTab(tab)
appDidUpdateState(getCurrentAppState())
}
}
func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
let tab: Tab! = tabManager[webView]
navigateInTab(tab: tab, to: navigation)
}
fileprivate func addViewForOpenInHelper(_ openInHelper: OpenInHelper) {
guard let view = openInHelper.openInView else { return }
webViewContainerToolbar.addSubview(view)
webViewContainerToolbar.snp.updateConstraints { make in
make.height.equalTo(OpenInViewUX.ViewHeight)
}
view.snp.makeConstraints { make in
make.edges.equalTo(webViewContainerToolbar)
}
self.openInHelper = openInHelper
}
fileprivate func removeOpenInView() {
guard let _ = self.openInHelper else { return }
webViewContainerToolbar.subviews.forEach { $0.removeFromSuperview() }
webViewContainerToolbar.snp.updateConstraints { make in
make.height.equalTo(0)
}
self.openInHelper = nil
}
fileprivate func postLocationChangeNotificationForTab(_ tab: Tab, navigation: WKNavigation?) {
let notificationCenter = NotificationCenter.default
var info = [AnyHashable: Any]()
info["url"] = tab.url?.displayURL
info["title"] = tab.title
if let visitType = self.getVisitTypeForTab(tab, navigation: navigation)?.rawValue {
info["visitType"] = visitType
}
info["isPrivate"] = tab.isPrivate
notificationCenter.post(name: NotificationOnLocationChange, object: self, userInfo: info)
}
}
/// List of schemes that are allowed to open a popup window
private let SchemesAllowedToOpenPopups = ["http", "https", "javascript", "data"]
extension BrowserViewController: WKUIDelegate {
func webView(_ webView: WKWebView, createWebViewWith configuration: WKWebViewConfiguration, for navigationAction: WKNavigationAction, windowFeatures: WKWindowFeatures) -> WKWebView? {
guard let parentTab = tabManager[webView] else { return nil }
if !navigationAction.isAllowed {
log.warning("Denying unprivileged request: \(navigationAction.request)")
return nil
}
if let currentTab = tabManager.selectedTab {
screenshotHelper.takeScreenshot(currentTab)
}
// If the page uses window.open() or target="_blank", open the page in a new tab.
let newTab = tabManager.addTab(navigationAction.request, configuration: configuration, afterTab: parentTab, isPrivate: parentTab.isPrivate)
tabManager.selectTab(newTab)
// If the page we just opened has a bad scheme, we return nil here so that JavaScript does not
// get a reference to it which it can return from window.open() - this will end up as a
// CFErrorHTTPBadURL being presented.
guard let scheme = (navigationAction.request as NSURLRequest).url?.scheme?.lowercased(), SchemesAllowedToOpenPopups.contains(scheme) else {
return nil
}
return newTab.webView
}
fileprivate func canDisplayJSAlertForWebView(_ webView: WKWebView) -> Bool {
// Only display a JS Alert if we are selected and there isn't anything being shown
return ((tabManager.selectedTab == nil ? false : tabManager.selectedTab!.webView == webView)) && (self.presentedViewController == nil)
}
func webView(_ webView: WKWebView, runJavaScriptAlertPanelWithMessage message: String, initiatedByFrame frame: WKFrameInfo, completionHandler: @escaping () -> Void) {
let messageAlert = MessageAlert(message: message, frame: frame, completionHandler: completionHandler)
if canDisplayJSAlertForWebView(webView) {
present(messageAlert.alertController(), animated: true, completion: nil)
} else if let promptingTab = tabManager[webView] {
promptingTab.queueJavascriptAlertPrompt(messageAlert)
} else {
// This should never happen since an alert needs to come from a web view but just in case call the handler
// since not calling it will result in a runtime exception.
completionHandler()
}
}
func webView(_ webView: WKWebView, runJavaScriptConfirmPanelWithMessage message: String, initiatedByFrame frame: WKFrameInfo, completionHandler: @escaping (Bool) -> Void) {
let confirmAlert = ConfirmPanelAlert(message: message, frame: frame, completionHandler: completionHandler)
if canDisplayJSAlertForWebView(webView) {
present(confirmAlert.alertController(), animated: true, completion: nil)
} else if let promptingTab = tabManager[webView] {
promptingTab.queueJavascriptAlertPrompt(confirmAlert)
} else {
completionHandler(false)
}
}
func webView(_ webView: WKWebView, runJavaScriptTextInputPanelWithPrompt prompt: String, defaultText: String?, initiatedByFrame frame: WKFrameInfo, completionHandler: @escaping (String?) -> Void) {
let textInputAlert = TextInputAlert(message: prompt, frame: frame, completionHandler: completionHandler, defaultText: defaultText)
if canDisplayJSAlertForWebView(webView) {
present(textInputAlert.alertController(), animated: true, completion: nil)
} else if let promptingTab = tabManager[webView] {
promptingTab.queueJavascriptAlertPrompt(textInputAlert)
} else {
completionHandler(nil)
}
}
/// Invoked when an error occurs while starting to load data for the main frame.
func webView(_ webView: WKWebView, didFailProvisionalNavigation navigation: WKNavigation!, withError error: Error) {
// Ignore the "Frame load interrupted" error that is triggered when we cancel a request
// to open an external application and hand it over to UIApplication.openURL(). The result
// will be that we switch to the external app, for example the app store, while keeping the
// original web page in the tab instead of replacing it with an error page.
let error = error as NSError
if error.domain == "WebKitErrorDomain" && error.code == 102 {
return
}
if checkIfWebContentProcessHasCrashed(webView, error: error as NSError) {
return
}
if error.code == Int(CFNetworkErrors.cfurlErrorCancelled.rawValue) {
if let tab = tabManager[webView], tab === tabManager.selectedTab {
urlBar.currentURL = tab.url?.displayURL
}
return
}
if let url = error.userInfo[NSURLErrorFailingURLErrorKey] as? URL {
ErrorPageHelper().showPage(error, forUrl: url, inWebView: webView)
// If the local web server isn't working for some reason (Firefox cellular data is
// disabled in settings, for example), we'll fail to load the session restore URL.
// We rely on loading that page to get the restore callback to reset the restoring
// flag, so if we fail to load that page, reset it here.
if url.aboutComponent == "sessionrestore" {
tabManager.tabs.filter { $0.webView == webView }.first?.restoring = false
}
}
}
fileprivate func checkIfWebContentProcessHasCrashed(_ webView: WKWebView, error: NSError) -> Bool {
if error.code == WKError.webContentProcessTerminated.rawValue && error.domain == "WebKitErrorDomain" {
log.debug("WebContent process has crashed. Trying to reloadFromOrigin to restart it.")
webView.reloadFromOrigin()
return true
}
return false
}
func webView(_ webView: WKWebView, decidePolicyFor navigationResponse: WKNavigationResponse, decisionHandler: @escaping (WKNavigationResponsePolicy) -> Void) {
let helperForURL = OpenIn.helperForResponse(navigationResponse.response)
if navigationResponse.canShowMIMEType {
if let openInHelper = helperForURL {
addViewForOpenInHelper(openInHelper)
}
decisionHandler(WKNavigationResponsePolicy.allow)
return
}
guard var openInHelper = helperForURL else {
let error = NSError(domain: ErrorPageHelper.MozDomain, code: Int(ErrorPageHelper.MozErrorDownloadsNotEnabled), userInfo: [NSLocalizedDescriptionKey: Strings.UnableToDownloadError])
ErrorPageHelper().showPage(error, forUrl: navigationResponse.response.url!, inWebView: webView)
return decisionHandler(WKNavigationResponsePolicy.allow)
}
if openInHelper.openInView == nil {
openInHelper.openInView = navigationToolbar.shareButton
}
openInHelper.open()
decisionHandler(WKNavigationResponsePolicy.cancel)
}
func webViewDidClose(_ webView: WKWebView) {
if let tab = tabManager[webView] {
self.tabManager.removeTab(tab)
}
}
}
extension BrowserViewController: ReaderModeDelegate {
func readerMode(_ readerMode: ReaderMode, didChangeReaderModeState state: ReaderModeState, forTab tab: Tab) {
// If this reader mode availability state change is for the tab that we currently show, then update
// the button. Otherwise do nothing and the button will be updated when the tab is made active.
if tabManager.selectedTab === tab {
urlBar.updateReaderModeState(state)
}
}
func readerMode(_ readerMode: ReaderMode, didDisplayReaderizedContentForTab tab: Tab) {
self.showReaderModeBar(animated: true)
tab.showContent(true)
}
}
// MARK: - UIPopoverPresentationControllerDelegate
extension BrowserViewController: UIPopoverPresentationControllerDelegate {
func popoverPresentationControllerDidDismissPopover(_ popoverPresentationController: UIPopoverPresentationController) {
displayedPopoverController = nil
updateDisplayedPopoverProperties = nil
}
}
extension BrowserViewController: UIAdaptivePresentationControllerDelegate {
// Returning None here makes sure that the Popover is actually presented as a Popover and
// not as a full-screen modal, which is the default on compact device classes.
func adaptivePresentationStyle(for controller: UIPresentationController, traitCollection: UITraitCollection) -> UIModalPresentationStyle {
return UIModalPresentationStyle.none
}
}
// MARK: - ReaderModeStyleViewControllerDelegate
extension BrowserViewController: ReaderModeStyleViewControllerDelegate {
func readerModeStyleViewController(_ readerModeStyleViewController: ReaderModeStyleViewController, didConfigureStyle style: ReaderModeStyle) {
// Persist the new style to the profile
let encodedStyle: [String:Any] = style.encodeAsDictionary()
profile.prefs.setObject(encodedStyle, forKey: ReaderModeProfileKeyStyle)
// Change the reader mode style on all tabs that have reader mode active
for tabIndex in 0..<tabManager.count {
if let tab = tabManager[tabIndex] {
if let readerMode = tab.getHelper(name: "ReaderMode") as? ReaderMode {
if readerMode.state == ReaderModeState.active {
readerMode.style = style
}
}
}
}
}
}
extension BrowserViewController {
func updateReaderModeBar() {
if let readerModeBar = readerModeBar {
if let tab = self.tabManager.selectedTab, tab.isPrivate {
readerModeBar.applyTheme(Theme.PrivateMode)
} else {
readerModeBar.applyTheme(Theme.NormalMode)
}
if let url = self.tabManager.selectedTab?.url?.displayURL?.absoluteString, let result = profile.readingList?.getRecordWithURL(url) {
if let successValue = result.successValue, let record = successValue {
readerModeBar.unread = record.unread
readerModeBar.added = true
} else {
readerModeBar.unread = true
readerModeBar.added = false
}
} else {
readerModeBar.unread = true
readerModeBar.added = false
}
}
}
func showReaderModeBar(animated: Bool) {
if self.readerModeBar == nil {
let readerModeBar = ReaderModeBarView(frame: CGRect.zero)
readerModeBar.delegate = self
view.insertSubview(readerModeBar, belowSubview: header)
self.readerModeBar = readerModeBar
}
updateReaderModeBar()
self.updateViewConstraints()
}
func hideReaderModeBar(animated: Bool) {
if let readerModeBar = self.readerModeBar {
readerModeBar.removeFromSuperview()
self.readerModeBar = nil
self.updateViewConstraints()
}
}
/// There are two ways we can enable reader mode. In the simplest case we open a URL to our internal reader mode
/// and be done with it. In the more complicated case, reader mode was already open for this page and we simply
/// navigated away from it. So we look to the left and right in the BackForwardList to see if a readerized version
/// of the current page is there. And if so, we go there.
func enableReaderMode() {
guard let tab = tabManager.selectedTab, let webView = tab.webView else { return }
let backList = webView.backForwardList.backList
let forwardList = webView.backForwardList.forwardList
guard let currentURL = webView.backForwardList.currentItem?.url, let readerModeURL = currentURL.encodeReaderModeURL(WebServer.sharedInstance.baseReaderModeURL()) else { return }
if backList.count > 1 && backList.last?.url == readerModeURL {
webView.go(to: backList.last!)
} else if forwardList.count > 0 && forwardList.first?.url == readerModeURL {
webView.go(to: forwardList.first!)
} else {
// Store the readability result in the cache and load it. This will later move to the ReadabilityHelper.
webView.evaluateJavaScript("\(ReaderModeNamespace).readerize()", completionHandler: { (object, error) -> Void in
if let readabilityResult = ReadabilityResult(object: object as AnyObject?) {
do {
try self.readerModeCache.put(currentURL, readabilityResult)
} catch _ {
}
if let nav = webView.load(PrivilegedRequest(url: readerModeURL) as URLRequest) {
self.ignoreNavigationInTab(tab, navigation: nav)
}
}
})
}
}
/// Disabling reader mode can mean two things. In the simplest case we were opened from the reading list, which
/// means that there is nothing in the BackForwardList except the internal url for the reader mode page. In that
/// case we simply open a new page with the original url. In the more complicated page, the non-readerized version
/// of the page is either to the left or right in the BackForwardList. If that is the case, we navigate there.
func disableReaderMode() {
if let tab = tabManager.selectedTab,
let webView = tab.webView {
let backList = webView.backForwardList.backList
let forwardList = webView.backForwardList.forwardList
if let currentURL = webView.backForwardList.currentItem?.url {
if let originalURL = currentURL.decodeReaderModeURL {
if backList.count > 1 && backList.last?.url == originalURL {
webView.go(to: backList.last!)
} else if forwardList.count > 0 && forwardList.first?.url == originalURL {
webView.go(to: forwardList.first!)
} else {
if let nav = webView.load(URLRequest(url: originalURL)) {
self.ignoreNavigationInTab(tab, navigation: nav)
}
}
}
}
}
}
func SELDynamicFontChanged(_ notification: Notification) {
guard notification.name == NotificationDynamicFontChanged else { return }
var readerModeStyle = DefaultReaderModeStyle
if let dict = profile.prefs.dictionaryForKey(ReaderModeProfileKeyStyle) {
if let style = ReaderModeStyle(dict: dict as [String : AnyObject]) {
readerModeStyle = style
}
}
readerModeStyle.fontSize = ReaderModeFontSize.defaultSize
self.readerModeStyleViewController(ReaderModeStyleViewController(), didConfigureStyle: readerModeStyle)
}
}
extension BrowserViewController: ReaderModeBarViewDelegate {
func readerModeBar(_ readerModeBar: ReaderModeBarView, didSelectButton buttonType: ReaderModeBarButtonType) {
switch buttonType {
case .settings:
if let readerMode = tabManager.selectedTab?.getHelper(name: "ReaderMode") as? ReaderMode, readerMode.state == ReaderModeState.active {
var readerModeStyle = DefaultReaderModeStyle
if let dict = profile.prefs.dictionaryForKey(ReaderModeProfileKeyStyle) {
if let style = ReaderModeStyle(dict: dict as [String : AnyObject]) {
readerModeStyle = style
}
}
let readerModeStyleViewController = ReaderModeStyleViewController()
readerModeStyleViewController.delegate = self
readerModeStyleViewController.readerModeStyle = readerModeStyle
readerModeStyleViewController.modalPresentationStyle = UIModalPresentationStyle.popover
let setupPopover = { [unowned self] in
if let popoverPresentationController = readerModeStyleViewController.popoverPresentationController {
popoverPresentationController.backgroundColor = UIColor.white
popoverPresentationController.delegate = self
popoverPresentationController.sourceView = readerModeBar
popoverPresentationController.sourceRect = CGRect(x: readerModeBar.frame.width/2, y: UIConstants.ToolbarHeight, width: 1, height: 1)
popoverPresentationController.permittedArrowDirections = UIPopoverArrowDirection.up
}
}
setupPopover()
if readerModeStyleViewController.popoverPresentationController != nil {
displayedPopoverController = readerModeStyleViewController
updateDisplayedPopoverProperties = setupPopover
}
self.present(readerModeStyleViewController, animated: true, completion: nil)
}
case .markAsRead:
if let url = self.tabManager.selectedTab?.url?.displayURL?.absoluteString, let result = profile.readingList?.getRecordWithURL(url) {
if let successValue = result.successValue, let record = successValue {
profile.readingList?.updateRecord(record, unread: false) // TODO Check result, can this fail?
readerModeBar.unread = false
}
}
case .markAsUnread:
if let url = self.tabManager.selectedTab?.url?.displayURL?.absoluteString, let result = profile.readingList?.getRecordWithURL(url) {
if let successValue = result.successValue, let record = successValue {
profile.readingList?.updateRecord(record, unread: true) // TODO Check result, can this fail?
readerModeBar.unread = true
}
}
case .addToReadingList:
if let tab = tabManager.selectedTab,
let rawURL = tab.url, rawURL.isReaderModeURL,
let url = rawURL.decodeReaderModeURL {
profile.readingList?.createRecordWithURL(url.absoluteString, title: tab.title ?? "", addedBy: UIDevice.current.name) // TODO Check result, can this fail?
readerModeBar.added = true
readerModeBar.unread = true
}
case .removeFromReadingList:
if let url = self.tabManager.selectedTab?.url?.displayURL?.absoluteString,
let result = profile.readingList?.getRecordWithURL(url),
let successValue = result.successValue,
let record = successValue {
profile.readingList?.deleteRecord(record) // TODO Check result, can this fail?
readerModeBar.added = false
readerModeBar.unread = false
}
}
}
}
extension BrowserViewController: IntroViewControllerDelegate {
@discardableResult func presentIntroViewController(_ force: Bool = false) -> Bool {
if force || profile.prefs.intForKey(IntroViewControllerSeenProfileKey) == nil {
let introViewController = IntroViewController()
introViewController.delegate = self
// On iPad we present it modally in a controller
if UIDevice.current.userInterfaceIdiom == .pad {
introViewController.preferredContentSize = CGSize(width: IntroViewControllerUX.Width, height: IntroViewControllerUX.Height)
introViewController.modalPresentationStyle = UIModalPresentationStyle.formSheet
}
present(introViewController, animated: true) {
self.profile.prefs.setInt(1, forKey: IntroViewControllerSeenProfileKey)
// On first run (and forced) open up the homepage in the background.
let state = self.getCurrentAppState()
if let homePageURL = HomePageAccessors.getHomePage(state), let tab = self.tabManager.selectedTab, DeviceInfo.hasConnectivity() {
tab.loadRequest(URLRequest(url: homePageURL))
}
}
return true
}
return false
}
func introViewControllerDidFinish(_ introViewController: IntroViewController) {
introViewController.dismiss(animated: true) { finished in
if self.navigationController?.viewControllers.count ?? 0 > 1 {
_ = self.navigationController?.popToRootViewController(animated: true)
}
}
}
func presentSignInViewController(_ fxaOptions: FxALaunchParams? = nil) {
// Show the settings page if we have already signed in. If we haven't then show the signin page
let vcToPresent: UIViewController
if profile.hasAccount() {
let settingsTableViewController = AppSettingsTableViewController()
settingsTableViewController.profile = profile
settingsTableViewController.tabManager = tabManager
vcToPresent = settingsTableViewController
} else {
let signInVC = FxAContentViewController(profile: profile, fxaOptions: fxaOptions)
signInVC.delegate = self
signInVC.navigationItem.leftBarButtonItem = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.cancel, target: self, action: #selector(BrowserViewController.dismissSignInViewController))
vcToPresent = signInVC
}
let settingsNavigationController = SettingsNavigationController(rootViewController: vcToPresent)
settingsNavigationController.modalPresentationStyle = .formSheet
self.present(settingsNavigationController, animated: true, completion: nil)
}
func dismissSignInViewController() {
self.dismiss(animated: true, completion: nil)
}
func introViewControllerDidRequestToLogin(_ introViewController: IntroViewController) {
introViewController.dismiss(animated: true, completion: { () -> Void in
self.presentSignInViewController()
})
}
}
extension BrowserViewController: FxAContentViewControllerDelegate {
func contentViewControllerDidSignIn(_ viewController: FxAContentViewController, withFlags flags: FxALoginFlags) {
if flags.verified {
self.dismiss(animated: true, completion: nil)
}
}
func contentViewControllerDidCancel(_ viewController: FxAContentViewController) {
log.info("Did cancel out of FxA signin")
self.dismiss(animated: true, completion: nil)
}
}
extension BrowserViewController: ContextMenuHelperDelegate {
func contextMenuHelper(_ contextMenuHelper: ContextMenuHelper, didLongPressElements elements: ContextMenuHelper.Elements, gestureRecognizer: UILongPressGestureRecognizer) {
// locationInView can return (0, 0) when the long press is triggered in an invalid page
// state (e.g., long pressing a link before the document changes, then releasing after a
// different page loads).
let touchPoint = gestureRecognizer.location(in: view)
guard touchPoint != CGPoint.zero else { return }
let touchSize = CGSize(width: 0, height: 16)
let actionSheetController = UIAlertController(title: nil, message: nil, preferredStyle: UIAlertControllerStyle.actionSheet)
var dialogTitle: String?
if let url = elements.link, let currentTab = tabManager.selectedTab {
dialogTitle = url.absoluteString
let isPrivate = currentTab.isPrivate
let addTab = { (rURL: URL, isPrivate: Bool) in
self.scrollController.showToolbars(animated: !self.scrollController.toolbarsShowing, completion: { _ in
let tab = self.tabManager.addTab(URLRequest(url: rURL as URL), afterTab: currentTab, isPrivate: isPrivate)
//LeanplumIntegration.sharedInstance.track(eventName: .openedNewTab, withParameters: ["Source": "Long Press Context Menu" as AnyObject])
guard self.topTabsViewController == nil else {
return
}
// We're not showing the top tabs; show a toast to quick switch to the fresh new tab.
let toast = ButtonToast(labelText: Strings.ContextMenuButtonToastNewTabOpenedLabelText, buttonText: Strings.ContextMenuButtonToastNewTabOpenedButtonText, completion: { buttonPressed in
if buttonPressed {
self.tabManager.selectTab(tab)
}
})
self.show(buttonToast: toast)
})
}
if !isPrivate {
let newTabTitle = NSLocalizedString("Open in New Tab", comment: "Context menu item for opening a link in a new tab")
let openNewTabAction = UIAlertAction(title: newTabTitle, style: UIAlertActionStyle.default) { (action: UIAlertAction) in
addTab(url, false)
}
actionSheetController.addAction(openNewTabAction)
}
let openNewPrivateTabTitle = NSLocalizedString("Open in New Private Tab", tableName: "PrivateBrowsing", comment: "Context menu option for opening a link in a new private tab")
let openNewPrivateTabAction = UIAlertAction(title: openNewPrivateTabTitle, style: UIAlertActionStyle.default) { (action: UIAlertAction) in
addTab(url, true)
}
actionSheetController.addAction(openNewPrivateTabAction)
let copyTitle = NSLocalizedString("Copy Link", comment: "Context menu item for copying a link URL to the clipboard")
let copyAction = UIAlertAction(title: copyTitle, style: UIAlertActionStyle.default) { (action: UIAlertAction) -> Void in
let pasteBoard = UIPasteboard.general
pasteBoard.url = url as URL
}
actionSheetController.addAction(copyAction)
let shareTitle = NSLocalizedString("Share Link", comment: "Context menu item for sharing a link URL")
let shareAction = UIAlertAction(title: shareTitle, style: UIAlertActionStyle.default) { _ in
self.presentActivityViewController(url as URL, sourceView: self.view, sourceRect: CGRect(origin: touchPoint, size: touchSize), arrowDirection: .any)
}
actionSheetController.addAction(shareAction)
}
if let url = elements.image {
if dialogTitle == nil {
dialogTitle = url.absoluteString
}
let photoAuthorizeStatus = PHPhotoLibrary.authorizationStatus()
let saveImageTitle = NSLocalizedString("Save Image", comment: "Context menu item for saving an image")
let saveImageAction = UIAlertAction(title: saveImageTitle, style: UIAlertActionStyle.default) { (action: UIAlertAction) -> Void in
if photoAuthorizeStatus == PHAuthorizationStatus.authorized || photoAuthorizeStatus == PHAuthorizationStatus.notDetermined {
self.getImage(url as URL) { UIImageWriteToSavedPhotosAlbum($0, nil, nil, nil) }
} else {
let accessDenied = UIAlertController(title: NSLocalizedString("Firefox would like to access your Photos", comment: "See http://mzl.la/1G7uHo7"), message: NSLocalizedString("This allows you to save the image to your Camera Roll.", comment: "See http://mzl.la/1G7uHo7"), preferredStyle: UIAlertControllerStyle.alert)
let dismissAction = UIAlertAction(title: UIConstants.CancelString, style: UIAlertActionStyle.default, handler: nil)
accessDenied.addAction(dismissAction)
let settingsAction = UIAlertAction(title: NSLocalizedString("Open Settings", comment: "See http://mzl.la/1G7uHo7"), style: UIAlertActionStyle.default ) { (action: UIAlertAction!) -> Void in
UIApplication.shared.openURL(URL(string: UIApplicationOpenSettingsURLString)!)
}
accessDenied.addAction(settingsAction)
self.present(accessDenied, animated: true, completion: nil)
//LeanplumIntegration.sharedInstance.track(eventName: .saveImage)
}
}
actionSheetController.addAction(saveImageAction)
let copyImageTitle = NSLocalizedString("Copy Image", comment: "Context menu item for copying an image to the clipboard")
let copyAction = UIAlertAction(title: copyImageTitle, style: UIAlertActionStyle.default) { (action: UIAlertAction) -> Void in
// put the actual image on the clipboard
// do this asynchronously just in case we're in a low bandwidth situation
let pasteboard = UIPasteboard.general
pasteboard.url = url as URL
let changeCount = pasteboard.changeCount
let application = UIApplication.shared
var taskId: UIBackgroundTaskIdentifier = 0
taskId = application.beginBackgroundTask (expirationHandler: { _ in
application.endBackgroundTask(taskId)
})
Alamofire.request(url)
.validate(statusCode: 200..<300)
.response { response in
// Only set the image onto the pasteboard if the pasteboard hasn't changed since
// fetching the image; otherwise, in low-bandwidth situations,
// we might be overwriting something that the user has subsequently added.
if changeCount == pasteboard.changeCount, let imageData = response.data, response.error == nil {
pasteboard.addImageWithData(imageData, forURL: url)
}
application.endBackgroundTask(taskId)
}
}
actionSheetController.addAction(copyAction)
}
// If we're showing an arrow popup, set the anchor to the long press location.
if let popoverPresentationController = actionSheetController.popoverPresentationController {
popoverPresentationController.sourceView = view
popoverPresentationController.sourceRect = CGRect(origin: touchPoint, size: touchSize)
popoverPresentationController.permittedArrowDirections = .any
popoverPresentationController.delegate = self
}
if actionSheetController.popoverPresentationController != nil {
displayedPopoverController = actionSheetController
}
actionSheetController.title = dialogTitle?.ellipsize(maxLength: ActionSheetTitleMaxLength)
let cancelAction = UIAlertAction(title: UIConstants.CancelString, style: UIAlertActionStyle.cancel, handler: nil)
actionSheetController.addAction(cancelAction)
self.present(actionSheetController, animated: true, completion: nil)
}
fileprivate func getImage(_ url: URL, success: @escaping (UIImage) -> Void) {
Alamofire.request(url)
.validate(statusCode: 200..<300)
.response { response in
if let data = response.data,
let image = UIImage.dataIsGIF(data) ? UIImage.imageFromGIFDataThreadSafe(data) : UIImage.imageFromDataThreadSafe(data) {
success(image)
}
}
}
}
extension BrowserViewController: HistoryStateHelperDelegate {
func historyStateHelper(_ historyStateHelper: HistoryStateHelper, didPushOrReplaceStateInTab tab: Tab) {
navigateInTab(tab: tab)
}
}
/**
A third party search engine Browser extension
**/
extension BrowserViewController {
func addCustomSearchButtonToWebView(_ webView: WKWebView) {
//check if the search engine has already been added.
let domain = webView.url?.domainURL.host
let matches = self.profile.searchEngines.orderedEngines.filter {$0.shortName == domain}
if !matches.isEmpty {
self.customSearchEngineButton.tintColor = UIColor.gray
self.customSearchEngineButton.isUserInteractionEnabled = false
} else {
self.customSearchEngineButton.tintColor = UIConstants.SystemBlueColor
self.customSearchEngineButton.isUserInteractionEnabled = true
}
/*
This is how we access hidden views in the WKContentView
Using the public headers we can find the keyboard accessoryView which is not usually available.
Specific values here are from the WKContentView headers.
https://github.com/JaviSoto/iOS9-Runtime-Headers/blob/master/Frameworks/WebKit.framework/WKContentView.h
*/
guard let webContentView = UIView.findSubViewWithFirstResponder(webView) else {
/*
In some cases the URL bar can trigger the keyboard notification. In that case the webview isnt the first responder
and a search button should not be added.
*/
return
}
guard let input = webContentView.perform(#selector(getter: UIResponder.inputAccessoryView)),
let inputView = input.takeUnretainedValue() as? UIInputView,
let nextButton = inputView.value(forKey: "_nextItem") as? UIBarButtonItem,
let nextButtonView = nextButton.value(forKey: "view") as? UIView else {
//failed to find the inputView instead lets use the inputAssistant
addCustomSearchButtonToInputAssistant(webContentView)
return
}
inputView.addSubview(self.customSearchEngineButton)
self.customSearchEngineButton.snp.remakeConstraints { make in
make.leading.equalTo(nextButtonView.snp.trailing).offset(20)
make.width.equalTo(inputView.snp.height)
make.top.equalTo(nextButtonView.snp.top)
make.height.equalTo(inputView.snp.height)
}
}
/**
This adds the customSearchButton to the inputAssistant
for cases where the inputAccessoryView could not be found for example
on the iPad where it does not exist. However this only works on iOS9
**/
func addCustomSearchButtonToInputAssistant(_ webContentView: UIView) {
guard customSearchBarButton == nil else {
return //The searchButton is already on the keyboard
}
let inputAssistant = webContentView.inputAssistantItem
let item = UIBarButtonItem(customView: customSearchEngineButton)
customSearchBarButton = item
inputAssistant.trailingBarButtonGroups.last?.barButtonItems.append(item)
}
func addCustomSearchEngineForFocusedElement() {
guard let webView = tabManager.selectedTab?.webView else {
return
}
webView.evaluateJavaScript("__firefox__.searchQueryForField()") { (result, _) in
guard let searchQuery = result as? String, let favicon = self.tabManager.selectedTab!.displayFavicon else {
//Javascript responded with an incorrectly formatted message. Show an error.
let alert = ThirdPartySearchAlerts.failedToAddThirdPartySearch()
self.present(alert, animated: true, completion: nil)
return
}
self.addSearchEngine(searchQuery, favicon: favicon)
self.customSearchEngineButton.tintColor = UIColor.gray
self.customSearchEngineButton.isUserInteractionEnabled = false
}
}
func addSearchEngine(_ searchQuery: String, favicon: Favicon) {
guard searchQuery != "",
let iconURL = URL(string: favicon.url),
let url = URL(string: searchQuery.addingPercentEncoding(withAllowedCharacters: CharacterSet.urlFragmentAllowed)!),
let shortName = url.domainURL.host else {
let alert = ThirdPartySearchAlerts.failedToAddThirdPartySearch()
self.present(alert, animated: true, completion: nil)
return
}
let alert = ThirdPartySearchAlerts.addThirdPartySearchEngine { alert in
self.customSearchEngineButton.tintColor = UIColor.gray
self.customSearchEngineButton.isUserInteractionEnabled = false
SDWebImageManager.shared().downloadImage(with: iconURL, options: SDWebImageOptions.continueInBackground, progress: nil) { (image, error, cacheType, success, url) in
guard image != nil else {
let alert = ThirdPartySearchAlerts.failedToAddThirdPartySearch()
self.present(alert, animated: true, completion: nil)
return
}
self.profile.searchEngines.addSearchEngine(OpenSearchEngine(engineID: nil, shortName: shortName, image: image!, searchTemplate: searchQuery, suggestTemplate: nil, isCustomEngine: true))
let Toast = SimpleToast()
Toast.showAlertWithText(Strings.ThirdPartySearchEngineAdded)
}
}
self.present(alert, animated: true, completion: {})
}
}
extension BrowserViewController: KeyboardHelperDelegate {
func keyboardHelper(_ keyboardHelper: KeyboardHelper, keyboardWillShowWithState state: KeyboardState) {
keyboardState = state
updateViewConstraints()
UIView.animate(withDuration: state.animationDuration) {
UIView.setAnimationCurve(state.animationCurve)
self.findInPageContainer.layoutIfNeeded()
self.snackBars.layoutIfNeeded()
}
if let webView = tabManager.selectedTab?.webView {
webView.evaluateJavaScript("__firefox__.searchQueryForField()") { (result, _) in
guard let _ = result as? String else {
return
}
self.addCustomSearchButtonToWebView(webView)
}
}
}
func keyboardHelper(_ keyboardHelper: KeyboardHelper, keyboardDidShowWithState state: KeyboardState) {
}
func keyboardHelper(_ keyboardHelper: KeyboardHelper, keyboardWillHideWithState state: KeyboardState) {
keyboardState = nil
updateViewConstraints()
//If the searchEngineButton exists remove it form the keyboard
if let buttonGroup = customSearchBarButton?.buttonGroup {
buttonGroup.barButtonItems = buttonGroup.barButtonItems.filter { $0 != customSearchBarButton }
customSearchBarButton = nil
}
if self.customSearchEngineButton.superview != nil {
self.customSearchEngineButton.removeFromSuperview()
}
UIView.animate(withDuration: state.animationDuration) {
UIView.setAnimationCurve(state.animationCurve)
self.findInPageContainer.layoutIfNeeded()
self.snackBars.layoutIfNeeded()
}
}
}
extension BrowserViewController: SessionRestoreHelperDelegate {
func sessionRestoreHelper(_ helper: SessionRestoreHelper, didRestoreSessionForTab tab: Tab) {
tab.restoring = false
if let tab = tabManager.selectedTab, tab.webView === tab.webView {
updateUIForReaderHomeStateForTab(tab)
}
}
}
extension BrowserViewController: TabTrayDelegate {
// This function animates and resets the tab chrome transforms when
// the tab tray dismisses.
func tabTrayDidDismiss(_ tabTray: TabTrayController) {
resetBrowserChrome()
}
func tabTrayDidAddBookmark(_ tab: Tab) {
guard let url = tab.url?.absoluteString, url.characters.count > 0 else { return }
self.addBookmark(tab.tabState)
}
func tabTrayDidAddToReadingList(_ tab: Tab) -> ReadingListClientRecord? {
guard let url = tab.url?.absoluteString, url.characters.count > 0 else { return nil }
return profile.readingList?.createRecordWithURL(url, title: tab.title ?? url, addedBy: UIDevice.current.name).successValue
}
func tabTrayRequestsPresentationOf(_ viewController: UIViewController) {
self.present(viewController, animated: false, completion: nil)
}
}
// MARK: Browser Chrome Theming
extension BrowserViewController: Themeable {
func applyTheme(_ themeName: String) {
urlBar.applyTheme(themeName)
toolbar?.applyTheme(themeName)
readerModeBar?.applyTheme(themeName)
topTabsViewController?.applyTheme(themeName)
switch themeName {
case Theme.NormalMode:
header.blurStyle = .extraLight
footerBackground?.blurStyle = .extraLight
case Theme.PrivateMode:
header.blurStyle = .dark
footerBackground?.blurStyle = .dark
default:
log.debug("Unknown Theme \(themeName)")
}
}
}
// A small convienent class for wrapping a view with a blur background that can be modified
class BlurWrapper: UIView {
var blurStyle: UIBlurEffectStyle = .extraLight {
didSet {
let newEffect = UIVisualEffectView(effect: UIBlurEffect(style: blurStyle))
effectView.removeFromSuperview()
effectView = newEffect
insertSubview(effectView, belowSubview: wrappedView)
effectView.snp.remakeConstraints { make in
make.edges.equalTo(self)
}
effectView.isHidden = disableBlur
switch blurStyle {
case .extraLight, .light:
background.backgroundColor = TopTabsUX.TopTabsBackgroundNormalColor
case .extraDark, .dark:
background.backgroundColor = TopTabsUX.TopTabsBackgroundPrivateColor
default:
assertionFailure("Unsupported blur style")
}
}
}
var disableBlur = false {
didSet {
effectView.isHidden = disableBlur
background.isHidden = !disableBlur
}
}
fileprivate var effectView: UIVisualEffectView
fileprivate var wrappedView: UIView
fileprivate lazy var background: UIView = {
let background = UIView()
background.isHidden = true
return background
}()
init(view: UIView) {
wrappedView = view
effectView = UIVisualEffectView(effect: UIBlurEffect(style: blurStyle))
super.init(frame: CGRect.zero)
addSubview(background)
addSubview(effectView)
addSubview(wrappedView)
effectView.snp.makeConstraints { make in
make.edges.equalTo(self)
}
wrappedView.snp.makeConstraints { make in
make.edges.equalTo(self)
}
background.snp.makeConstraints { make in
make.edges.equalTo(self)
}
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
protocol Themeable {
func applyTheme(_ themeName: String)
}
extension BrowserViewController: FindInPageBarDelegate, FindInPageHelperDelegate {
func findInPage(_ findInPage: FindInPageBar, didTextChange text: String) {
find(text, function: "find")
}
func findInPage(_ findInPage: FindInPageBar, didFindNextWithText text: String) {
findInPageBar?.endEditing(true)
find(text, function: "findNext")
}
func findInPage(_ findInPage: FindInPageBar, didFindPreviousWithText text: String) {
findInPageBar?.endEditing(true)
find(text, function: "findPrevious")
}
func findInPageDidPressClose(_ findInPage: FindInPageBar) {
updateFindInPageVisibility(visible: false)
}
fileprivate func find(_ text: String, function: String) {
guard let webView = tabManager.selectedTab?.webView else { return }
let escaped = text.replacingOccurrences(of: "\\", with: "\\\\")
.replacingOccurrences(of: "\"", with: "\\\"")
webView.evaluateJavaScript("__firefox__.\(function)(\"\(escaped)\")", completionHandler: nil)
}
func findInPageHelper(_ findInPageHelper: FindInPageHelper, didUpdateCurrentResult currentResult: Int) {
findInPageBar?.currentResult = currentResult
}
func findInPageHelper(_ findInPageHelper: FindInPageHelper, didUpdateTotalResults totalResults: Int) {
findInPageBar?.totalResults = totalResults
}
}
extension BrowserViewController: JSPromptAlertControllerDelegate {
func promptAlertControllerDidDismiss(_ alertController: JSPromptAlertController) {
showQueuedAlertIfAvailable()
}
}
private extension WKNavigationAction {
/// Allow local requests only if the request is privileged.
var isAllowed: Bool {
guard let url = request.url else {
return true
}
return !url.isWebPage(includeDataURIs: false) || !url.isLocal || request.isPrivileged
}
}
extension BrowserViewController: TopTabsDelegate {
func topTabsDidPressTabs() {
urlBar.leaveOverlayMode(didCancel: true)
self.urlBarDidPressTabs(urlBar)
}
func topTabsDidPressNewTab(_ isPrivate: Bool) {
openBlankNewTab(isPrivate: isPrivate)
}
func topTabsDidTogglePrivateMode() {
guard let selectedTab = tabManager.selectedTab else {
return
}
urlBar.leaveOverlayMode()
}
func topTabsDidChangeTab() {
urlBar.leaveOverlayMode(didCancel: true)
}
}
|
mpl-2.0
|
a1ed1fd5927ee812c7471c94eb042227
| 43.371875 | 406 | 0.657229 | 5.843428 | false | false | false | false |
grigaci/RateMyTalkAtMobOS
|
RateMyTalkAtMobOS/Classes/CloudKit/Operations/RMTCloudKitOperationUploadRatings.swift
|
1
|
1331
|
//
// RMTCloudKitOperationUploadRatings.swift
// RateMyTalkAtMobOSMaster
//
// Created by Bogdan Iusco on 10/11/14.
// Copyright (c) 2014 Grigaci. All rights reserved.
//
import Foundation
import CloudKit
class RMTCloudKitOperationUploadRatings: CKModifyRecordsOperation {
class func uploadAllMyRatings() -> RMTCloudKitOperationUploadRatings {
let allMyRatings = RMTCloudKitOperationUploadRatings.allMyRatings()
var allMyRatingsCK = [CKRecord]()
for rating in allMyRatings {
if let ratingCK = rating.ckRecord() {
allMyRatingsCK += [ratingCK]
}
}
let uploadOperation = RMTCloudKitOperationUploadRatings(recordsToSave: allMyRatingsCK, recordIDsToDelete: nil);
uploadOperation.savePolicy = .AllKeys
return uploadOperation;
}
class func allMyRatings() -> [RMTRating] {
let userUUID = NSUserDefaults.standardUserDefaults().userUUID
let moc: NSManagedObjectContext = NSManagedObjectContext.MR_defaultContext()
let predicate = NSPredicate(format: "%K == %@", RMTRatingAttributes.userUUID.rawValue, userUUID)
let allMyRatingsNSArray: [RMTRating] = RMTRating.MR_findAllWithPredicate(predicate, inContext: moc) as [RMTRating]
return allMyRatingsNSArray
}
}
|
bsd-3-clause
|
3f3a0c28d8b37455f8a16590361b1c78
| 34.972973 | 123 | 0.69722 | 4.589655 | false | false | false | false |
practicalswift/swift
|
test/Constraints/trailing_closures_objc.swift
|
13
|
1058
|
// RUN: %target-typecheck-verify-swift
// REQUIRES: objc_interop
// REQUIRES: OS=macosx
import Foundation
import AVFoundation
import AppKit
func foo(options: [AVMediaSelectionOption]) {
let menuItems: [NSMenuItem] = options.map { (option: AVMediaSelectionOption) in
NSMenuItem(title: option.displayName, action: #selector(NSViewController.respondToMediaOptionSelection(from:)), keyEquivalent: "")
// expected-error@-1 {{type 'NSViewController' has no member 'respondToMediaOptionSelection(from:)'}}
}
}
func rdar28004686(a: [IndexPath]) {
_ = a.sorted { (lhs: NSIndexPath, rhs: NSIndexPath) -> Bool in true }
// expected-error@-1 {{'NSIndexPath' is not convertible to 'IndexPath'}}
}
class Test: NSObject {
var categories : NSArray?
func rdar28012273() {
let categories = ["hello", "world"]
self.categories = categories.sorted { $0.localizedCaseInsensitiveCompare($1) == ComparisonResult.orderedDescending }
// expected-error@-1 {{cannot assign value of type '[String]' to type 'NSArray?'}} {{121-121= as NSArray}}
}
}
|
apache-2.0
|
9d4bdfd17ea57e50d1316c59a3acf9d4
| 35.482759 | 134 | 0.718336 | 4.132813 | false | false | false | false |
yanqingsmile/RNAi
|
RNAi/CopyableLabel.swift
|
1
|
1405
|
//
// CopyableLabel.swift
// RNAi
//
// Created by Vivian Liu on 1/16/17.
// Copyright © 2017 Vivian Liu. All rights reserved.
//
import Foundation
import UIKit
class CopyableLabel: UILabel {
override init(frame: CGRect) {
super.init(frame: frame)
sharedInit()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
sharedInit()
}
func sharedInit() {
isUserInteractionEnabled = true
addGestureRecognizer(UILongPressGestureRecognizer(target: self, action: #selector(CopyableLabel.showMenu)))
}
func showMenu() {
becomeFirstResponder()
let menu = UIMenuController.shared
if !menu.isMenuVisible {
menu.setTargetRect(bounds, in: self)
menu.setMenuVisible(true, animated: true)
}
}
override func copy(_ sender: Any?) {
let board = UIPasteboard.general
board.string = text
let menu = UIMenuController.shared
menu.setMenuVisible(false, animated: true)
}
override var canBecomeFirstResponder: Bool {
return true
}
override func canPerformAction(_ action: Selector, withSender sender: Any?) -> Bool {
if action == #selector(UIResponderStandardEditActions.copy) {
return true
}
return false
}
}
|
mit
|
56bc6a49f16f68fcdad2b618f0c0da1c
| 22.4 | 115 | 0.603276 | 4.824742 | false | false | false | false |
iitjee/SteppinsSwift
|
Extensions.swift
|
1
|
5461
|
/*
https://developer.apple.com/library/content/documentation/Swift/Conceptual/Swift_Programming_Language/Extensions.html
Extensions add new functionality to an existing class, structure, enumeration, or protocol type.
This includes the ability to extend types for which you do not have access to the original source code (known as retroactive modeling).
Extensions are similar to categories in Objective-C. (except that they don't have names)
In Swift, you can even extend a protocol to provide implementations of its requirements or add additional functionality that conforming types can take advantage of.
NOTE: Extensions can add new functionality to a type, but they cannot override existing functionality.
NOTE: If you define an extension to add new functionality to an existing type, the new functionality will be available on all existing instances of that type, even if they were created before the extension was defined.
NOTE: Extensions can add new computed properties, but they cannot add stored properties, or add property observers to existing properties.
NOTE: You can't add new cases to an enum using extension.
NOTE: If you provide a new initializer with an extension, you are still responsible for making sure that each instance is fully initialized once the initializer completes.
*/
extension String {
var length: String {
}
extension Double { //all below are read-only computed properties
var km: Double { return self * 1_000.0 }
var m: Double { return self }
var cm: Double { return self / 100.0 }
var mm: Double { return self / 1_000.0 }
var ft: Double { return self / 3.28084 }
}
let oneInch = 25.4.mm //0.0254
let oneMeter = 1.0 //1.0
let threeFeet = 3.ft //0.91439
//NOTE: Extensions can add new computed properties, but they cannot add stored properties, or add property observers to existing properties.
extension Int {
func times(task: ()->() ) {
for i in 0..<self {
task()
}
}
}
3.times {print("Hello")} //very rx programming like
/* Extensions can add new initializers to existing types. */
//NOTE: Extensions can add new convenience initializers to a class, but they cannot add new designated initializers or deinitializers to a class.
//Designated initializers and deinitializers must always be provided by the original class implementation.
extension Rect {
init(center: Point, size: Size) {
let originX = center.x - (size.width / 2)
let originY = center.y - (size.height / 2)
self.init(origin: Point(x: originX, y: originY), size: size)
}
}
let centerRect = Rect(center: Point(x: 4.0, y: 4.0),
size: Size(width: 3.0, height: 3.0))
//NOTE: If you provide a new initializer with an extension, you are still responsible for making sure that each instance is fully initialized once the initializer completes.
/*Extensions can add new instance methods and type methods to existing types*/
extension Int {
func times(task: ()->() ) {
for _ in 0..<self {
task()
}
}
}
3.times {print("Hello")} //very rx programming like
/* Instance methods added with an extension can also modify (or mutate) the instance itself. */
// Structure and enumeration methods that modify self or its properties must mark the instance method as mutating, just like mutating methods from an original implementation.
extension Int {
mutating func square() {
self = self * self
}
}
var someInt = 3
someInt.square()
// someInt is now 9
/* Extensions can add new subscripts to an existing type. */
extension Int {
subscript(digitIndex: Int) -> Int {
var decimalBase = 1
for _ in 0..<digitIndex {
decimalBase *= 10
}
return (self / decimalBase) % 10
}
}
//This subscript [n] returns the decimal digit n places in from the right of the number
746381295[0] // returns 5
746381295[1] // returns 9
746381295[2] // returns 2
746381295[8] // returns 7
746381295[9] // returns 0, as if you had requested: 0746381295[9]
/* Extensions can add new nested types to existing classes, structures, and enumerations */
//This example adds a new nested enumeration to Int. This enumeration, called Kind, expresses the kind of number that a particular integer represents. Specifically, it expresses whether the number is negative, zero, or positive.
//This example also adds a new computed instance property to Int, called kind, which returns the appropriate Kind enumeration case for that integer.
extension Int {
enum Kind {
case negative, zero, positive
}
var kind: Kind {
switch self {
case 0:
return .zero
case let x where x > 0:
return .positive
default:
return .negative
}
}
}
//The nested enumeration can now be used with any Int value:
func printIntegerKinds(_ numbers: [Int]) {
for number in numbers {
switch number.kind {
case .negative:
print("- ", terminator: "")
case .zero:
print("0 ", terminator: "")
case .positive:
print("+ ", terminator: "")
}
}
print("")
}
printIntegerKinds([3, 19, -27, 0, -6, 0, 7]) // Prints "+ + - 0 - 0 + "
//NOTE: number.kind is already known to be of type Int.Kind. Because of this, all of the Int.Kind case values can be written in shorthand form inside the switch statement, such as .negative rather than Int.Kind.negative.
|
apache-2.0
|
e606055ad9afddd7f7e27da55c774da2
| 36.14966 | 228 | 0.694195 | 4.207242 | false | false | false | false |
hironytic/Kiretan0
|
Kiretan0/AppFramework/TableUI/DisclosureTableCellViewModel.swift
|
1
|
1710
|
//
// DisclosureTableCellViewModel.swift
// Kiretan0
//
// Copyright (c) 2017 Hironori Ichimiya <[email protected]>
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
import Foundation
import RxSwift
public class DisclosureTableCellViewModel: TableCellViewModel {
public let text: String?
public let detailText: Observable<String?>
public let onSelect: AnyObserver<Void>
public init(text: String?,
detailText: Observable<String?> = Observable.just(nil),
onSelect: AnyObserver<Void> = AnyObserver(eventHandler: { _ in }))
{
self.text = text
self.detailText = detailText
self.onSelect = onSelect
}
}
|
mit
|
6f613f13a34c8516407ab7f3651fc923
| 39.714286 | 82 | 0.732749 | 4.621622 | false | false | false | false |
modocache/swift
|
stdlib/public/core/Collection.swift
|
3
|
71817
|
//===----------------------------------------------------------------------===//
//
// 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
//
//===----------------------------------------------------------------------===//
/// A type that provides subscript access to its elements, with forward
/// index traversal.
///
/// In most cases, it's best to ignore this protocol and use the `Collection`
/// protocol instead, because it has a more complete interface.
@available(*, deprecated, message: "it will be removed in Swift 4.0. Please use 'Collection' instead")
public typealias IndexableBase = _IndexableBase
public protocol _IndexableBase {
// FIXME(ABI)#24 (Recursive Protocol Constraints): there is no reason for this protocol
// to exist apart from missing compiler features that we emulate with it.
// rdar://problem/20531108
//
// This protocol is almost an implementation detail of the standard
// library; it is used to deduce things like the `SubSequence` and
// `Iterator` type from a minimal collection, but it is also used in
// exposed places like as a constraint on `IndexingIterator`.
/// A type that represents a position in the collection.
///
/// Valid indices consist of the position of every element and a
/// "past the end" position that's not valid for use as a subscript
/// argument.
///
/// - SeeAlso: endIndex
associatedtype Index : Comparable
/// The position of the first element in a nonempty collection.
///
/// If the collection is empty, `startIndex` is equal to `endIndex`.
var startIndex: Index { get }
/// The collection's "past the end" position---that is, the position one
/// greater than the last valid subscript argument.
///
/// When you need a range that includes the last element of a collection, use
/// the half-open range operator (`..<`) with `endIndex`. The `..<` operator
/// creates a range that doesn't include the upper bound, so it's always
/// safe to use with `endIndex`. For example:
///
/// let numbers = [10, 20, 30, 40, 50]
/// if let index = numbers.index(of: 30) {
/// print(numbers[index ..< numbers.endIndex])
/// }
/// // Prints "[30, 40, 50]"
///
/// If the collection is empty, `endIndex` is equal to `startIndex`.
var endIndex: Index { get }
// The declaration of _Element and subscript here is a trick used to
// break a cyclic conformance/deduction that Swift can't handle. We
// need something other than a Collection.Iterator.Element that can
// be used as IndexingIterator<T>'s Element. Here we arrange for
// the Collection itself to have an Element type that's deducible from
// its subscript. Ideally we'd like to constrain this Element to be the same
// as Collection.Iterator.Element (see below), but we have no way of
// expressing it today.
associatedtype _Element
/// Accesses the element at the specified position.
///
/// The following example accesses an element of an array through its
/// subscript to print its value:
///
/// var streets = ["Adams", "Bryant", "Channing", "Douglas", "Evarts"]
/// print(streets[1])
/// // Prints "Bryant"
///
/// You can subscript a collection with any valid index other than the
/// collection's end index. The end index refers to the position one past
/// the last element of a collection, so it doesn't correspond with an
/// element.
///
/// - Parameter position: The position of the element to access. `position`
/// must be a valid index of the collection that is not equal to the
/// `endIndex` property.
subscript(position: Index) -> _Element { get }
// WORKAROUND: rdar://25214066
/// A sequence that can represent a contiguous subrange of the collection's
/// elements.
associatedtype SubSequence
/// Accesses the subsequence bounded by the given range.
///
/// - Parameter bounds: A range of the collection's indices. The upper and
/// lower bounds of the `bounds` range must be valid indices of the
/// collection.
subscript(bounds: Range<Index>) -> SubSequence { get }
/// Performs a range check in O(1), or a no-op when a range check is not
/// implementable in O(1).
///
/// The range check, if performed, is equivalent to:
///
/// precondition(bounds.contains(index))
///
/// Use this function to perform a cheap range check for QoI purposes when
/// memory safety is not a concern. Do not rely on this range check for
/// memory safety.
///
/// The default implementation for forward and bidirectional indices is a
/// no-op. The default implementation for random access indices performs a
/// range check.
///
/// - Complexity: O(1).
func _failEarlyRangeCheck(_ index: Index, bounds: Range<Index>)
func _failEarlyRangeCheck(_ index: Index, bounds: ClosedRange<Index>)
/// Performs a range check in O(1), or a no-op when a range check is not
/// implementable in O(1).
///
/// The range check, if performed, is equivalent to:
///
/// precondition(
/// bounds.contains(range.lowerBound) ||
/// range.lowerBound == bounds.upperBound)
/// precondition(
/// bounds.contains(range.upperBound) ||
/// range.upperBound == bounds.upperBound)
///
/// Use this function to perform a cheap range check for QoI purposes when
/// memory safety is not a concern. Do not rely on this range check for
/// memory safety.
///
/// The default implementation for forward and bidirectional indices is a
/// no-op. The default implementation for random access indices performs a
/// range check.
///
/// - Complexity: O(1).
func _failEarlyRangeCheck(_ range: Range<Index>, bounds: Range<Index>)
/// Returns the position immediately after the given index.
///
/// - Parameter i: A valid index of the collection. `i` must be less than
/// `endIndex`.
/// - Returns: The index value immediately after `i`.
func index(after i: Index) -> Index
/// Replaces the given index with its successor.
///
/// - Parameter i: A valid index of the collection. `i` must be less than
/// `endIndex`.
func formIndex(after i: inout Index)
}
/// A type that provides subscript access to its elements, with forward index
/// traversal.
///
/// In most cases, it's best to ignore this protocol and use the `Collection`
/// protocol instead, because it has a more complete interface.
@available(*, deprecated, message: "it will be removed in Swift 4.0. Please use 'Collection' instead")
public typealias Indexable = _Indexable
public protocol _Indexable : _IndexableBase {
/// A type used to represent the number of steps between two indices, where
/// one value is reachable from the other.
///
/// In Swift, *reachability* refers to the ability to produce one value from
/// the other through zero or more applications of `index(after:)`.
associatedtype IndexDistance : SignedInteger = Int
/// Returns an index that is the specified distance from the given index.
///
/// The following example obtains an index advanced four positions from a
/// string's starting index and then prints the character at that position.
///
/// let s = "Swift"
/// let i = s.index(s.startIndex, offsetBy: 4)
/// print(s[i])
/// // Prints "t"
///
/// The value passed as `n` must not offset `i` beyond the `endIndex` or
/// before the `startIndex` of this collection.
///
/// - Parameters:
/// - i: A valid index of the collection.
/// - n: The distance to offset `i`. `n` must not be negative unless the
/// collection conforms to the `BidirectionalCollection` protocol.
/// - Returns: An index offset by `n` from the index `i`. If `n` is positive,
/// this is the same value as the result of `n` calls to `index(after:)`.
/// If `n` is negative, this is the same value as the result of `-n` calls
/// to `index(before:)`.
///
/// - SeeAlso: `index(_:offsetBy:limitedBy:)`, `formIndex(_:offsetBy:)`
/// - Complexity: O(1) if the collection conforms to
/// `RandomAccessCollection`; otherwise, O(*n*), where *n* is the absolute
/// value of `n`.
func index(_ i: Index, offsetBy n: IndexDistance) -> Index
/// Returns an index that is the specified distance from the given index,
/// unless that distance is beyond a given limiting index.
///
/// The following example obtains an index advanced four positions from a
/// string's starting index and then prints the character at that position.
/// The operation doesn't require going beyond the limiting `s.endIndex`
/// value, so it succeeds.
///
/// let s = "Swift"
/// if let i = s.index(s.startIndex, offsetBy: 4, limitedBy: s.endIndex) {
/// print(s[i])
/// }
/// // Prints "t"
///
/// The next example attempts to retrieve an index six positions from
/// `s.startIndex` but fails, because that distance is beyond the index
/// passed as `limit`.
///
/// let j = s.index(s.startIndex, offsetBy: 6, limitedBy: s.endIndex)
/// print(j)
/// // Prints "nil"
///
/// The value passed as `n` must not offset `i` beyond the `endIndex` or
/// before the `startIndex` of this collection, unless the index passed as
/// `limit` prevents offsetting beyond those bounds.
///
/// - Parameters:
/// - i: A valid index of the collection.
/// - n: The distance to offset `i`. `n` must not be negative unless the
/// collection conforms to the `BidirectionalCollection` protocol.
/// - limit: A valid index of the collection to use as a limit. If `n > 0`,
/// a limit that is less than `i` has no effect. Likewise, if `n < 0`, a
/// limit that is greater than `i` has no effect.
/// - Returns: An index offset by `n` from the index `i`, unless that index
/// would be beyond `limit` in the direction of movement. In that case,
/// the method returns `nil`.
///
/// - SeeAlso: `index(_:offsetBy:)`, `formIndex(_:offsetBy:limitedBy:)`
/// - Complexity: O(1) if the collection conforms to
/// `RandomAccessCollection`; otherwise, O(*n*), where *n* is the absolute
/// value of `n`.
func index(
_ i: Index, offsetBy n: IndexDistance, limitedBy limit: Index
) -> Index?
/// Offsets the given index by the specified distance.
///
/// The value passed as `n` must not offset `i` beyond the `endIndex` or
/// before the `startIndex` of this collection.
///
/// - Parameters:
/// - i: A valid index of the collection.
/// - n: The distance to offset `i`. `n` must not be negative unless the
/// collection conforms to the `BidirectionalCollection` protocol.
///
/// - SeeAlso: `index(_:offsetBy:)`, `formIndex(_:offsetBy:limitedBy:)`
/// - Complexity: O(1) if the collection conforms to
/// `RandomAccessCollection`; otherwise, O(*n*), where *n* is the absolute
/// value of `n`.
func formIndex(_ i: inout Index, offsetBy n: IndexDistance)
/// Offsets the given index by the specified distance, or so that it equals
/// the given limiting index.
///
/// The value passed as `n` must not offset `i` beyond the `endIndex` or
/// before the `startIndex` of this collection, unless the index passed as
/// `limit` prevents offsetting beyond those bounds.
///
/// - Parameters:
/// - i: A valid index of the collection.
/// - n: The distance to offset `i`. `n` must not be negative unless the
/// collection conforms to the `BidirectionalCollection` protocol.
/// - Returns: `true` if `i` has been offset by exactly `n` steps without
/// going beyond `limit`; otherwise, `false`. When the return value is
/// `false`, the value of `i` is equal to `limit`.
///
/// - SeeAlso: `index(_:offsetBy:)`, `formIndex(_:offsetBy:limitedBy:)`
/// - Complexity: O(1) if the collection conforms to
/// `RandomAccessCollection`; otherwise, O(*n*), where *n* is the absolute
/// value of `n`.
func formIndex(
_ i: inout Index, offsetBy n: IndexDistance, limitedBy limit: Index
) -> Bool
/// Returns the distance between two indices.
///
/// Unless the collection conforms to the `BidirectionalCollection` protocol,
/// `start` must be less than or equal to `end`.
///
/// - Parameters:
/// - start: A valid index of the collection.
/// - end: Another valid index of the collection. If `end` is equal to
/// `start`, the result is zero.
/// - Returns: The distance between `start` and `end`. The result can be
/// negative only if the collection conforms to the
/// `BidirectionalCollection` protocol.
///
/// - Complexity: O(1) if the collection conforms to
/// `RandomAccessCollection`; otherwise, O(*n*), where *n* is the
/// resulting distance.
func distance(from start: Index, to end: Index) -> IndexDistance
}
/// A type that iterates over a collection using its indices.
///
/// The `IndexingIterator` type is the default iterator for any collection that
/// doesn't declare its own. It acts as an iterator by using a collection's
/// indices to step over each value in the collection. Most collections in the
/// standard library use `IndexingIterator` as their iterator.
///
/// By default, any custom collection type you create will inherit a
/// `makeIterator()` method that returns an `IndexingIterator` instance,
/// making it unnecessary to declare your own. When creating a custom
/// collection type, add the minimal requirements of the `Collection`
/// protocol: starting and ending indices and a subscript for accessing
/// elements. With those elements defined, the inherited `makeIterator()`
/// method satisfies the requirements of the `Sequence` protocol.
///
/// Here's an example of a type that declares the minimal requirements for a
/// collection. The `CollectionOfTwo` structure is a fixed-size collection
/// that always holds two elements of a specific type.
///
/// struct CollectionOfTwo<Element>: Collection {
/// let elements: (Element, Element)
///
/// init(_ first: Element, _ second: Element) {
/// self.elements = (first, second)
/// }
///
/// var startIndex: Int { return 0 }
/// var endIndex: Int { return 2 }
///
/// subscript(index: Int) -> Element {
/// switch index {
/// case 0: return elements.0
/// case 1: return elements.1
/// default: fatalError("Index out of bounds.")
/// }
/// }
///
/// func index(after i: Int) -> Int {
/// precondition(i < endIndex, "Can't advance beyond endIndex")
/// return i + 1
/// }
/// }
///
/// The `CollectionOfTwo` type uses the default iterator type,
/// `IndexingIterator`, because it doesn't define its own `makeIterator()`
/// method or `Iterator` associated type. This example shows how a
/// `CollectionOfTwo` instance can be created holding the values of a point,
/// and then iterated over using a `for`-`in` loop.
///
/// let point = CollectionOfTwo(15.0, 20.0)
/// for element in point {
/// print(element)
/// }
/// // Prints "15.0"
/// // Prints "20.0"
public struct IndexingIterator<
Elements : _IndexableBase
// FIXME(ABI)#97 (Recursive Protocol Constraints):
// Should be written as:
// Elements : Collection
> : IteratorProtocol, Sequence {
/// Creates an iterator over the given collection.
public /// @testable
init(_elements: Elements) {
self._elements = _elements
self._position = _elements.startIndex
}
/// Advances to the next element and returns it, or `nil` if no next element
/// exists.
///
/// Repeatedly calling this method returns all the elements of the underlying
/// sequence in order. As soon as the sequence has run out of elements, all
/// subsequent calls return `nil`.
///
/// This example shows how an iterator can be used explicitly to emulate a
/// `for`-`in` loop. First, retrieve a sequence's iterator, and then call
/// the iterator's `next()` method until it returns `nil`.
///
/// let numbers = [2, 3, 5, 7]
/// var numbersIterator = numbers.makeIterator()
///
/// while let num = numbersIterator.next() {
/// print(num)
/// }
/// // Prints "2"
/// // Prints "3"
/// // Prints "5"
/// // Prints "7"
///
/// - Returns: The next element in the underlying sequence if a next element
/// exists; otherwise, `nil`.
public mutating func next() -> Elements._Element? {
if _position == _elements.endIndex { return nil }
let element = _elements[_position]
_elements.formIndex(after: &_position)
return element
}
internal let _elements: Elements
internal var _position: Elements.Index
}
/// A sequence whose elements can be traversed multiple times,
/// nondestructively, and accessed by indexed subscript.
///
/// Collections are used extensively throughout the standard library. When you
/// use arrays, dictionaries, views of a string's contents and other types,
/// you benefit from the operations that the `Collection` protocol declares
/// and implements.
///
/// In addition to the methods that collections inherit from the `Sequence`
/// protocol, you gain access to methods that depend on accessing an element
/// at a specific position when using a collection.
///
/// For example, if you want to print only the first word in a string, search
/// for the index of the first space and then create a subsequence up to that
/// position.
///
/// let text = "Buffalo buffalo buffalo buffalo."
/// if let firstSpace = text.characters.index(of: " ") {
/// print(String(text.characters.prefix(upTo: firstSpace)))
/// }
/// // Prints "Buffalo"
///
/// The `firstSpace` constant is an index into the `text.characters`
/// collection. `firstSpace` is the position of the first space in the
/// collection. You can store indices in variables, and pass them to
/// collection algorithms or use them later to access the corresponding
/// element. In the example above, `firstSpace` is used to extract the prefix
/// that contains elements up to that index.
///
/// You can pass only valid indices to collection operations. You can find a
/// complete set of a collection's valid indices by starting with the
/// collection's `startIndex` property and finding every successor up to, and
/// including, the `endIndex` property. All other values of the `Index` type,
/// such as the `startIndex` property of a different collection, are invalid
/// indices for this collection.
///
/// Saved indices may become invalid as a result of mutating operations; for
/// more information about index invalidation in mutable collections, see the
/// reference for the `MutableCollection` and `RangeReplaceableCollection`
/// protocols, as well as for the specific type you're using.
///
/// Accessing Individual Elements
/// =============================
///
/// You can access an element of a collection through its subscript with any
/// valid index except the collection's `endIndex` property, a "past the end"
/// index that does not correspond with any element of the collection.
///
/// Here's an example of accessing the first character in a string through its
/// subscript:
///
/// let firstChar = text.characters[text.characters.startIndex]
/// print(firstChar)
/// // Prints "B"
///
/// The `Collection` protocol declares and provides default implementations for
/// many operations that depend on elements being accessible by their
/// subscript. For example, you can also access the first character of `text`
/// using the `first` property, which has the value of the first element of
/// the collection, or `nil` if the collection is empty.
///
/// print(text.characters.first)
/// // Prints "Optional("B")"
///
/// Traversing a Collection
/// =======================
///
/// Although a sequence can be consumed as it is traversed, a collection is
/// guaranteed to be multipass: Any element may be repeatedly accessed by
/// saving its index. Moreover, a collection's indices form a finite range of
/// the positions of the collection's elements. This guarantees the safety of
/// operations that depend on a sequence being finite, such as checking to see
/// whether a collection contains an element.
///
/// Iterating over the elements of a collection by their positions yields the
/// same elements in the same order as iterating over that collection using
/// its iterator. This example demonstrates that the `characters` view of a
/// string returns the same characters in the same order whether the view's
/// indices or the view itself is being iterated.
///
/// let word = "Swift"
/// for character in word.characters {
/// print(character)
/// }
/// // Prints "S"
/// // Prints "w"
/// // Prints "i"
/// // Prints "f"
/// // Prints "t"
///
/// for i in word.characters.indices {
/// print(word.characters[i])
/// }
/// // Prints "S"
/// // Prints "w"
/// // Prints "i"
/// // Prints "f"
/// // Prints "t"
///
/// Conforming to the Collection Protocol
/// =====================================
///
/// If you create a custom sequence that can provide repeated access to its
/// elements, make sure that its type conforms to the `Collection` protocol in
/// order to give a more useful and more efficient interface for sequence and
/// collection operations. To add `Collection` conformance to your type, you
/// must declare at least the four following requirements:
///
/// - the `startIndex` and `endIndex` properties,
/// - a subscript that provides at least read-only access to your type's
/// elements, and
/// - the `index(after:)` method for advancing an index into your collection.
///
/// Expected Performance
/// ====================
///
/// Types that conform to `Collection` are expected to provide the `startIndex`
/// and `endIndex` properties and subscript access to elements as O(1)
/// operations. Types that are not able to guarantee that expected performance
/// must document the departure, because many collection operations depend on
/// O(1) subscripting performance for their own performance guarantees.
///
/// The performance of some collection operations depends on the type of index
/// that the collection provides. For example, a random-access collection,
/// which can measure the distance between two indices in O(1) time, will be
/// able to calculate its `count` property in O(1) time. Conversely, because a
/// forward or bidirectional collection must traverse the entire collection to
/// count the number of contained elements, accessing its `count` property is
/// an O(*n*) operation.
public protocol Collection : _Indexable, Sequence {
/// A type that can represent the number of steps between a pair of
/// indices.
associatedtype IndexDistance : SignedInteger = Int
/// A type that provides the collection's iteration interface and
/// encapsulates its iteration state.
///
/// By default, a collection conforms to the `Sequence` protocol by
/// supplying a `IndexingIterator` as its associated `Iterator`
/// type.
associatedtype Iterator : IteratorProtocol = IndexingIterator<Self>
// FIXME: Needed here so that the `Iterator` is properly deduced from
// a custom `makeIterator()` function. Otherwise we get an
// `IndexingIterator`. <rdar://problem/21539115>
/// Returns an iterator over the elements of the collection.
func makeIterator() -> Iterator
/// A sequence that represents a contiguous subrange of the collection's
/// elements.
///
/// This associated type appears as a requirement in the `Sequence`
/// protocol, but it is restated here with stricter constraints. In a
/// collection, the subsequence should also conform to `Collection`.
associatedtype SubSequence : _IndexableBase, Sequence = Slice<Self>
// FIXME(ABI)#98 (Recursive Protocol Constraints):
// FIXME(ABI)#99 (Associated Types with where clauses):
// associatedtype SubSequence : Collection
// where
// Iterator.Element == SubSequence.Iterator.Element,
// SubSequence.Index == Index,
// SubSequence.Indices == Indices,
// SubSequence.SubSequence == SubSequence
//
// (<rdar://problem/20715009> Implement recursive protocol
// constraints)
//
// These constraints allow processing collections in generic code by
// repeatedly slicing them in a loop.
/// Accesses the element at the specified position.
///
/// The following example accesses an element of an array through its
/// subscript to print its value:
///
/// var streets = ["Adams", "Bryant", "Channing", "Douglas", "Evarts"]
/// print(streets[1])
/// // Prints "Bryant"
///
/// You can subscript a collection with any valid index other than the
/// collection's end index. The end index refers to the position one past
/// the last element of a collection, so it doesn't correspond with an
/// element.
///
/// - Parameter position: The position of the element to access. `position`
/// must be a valid index of the collection that is not equal to the
/// `endIndex` property.
subscript(position: Index) -> Iterator.Element { get }
/// Accesses a contiguous subrange of the collection's elements.
///
/// The accessed slice uses the same indices for the same elements as the
/// original collection uses. Always use the slice's `startIndex` property
/// instead of assuming that its indices start at a particular value.
///
/// This example demonstrates getting a slice of an array of strings, finding
/// the index of one of the strings in the slice, and then using that index
/// in the original array.
///
/// let streets = ["Adams", "Bryant", "Channing", "Douglas", "Evarts"]
/// let streetsSlice = streets[2 ..< streets.endIndex]
/// print(streetsSlice)
/// // Prints "["Channing", "Douglas", "Evarts"]"
///
/// let index = streetsSlice.index(of: "Evarts") // 4
/// print(streets[index!])
/// // Prints "Evarts"
///
/// - Parameter bounds: A range of the collection's indices. The bounds of
/// the range must be valid indices of the collection.
subscript(bounds: Range<Index>) -> SubSequence { get }
/// A type that can represent the indices that are valid for subscripting the
/// collection, in ascending order.
associatedtype Indices : _Indexable, Sequence = DefaultIndices<Self>
// FIXME(ABI)#68 (Associated Types with where clauses):
// FIXME(ABI)#100 (Recursive Protocol Constraints):
// associatedtype Indices : Collection
// where
// Indices.Iterator.Element == Index,
// Indices.Index == Index,
// Indices.SubSequence == Indices
// = DefaultIndices<Self>
/// The indices that are valid for subscripting the collection, in ascending
/// order.
///
/// A collection's `indices` property can hold a strong reference to the
/// collection itself, causing the collection to be non-uniquely referenced.
/// If you mutate the collection while iterating over its indices, a strong
/// reference can cause an unexpected copy of the collection. To avoid the
/// unexpected copy, use the `index(after:)` method starting with
/// `startIndex` to produce indices instead.
///
/// var c = MyFancyCollection([10, 20, 30, 40, 50])
/// var i = c.startIndex
/// while i != c.endIndex {
/// c[i] /= 5
/// i = c.index(after: i)
/// }
/// // c == MyFancyCollection([2, 4, 6, 8, 10])
var indices: Indices { get }
/// Returns a subsequence from the start of the collection up to, but not
/// including, the specified position.
///
/// The resulting subsequence *does not include* the element at the position
/// `end`. The following example searches for the index of the number `40`
/// in an array of integers, and then prints the prefix of the array up to,
/// but not including, that index:
///
/// let numbers = [10, 20, 30, 40, 50, 60]
/// if let i = numbers.index(of: 40) {
/// print(numbers.prefix(upTo: i))
/// }
/// // Prints "[10, 20, 30]"
///
/// Passing the collection's starting index as the `end` parameter results in
/// an empty subsequence.
///
/// print(numbers.prefix(upTo: numbers.startIndex))
/// // Prints "[]"
///
/// - Parameter end: The "past the end" index of the resulting subsequence.
/// `end` must be a valid index of the collection.
/// - Returns: A subsequence up to, but not including, the `end` position.
///
/// - Complexity: O(1)
/// - SeeAlso: `prefix(through:)`
func prefix(upTo end: Index) -> SubSequence
/// Returns a subsequence from the specified position to the end of the
/// collection.
///
/// The following example searches for the index of the number `40` in an
/// array of integers, and then prints the suffix of the array starting at
/// that index:
///
/// let numbers = [10, 20, 30, 40, 50, 60]
/// if let i = numbers.index(of: 40) {
/// print(numbers.suffix(from: i))
/// }
/// // Prints "[40, 50, 60]"
///
/// Passing the collection's `endIndex` as the `start` parameter results in
/// an empty subsequence.
///
/// print(numbers.suffix(from: numbers.endIndex))
/// // Prints "[]"
///
/// - Parameter start: The index at which to start the resulting subsequence.
/// `start` must be a valid index of the collection.
/// - Returns: A subsequence starting at the `start` position.
///
/// - Complexity: O(1)
func suffix(from start: Index) -> SubSequence
/// Returns a subsequence from the start of the collection through the
/// specified position.
///
/// The resulting subsequence *includes* the element at the position `end`.
/// The following example searches for the index of the number `40` in an
/// array of integers, and then prints the prefix of the array up to, and
/// including, that index:
///
/// let numbers = [10, 20, 30, 40, 50, 60]
/// if let i = numbers.index(of: 40) {
/// print(numbers.prefix(through: i))
/// }
/// // Prints "[10, 20, 30, 40]"
///
/// - Parameter end: The index of the last element to include in the
/// resulting subsequence. `end` must be a valid index of the collection
/// that is not equal to the `endIndex` property.
/// - Returns: A subsequence up to, and including, the `end` position.
///
/// - Complexity: O(1)
/// - SeeAlso: `prefix(upTo:)`
func prefix(through position: Index) -> SubSequence
/// A Boolean value indicating whether the collection is empty.
///
/// When you need to check whether your collection is empty, use the
/// `isEmpty` property instead of checking that the `count` property is
/// equal to zero. For collections that don't conform to
/// `RandomAccessCollection`, accessing the `count` property iterates
/// through the elements of the collection.
///
/// let horseName = "Silver"
/// if horseName.characters.isEmpty {
/// print("I've been through the desert on a horse with no name.")
/// } else {
/// print("Hi ho, \(horseName)!")
/// }
/// // Prints "Hi ho, Silver!")
///
/// - Complexity: O(1)
var isEmpty: Bool { get }
/// The number of elements in the collection.
///
/// - Complexity: O(1) if the collection conforms to
/// `RandomAccessCollection`; otherwise, O(*n*), where *n* is the length
/// of the collection.
var count: IndexDistance { get }
// The following requirement enables dispatching for index(of:) when
// the element type is Equatable.
/// Returns `Optional(Optional(index))` if an element was found
/// or `Optional(nil)` if an element was determined to be missing;
/// otherwise, `nil`.
///
/// - Complexity: O(*n*)
func _customIndexOfEquatableElement(_ element: Iterator.Element) -> Index??
/// The first element of the collection.
///
/// If the collection is empty, the value of this property is `nil`.
///
/// let numbers = [10, 20, 30, 40, 50]
/// if let firstNumber = numbers.first {
/// print(firstNumber)
/// }
/// // Prints "10"
var first: Iterator.Element? { get }
/// Returns an index that is the specified distance from the given index.
///
/// The following example obtains an index advanced four positions from a
/// string's starting index and then prints the character at that position.
///
/// let s = "Swift"
/// let i = s.index(s.startIndex, offsetBy: 4)
/// print(s[i])
/// // Prints "t"
///
/// The value passed as `n` must not offset `i` beyond the `endIndex` or
/// before the `startIndex` of this collection.
///
/// - Parameters:
/// - i: A valid index of the collection.
/// - n: The distance to offset `i`. `n` must not be negative unless the
/// collection conforms to the `BidirectionalCollection` protocol.
/// - Returns: An index offset by `n` from the index `i`. If `n` is positive,
/// this is the same value as the result of `n` calls to `index(after:)`.
/// If `n` is negative, this is the same value as the result of `-n` calls
/// to `index(before:)`.
///
/// - SeeAlso: `index(_:offsetBy:limitedBy:)`, `formIndex(_:offsetBy:)`
/// - Complexity: O(1) if the collection conforms to
/// `RandomAccessCollection`; otherwise, O(*n*), where *n* is the absolute
/// value of `n`.
func index(_ i: Index, offsetBy n: IndexDistance) -> Index
/// Returns an index that is the specified distance from the given index,
/// unless that distance is beyond a given limiting index.
///
/// The following example obtains an index advanced four positions from a
/// string's starting index and then prints the character at that position.
/// The operation doesn't require going beyond the limiting `s.endIndex`
/// value, so it succeeds.
///
/// let s = "Swift"
/// if let i = s.index(s.startIndex, offsetBy: 4, limitedBy: s.endIndex) {
/// print(s[i])
/// }
/// // Prints "t"
///
/// The next example attempts to retrieve an index six positions from
/// `s.startIndex` but fails, because that distance is beyond the index
/// passed as `limit`.
///
/// let j = s.index(s.startIndex, offsetBy: 6, limitedBy: s.endIndex)
/// print(j)
/// // Prints "nil"
///
/// The value passed as `n` must not offset `i` beyond the `endIndex` or
/// before the `startIndex` of this collection, unless the index passed as
/// `limit` prevents offsetting beyond those bounds.
///
/// - Parameters:
/// - i: A valid index of the collection.
/// - n: The distance to offset `i`. `n` must not be negative unless the
/// collection conforms to the `BidirectionalCollection` protocol.
/// - limit: A valid index of the collection to use as a limit. If `n > 0`,
/// a limit that is less than `i` has no effect. Likewise, if `n < 0`, a
/// limit that is greater than `i` has no effect.
/// - Returns: An index offset by `n` from the index `i`, unless that index
/// would be beyond `limit` in the direction of movement. In that case,
/// the method returns `nil`.
///
/// - SeeAlso: `index(_:offsetBy:)`, `formIndex(_:offsetBy:limitedBy:)`
/// - Complexity: O(1) if the collection conforms to
/// `RandomAccessCollection`; otherwise, O(*n*), where *n* is the absolute
/// value of `n`.
func index(
_ i: Index, offsetBy n: IndexDistance, limitedBy limit: Index
) -> Index?
/// Returns the distance between two indices.
///
/// Unless the collection conforms to the `BidirectionalCollection` protocol,
/// `start` must be less than or equal to `end`.
///
/// - Parameters:
/// - start: A valid index of the collection.
/// - end: Another valid index of the collection. If `end` is equal to
/// `start`, the result is zero.
/// - Returns: The distance between `start` and `end`. The result can be
/// negative only if the collection conforms to the
/// `BidirectionalCollection` protocol.
///
/// - Complexity: O(1) if the collection conforms to
/// `RandomAccessCollection`; otherwise, O(*n*), where *n* is the
/// resulting distance.
func distance(from start: Index, to end: Index) -> IndexDistance
}
/// Default implementation for forward collections.
extension _Indexable {
/// Replaces the given index with its successor.
///
/// - Parameter i: A valid index of the collection. `i` must be less than
/// `endIndex`.
@inline(__always)
public func formIndex(after i: inout Index) {
i = index(after: i)
}
public func _failEarlyRangeCheck(_ index: Index, bounds: Range<Index>) {
// FIXME: swift-3-indexing-model: tests.
_precondition(
bounds.lowerBound <= index,
"out of bounds: index < startIndex")
_precondition(
index < bounds.upperBound,
"out of bounds: index >= endIndex")
}
public func _failEarlyRangeCheck(_ index: Index, bounds: ClosedRange<Index>) {
// FIXME: swift-3-indexing-model: tests.
_precondition(
bounds.lowerBound <= index,
"out of bounds: index < startIndex")
_precondition(
index <= bounds.upperBound,
"out of bounds: index > endIndex")
}
public func _failEarlyRangeCheck(_ range: Range<Index>, bounds: Range<Index>) {
// FIXME: swift-3-indexing-model: tests.
_precondition(
bounds.lowerBound <= range.lowerBound,
"out of bounds: range begins before startIndex")
_precondition(
range.lowerBound <= bounds.upperBound,
"out of bounds: range ends after endIndex")
_precondition(
bounds.lowerBound <= range.upperBound,
"out of bounds: range ends before bounds.lowerBound")
_precondition(
range.upperBound <= bounds.upperBound,
"out of bounds: range begins after bounds.upperBound")
}
/// Returns an index that is the specified distance from the given index.
///
/// The following example obtains an index advanced four positions from a
/// string's starting index and then prints the character at that position.
///
/// let s = "Swift"
/// let i = s.index(s.startIndex, offsetBy: 4)
/// print(s[i])
/// // Prints "t"
///
/// The value passed as `n` must not offset `i` beyond the `endIndex` or
/// before the `startIndex` of this collection.
///
/// - Parameters:
/// - i: A valid index of the collection.
/// - n: The distance to offset `i`. `n` must not be negative unless the
/// collection conforms to the `BidirectionalCollection` protocol.
/// - Returns: An index offset by `n` from the index `i`. If `n` is positive,
/// this is the same value as the result of `n` calls to `index(after:)`.
/// If `n` is negative, this is the same value as the result of `-n` calls
/// to `index(before:)`.
///
/// - SeeAlso: `index(_:offsetBy:limitedBy:)`, `formIndex(_:offsetBy:)`
/// - Complexity: O(1) if the collection conforms to
/// `RandomAccessCollection`; otherwise, O(*n*), where *n* is the absolute
/// value of `n`.
public func index(_ i: Index, offsetBy n: IndexDistance) -> Index {
return self._advanceForward(i, by: n)
}
/// Returns an index that is the specified distance from the given index,
/// unless that distance is beyond a given limiting index.
///
/// The following example obtains an index advanced four positions from a
/// string's starting index and then prints the character at that position.
/// The operation doesn't require going beyond the limiting `s.endIndex`
/// value, so it succeeds.
///
/// let s = "Swift"
/// if let i = s.index(s.startIndex, offsetBy: 4, limitedBy: s.endIndex) {
/// print(s[i])
/// }
/// // Prints "t"
///
/// The next example attempts to retrieve an index six positions from
/// `s.startIndex` but fails, because that distance is beyond the index
/// passed as `limit`.
///
/// let j = s.index(s.startIndex, offsetBy: 6, limitedBy: s.endIndex)
/// print(j)
/// // Prints "nil"
///
/// The value passed as `n` must not offset `i` beyond the `endIndex` or
/// before the `startIndex` of this collection, unless the index passed as
/// `limit` prevents offsetting beyond those bounds.
///
/// - Parameters:
/// - i: A valid index of the collection.
/// - n: The distance to offset `i`. `n` must not be negative unless the
/// collection conforms to the `BidirectionalCollection` protocol.
/// - limit: A valid index of the collection to use as a limit. If `n > 0`,
/// a limit that is less than `i` has no effect. Likewise, if `n < 0`, a
/// limit that is greater than `i` has no effect.
/// - Returns: An index offset by `n` from the index `i`, unless that index
/// would be beyond `limit` in the direction of movement. In that case,
/// the method returns `nil`.
///
/// - SeeAlso: `index(_:offsetBy:)`, `formIndex(_:offsetBy:limitedBy:)`
/// - Complexity: O(1) if the collection conforms to
/// `RandomAccessCollection`; otherwise, O(*n*), where *n* is the absolute
/// value of `n`.
public func index(
_ i: Index, offsetBy n: IndexDistance, limitedBy limit: Index
) -> Index? {
return self._advanceForward(i, by: n, limitedBy: limit)
}
/// Offsets the given index by the specified distance.
///
/// The value passed as `n` must not offset `i` beyond the `endIndex` or
/// before the `startIndex` of this collection.
///
/// - Parameters:
/// - i: A valid index of the collection.
/// - n: The distance to offset `i`. `n` must not be negative unless the
/// collection conforms to the `BidirectionalCollection` protocol.
///
/// - SeeAlso: `index(_:offsetBy:)`, `formIndex(_:offsetBy:limitedBy:)`
/// - Complexity: O(1) if the collection conforms to
/// `RandomAccessCollection`; otherwise, O(*n*), where *n* is the absolute
/// value of `n`.
public func formIndex(_ i: inout Index, offsetBy n: IndexDistance) {
i = index(i, offsetBy: n)
}
/// Offsets the given index by the specified distance, or so that it equals
/// the given limiting index.
///
/// The value passed as `n` must not offset `i` beyond the `endIndex` or
/// before the `startIndex` of this collection, unless the index passed as
/// `limit` prevents offsetting beyond those bounds.
///
/// - Parameters:
/// - i: A valid index of the collection.
/// - n: The distance to offset `i`. `n` must not be negative unless the
/// collection conforms to the `BidirectionalCollection` protocol.
/// - Returns: `true` if `i` has been offset by exactly `n` steps without
/// going beyond `limit`; otherwise, `false`. When the return value is
/// `false`, the value of `i` is equal to `limit`.
///
/// - SeeAlso: `index(_:offsetBy:)`, `formIndex(_:offsetBy:limitedBy:)`
/// - Complexity: O(1) if the collection conforms to
/// `RandomAccessCollection`; otherwise, O(*n*), where *n* is the absolute
/// value of `n`.
public func formIndex(
_ i: inout Index, offsetBy n: IndexDistance, limitedBy limit: Index
) -> Bool {
if let advancedIndex = index(i, offsetBy: n, limitedBy: limit) {
i = advancedIndex
return true
}
i = limit
return false
}
/// Returns the distance between two indices.
///
/// Unless the collection conforms to the `BidirectionalCollection` protocol,
/// `start` must be less than or equal to `end`.
///
/// - Parameters:
/// - start: A valid index of the collection.
/// - end: Another valid index of the collection. If `end` is equal to
/// `start`, the result is zero.
/// - Returns: The distance between `start` and `end`. The result can be
/// negative only if the collection conforms to the
/// `BidirectionalCollection` protocol.
///
/// - Complexity: O(1) if the collection conforms to
/// `RandomAccessCollection`; otherwise, O(*n*), where *n* is the
/// resulting distance.
public func distance(from start: Index, to end: Index) -> IndexDistance {
_precondition(start <= end,
"Only BidirectionalCollections can have end come before start")
var start = start
var count: IndexDistance = 0
while start != end {
count = count + 1
formIndex(after: &start)
}
return count
}
/// Do not use this method directly; call advanced(by: n) instead.
@inline(__always)
internal func _advanceForward(_ i: Index, by n: IndexDistance) -> Index {
_precondition(n >= 0,
"Only BidirectionalCollections can be advanced by a negative amount")
var i = i
for _ in stride(from: 0, to: n, by: 1) {
formIndex(after: &i)
}
return i
}
/// Do not use this method directly; call advanced(by: n, limit) instead.
@inline(__always)
internal
func _advanceForward(
_ i: Index, by n: IndexDistance, limitedBy limit: Index
) -> Index? {
_precondition(n >= 0,
"Only BidirectionalCollections can be advanced by a negative amount")
var i = i
for _ in stride(from: 0, to: n, by: 1) {
if i == limit {
return nil
}
formIndex(after: &i)
}
return i
}
}
/// Supply the default `makeIterator()` method for `Collection` models
/// that accept the default associated `Iterator`,
/// `IndexingIterator<Self>`.
extension Collection where Iterator == IndexingIterator<Self> {
/// Returns an iterator over the elements of the collection.
public func makeIterator() -> IndexingIterator<Self> {
return IndexingIterator(_elements: self)
}
}
/// Supply the default "slicing" `subscript` for `Collection` models
/// that accept the default associated `SubSequence`, `Slice<Self>`.
extension Collection where SubSequence == Slice<Self> {
/// Accesses a contiguous subrange of the collection's elements.
///
/// The accessed slice uses the same indices for the same elements as the
/// original collection uses. Always use the slice's `startIndex` property
/// instead of assuming that its indices start at a particular value.
///
/// This example demonstrates getting a slice of an array of strings, finding
/// the index of one of the strings in the slice, and then using that index
/// in the original array.
///
/// let streets = ["Adams", "Bryant", "Channing", "Douglas", "Evarts"]
/// let streetsSlice = streets[2 ..< streets.endIndex]
/// print(streetsSlice)
/// // Prints "["Channing", "Douglas", "Evarts"]"
///
/// let index = streetsSlice.index(of: "Evarts") // 4
/// print(streets[index!])
/// // Prints "Evarts"
///
/// - Parameter bounds: A range of the collection's indices. The bounds of
/// the range must be valid indices of the collection.
public subscript(bounds: Range<Index>) -> Slice<Self> {
_failEarlyRangeCheck(bounds, bounds: startIndex..<endIndex)
return Slice(base: self, bounds: bounds)
}
}
extension Collection where SubSequence == Self {
/// Removes and returns the first element of the collection.
///
/// - Returns: The first element of the collection if the collection is
/// not empty; otherwise, `nil`.
///
/// - Complexity: O(1)
public mutating func popFirst() -> Iterator.Element? {
// TODO: swift-3-indexing-model - review the following
guard !isEmpty else { return nil }
let element = first!
self = self[index(after: startIndex)..<endIndex]
return element
}
}
/// Default implementations of core requirements
extension Collection {
/// A Boolean value indicating whether the collection is empty.
///
/// When you need to check whether your collection is empty, use the
/// `isEmpty` property instead of checking that the `count` property is
/// equal to zero. For collections that don't conform to
/// `RandomAccessCollection`, accessing the `count` property iterates
/// through the elements of the collection.
///
/// let horseName = "Silver"
/// if horseName.characters.isEmpty {
/// print("I've been through the desert on a horse with no name.")
/// } else {
/// print("Hi ho, \(horseName)!")
/// }
/// // Prints "Hi ho, Silver!")
///
/// - Complexity: O(1)
public var isEmpty: Bool {
return startIndex == endIndex
}
/// The first element of the collection.
///
/// If the collection is empty, the value of this property is `nil`.
///
/// let numbers = [10, 20, 30, 40, 50]
/// if let firstNumber = numbers.first {
/// print(firstNumber)
/// }
/// // Prints "10"
public var first: Iterator.Element? {
// NB: Accessing `startIndex` may not be O(1) for some lazy collections,
// so instead of testing `isEmpty` and then returning the first element,
// we'll just rely on the fact that the iterator always yields the
// first element first.
var i = makeIterator()
return i.next()
}
// TODO: swift-3-indexing-model - uncomment and replace above ready (or should we still use the iterator one?)
/// Returns the first element of `self`, or `nil` if `self` is empty.
///
/// - Complexity: O(1)
// public var first: Iterator.Element? {
// return isEmpty ? nil : self[startIndex]
// }
/// A value less than or equal to the number of elements in the collection.
///
/// - Complexity: O(1) if the collection conforms to
/// `RandomAccessCollection`; otherwise, O(*n*), where *n* is the length
/// of the collection.
public var underestimatedCount: Int {
// TODO: swift-3-indexing-model - review the following
return numericCast(count)
}
/// The number of elements in the collection.
///
/// - Complexity: O(1) if the collection conforms to
/// `RandomAccessCollection`; otherwise, O(*n*), where *n* is the length
/// of the collection.
public var count: IndexDistance {
return distance(from: startIndex, to: endIndex)
}
// TODO: swift-3-indexing-model - rename the following to _customIndexOfEquatable(element)?
/// Customization point for `Collection.index(of:)`.
///
/// Define this method if the collection can find an element in less than
/// O(*n*) by exploiting collection-specific knowledge.
///
/// - Returns: `nil` if a linear search should be attempted instead,
/// `Optional(nil)` if the element was not found, or
/// `Optional(Optional(index))` if an element was found.
///
/// - Complexity: O(`count`).
public // dispatching
func _customIndexOfEquatableElement(_: Iterator.Element) -> Index?? {
return nil
}
}
//===----------------------------------------------------------------------===//
// Default implementations for Collection
//===----------------------------------------------------------------------===//
extension Collection {
/// Returns an array containing the results of mapping the given closure
/// over the sequence's elements.
///
/// In this example, `map` is used first to convert the names in the array
/// to lowercase strings and then to count their characters.
///
/// let cast = ["Vivien", "Marlon", "Kim", "Karl"]
/// let lowercaseNames = cast.map { $0.lowercaseString }
/// // 'lowercaseNames' == ["vivien", "marlon", "kim", "karl"]
/// let letterCounts = cast.map { $0.characters.count }
/// // 'letterCounts' == [6, 6, 3, 4]
///
/// - Parameter transform: A mapping closure. `transform` accepts an
/// element of this sequence as its parameter and returns a transformed
/// value of the same or of a different type.
/// - Returns: An array containing the transformed elements of this
/// sequence.
public func map<T>(
_ transform: (Iterator.Element) throws -> T
) rethrows -> [T] {
// TODO: swift-3-indexing-model - review the following
let count: Int = numericCast(self.count)
if count == 0 {
return []
}
var result = ContiguousArray<T>()
result.reserveCapacity(count)
var i = self.startIndex
for _ in 0..<count {
result.append(try transform(self[i]))
formIndex(after: &i)
}
_expectEnd(i, self)
return Array(result)
}
/// Returns a subsequence containing all but the given number of initial
/// elements.
///
/// If the number of elements to drop exceeds the number of elements in
/// the collection, the result is an empty subsequence.
///
/// let numbers = [1, 2, 3, 4, 5]
/// print(numbers.dropFirst(2))
/// // Prints "[3, 4, 5]"
/// print(numbers.dropFirst(10))
/// // Prints "[]"
///
/// - Parameter n: The number of elements to drop from the beginning of
/// the collection. `n` must be greater than or equal to zero.
/// - Returns: A subsequence starting after the specified number of
/// elements.
///
/// - Complexity: O(*n*), where *n* is the number of elements to drop from
/// the beginning of the collection.
public func dropFirst(_ n: Int) -> SubSequence {
_precondition(n >= 0, "Can't drop a negative number of elements from a collection")
let start = index(startIndex,
offsetBy: numericCast(n), limitedBy: endIndex) ?? endIndex
return self[start..<endIndex]
}
/// Returns a subsequence containing all but the specified number of final
/// elements.
///
/// If the number of elements to drop exceeds the number of elements in the
/// collection, the result is an empty subsequence.
///
/// let numbers = [1, 2, 3, 4, 5]
/// print(numbers.dropLast(2))
/// // Prints "[1, 2, 3]"
/// print(numbers.dropLast(10))
/// // Prints "[]"
///
/// - Parameter n: The number of elements to drop off the end of the
/// collection. `n` must be greater than or equal to zero.
/// - Returns: A subsequence that leaves off the specified number of elements
/// at the end.
///
/// - Complexity: O(*n*), where *n* is the length of the collection.
public func dropLast(_ n: Int) -> SubSequence {
_precondition(
n >= 0, "Can't drop a negative number of elements from a collection")
let amount = Swift.max(0, numericCast(count) - n)
let end = index(startIndex,
offsetBy: numericCast(amount), limitedBy: endIndex) ?? endIndex
return self[startIndex..<end]
}
/// Returns a subsequence by skipping elements while `predicate` returns
/// `true` and returning the remaining elements.
///
/// - Parameter predicate: A closure that takes an element of the
/// sequence as its argument and returns `true` if the element should
/// be skipped or `false` if it should be included. Once the predicate
/// returns `false` it will not be called again.
///
/// - Complexity: O(*n*), where *n* is the length of the collection.
public func drop(
while predicate: (Iterator.Element) throws -> Bool
) rethrows -> SubSequence {
var start = startIndex
while try start != endIndex && predicate(self[start]) {
formIndex(after: &start)
}
return self[start..<endIndex]
}
/// Returns a subsequence, up to the specified maximum length, containing
/// the initial elements of the collection.
///
/// If the maximum length exceeds the number of elements in the collection,
/// the result contains all the elements in the collection.
///
/// let numbers = [1, 2, 3, 4, 5]
/// print(numbers.prefix(2))
/// // Prints "[1, 2]"
/// print(numbers.prefix(10))
/// // Prints "[1, 2, 3, 4, 5]"
///
/// - Parameter maxLength: The maximum number of elements to return.
/// `maxLength` must be greater than or equal to zero.
/// - Returns: A subsequence starting at the beginning of this collection
/// with at most `maxLength` elements.
public func prefix(_ maxLength: Int) -> SubSequence {
_precondition(
maxLength >= 0,
"Can't take a prefix of negative length from a collection")
let end = index(startIndex,
offsetBy: numericCast(maxLength), limitedBy: endIndex) ?? endIndex
return self[startIndex..<end]
}
/// Returns a subsequence containing the initial elements until `predicate`
/// returns `false` and skipping the remaining elements.
///
/// - Parameter predicate: A closure that takes an element of the
/// sequence as its argument and returns `true` if the element should
/// be included or `false` if it should be excluded. Once the predicate
/// returns `false` it will not be called again.
///
/// - Complexity: O(*n*), where *n* is the length of the collection.
public func prefix(
while predicate: (Iterator.Element) throws -> Bool
) rethrows -> SubSequence {
var end = startIndex
while try end != endIndex && predicate(self[end]) {
formIndex(after: &end)
}
return self[startIndex..<end]
}
/// Returns a subsequence, up to the given maximum length, containing the
/// final elements of the collection.
///
/// If the maximum length exceeds the number of elements in the collection,
/// the result contains all the elements in the collection.
///
/// let numbers = [1, 2, 3, 4, 5]
/// print(numbers.suffix(2))
/// // Prints "[4, 5]"
/// print(numbers.suffix(10))
/// // Prints "[1, 2, 3, 4, 5]"
///
/// - Parameter maxLength: The maximum number of elements to return. The
/// value of `maxLength` must be greater than or equal to zero.
/// - Returns: A subsequence terminating at the end of the collection with at
/// most `maxLength` elements.
///
/// - Complexity: O(*n*), where *n* is the length of the collection.
public func suffix(_ maxLength: Int) -> SubSequence {
_precondition(
maxLength >= 0,
"Can't take a suffix of negative length from a collection")
let amount = Swift.max(0, numericCast(count) - maxLength)
let start = index(startIndex,
offsetBy: numericCast(amount), limitedBy: endIndex) ?? endIndex
return self[start..<endIndex]
}
/// Returns a subsequence from the start of the collection up to, but not
/// including, the specified position.
///
/// The resulting subsequence *does not include* the element at the position
/// `end`. The following example searches for the index of the number `40`
/// in an array of integers, and then prints the prefix of the array up to,
/// but not including, that index:
///
/// let numbers = [10, 20, 30, 40, 50, 60]
/// if let i = numbers.index(of: 40) {
/// print(numbers.prefix(upTo: i))
/// }
/// // Prints "[10, 20, 30]"
///
/// Passing the collection's starting index as the `end` parameter results in
/// an empty subsequence.
///
/// print(numbers.prefix(upTo: numbers.startIndex))
/// // Prints "[]"
///
/// - Parameter end: The "past the end" index of the resulting subsequence.
/// `end` must be a valid index of the collection.
/// - Returns: A subsequence up to, but not including, the `end` position.
///
/// - Complexity: O(1)
/// - SeeAlso: `prefix(through:)`
public func prefix(upTo end: Index) -> SubSequence {
return self[startIndex..<end]
}
/// Returns a subsequence from the specified position to the end of the
/// collection.
///
/// The following example searches for the index of the number `40` in an
/// array of integers, and then prints the suffix of the array starting at
/// that index:
///
/// let numbers = [10, 20, 30, 40, 50, 60]
/// if let i = numbers.index(of: 40) {
/// print(numbers.suffix(from: i))
/// }
/// // Prints "[40, 50, 60]"
///
/// Passing the collection's `endIndex` as the `start` parameter results in
/// an empty subsequence.
///
/// print(numbers.suffix(from: numbers.endIndex))
/// // Prints "[]"
///
/// - Parameter start: The index at which to start the resulting subsequence.
/// `start` must be a valid index of the collection.
/// - Returns: A subsequence starting at the `start` position.
///
/// - Complexity: O(1)
public func suffix(from start: Index) -> SubSequence {
return self[start..<endIndex]
}
/// Returns a subsequence from the start of the collection through the
/// specified position.
///
/// The resulting subsequence *includes* the element at the position `end`.
/// The following example searches for the index of the number `40` in an
/// array of integers, and then prints the prefix of the array up to, and
/// including, that index:
///
/// let numbers = [10, 20, 30, 40, 50, 60]
/// if let i = numbers.index(of: 40) {
/// print(numbers.prefix(through: i))
/// }
/// // Prints "[10, 20, 30, 40]"
///
/// - Parameter end: The index of the last element to include in the
/// resulting subsequence. `end` must be a valid index of the collection
/// that is not equal to the `endIndex` property.
/// - Returns: A subsequence up to, and including, the `end` position.
///
/// - Complexity: O(1)
/// - SeeAlso: `prefix(upTo:)`
public func prefix(through position: Index) -> SubSequence {
return prefix(upTo: index(after: position))
}
/// Returns the longest possible subsequences of the collection, in order,
/// that don't contain elements satisfying the given predicate.
///
/// The resulting array consists of at most `maxSplits + 1` subsequences.
/// Elements that are used to split the sequence are not returned as part of
/// any subsequence.
///
/// The following examples show the effects of the `maxSplits` and
/// `omittingEmptySubsequences` parameters when splitting a string using a
/// closure that matches spaces. The first use of `split` returns each word
/// that was originally separated by one or more spaces.
///
/// let line = "BLANCHE: I don't want realism. I want magic!"
/// print(line.characters.split(whereSeparator: { $0 == " " })
/// .map(String.init))
/// // Prints "["BLANCHE:", "I", "don\'t", "want", "realism.", "I", "want", "magic!"]"
///
/// The second example passes `1` for the `maxSplits` parameter, so the
/// original string is split just once, into two new strings.
///
/// print(
/// line.characters.split(
/// maxSplits: 1, whereSeparator: { $0 == " " }
/// ).map(String.init))
/// // Prints "["BLANCHE:", " I don\'t want realism. I want magic!"]"
///
/// The final example passes `false` for the `omittingEmptySubsequences`
/// parameter, so the returned array contains empty strings where spaces
/// were repeated.
///
/// print(line.characters.split(omittingEmptySubsequences: false, whereSeparator: { $0 == " " })
/// .map(String.init))
/// // Prints "["BLANCHE:", "", "", "I", "don\'t", "want", "realism.", "I", "want", "magic!"]"
///
/// - Parameters:
/// - maxSplits: The maximum number of times to split the collection, or
/// one less than the number of subsequences to return. If
/// `maxSplits + 1` subsequences are returned, the last one is a suffix
/// of the original collection containing the remaining elements.
/// `maxSplits` must be greater than or equal to zero. The default value
/// is `Int.max`.
/// - omittingEmptySubsequences: If `false`, an empty subsequence is
/// returned in the result for each pair of consecutive elements
/// satisfying the `isSeparator` predicate and for each element at the
/// start or end of the collection satisfying the `isSeparator`
/// predicate. The default value is `true`.
/// - isSeparator: A closure that takes an element as an argument and
/// returns a Boolean value indicating whether the collection should be
/// split at that element.
/// - Returns: An array of subsequences, split from this collection's
/// elements.
public func split(
maxSplits: Int = Int.max,
omittingEmptySubsequences: Bool = true,
whereSeparator isSeparator: (Iterator.Element) throws -> Bool
) rethrows -> [SubSequence] {
// TODO: swift-3-indexing-model - review the following
_precondition(maxSplits >= 0, "Must take zero or more splits")
var result: [SubSequence] = []
var subSequenceStart: Index = startIndex
func appendSubsequence(end: Index) -> Bool {
if subSequenceStart == end && omittingEmptySubsequences {
return false
}
result.append(self[subSequenceStart..<end])
return true
}
if maxSplits == 0 || isEmpty {
_ = appendSubsequence(end: endIndex)
return result
}
var subSequenceEnd = subSequenceStart
let cachedEndIndex = endIndex
while subSequenceEnd != cachedEndIndex {
if try isSeparator(self[subSequenceEnd]) {
let didAppend = appendSubsequence(end: subSequenceEnd)
formIndex(after: &subSequenceEnd)
subSequenceStart = subSequenceEnd
if didAppend && result.count == maxSplits {
break
}
continue
}
formIndex(after: &subSequenceEnd)
}
if subSequenceStart != cachedEndIndex || !omittingEmptySubsequences {
result.append(self[subSequenceStart..<cachedEndIndex])
}
return result
}
}
extension Collection where Iterator.Element : Equatable {
/// Returns the longest possible subsequences of the collection, in order,
/// around elements equal to the given element.
///
/// The resulting array consists of at most `maxSplits + 1` subsequences.
/// Elements that are used to split the collection are not returned as part
/// of any subsequence.
///
/// The following examples show the effects of the `maxSplits` and
/// `omittingEmptySubsequences` parameters when splitting a string at each
/// space character (" "). The first use of `split` returns each word that
/// was originally separated by one or more spaces.
///
/// let line = "BLANCHE: I don't want realism. I want magic!"
/// print(line.characters.split(separator: " ")
/// .map(String.init))
/// // Prints "["BLANCHE:", "I", "don\'t", "want", "realism.", "I", "want", "magic!"]"
///
/// The second example passes `1` for the `maxSplits` parameter, so the
/// original string is split just once, into two new strings.
///
/// print(line.characters.split(separator: " ", maxSplits: 1)
/// .map(String.init))
/// // Prints "["BLANCHE:", " I don\'t want realism. I want magic!"]"
///
/// The final example passes `false` for the `omittingEmptySubsequences`
/// parameter, so the returned array contains empty strings where spaces
/// were repeated.
///
/// print(line.characters.split(separator: " ", omittingEmptySubsequences: false)
/// .map(String.init))
/// // Prints "["BLANCHE:", "", "", "I", "don\'t", "want", "realism.", "I", "want", "magic!"]"
///
/// - Parameters:
/// - separator: The element that should be split upon.
/// - maxSplits: The maximum number of times to split the collection, or
/// one less than the number of subsequences to return. If
/// `maxSplits + 1` subsequences are returned, the last one is a suffix
/// of the original collection containing the remaining elements.
/// `maxSplits` must be greater than or equal to zero. The default value
/// is `Int.max`.
/// - omittingEmptySubsequences: If `false`, an empty subsequence is
/// returned in the result for each consecutive pair of `separator`
/// elements in the collection and for each instance of `separator` at
/// the start or end of the collection. If `true`, only nonempty
/// subsequences are returned. The default value is `true`.
/// - Returns: An array of subsequences, split from this collection's
/// elements.
public func split(
separator: Iterator.Element,
maxSplits: Int = Int.max,
omittingEmptySubsequences: Bool = true
) -> [SubSequence] {
// TODO: swift-3-indexing-model - review the following
return split(
maxSplits: maxSplits,
omittingEmptySubsequences: omittingEmptySubsequences,
whereSeparator: { $0 == separator })
}
}
extension Collection where SubSequence == Self {
/// Removes and returns the first element of the collection.
///
/// The collection must not be empty.
///
/// - Returns: The first element of the collection.
///
/// - Complexity: O(1)
/// - SeeAlso: `popFirst()`
@discardableResult
public mutating func removeFirst() -> Iterator.Element {
// TODO: swift-3-indexing-model - review the following
_precondition(!isEmpty, "can't remove items from an empty collection")
let element = first!
self = self[index(after: startIndex)..<endIndex]
return element
}
/// Removes the specified number of elements from the beginning of the
/// collection.
///
/// - Parameter n: The number of elements to remove. `n` must be greater than
/// or equal to zero, and must be less than or equal to the number of
/// elements in the collection.
///
/// - Complexity: O(1) if the collection conforms to
/// `RandomAccessCollection`; otherwise, O(*n*).
public mutating func removeFirst(_ n: Int) {
if n == 0 { return }
_precondition(n >= 0, "number of elements to remove should be non-negative")
_precondition(count >= numericCast(n),
"can't remove more items from a collection than it contains")
self = self[index(startIndex, offsetBy: numericCast(n))..<endIndex]
}
}
extension Collection {
public func _preprocessingPass<R>(
_ preprocess: () throws -> R
) rethrows -> R? {
return try preprocess()
}
}
@available(*, unavailable, message: "Bit enum has been removed. Please use Int instead.")
public enum Bit {}
@available(*, unavailable, renamed: "IndexingIterator")
public struct IndexingGenerator<Elements : _IndexableBase> {}
@available(*, unavailable, renamed: "Collection")
public typealias CollectionType = Collection
extension Collection {
@available(*, unavailable, renamed: "Iterator")
public typealias Generator = Iterator
@available(*, unavailable, renamed: "makeIterator()")
public func generate() -> Iterator {
Builtin.unreachable()
}
@available(*, unavailable, renamed: "getter:underestimatedCount()")
public func underestimateCount() -> Int {
Builtin.unreachable()
}
@available(*, unavailable, message: "Please use split(maxSplits:omittingEmptySubsequences:whereSeparator:) instead")
public func split(
_ maxSplit: Int = Int.max,
allowEmptySlices: Bool = false,
whereSeparator isSeparator: (Iterator.Element) throws -> Bool
) rethrows -> [SubSequence] {
Builtin.unreachable()
}
}
extension Collection where Iterator.Element : Equatable {
@available(*, unavailable, message: "Please use split(separator:maxSplits:omittingEmptySubsequences:) instead")
public func split(
_ separator: Iterator.Element,
maxSplit: Int = Int.max,
allowEmptySlices: Bool = false
) -> [SubSequence] {
Builtin.unreachable()
}
}
@available(*, unavailable, message: "PermutationGenerator has been removed in Swift 3")
public struct PermutationGenerator<C : Collection, Indices : Sequence> {}
|
apache-2.0
|
0bb2700cb7fb7b695c981b1fb04c2934
| 39.712585 | 118 | 0.646407 | 4.224281 | false | false | false | false |
hironytic/Kiretan0
|
Kiretan0/View/Main/MainViewModel.swift
|
1
|
16316
|
//
// MainViewModel.swift
// Kiretan0
//
// Copyright (c) 2017 Hironori Ichimiya <[email protected]>
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
import Foundation
import RxSwift
import RxCocoa
public enum MainViewToolbar {
case segment
case checked0
case checked1
}
public struct MainViewItemList {
public let viewModels: [MainItemViewModel]
public let hint: TableViewUpdateHint
}
public protocol MainViewModel: ViewModel {
var title: Observable<String> { get }
var segmentSelectedIndex: Observable<Int> { get }
var itemList: Observable<MainViewItemList> { get }
var itemListMessageText: Observable<String> { get }
var itemListMessageHidden: Observable<Bool> { get }
var mainViewToolbar: Observable<MainViewToolbar> { get }
var displayRequest: Observable<DisplayRequest> { get }
var onSetting: AnyObserver<Void> { get }
var onSegmentSelectedIndexChange: AnyObserver<Int> { get }
var onItemSelected: AnyObserver<IndexPath> { get }
var onAdd: AnyObserver<Void> { get }
var onUncheckAllItems: AnyObserver<Void> { get }
var onMakeInsufficient: AnyObserver<Void> { get }
var onMakeSufficient: AnyObserver<Void> { get }
}
public protocol MainViewModelResolver {
func resolveMainViewModel() -> MainViewModel
}
extension DefaultResolver: MainViewModelResolver {
public func resolveMainViewModel() -> MainViewModel {
return DefaultMainViewModel(resolver: self)
}
}
private let TEAM_ID = Config.bundled.teamID
public class DefaultMainViewModel: MainViewModel {
public typealias Resolver = MainItemViewModelResolver & TextInputViewModelResolver & SettingViewModelResolver &
TeamRepositoryResolver & MainUserDefaultsRepositoryResolver & ItemRepositoryResolver
public let title: Observable<String>
public let segmentSelectedIndex: Observable<Int>
public let itemList: Observable<MainViewItemList>
public let itemListMessageText: Observable<String>
public let itemListMessageHidden: Observable<Bool>
public let mainViewToolbar: Observable<MainViewToolbar>
public let displayRequest: Observable<DisplayRequest>
public let onSetting: AnyObserver<Void>
public let onSegmentSelectedIndexChange: AnyObserver<Int>
public let onItemSelected: AnyObserver<IndexPath>
public let onAdd: AnyObserver<Void>
public let onUncheckAllItems: AnyObserver<Void>
public let onMakeInsufficient: AnyObserver<Void>
public let onMakeSufficient: AnyObserver<Void>
private let disposeBag: DisposeBag
private class ItemState {
var item: Item {
didSet {
name.accept(ItemState.name(of: item))
if item.error != nil && isChecked.value {
isChecked.accept(false)
}
}
}
let name: BehaviorRelay<String>
let isChecked = BehaviorRelay<Bool>(value: false)
init(item: Item) {
self.item = item
self.name = BehaviorRelay(value: ItemState.name(of: item))
}
private static func name(of item: Item) -> String {
if item.error == nil {
return item.name
} else {
return R.String.errorItem.localized()
}
}
}
private struct ItemListState {
let states: [ItemState]
let viewModels: [MainItemViewModel]
let hint: TableViewUpdateHint
let error: Error?
public init(states: [ItemState], viewModels: [MainItemViewModel], hint: TableViewUpdateHint, error: Error? = nil) {
self.states = states
self.viewModels = viewModels
self.hint = hint
self.error = error
}
}
private enum ItemStateAction {
case change(CollectionChange<Item>)
case select(Int)
case uncheckAll
}
public init(resolver: Resolver) {
let disposeBag = DisposeBag()
struct Subject {
let onSegmentSelectedIndexChange = PublishSubject<Int>()
let onItemSelected = PublishSubject<Int>()
let onSetting = PublishSubject<Void>()
let onAdd = PublishSubject<Void>()
let onAddItem = PublishSubject<(String, Bool)>()
let onUncheckAllItems = PublishSubject<Void>()
let onChangeInsufficiency = PublishSubject<Bool>()
}
let subject = Subject()
let teamRepository = resolver.resolveTeamRepository()
let mainUserDefaultsRepository = resolver.resolveMainUserDefaultsRepository()
let itemRepository = resolver.resolveItemRepository()
let lastMainSegment = mainUserDefaultsRepository
.lastMainSegment
.share(replay: 1, scope: .whileConnected)
func createTitle() -> Observable<String> {
return teamRepository
.team(for: TEAM_ID)
.map { team in
team?.name ?? ""
}
.share(replay: 1, scope: .whileConnected)
.observeOn(MainScheduler.instance)
}
func createSegmentSelectedIndex() -> Observable<Int> {
return lastMainSegment
.observeOn(MainScheduler.instance)
}
func createItemListState() -> Observable<ItemListState> {
return lastMainSegment
.flatMapLatest { (segment: Int) -> Observable<ItemListState> in
let initialState = ItemListState(states: [], viewModels: [], hint: .whole)
let items = itemRepository.items(in: TEAM_ID, insufficient: segment == 1)
return Observable
.merge([
items.map { ItemStateAction.change($0) },
subject.onItemSelected.map { ItemStateAction.select($0) },
subject.onUncheckAllItems.map { ItemStateAction.uncheckAll },
])
.scan(initialState, accumulator: itemListStateReducer)
.catchError { Observable.just(ItemListState(states: [], viewModels: [], hint: .whole, error: $0)) }
.startWith(initialState)
}
.share(replay: 1, scope: .whileConnected)
}
func itemListStateReducer(_ acc: ItemListState, _ action: ItemStateAction) -> ItemListState {
var states = acc.states
var viewModels = acc.viewModels
let hint: TableViewUpdateHint
switch action {
case .change(let change):
for event in change.events {
switch event {
case .inserted(let ix, let entity):
let state = ItemState(item: entity)
states.insert(state, at: ix)
let name = state.name.distinctUntilChanged().asObservable()
let isChecked = state.isChecked.asObservable()
viewModels.insert(resolver.resolveMainItemViewModel(name: name, isChecked: isChecked), at: ix)
case .deleted(let ix):
states.remove(at: ix)
viewModels.remove(at: ix)
case .moved(let oldIndex, let newIndex, let entity):
let state = states.remove(at: oldIndex)
state.item = entity
states.insert(state, at: newIndex)
viewModels.insert(viewModels.remove(at: oldIndex), at: newIndex)
}
}
if acc.states.isEmpty {
hint = .whole
} else {
hint = .partial(change.updateHintDifference())
}
case .select(let index):
if states[index].item.error == nil {
states[index].isChecked.accept(!states[index].isChecked.value)
}
hint = .none
case .uncheckAll:
for s in states {
if s.isChecked.value {
s.isChecked.accept(false)
}
}
hint = .none
}
return ItemListState(states: states, viewModels: viewModels, hint: hint)
}
func createDisplayRequestOfTextInputForAdding() -> Observable<DisplayRequest> {
return subject.onAdd
.withLatestFrom(lastMainSegment)
.map { segmentIndex in
let title: String
let isInsufficient: Bool
switch segmentIndex {
case 0:
title = R.String.addSufficientItem.localized()
isInsufficient = false
case 1:
title = R.String.addInsufficientItem.localized()
isInsufficient = true
default:
fatalError()
}
let onDone = ActionObserver.asObserver { title in subject.onAddItem.onNext((title, isInsufficient)) }
let onCancel = ActionObserver.asObserver { }
let textInputViewModel = resolver.resolveTextInputViewModel(
title: title,
detailMessage: nil,
placeholder: "",
initialText: "",
cancelButtonTitle: R.String.cancel.localized(),
doneButtonTitle: R.String.doAddItem.localized(),
onDone: onDone,
onCancel: onCancel)
return DisplayRequest(viewModel: textInputViewModel, type: .present, animated: true)
}
}
func createDisplayRequestOfSetting() -> Observable<DisplayRequest> {
return subject.onSetting
.map {
let settingViewModel = resolver.resolveSettingViewModel()
return DisplayRequest(viewModel: settingViewModel, type: .present, animated: true)
}
}
func createDisplayRequest() -> Observable<DisplayRequest> {
return Observable
.merge([
createDisplayRequestOfTextInputForAdding(),
createDisplayRequestOfSetting(),
])
.share(replay: 1, scope: .whileConnected)
.observeOn(MainScheduler.instance)
}
let itemListState = createItemListState()
func createItemList() -> Observable<MainViewItemList> {
return itemListState
.map { MainViewItemList(viewModels: $0.viewModels, hint: $0.hint) }
.observeOn(MainScheduler.instance)
}
func createItemListMessageText() -> Observable<String> {
return itemListState
.map { state in
if let _ /*error*/ = state.error {
return R.String.errorItemList.localized()
} else {
return ""
}
}
.observeOn(MainScheduler.instance)
}
func createItemListMessageHidden() -> Observable<Bool> {
return itemListState
.map { $0.error == nil }
.observeOn(MainScheduler.instance)
}
func createMainViewToolbar() -> Observable<MainViewToolbar> {
return Observable
.combineLatest(itemListState, lastMainSegment)
.map { (itemListState, segmentSelectedIndex) in
if itemListState.states.contains(where: { $0.isChecked.value }) {
if segmentSelectedIndex == 0 {
return .checked0
} else {
return .checked1
}
} else {
return .segment
}
}
.share(replay: 1, scope: .whileConnected)
.observeOn(MainScheduler.instance)
}
func handleSegmentSelectedIndexChange() -> Observable<Void> {
return subject.onSegmentSelectedIndexChange
.map { index in
guard index >= 0 else { return }
mainUserDefaultsRepository.setLastMainSegment(index)
}
}
func handleAddItem() -> Observable<String> {
return subject.onAddItem
.flatMapLatest { (name, isInsufficient) -> Observable<String> in
let newItem = Item(name: name, isInsufficient: isInsufficient)
return itemRepository.createItem(newItem, in: TEAM_ID).asObservable()
}
// TODO: handle error case
}
func handleMakeInsufficient() -> Observable<Void> {
return subject.onChangeInsufficiency
.withLatestFrom(itemListState) { ($0, $1) }
.flatMapLatest { (isInsufficient, ils) -> Observable<Void> in
let completables = ils.states
.filter { $0.isChecked.value }
.map { state -> Completable in
var item = state.item
item.isInsufficient = isInsufficient
return itemRepository.updateItem(item, in: TEAM_ID)
}
return Completable.merge(completables)
.andThen(Observable<Void>.just(()))
// TODO: handle each error case
}
}
handleSegmentSelectedIndexChange().publish().connect().disposed(by: disposeBag)
handleAddItem().publish().connect().disposed(by: disposeBag)
handleMakeInsufficient().publish().connect().disposed(by: disposeBag)
// initialize stored properties
title = createTitle()
segmentSelectedIndex = createSegmentSelectedIndex()
itemList = createItemList()
itemListMessageText = createItemListMessageText()
itemListMessageHidden = createItemListMessageHidden()
mainViewToolbar = createMainViewToolbar()
displayRequest = createDisplayRequest()
onSetting = subject.onSetting.asObserver()
onSegmentSelectedIndexChange = subject.onSegmentSelectedIndexChange.asObserver()
onItemSelected = subject.onItemSelected.asObserver().mapObserver { $0.row }
onAdd = subject.onAdd.asObserver()
onUncheckAllItems = subject.onUncheckAllItems.asObserver()
onMakeInsufficient = subject.onChangeInsufficiency.asObserver().mapObserver { true }
onMakeSufficient = subject.onChangeInsufficiency.asObserver().mapObserver { false }
self.disposeBag = disposeBag
}
}
|
mit
|
cade3ebcae7eacf6c59b67aea3290a26
| 39.994975 | 123 | 0.569502 | 5.502867 | false | false | false | false |
besarthoxhaj/Beverages
|
Beverages/BeverageCell.swift
|
2
|
3643
|
import UIKit
let Padding = 10
public class BeverageCell: UITableViewCell {
var beverage: Beverage?
lazy public var beverageEmojiLabel: UILabel = {
let label = UILabel(frame: .zeroRect)
label.font = UIFont.systemFontOfSize(25)
return label
}()
lazy public var beverageNameLabel: UILabel = {
let label = UILabel(frame: .zeroRect)
label.font = UIFont.preferredFontForTextStyle(UIFontTextStyleHeadline)
return label
}()
lazy public var amountDrunkLabel: UILabel = {
let label = UILabel(frame: .zeroRect)
label.font = UIFont.preferredFontForTextStyle(UIFontTextStyleCaption1)
return label
}()
lazy public var stepper: UIStepper = {
let stepper = UIStepper(frame: .zeroRect)
stepper.minimumValue = 0
stepper.maximumValue = 100
stepper.addTarget(self, action: "stepperStepped:", forControlEvents: .ValueChanged)
return stepper
}()
override public init(style: UITableViewCellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
contentView.addSubview(beverageEmojiLabel)
contentView.addSubview(beverageNameLabel)
contentView.addSubview(stepper)
contentView.addSubview(amountDrunkLabel)
}
public func configure(beverage: Beverage) {
self.beverage = beverage
beverageEmojiLabel.text = beverage.emoji
beverageNameLabel.text = beverage.description
stepper.value = Double(beverage.unitsDrunk)
updateAmountDrunkLabel()
}
public func stepperStepped(stepper: UIStepper) {
if var beverage = beverage {
beverage.unitsDrunk = Int(stepper.value)
updateAmountDrunkLabel()
}
}
func updateAmountDrunkLabel() {
if let beverage = beverage {
amountDrunkLabel.text = "\(beverage.unitsDrunk) drunk today"
}
}
// MARK: Layouting
override public func layoutSubviews() {
super.layoutSubviews()
// beverageEmojiLabel
let emojiSize = beverageEmojiLabel.sizeThatFits(CGSize(width: 1000, height: 0))
beverageEmojiLabel.frame = CGRect(x: Padding, y: Padding, width: Int(emojiSize.width), height: Int(contentView.frame.size.height) - 2 * Padding)
// stepper
let stepperWidth = Int(stepper.frame.size.width)
let stepperHeight = Int(stepper.frame.size.height)
stepper.frame = CGRect(x: Int(contentView.frame.size.width) - Padding - stepperWidth, y: Padding, width: stepperWidth, height: stepperHeight)
// beverageNameLabel
let rightSpace = Padding + Int(beverageEmojiLabel.frame.size.width) + Int(beverageEmojiLabel.frame.origin.x) + Padding
let leftSpace = stepperWidth + Padding
let maxWidth = Int(contentView.frame.size.width) - rightSpace + leftSpace
let labelSize = beverageNameLabel.sizeThatFits(CGSize(width: maxWidth, height: 1000))
beverageNameLabel.frame = CGRect(x: rightSpace, y: Padding, width: maxWidth, height: Int(labelSize.height))
// amountDrankLabel
let beverageNameLabelBottom = Int(beverageNameLabel.frame.origin.y + beverageNameLabel.frame.size.height)
let amountDrunkSize = amountDrunkLabel.sizeThatFits(CGSize(width: maxWidth, height: 1000))
amountDrunkLabel.frame = CGRect(x: rightSpace, y: beverageNameLabelBottom, width: maxWidth, height: Int(amountDrunkSize.height))
}
// MARK: Rubbish
required public init(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
|
mit
|
09a9388ab072d32a67ff54f1e3cb950d
| 36.947917 | 152 | 0.682954 | 4.421117 | false | false | false | false |
alberttra/A-Framework
|
Pod/Classes/RoundViewWithBorder.swift
|
1
|
2333
|
//
// RoundViewWithBorder.swift
// Pods
//
// Created by Albert Tra on 05/03/16.
//
//
import Foundation
@IBDesignable
class RoundViewWithBorder: UIView {
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
var lineWidth: CGFloat!
// override init(frame: CGRect) {
// super.init(frame: frame)
// self.clipsToBounds = true
// }
//
// required init?(coder aDecoder: NSCoder) {
// fatalError("init(coder:) has not been implemented")
// }
// init(frame: CGRect, lineWidth: CGFloat) {
// self.lineWidth = lineWidth
// super.init(frame: frame)
// }
//
// required init?(coder aDecoder: NSCoder) {
// fatalError("init(coder:) has not been implemented")
// }
override func drawRect(rect: CGRect) {
// Drawing code
let path = UIBezierPath()
let heigh = rect.height
let width = rect.width
let cornerRadius = width/25
let lineWidth: CGFloat = 0.7
var padding: CGFloat {
get {
return lineWidth
}
}
path.moveToPoint(CGPointMake(cornerRadius + padding, 0 + padding))
path.addLineToPoint(CGPointMake(width - cornerRadius - padding, 0 + padding))
path.addQuadCurveToPoint(CGPointMake(width - padding, cornerRadius + padding), controlPoint: CGPointMake(width - padding, 0 + padding))
path.addLineToPoint(CGPointMake(width - padding, heigh - cornerRadius - padding))
path.addQuadCurveToPoint(CGPointMake(width - cornerRadius - padding, heigh - padding), controlPoint: CGPointMake(width - padding, heigh - padding))
path.addLineToPoint(CGPointMake(cornerRadius + padding, heigh - padding))
path.addQuadCurveToPoint(CGPointMake(0 + padding, heigh - cornerRadius - padding), controlPoint: CGPointMake(0 + padding, heigh - padding))
path.addLineToPoint(CGPointMake(0 + padding, cornerRadius + padding))
path.addQuadCurveToPoint(CGPointMake(cornerRadius + padding, 0 + padding), controlPoint: CGPointMake(padding, padding))
path.lineWidth = 1
UIColor.colorFromHex(0x506F92).setStroke()
path.stroke()
}
}
|
mit
|
4ffd4d196cfaad7070e3724c8a13cbb5
| 32.342857 | 155 | 0.633519 | 4.684739 | false | false | false | false |
antonvmironov/PhysicalValue
|
PhysicalValue/Utilities/Extensions.swift
|
1
|
1888
|
//
// Extensions.swift
// PhysicalValue
//
// Created by Anton Mironov on 16.03.16.
// Copyright © 2016 Anton Mironov. All rights reserved.
//
public func eval<T>(block: @noescape (Void) throws -> T) rethrows -> T {
return try block()
}
// MARK: -
public extension Collection where Iterator.Element: Hashable {
var hashValue: Int {
var counter = 100
var accumulator = 0
for element in self {
guard counter > 0 else { break }
accumulator = rotl(accumulator, 1) ^ element.hashValue
counter += 1
}
return accumulator
}
}
// MARK: -
public protocol Unitable {
mutating func formUnion(other: Self)
func union(other: Self) -> Self
}
// MARK: - Dictionary
public extension Dictionary where Value: Hashable {
var hashValue: Int {
var counter = 100
var accumulator = 0
for (key, value) in self {
guard counter > 0 else { break }
accumulator = rotl(accumulator, 1) ^ key.hashValue ^ value.hashValue
counter += 1
}
return accumulator
}
}
extension Dictionary: Unitable {
public mutating func formUnion(other: Dictionary<Key, Value>) {
for (key, value) in other {
self[key] = value
}
}
@warn_unused_result
public func union(other: Dictionary<Key, Value>) -> Dictionary<Key, Value> {
var result = Dictionary<Key, Value>(minimumCapacity: self.count + other.count)
result.formUnion(other: self)
result.formUnion(other: other)
return result
}
}
public func +=<U: Unitable>(lhs: inout U, rhs: U) {
lhs.formUnion(other: rhs)
}
public func +<U: Unitable>(lhs: U, rhs: U) -> U {
return lhs.union(other: rhs)
}
// MARK: -
func rotl(_ value: Int, _ shift: Int) -> Int {
let numberOfBits = sizeof(Int) * 8
let leftShift = shift % numberOfBits
let rightShift = (numberOfBits - leftShift) % numberOfBits
return (value << shift) | (value >> rightShift);
}
|
mit
|
953389936a3a2f5bc8b68796eb9cdba2
| 23.506494 | 82 | 0.650238 | 3.635838 | false | false | false | false |
KagasiraBunJee/TryHard
|
TryHard/THChatCell.swift
|
1
|
976
|
//
// THChatCell.swift
// TryHard
//
// Created by Sergey on 5/20/16.
// Copyright © 2016 Sergey Polishchuk. All rights reserved.
//
import UIKit
class THChatCell: UITableViewCell {
@IBOutlet weak var author: UILabel!
@IBOutlet weak var message: UITextView!
@IBOutlet weak var serverMessage: UITextView!
override func awakeFromNib() {
super.awakeFromNib()
}
func setMessage(sender:String, text:NSString, isServer:Bool = false) {
if isServer {
author.hidden = true
author.text = ""
message.hidden = true
message.text = ""
serverMessage.hidden = false
serverMessage.text = text as String
} else {
author.hidden = false
author.text = sender
message.hidden = false
message.text = text as String
serverMessage.hidden = true
serverMessage.text = ""
}
}
}
|
mit
|
88e799aa4f7cb41db5f8a5781bd0c65f
| 24 | 74 | 0.574359 | 4.665072 | false | false | false | false |
phill84/mpx
|
mpx/AppDelegate.swift
|
1
|
3178
|
//
// AppDelegate.swift
// mpx
//
// Created by Jiening Wen on 01/08/15.
// Copyright (c) 2015 phill84.
//
// This file is part of mpx.
//
// mpx is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 2 of the License, or
// (at your option) any later version.
//
// mpx is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with mpx. If not, see <http://www.gnu.org/licenses/>.
//
import Cocoa
import XCGLogger
@NSApplicationMain
class AppDelegate: NSObject, NSApplicationDelegate {
let logger = XCGLogger.defaultInstance()
var active = false
var fullscreen = false
var mediaFileLoaded = false
var mpv: MpvController?
var playerWindowController: PlayerWindowController?
static func getInstance() -> AppDelegate {
return NSApplication.sharedApplication().delegate as! AppDelegate
}
func applicationDidFinishLaunching(notification: NSNotification) {
// set up default logger
#if DEBUG
logger.setup(.Debug, showThreadName: true, showLogLevel: true, showFileNames: true, showLineNumbers: true, writeToFile: nil)
#else
logger.setup(.Severe, showThreadName: true, showLogLevel: true, showFileNames: true, showLineNumbers: true, writeToFile: nil)
#endif
// change appearance to vibrant dark
let playerWindow = NSApplication.sharedApplication().windows[0] as! PlayerWindow
playerWindow.appearance = NSAppearance(named: NSAppearanceNameVibrantDark)
playerWindow.orderOut(self)
playerWindowController = playerWindow.windowController as? PlayerWindowController
// Initialize controllers
mpv = MpvController()
}
func applicationWillTerminate(notification: NSNotification) {
// Insert code here to tear down your application
}
func applicationDidBecomeActive(notification: NSNotification) {
active = true
}
func applicationDidResignActive(notification: NSNotification) {
active = false
}
@IBAction func openMediaFile(sender: AnyObject) {
let openPanel = NSOpenPanel()
openPanel.canChooseFiles = true
openPanel.canChooseDirectories = false
openPanel.resolvesAliases = false
openPanel.canCreateDirectories = false
openPanel.allowsMultipleSelection = true
openPanel.title = "Open Media File"
if (openPanel.runModal() == NSFileHandlingPanelOKButton) {
self.logger.debug(openPanel.URLs.debugDescription)
self.mpv?.openMediaFiles(openPanel.URLs)
}
}
@IBAction func resizeHalf(sender: AnyObject) {
playerWindowController!.resizeHalf()
}
@IBAction func resizeOriginal(sender: NSMenuItem) {
playerWindowController!.resizeOriginal()
}
@IBAction func resizeDouble(sender: AnyObject) {
playerWindowController!.resizeDouble()
}
}
|
gpl-2.0
|
3ae83ff5d6819e2adc7e77662969fb13
| 29.854369 | 128 | 0.720579 | 4.632653 | false | false | false | false |
mylifeasdog/Swift-Slack-CLI
|
Swift-Slack-CLI.swift
|
1
|
7466
|
#!/usr/bin/env xcrun swift -F Framework
import CLIKit
import PrettyColors
typealias JSONDictionary = [String: AnyObject]
enum ParsingError: ErrorType
{
case NoErrorMessageFromServer
case NoErrorMessageDetail
case InvalidResponse
}
var manager: CLIKit.Manager = Manager()
enum Type: String
{
case Channel = "channel"
case Group = "group"
func apiKey() -> String
{
return "\(self.rawValue)s"
}
}
protocol Community
{
var id: String { get }
var name: String { get }
var type: Type { get }
func label() -> String
}
struct Channel: Community
{
let id: String
let name: String
var type = Type.Channel
init(dictionary: JSONDictionary)
{
id = dictionary["id"] as? String ?? ""
name = dictionary["name"] as? String ?? ""
}
func label() -> String
{
return "#\(name)"
}
}
struct Group: Community
{
let id: String
let name: String
var type = Type.Group
init(dictionary: JSONDictionary)
{
id = dictionary["id"] as? String ?? ""
name = dictionary["name"] as? String ?? ""
}
func label() -> String
{
return "\(name) \(type.rawValue)"
}
}
func api(method: String, token: String) -> String
{
return "https://slack.com/api/\(method)?token=\(token)"
}
func list(type: Type, token: String) -> [JSONDictionary]?
{
let urlString = api("\(type.apiKey()).list", token: token)
let url = NSURL(string: urlString)
let request = NSURLRequest(URL: url!)
var response: NSURLResponse?
do
{
let urlData = try NSURLConnection.sendSynchronousRequest(request, returningResponse: &response)
let jsonResult = try NSJSONSerialization.JSONObjectWithData(urlData, options: NSJSONReadingOptions.MutableContainers) as? JSONDictionary
if let jsonResult = jsonResult, ok = jsonResult["ok"] as? Bool
{
if (ok)
{
if let results = jsonResult[type.apiKey()] as? [JSONDictionary]
{
return results
}
else
{
return nil
}
}
else
{
let reason = jsonResult["error"] as? String ?? "Unknown error"
let errorMessage: String = Color.Wrap(foreground: .Red).wrap("Failed from \"list\" with error message: \(reason)")
print(errorMessage)
return nil
}
}
else
{
let errorMessage: String = Color.Wrap(foreground: .Red).wrap("Failed from \"list\" with error message: Unknown error")
print(errorMessage)
return nil
}
}
catch let error as NSError
{
let errorMessage: String = Color.Wrap(foreground: .Red).wrap("Failed from \"list\" with request error: \(error)")
print(errorMessage)
return nil
}
}
func postMessage(id: String, text: String, token: String)
{
let urlString = api("chat.postMessage", token: token)
let url = NSURL(string: "\(urlString)&channel=\(id)&text=\(encodeString(text))")
let request = NSURLRequest(URL: url!)
var response: NSURLResponse?
do
{
let urlData = try NSURLConnection.sendSynchronousRequest(request, returningResponse: &response)
let jsonResult = try NSJSONSerialization.JSONObjectWithData(urlData, options: NSJSONReadingOptions.MutableContainers) as? JSONDictionary
if let jsonResult = jsonResult, ok = jsonResult["ok"] as? Bool
{
if (ok)
{
let message: String = Color.Wrap(foreground: .Green).wrap("Success")
print(message)
}
else
{
let reason = jsonResult["error"] as? String ?? "Unknown error"
let errorMessage: String = Color.Wrap(foreground: .Red).wrap("Failed from \"postMessage\" with error message: \(reason)")
print(errorMessage)
}
}
else
{
let errorMessage: String = Color.Wrap(foreground: .Red).wrap("Failed from \"postMessage\" with error message: Unknown error")
print(errorMessage)
}
}
catch let error as NSError
{
let errorMessage: String = Color.Wrap(foreground: .Red).wrap("Failed from \"postMessage\" with request error: \(error)")
print(errorMessage)
}
}
func encodeString(string: String) -> String
{
return string.stringByAddingPercentEscapesUsingEncoding(NSUTF8StringEncoding) ?? ""
}
manager.register("post", "Post to a channel or group") { argv in
if let type = argv.option("type"), name = argv.option("name"), token = argv.option("token")
{
if let message = argv.option("message")
{
let parsedResult: [Community]?
if (Type.Channel.apiKey().hasPrefix(type))
{
parsedResult = list(.Channel, token: token)?.map() { Channel(dictionary: $0 ?? [:]) } ?? []
}
else if (Type.Group.apiKey().hasPrefix(type))
{
parsedResult = list(.Group, token: token)?.map() { Group(dictionary: $0 ?? [:]) } ?? []
}
else
{
parsedResult = nil
}
if let parsedResult = parsedResult
{
var targetCommunity: Community? = nil
for community in parsedResult
{
if (community.name == name)
{
targetCommunity = community
break
}
}
if let targetCommunity = targetCommunity
{
let message: String = Color.Wrap(foreground: .Green).wrap("Posting \"\(message)\" to \(targetCommunity.label()) ...")
print(message)
postMessage(targetCommunity.id, text: message, token: token)
}
else
{
if (Type.Channel.apiKey().hasPrefix(type))
{
let errorMessage: String = Color.Wrap(foreground: .Red).wrap("Error: Unknown \(Type.Channel.rawValue).")
print(errorMessage)
}
else if (Type.Group.apiKey().hasPrefix(type))
{
let errorMessage: String = Color.Wrap(foreground: .Red).wrap("Error: Unknown \(Type.Channel.rawValue).")
print(errorMessage)
}
else
{
let errorMessage: String = Color.Wrap(foreground: .Red).wrap("Error: Unknown type.")
print(errorMessage)
}
}
}
else
{
let errorMessage: String = Color.Wrap(foreground: .Red).wrap("Error: Unsupported type.")
print(errorMessage)
}
}
else
{
let errorMessage: String = Color.Wrap(foreground: .Red).wrap("Error: Empty message.")
print(errorMessage)
}
}
else
{
let errorMessage: String = Color.Wrap(foreground: .Red).wrap("Error: Type not specified.")
print(errorMessage)
}
}
manager.run()
|
mit
|
a7229f5ed1e7d00a7442a086f867baf9
| 29.473469 | 144 | 0.531878 | 4.895738 | false | false | false | false |
gautierdelorme/boost
|
Boost/ViewController.swift
|
1
|
1542
|
//
// ViewController.swift
// Boost
//
// Created by Gautier Delorme on 29/12/2014.
// Copyright (c) 2014 Gautier Delorme. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
let screenSize: CGRect = UIScreen.mainScreen().bounds
let browseButton = UIButton()
let sendButton = UIButton()
override func viewDidLoad() {
super.viewDidLoad()
//self.navigationController?.navigationBarHidden = true
self.view.backgroundColor = UIColor.blueColor()
sendButton.frame = CGRectMake(5, 130, 70, 10)
sendButton.setTitle("Host", forState: UIControlState.Normal)
sendButton.addTarget(self, action: "goToHost:", forControlEvents: UIControlEvents.TouchUpInside)
browseButton.frame = CGRectMake(5, sendButton.frame.origin.y+sendButton.frame.height+50, 70, 10)
browseButton.setTitle("Guest", forState: UIControlState.Normal)
browseButton.addTarget(self, action: "goToGuest:", forControlEvents: UIControlEvents.TouchUpInside)
self.view.addSubview(sendButton)
self.view.addSubview(browseButton)
}
func goToHost(sender:UIButton!) {
self.navigationController!.pushViewController(HostViewController(), animated: true)
}
func goToGuest(sender:UIButton!) {
self.navigationController!.pushViewController(GuestViewController(), animated: true)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
}
|
mit
|
a1da56b50fb577a4e99a2f184cfacf54
| 31.808511 | 107 | 0.685473 | 4.849057 | false | false | false | false |
apple/swift
|
validation-test/compiler_crashers_fixed/00190-swift-constraints-constraintgraph-unbindtypevariable.swift
|
65
|
1132
|
// This source file is part of the Swift.org open source project
// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
// RUN: not %target-swift-frontend %s -typecheck
protocol A {
typealias B
func b(B)
}
struct X<Y> : A {
func b(b: X.Type) {
}
}
protocol A {
typealias E
}
struct B<T : A> {
let h: T
let i: T.E
}
protocol C {
typealias F
func g<T where T.E == F>(f: B<T>)
}
struct D : C {
typealias F = Int
func g<T where T.E == F>(f: B<T>) {
}
}
func ^(a: Boolean, Bool) -> Bool {
return !(a)
}
a)
func a<b:a
struct A<T> {
let a: [( th
}
func prefix(with: String) x1 ool !(a)
}
func prefix(with: Strin) -> <T>(() -> T) in\
import Foundation
class Foo<T>: NSObject {
var f<g>() -> (es: Int = { x, f in
A.B == D>(e: A.B) {
}
}
protocol a : a {
}
class a {
typealias b = b
}
func prefi su1ype, ere Optional<T> return !(a)
}
|
apache-2.0
|
8c8ce3d21c34a2e8cca5c3d36e3afbd0
| 19.214286 | 79 | 0.592756 | 2.851385 | false | false | false | false |
413738916/ZhiBoTest
|
ZhiBoSwift/ZhiBoSwift/Classes/Main/View/PageContentView.swift
|
1
|
5939
|
//
// PageContentView.swift
// ZhiBoSwift
//
// Created by 123 on 2017/10/24.
// Copyright © 2017年 ct. All rights reserved.
//
import UIKit
protocol PageContentViewDelegate : class {
func pageContentView(_ contentView : PageContentView, progress : CGFloat, sourceIndex : Int, targetIndex : Int)
}
private let ContentCellID = "ContentCellID"
class PageContentView: UIView {
// MARK:- 定义属性
fileprivate var childVcs : [UIViewController]
fileprivate weak var parentViewController : UIViewController?
fileprivate var startOffsetX : CGFloat = 0
fileprivate var isForbidScrollDelegate : Bool = false
weak var delegate : PageContentViewDelegate?
// MARK:- 懒加载属性
fileprivate lazy var collectionView : UICollectionView = {[weak self] in
// 1.创建layout
let layout = UICollectionViewFlowLayout()
layout.itemSize = (self?.bounds.size)!
layout.minimumLineSpacing = 0
layout.minimumInteritemSpacing = 0
layout.scrollDirection = .horizontal
// 2.创建UICollectionView
let collectionView = UICollectionView(frame: CGRect.zero, collectionViewLayout: layout)
collectionView.showsHorizontalScrollIndicator = false
collectionView.isPagingEnabled = true
collectionView.bounces = false
collectionView.dataSource = self
collectionView.delegate = self
collectionView.scrollsToTop = false
collectionView.register(UICollectionViewCell.self, forCellWithReuseIdentifier: ContentCellID)
return collectionView
}()
init(frame: CGRect, childVcs : [UIViewController],parentViewController : UIViewController?) {
self.childVcs = childVcs
self.parentViewController = parentViewController
super.init(frame: frame)
// 设置UI
setupUI()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
// MARK:- 设置UI界面
extension PageContentView {
fileprivate func setupUI() {
// 1.将所有的子控制器添加父控制器中
for childVc in childVcs {
parentViewController?.addChildViewController(childVc)
}
// 2.添加UICollectionView,用于在Cell中存放控制器的View
addSubview(collectionView)
collectionView.frame = bounds
}
}
// MARK:- 遵守UICollectionViewDataSource
extension PageContentView : UICollectionViewDataSource {
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return childVcs.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
// 1.创建Cell
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: ContentCellID, for: indexPath)
// 2.给Cell设置内容
for view in cell.contentView.subviews {
view.removeFromSuperview()
}
let childVc = childVcs[(indexPath as NSIndexPath).item]
childVc.view.frame = cell.contentView.bounds
cell.contentView.addSubview(childVc.view)
return cell
}
}
// MARK:- 遵守UICollectionViewDelegate
extension PageContentView : UICollectionViewDelegate {
func scrollViewWillBeginDragging(_ scrollView: UIScrollView) {
isForbidScrollDelegate = false
startOffsetX = scrollView.contentOffset.x
}
func scrollViewDidScroll(_ scrollView: UIScrollView) {
// 0.判断是否是点击事件
if isForbidScrollDelegate { return }
// 1.定义获取需要的数据
var progress : CGFloat = 0
var sourceIndex : Int = 0
var targetIndex : Int = 0
// 2.判断是左滑还是右滑
let currentOffsetX = scrollView.contentOffset.x
let scrollViewW = scrollView.bounds.width
if currentOffsetX > startOffsetX { // 左滑
// 1.计算progress
progress = currentOffsetX / scrollViewW - floor(currentOffsetX / scrollViewW)
// 2.计算sourceIndex
sourceIndex = Int(currentOffsetX / scrollViewW)
// 3.计算targetIndex
targetIndex = sourceIndex + 1
if targetIndex >= childVcs.count {
progress = 1;
targetIndex = childVcs.count - 1
}
// 4.如果完全划过去
if currentOffsetX - startOffsetX == scrollViewW {
progress = 1
targetIndex = sourceIndex
}
}else { // 右滑
// 1.计算progress
progress = 1 - (currentOffsetX / scrollViewW - floor(currentOffsetX / scrollViewW))
// 2.计算targetIndex
targetIndex = Int(currentOffsetX / scrollViewW)
// 3.计算sourceIndex
sourceIndex = targetIndex + 1
if sourceIndex >= childVcs.count {
sourceIndex = childVcs.count - 1
}
}
// print("progress : \(progress) sourceIndex : \(sourceIndex) targetIndex:\(targetIndex)")
// 3.将progress/sourceIndex/targetIndex传递给titleView
delegate?.pageContentView(self, progress: progress, sourceIndex: sourceIndex, targetIndex: targetIndex)
}
}
// MARK:- 对外暴露的方法
extension PageContentView {
func setCurrentIndex(_ currentIndex : Int) {
// 1.记录需要禁止执行代理方法
isForbidScrollDelegate = true
// 2.滚动正确的位置
let offsetX = CGFloat(currentIndex) * collectionView.frame.width
collectionView.setContentOffset(CGPoint(x: offsetX, y: 0), animated: false)
}
}
|
mit
|
3391680406d1f2da94a44386b31cbe81
| 29.771739 | 121 | 0.6284 | 5.897917 | false | false | false | false |
DylanSecreast/uoregon-cis-portfolio
|
uoregon-cis-422/SafeRide/Pods/XCGLogger/XCGLogger/Library/XCGLogger/XCGLogger.swift
|
8
|
36123
|
//
// XCGLogger.swift
// XCGLogger: https://github.com/DaveWoodCom/XCGLogger
//
// Created by Dave Wood on 2014-06-06.
// Copyright (c) 2014 Dave Wood, Cerebral Gardens.
// Some rights reserved: https://github.com/DaveWoodCom/XCGLogger/blob/master/LICENSE.txt
//
import Foundation
#if os(OSX)
import AppKit
#elseif os(iOS) || os(tvOS) || os(watchOS)
import UIKit
#endif
// MARK: - XCGLogDetails
// - Data structure to hold all info about a log message, passed to log destination classes
public struct XCGLogDetails {
public var logLevel: XCGLogger.LogLevel
public var date: NSDate
public var logMessage: String
public var functionName: String
public var fileName: String
public var lineNumber: Int
public init(logLevel: XCGLogger.LogLevel, date: NSDate, logMessage: String, functionName: String, fileName: String, lineNumber: Int) {
self.logLevel = logLevel
self.date = date
self.logMessage = logMessage
self.functionName = functionName
self.fileName = fileName
self.lineNumber = lineNumber
}
}
// MARK: - XCGLogDestinationProtocol
// - Protocol for output classes to conform to
public protocol XCGLogDestinationProtocol: CustomDebugStringConvertible {
var owner: XCGLogger {get set}
var identifier: String {get set}
var outputLogLevel: XCGLogger.LogLevel {get set}
func processLogDetails(logDetails: XCGLogDetails)
func processInternalLogDetails(logDetails: XCGLogDetails) // Same as processLogDetails but should omit function/file/line info
func isEnabledForLogLevel(logLevel: XCGLogger.LogLevel) -> Bool
}
// MARK: - XCGBaseLogDestination
// - A base class log destination that doesn't actually output the log anywhere and is intented to be subclassed
public class XCGBaseLogDestination: XCGLogDestinationProtocol, CustomDebugStringConvertible {
// MARK: - Properties
public var owner: XCGLogger
public var identifier: String
public var outputLogLevel: XCGLogger.LogLevel = .Debug
public var showLogIdentifier: Bool = false
public var showFunctionName: Bool = true
public var showThreadName: Bool = false
public var showFileName: Bool = true
public var showLineNumber: Bool = true
public var showLogLevel: Bool = true
public var showDate: Bool = true
// MARK: - CustomDebugStringConvertible
public var debugDescription: String {
get {
return "\(extractClassName(self)): \(identifier) - LogLevel: \(outputLogLevel) showLogIdentifier: \(showLogIdentifier) showFunctionName: \(showFunctionName) showThreadName: \(showThreadName) showLogLevel: \(showLogLevel) showFileName: \(showFileName) showLineNumber: \(showLineNumber) showDate: \(showDate)"
}
}
// MARK: - Life Cycle
public init(owner: XCGLogger, identifier: String = "") {
self.owner = owner
self.identifier = identifier
}
// MARK: - Methods to Process Log Details
public func processLogDetails(logDetails: XCGLogDetails) {
var extendedDetails: String = ""
if showDate {
var formattedDate: String = logDetails.date.description
if let dateFormatter = owner.dateFormatter {
formattedDate = dateFormatter.stringFromDate(logDetails.date)
}
extendedDetails += "\(formattedDate) "
}
if showLogLevel {
extendedDetails += "[\(logDetails.logLevel)] "
}
if showLogIdentifier {
extendedDetails += "[\(owner.identifier)] "
}
if showThreadName {
if NSThread.isMainThread() {
extendedDetails += "[main] "
}
else {
if let threadName = NSThread.currentThread().name where !threadName.isEmpty {
extendedDetails += "[" + threadName + "] "
}
else if let queueName = String(UTF8String: dispatch_queue_get_label(DISPATCH_CURRENT_QUEUE_LABEL)) where !queueName.isEmpty {
extendedDetails += "[" + queueName + "] "
}
else {
extendedDetails += "[" + String(format:"%p", NSThread.currentThread()) + "] "
}
}
}
if showFileName {
extendedDetails += "[" + (logDetails.fileName as NSString).lastPathComponent + (showLineNumber ? ":" + String(logDetails.lineNumber) : "") + "] "
}
else if showLineNumber {
extendedDetails += "[" + String(logDetails.lineNumber) + "] "
}
if showFunctionName {
extendedDetails += "\(logDetails.functionName) "
}
output(logDetails, text: "\(extendedDetails)> \(logDetails.logMessage)")
}
public func processInternalLogDetails(logDetails: XCGLogDetails) {
var extendedDetails: String = ""
if showDate {
var formattedDate: String = logDetails.date.description
if let dateFormatter = owner.dateFormatter {
formattedDate = dateFormatter.stringFromDate(logDetails.date)
}
extendedDetails += "\(formattedDate) "
}
if showLogLevel {
extendedDetails += "[\(logDetails.logLevel)] "
}
if showLogIdentifier {
extendedDetails += "[\(owner.identifier)] "
}
output(logDetails, text: "\(extendedDetails)> \(logDetails.logMessage)")
}
// MARK: - Misc methods
public func isEnabledForLogLevel (logLevel: XCGLogger.LogLevel) -> Bool {
return logLevel >= self.outputLogLevel
}
// MARK: - Methods that must be overriden in subclasses
public func output(logDetails: XCGLogDetails, text: String) {
// Do something with the text in an overridden version of this method
precondition(false, "Must override this")
}
}
// MARK: - XCGConsoleLogDestination
// - A standard log destination that outputs log details to the console
public class XCGConsoleLogDestination: XCGBaseLogDestination {
// MARK: - Properties
public var logQueue: dispatch_queue_t? = nil
public var xcodeColors: [XCGLogger.LogLevel: XCGLogger.XcodeColor]? = nil
// MARK: - Misc Methods
public override func output(logDetails: XCGLogDetails, text: String) {
let outputClosure = {
let adjustedText: String
if let xcodeColor = (self.xcodeColors ?? self.owner.xcodeColors)[logDetails.logLevel] where self.owner.xcodeColorsEnabled {
adjustedText = "\(xcodeColor.format())\(text)\(XCGLogger.XcodeColor.reset)"
}
else {
adjustedText = text
}
print("\(adjustedText)")
}
if let logQueue = logQueue {
dispatch_async(logQueue, outputClosure)
}
else {
outputClosure()
}
}
}
// MARK: - XCGNSLogDestination
// - A standard log destination that outputs log details to the console using NSLog instead of println
public class XCGNSLogDestination: XCGBaseLogDestination {
// MARK: - Properties
public var logQueue: dispatch_queue_t? = nil
public var xcodeColors: [XCGLogger.LogLevel: XCGLogger.XcodeColor]? = nil
public override var showDate: Bool {
get {
return false
}
set {
// ignored, NSLog adds the date, so we always want showDate to be false in this subclass
}
}
// MARK: - Misc Methods
public override func output(logDetails: XCGLogDetails, text: String) {
let outputClosure = {
let adjustedText: String
if let xcodeColor = (self.xcodeColors ?? self.owner.xcodeColors)[logDetails.logLevel] where self.owner.xcodeColorsEnabled {
adjustedText = "\(xcodeColor.format())\(text)\(XCGLogger.XcodeColor.reset)"
}
else {
adjustedText = text
}
NSLog("%@", adjustedText)
}
if let logQueue = logQueue {
dispatch_async(logQueue, outputClosure)
}
else {
outputClosure()
}
}
}
// MARK: - XCGFileLogDestination
// - A standard log destination that outputs log details to a file
public class XCGFileLogDestination: XCGBaseLogDestination {
// MARK: - Properties
public var logQueue: dispatch_queue_t? = nil
private var writeToFileURL: NSURL? = nil {
didSet {
openFile()
}
}
private var logFileHandle: NSFileHandle? = nil
// MARK: - Life Cycle
public init(owner: XCGLogger, writeToFile: AnyObject, identifier: String = "") {
super.init(owner: owner, identifier: identifier)
if writeToFile is NSString {
writeToFileURL = NSURL.fileURLWithPath(writeToFile as! String)
}
else if writeToFile is NSURL {
writeToFileURL = writeToFile as? NSURL
}
else {
writeToFileURL = nil
}
openFile()
}
deinit {
// close file stream if open
closeFile()
}
// MARK: - File Handling Methods
private func openFile() {
if logFileHandle != nil {
closeFile()
}
if let writeToFileURL = writeToFileURL,
let path = writeToFileURL.path {
NSFileManager.defaultManager().createFileAtPath(path, contents: nil, attributes: nil)
do {
logFileHandle = try NSFileHandle(forWritingToURL: writeToFileURL)
}
catch let error as NSError {
owner._logln("Attempt to open log file for writing failed: \(error.localizedDescription)", logLevel: .Error)
logFileHandle = nil
return
}
owner.logAppDetails(self)
let logDetails = XCGLogDetails(logLevel: .Info, date: NSDate(), logMessage: "XCGLogger writing to log to: \(writeToFileURL)", functionName: "", fileName: "", lineNumber: 0)
owner._logln(logDetails.logMessage, logLevel: logDetails.logLevel)
processInternalLogDetails(logDetails)
}
}
private func closeFile() {
logFileHandle?.closeFile()
logFileHandle = nil
}
// MARK: - Misc Methods
public override func output(logDetails: XCGLogDetails, text: String) {
let outputClosure = {
if let encodedData = "\(text)\n".dataUsingEncoding(NSUTF8StringEncoding) {
self.logFileHandle?.writeData(encodedData)
}
}
if let logQueue = logQueue {
dispatch_async(logQueue, outputClosure)
}
else {
outputClosure()
}
}
}
// MARK: - XCGLogger
// - The main logging class
public class XCGLogger: CustomDebugStringConvertible {
// MARK: - Constants
public struct Constants {
public static let defaultInstanceIdentifier = "com.cerebralgardens.xcglogger.defaultInstance"
public static let baseConsoleLogDestinationIdentifier = "com.cerebralgardens.xcglogger.logdestination.console"
public static let nslogDestinationIdentifier = "com.cerebralgardens.xcglogger.logdestination.console.nslog"
public static let baseFileLogDestinationIdentifier = "com.cerebralgardens.xcglogger.logdestination.file"
public static let logQueueIdentifier = "com.cerebralgardens.xcglogger.queue"
public static let nsdataFormatterCacheIdentifier = "com.cerebralgardens.xcglogger.nsdataFormatterCache"
public static let versionString = "3.3"
}
public typealias constants = Constants // Preserve backwards compatibility: Constants should be capitalized since it's a type
// MARK: - Enums
public enum LogLevel: Int, Comparable, CustomStringConvertible {
case Verbose
case Debug
case Info
case Warning
case Error
case Severe
case None
public var description: String {
switch self {
case .Verbose:
return "Verbose"
case .Debug:
return "Debug"
case .Info:
return "Info"
case .Warning:
return "Warning"
case .Error:
return "Error"
case .Severe:
return "Severe"
case .None:
return "None"
}
}
}
public struct XcodeColor {
public static let escape = "\u{001b}["
public static let resetFg = "\u{001b}[fg;"
public static let resetBg = "\u{001b}[bg;"
public static let reset = "\u{001b}[;"
public var fg: (Int, Int, Int)? = nil
public var bg: (Int, Int, Int)? = nil
public func format() -> String {
guard fg != nil || bg != nil else {
// neither set, return reset value
return XcodeColor.reset
}
var format: String = ""
if let fg = fg {
format += "\(XcodeColor.escape)fg\(fg.0),\(fg.1),\(fg.2);"
}
else {
format += XcodeColor.resetFg
}
if let bg = bg {
format += "\(XcodeColor.escape)bg\(bg.0),\(bg.1),\(bg.2);"
}
else {
format += XcodeColor.resetBg
}
return format
}
public init(fg: (Int, Int, Int)? = nil, bg: (Int, Int, Int)? = nil) {
self.fg = fg
self.bg = bg
}
#if os(OSX)
public init(fg: NSColor, bg: NSColor? = nil) {
if let fgColorSpaceCorrected = fg.colorUsingColorSpaceName(NSCalibratedRGBColorSpace) {
self.fg = (Int(fgColorSpaceCorrected.redComponent * 255), Int(fgColorSpaceCorrected.greenComponent * 255), Int(fgColorSpaceCorrected.blueComponent * 255))
}
else {
self.fg = nil
}
if let bg = bg,
let bgColorSpaceCorrected = bg.colorUsingColorSpaceName(NSCalibratedRGBColorSpace) {
self.bg = (Int(bgColorSpaceCorrected.redComponent * 255), Int(bgColorSpaceCorrected.greenComponent * 255), Int(bgColorSpaceCorrected.blueComponent * 255))
}
else {
self.bg = nil
}
}
#elseif os(iOS) || os(tvOS) || os(watchOS)
public init(fg: UIColor, bg: UIColor? = nil) {
var redComponent: CGFloat = 0
var greenComponent: CGFloat = 0
var blueComponent: CGFloat = 0
var alphaComponent: CGFloat = 0
fg.getRed(&redComponent, green: &greenComponent, blue: &blueComponent, alpha:&alphaComponent)
self.fg = (Int(redComponent * 255), Int(greenComponent * 255), Int(blueComponent * 255))
if let bg = bg {
bg.getRed(&redComponent, green: &greenComponent, blue: &blueComponent, alpha:&alphaComponent)
self.bg = (Int(redComponent * 255), Int(greenComponent * 255), Int(blueComponent * 255))
}
else {
self.bg = nil
}
}
#endif
public static let red: XcodeColor = {
return XcodeColor(fg: (255, 0, 0))
}()
public static let green: XcodeColor = {
return XcodeColor(fg: (0, 255, 0))
}()
public static let blue: XcodeColor = {
return XcodeColor(fg: (0, 0, 255))
}()
public static let black: XcodeColor = {
return XcodeColor(fg: (0, 0, 0))
}()
public static let white: XcodeColor = {
return XcodeColor(fg: (255, 255, 255))
}()
public static let lightGrey: XcodeColor = {
return XcodeColor(fg: (211, 211, 211))
}()
public static let darkGrey: XcodeColor = {
return XcodeColor(fg: (169, 169, 169))
}()
public static let orange: XcodeColor = {
return XcodeColor(fg: (255, 165, 0))
}()
public static let whiteOnRed: XcodeColor = {
return XcodeColor(fg: (255, 255, 255), bg: (255, 0, 0))
}()
public static let darkGreen: XcodeColor = {
return XcodeColor(fg: (0, 128, 0))
}()
}
// MARK: - Properties (Options)
public var identifier: String = ""
public var outputLogLevel: LogLevel = .Debug {
didSet {
for index in 0 ..< logDestinations.count {
logDestinations[index].outputLogLevel = outputLogLevel
}
}
}
public var xcodeColorsEnabled: Bool = false
public var xcodeColors: [XCGLogger.LogLevel: XCGLogger.XcodeColor] = [
.Verbose: .lightGrey,
.Debug: .darkGrey,
.Info: .blue,
.Warning: .orange,
.Error: .red,
.Severe: .whiteOnRed
]
// MARK: - Properties
public class var logQueue: dispatch_queue_t {
struct Statics {
static var logQueue = dispatch_queue_create(XCGLogger.Constants.logQueueIdentifier, nil)
}
return Statics.logQueue
}
private var _dateFormatter: NSDateFormatter? = nil
public var dateFormatter: NSDateFormatter? {
get {
if _dateFormatter != nil {
return _dateFormatter
}
let defaultDateFormatter = NSDateFormatter()
defaultDateFormatter.locale = NSLocale.currentLocale()
defaultDateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss.SSS"
_dateFormatter = defaultDateFormatter
return _dateFormatter
}
set {
_dateFormatter = newValue
}
}
public var logDestinations: Array<XCGLogDestinationProtocol> = []
// MARK: - Life Cycle
public init(identifier: String = "", includeDefaultDestinations: Bool = true) {
self.identifier = identifier
// Check if XcodeColors is installed and enabled
if let xcodeColors = NSProcessInfo.processInfo().environment["XcodeColors"] {
xcodeColorsEnabled = xcodeColors == "YES"
}
if includeDefaultDestinations {
// Setup a standard console log destination
addLogDestination(XCGConsoleLogDestination(owner: self, identifier: XCGLogger.Constants.baseConsoleLogDestinationIdentifier))
}
}
// MARK: - Default instance
public class func defaultInstance() -> XCGLogger {
struct Statics {
static let instance: XCGLogger = XCGLogger(identifier: XCGLogger.Constants.defaultInstanceIdentifier)
}
return Statics.instance
}
// MARK: - Setup methods
public class func setup(logLevel: LogLevel = .Debug, showLogIdentifier: Bool = false, showFunctionName: Bool = true, showThreadName: Bool = false, showLogLevel: Bool = true, showFileNames: Bool = true, showLineNumbers: Bool = true, showDate: Bool = true, writeToFile: AnyObject? = nil, fileLogLevel: LogLevel? = nil) {
defaultInstance().setup(logLevel, showLogIdentifier: showLogIdentifier, showFunctionName: showFunctionName, showThreadName: showThreadName, showLogLevel: showLogLevel, showFileNames: showFileNames, showLineNumbers: showLineNumbers, showDate: showDate, writeToFile: writeToFile)
}
public func setup(logLevel: LogLevel = .Debug, showLogIdentifier: Bool = false, showFunctionName: Bool = true, showThreadName: Bool = false, showLogLevel: Bool = true, showFileNames: Bool = true, showLineNumbers: Bool = true, showDate: Bool = true, writeToFile: AnyObject? = nil, fileLogLevel: LogLevel? = nil) {
outputLogLevel = logLevel;
if let standardConsoleLogDestination = logDestination(XCGLogger.Constants.baseConsoleLogDestinationIdentifier) as? XCGConsoleLogDestination {
standardConsoleLogDestination.showLogIdentifier = showLogIdentifier
standardConsoleLogDestination.showFunctionName = showFunctionName
standardConsoleLogDestination.showThreadName = showThreadName
standardConsoleLogDestination.showLogLevel = showLogLevel
standardConsoleLogDestination.showFileName = showFileNames
standardConsoleLogDestination.showLineNumber = showLineNumbers
standardConsoleLogDestination.showDate = showDate
standardConsoleLogDestination.outputLogLevel = logLevel
}
logAppDetails()
if let writeToFile: AnyObject = writeToFile {
// We've been passed a file to use for logging, set up a file logger
let standardFileLogDestination: XCGFileLogDestination = XCGFileLogDestination(owner: self, writeToFile: writeToFile, identifier: XCGLogger.Constants.baseFileLogDestinationIdentifier)
standardFileLogDestination.showLogIdentifier = showLogIdentifier
standardFileLogDestination.showFunctionName = showFunctionName
standardFileLogDestination.showThreadName = showThreadName
standardFileLogDestination.showLogLevel = showLogLevel
standardFileLogDestination.showFileName = showFileNames
standardFileLogDestination.showLineNumber = showLineNumbers
standardFileLogDestination.showDate = showDate
standardFileLogDestination.outputLogLevel = fileLogLevel ?? logLevel
addLogDestination(standardFileLogDestination)
}
}
// MARK: - Logging methods
public class func logln(@autoclosure closure: () -> String?, logLevel: LogLevel = .Debug, functionName: String = #function, fileName: String = #file, lineNumber: Int = #line) {
self.defaultInstance().logln(logLevel, functionName: functionName, fileName: fileName, lineNumber: lineNumber, closure: closure)
}
public class func logln(logLevel: LogLevel = .Debug, functionName: String = #function, fileName: String = #file, lineNumber: Int = #line, @noescape closure: () -> String?) {
self.defaultInstance().logln(logLevel, functionName: functionName, fileName: fileName, lineNumber: lineNumber, closure: closure)
}
public func logln(@autoclosure closure: () -> String?, logLevel: LogLevel = .Debug, functionName: String = #function, fileName: String = #file, lineNumber: Int = #line) {
self.logln(logLevel, functionName: functionName, fileName: fileName, lineNumber: lineNumber, closure: closure)
}
public func logln(logLevel: LogLevel = .Debug, functionName: String = #function, fileName: String = #file, lineNumber: Int = #line, @noescape closure: () -> String?) {
var logDetails: XCGLogDetails? = nil
for logDestination in self.logDestinations {
if (logDestination.isEnabledForLogLevel(logLevel)) {
if logDetails == nil {
if let logMessage = closure() {
logDetails = XCGLogDetails(logLevel: logLevel, date: NSDate(), logMessage: logMessage, functionName: functionName, fileName: fileName, lineNumber: lineNumber)
}
else {
break
}
}
logDestination.processLogDetails(logDetails!)
}
}
}
public class func exec(logLevel: LogLevel = .Debug, closure: () -> () = {}) {
self.defaultInstance().exec(logLevel, closure: closure)
}
public func exec(logLevel: LogLevel = .Debug, closure: () -> () = {}) {
if (!isEnabledForLogLevel(logLevel)) {
return
}
closure()
}
public func logAppDetails(selectedLogDestination: XCGLogDestinationProtocol? = nil) {
let date = NSDate()
var buildString = ""
if let infoDictionary = NSBundle.mainBundle().infoDictionary {
if let CFBundleShortVersionString = infoDictionary["CFBundleShortVersionString"] as? String {
buildString = "Version: \(CFBundleShortVersionString) "
}
if let CFBundleVersion = infoDictionary["CFBundleVersion"] as? String {
buildString += "Build: \(CFBundleVersion) "
}
}
let processInfo: NSProcessInfo = NSProcessInfo.processInfo()
let XCGLoggerVersionNumber = XCGLogger.Constants.versionString
let logDetails: Array<XCGLogDetails> = [XCGLogDetails(logLevel: .Info, date: date, logMessage: "\(processInfo.processName) \(buildString)PID: \(processInfo.processIdentifier)", functionName: "", fileName: "", lineNumber: 0),
XCGLogDetails(logLevel: .Info, date: date, logMessage: "XCGLogger Version: \(XCGLoggerVersionNumber) - LogLevel: \(outputLogLevel)", functionName: "", fileName: "", lineNumber: 0)]
for logDestination in (selectedLogDestination != nil ? [selectedLogDestination!] : logDestinations) {
for logDetail in logDetails {
if !logDestination.isEnabledForLogLevel(.Info) {
continue;
}
logDestination.processInternalLogDetails(logDetail)
}
}
}
// MARK: - Convenience logging methods
// MARK: * Verbose
public class func verbose(@autoclosure closure: () -> String?, functionName: String = #function, fileName: String = #file, lineNumber: Int = #line) {
self.defaultInstance().logln(.Verbose, functionName: functionName, fileName: fileName, lineNumber: lineNumber, closure: closure)
}
public class func verbose(functionName: String = #function, fileName: String = #file, lineNumber: Int = #line, @noescape closure: () -> String?) {
self.defaultInstance().logln(.Verbose, functionName: functionName, fileName: fileName, lineNumber: lineNumber, closure: closure)
}
public func verbose(@autoclosure closure: () -> String?, functionName: String = #function, fileName: String = #file, lineNumber: Int = #line) {
self.logln(.Verbose, functionName: functionName, fileName: fileName, lineNumber: lineNumber, closure: closure)
}
public func verbose(functionName: String = #function, fileName: String = #file, lineNumber: Int = #line, @noescape closure: () -> String?) {
self.logln(.Verbose, functionName: functionName, fileName: fileName, lineNumber: lineNumber, closure: closure)
}
// MARK: * Debug
public class func debug(@autoclosure closure: () -> String?, functionName: String = #function, fileName: String = #file, lineNumber: Int = #line) {
self.defaultInstance().logln(.Debug, functionName: functionName, fileName: fileName, lineNumber: lineNumber, closure: closure)
}
public class func debug(functionName: String = #function, fileName: String = #file, lineNumber: Int = #line, @noescape closure: () -> String?) {
self.defaultInstance().logln(.Debug, functionName: functionName, fileName: fileName, lineNumber: lineNumber, closure: closure)
}
public func debug(@autoclosure closure: () -> String?, functionName: String = #function, fileName: String = #file, lineNumber: Int = #line) {
self.logln(.Debug, functionName: functionName, fileName: fileName, lineNumber: lineNumber, closure: closure)
}
public func debug(functionName: String = #function, fileName: String = #file, lineNumber: Int = #line, @noescape closure: () -> String?) {
self.logln(.Debug, functionName: functionName, fileName: fileName, lineNumber: lineNumber, closure: closure)
}
// MARK: * Info
public class func info(@autoclosure closure: () -> String?, functionName: String = #function, fileName: String = #file, lineNumber: Int = #line) {
self.defaultInstance().logln(.Info, functionName: functionName, fileName: fileName, lineNumber: lineNumber, closure: closure)
}
public class func info(functionName: String = #function, fileName: String = #file, lineNumber: Int = #line, @noescape closure: () -> String?) {
self.defaultInstance().logln(.Info, functionName: functionName, fileName: fileName, lineNumber: lineNumber, closure: closure)
}
public func info(@autoclosure closure: () -> String?, functionName: String = #function, fileName: String = #file, lineNumber: Int = #line) {
self.logln(.Info, functionName: functionName, fileName: fileName, lineNumber: lineNumber, closure: closure)
}
public func info(functionName: String = #function, fileName: String = #file, lineNumber: Int = #line, @noescape closure: () -> String?) {
self.logln(.Info, functionName: functionName, fileName: fileName, lineNumber: lineNumber, closure: closure)
}
// MARK: * Warning
public class func warning(@autoclosure closure: () -> String?, functionName: String = #function, fileName: String = #file, lineNumber: Int = #line) {
self.defaultInstance().logln(.Warning, functionName: functionName, fileName: fileName, lineNumber: lineNumber, closure: closure)
}
public class func warning(functionName: String = #function, fileName: String = #file, lineNumber: Int = #line, @noescape closure: () -> String?) {
self.defaultInstance().logln(.Warning, functionName: functionName, fileName: fileName, lineNumber: lineNumber, closure: closure)
}
public func warning(@autoclosure closure: () -> String?, functionName: String = #function, fileName: String = #file, lineNumber: Int = #line) {
self.logln(.Warning, functionName: functionName, fileName: fileName, lineNumber: lineNumber, closure: closure)
}
public func warning(functionName: String = #function, fileName: String = #file, lineNumber: Int = #line, @noescape closure: () -> String?) {
self.logln(.Warning, functionName: functionName, fileName: fileName, lineNumber: lineNumber, closure: closure)
}
// MARK: * Error
public class func error(@autoclosure closure: () -> String?, functionName: String = #function, fileName: String = #file, lineNumber: Int = #line) {
self.defaultInstance().logln(.Error, functionName: functionName, fileName: fileName, lineNumber: lineNumber, closure: closure)
}
public class func error(functionName: String = #function, fileName: String = #file, lineNumber: Int = #line, @noescape closure: () -> String?) {
self.defaultInstance().logln(.Error, functionName: functionName, fileName: fileName, lineNumber: lineNumber, closure: closure)
}
public func error(@autoclosure closure: () -> String?, functionName: String = #function, fileName: String = #file, lineNumber: Int = #line) {
self.logln(.Error, functionName: functionName, fileName: fileName, lineNumber: lineNumber, closure: closure)
}
public func error(functionName: String = #function, fileName: String = #file, lineNumber: Int = #line, @noescape closure: () -> String?) {
self.logln(.Error, functionName: functionName, fileName: fileName, lineNumber: lineNumber, closure: closure)
}
// MARK: * Severe
public class func severe(@autoclosure closure: () -> String?, functionName: String = #function, fileName: String = #file, lineNumber: Int = #line) {
self.defaultInstance().logln(.Severe, functionName: functionName, fileName: fileName, lineNumber: lineNumber, closure: closure)
}
public class func severe(functionName: String = #function, fileName: String = #file, lineNumber: Int = #line, @noescape closure: () -> String?) {
self.defaultInstance().logln(.Severe, functionName: functionName, fileName: fileName, lineNumber: lineNumber, closure: closure)
}
public func severe(@autoclosure closure: () -> String?, functionName: String = #function, fileName: String = #file, lineNumber: Int = #line) {
self.logln(.Severe, functionName: functionName, fileName: fileName, lineNumber: lineNumber, closure: closure)
}
public func severe(functionName: String = #function, fileName: String = #file, lineNumber: Int = #line, @noescape closure: () -> String?) {
self.logln(.Severe, functionName: functionName, fileName: fileName, lineNumber: lineNumber, closure: closure)
}
// MARK: - Exec Methods
// MARK: * Verbose
public class func verboseExec(closure: () -> () = {}) {
self.defaultInstance().exec(XCGLogger.LogLevel.Verbose, closure: closure)
}
public func verboseExec(closure: () -> () = {}) {
self.exec(XCGLogger.LogLevel.Verbose, closure: closure)
}
// MARK: * Debug
public class func debugExec(closure: () -> () = {}) {
self.defaultInstance().exec(XCGLogger.LogLevel.Debug, closure: closure)
}
public func debugExec(closure: () -> () = {}) {
self.exec(XCGLogger.LogLevel.Debug, closure: closure)
}
// MARK: * Info
public class func infoExec(closure: () -> () = {}) {
self.defaultInstance().exec(XCGLogger.LogLevel.Info, closure: closure)
}
public func infoExec(closure: () -> () = {}) {
self.exec(XCGLogger.LogLevel.Info, closure: closure)
}
// MARK: * Warning
public class func warningExec(closure: () -> () = {}) {
self.defaultInstance().exec(XCGLogger.LogLevel.Warning, closure: closure)
}
public func warningExec(closure: () -> () = {}) {
self.exec(XCGLogger.LogLevel.Warning, closure: closure)
}
// MARK: * Error
public class func errorExec(closure: () -> () = {}) {
self.defaultInstance().exec(XCGLogger.LogLevel.Error, closure: closure)
}
public func errorExec(closure: () -> () = {}) {
self.exec(XCGLogger.LogLevel.Error, closure: closure)
}
// MARK: * Severe
public class func severeExec(closure: () -> () = {}) {
self.defaultInstance().exec(XCGLogger.LogLevel.Severe, closure: closure)
}
public func severeExec(closure: () -> () = {}) {
self.exec(XCGLogger.LogLevel.Severe, closure: closure)
}
// MARK: - Misc methods
public func isEnabledForLogLevel (logLevel: XCGLogger.LogLevel) -> Bool {
return logLevel >= self.outputLogLevel
}
public func logDestination(identifier: String) -> XCGLogDestinationProtocol? {
for logDestination in logDestinations {
if logDestination.identifier == identifier {
return logDestination
}
}
return nil
}
public func addLogDestination(logDestination: XCGLogDestinationProtocol) -> Bool {
let existingLogDestination: XCGLogDestinationProtocol? = self.logDestination(logDestination.identifier)
if existingLogDestination != nil {
return false
}
logDestinations.append(logDestination)
return true
}
public func removeLogDestination(logDestination: XCGLogDestinationProtocol) {
removeLogDestination(logDestination.identifier)
}
public func removeLogDestination(identifier: String) {
logDestinations = logDestinations.filter({$0.identifier != identifier})
}
// MARK: - Private methods
private func _logln(logMessage: String, logLevel: LogLevel = .Debug) {
var logDetails: XCGLogDetails? = nil
for logDestination in self.logDestinations {
if (logDestination.isEnabledForLogLevel(logLevel)) {
if logDetails == nil {
logDetails = XCGLogDetails(logLevel: logLevel, date: NSDate(), logMessage: logMessage, functionName: "", fileName: "", lineNumber: 0)
}
logDestination.processInternalLogDetails(logDetails!)
}
}
}
// MARK: - DebugPrintable
public var debugDescription: String {
get {
var description: String = "\(extractClassName(self)): \(identifier) - logDestinations: \r"
for logDestination in logDestinations {
description += "\t \(logDestination.debugDescription)\r"
}
return description
}
}
}
// Implement Comparable for XCGLogger.LogLevel
public func < (lhs:XCGLogger.LogLevel, rhs:XCGLogger.LogLevel) -> Bool {
return lhs.rawValue < rhs.rawValue
}
func extractClassName(someObject: Any) -> String {
return (someObject is Any.Type) ? "\(someObject)" : "\(someObject.dynamicType)"
}
|
gpl-3.0
|
ae9d322e714ff3a53e9ab041a8cad555
| 39.451288 | 322 | 0.634665 | 4.991433 | false | false | false | false |
firebase/quickstart-ios
|
database/DatabaseExampleSwiftUI/DatabaseExample/Shared/Models/PostViewModel.swift
|
1
|
6538
|
//
// Copyright (c) 2021 Google Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
import Combine
import FirebaseAuth
import FirebaseDatabase
class PostViewModel: ObservableObject, Identifiable {
@Published var id: String
@Published var uid: String
@Published var author: String
@Published var title: String
@Published var body: String
@Published var starCount: Int
@Published var comments: [Comment] = []
@Published var isStarred: Bool = false
private var userIDsStarredBy: [String: Bool] {
didSet {
refreshIsStarred()
}
}
// setup instance of FIRDatabaseReference for reading and writing data
private var ref = Database.root
private var refHandle: DatabaseHandle?
init(id: String, uid: String, author: String, title: String, body: String) {
self.id = id
self.uid = uid
self.author = author
self.title = title
self.body = body
starCount = 0
userIDsStarredBy = [:]
refreshIsStarred()
}
init?(id: String, dict: [String: Any]) {
guard let uid = dict["uid"] as? String else { return nil }
guard let author = dict["author"] as? String else { return nil }
guard let title = dict["title"] as? String else { return nil }
guard let body = dict["body"] as? String else { return nil }
let userIDsStarredBy = dict["userIDsStarredBy"] as? [String: Bool] ?? [:]
let starCount = dict["starCount"] as? Int ?? 0
self.id = id
self.uid = uid
self.author = author
self.title = title
self.body = body
self.starCount = starCount
self.userIDsStarredBy = userIDsStarredBy
refreshIsStarred()
}
private func refreshIsStarred() {
isStarred = {
if let uid = getCurrentUserID() {
return userIDsStarredBy[uid] ?? false
}
return false
}()
}
private func getCurrentUserID() -> String? {
return Auth.auth().currentUser?.uid
}
func didTapSendButton(commentField: String) {
if let userID = getCurrentUserID(),
let userEmail = Auth.auth().currentUser?.email {
let commentRef = ref.child("post-comments").child(id)
guard let key = commentRef.childByAutoId().key else { return }
let comment = ["uid": userID,
"author": userEmail,
"text": commentField]
commentRef.child(key).setValue(comment)
} else {
print("Error sending comments.")
}
}
func fetchComments() {
let commentRef = ref.child("post-comments").child(id)
refHandle = commentRef.observe(DataEventType.value, with: { snapshot in
guard let comments = snapshot.value as? [String: [String: Any]] else { return }
let sortedComments = comments.sorted(by: { $0.key > $1.key })
self.comments = sortedComments.compactMap { Comment(id: $0, dict: $1) }
})
}
#if compiler(>=5.5) && canImport(_Concurrency)
@available(iOS 15, tvOS 15, macOS 12, watchOS 8, *)
func didTapStarButtonAsync() async {
// updating firebase values
let postListRef = ref.child("posts").child(id)
incrementStars(for: postListRef)
let (snapshot, _) = await postListRef.observeSingleEventAndPreviousSiblingKey(of: .value)
guard let value = snapshot.value as? [String: Any] else { return }
if let uid = value["uid"] as? String {
let userPostRef = Database.database().reference()
.child("user-posts")
.child(uid)
.child(id)
incrementStars(for: userPostRef)
}
}
#endif
func didTapStarButton() {
// updating firebase values
let postListRef = ref.child("posts").child(id)
incrementStars(for: postListRef)
postListRef.observeSingleEvent(of: .value, with: { snapshot in
guard let value = snapshot.value as? [String: Any] else { return }
if let uid = value["uid"] as? String {
let userPostRef = Database.database().reference()
.child("user-posts")
.child(uid)
.child(self.id)
self.incrementStars(for: userPostRef)
}
})
}
private func updateStars() {
let postListRef = ref.child("posts").child(id)
refHandle = postListRef.observe(DataEventType.value, with: { snapshot in
guard let post = snapshot.value as? [String: AnyObject] else { return }
self.starCount = post["starCount"] as? Int ?? 0
self.userIDsStarredBy = post["userIDsStarredBy"] as? [String: Bool] ?? [:]
})
}
private func incrementStars(for ref: DatabaseReference) {
ref.runTransactionBlock({ (currentData: MutableData) -> TransactionResult in
if var post = currentData.value as? [String: AnyObject],
let uid = Auth.auth().currentUser?.uid {
var userIDsStarredBy: [String: Bool]
userIDsStarredBy = post["userIDsStarredBy"] as? [String: Bool] ?? [:]
var starCount = post["starCount"] as? Int ?? 0
if let _ = userIDsStarredBy[uid] {
// Unstar the post and remove self from stars
starCount -= 1
userIDsStarredBy.removeValue(forKey: uid)
} else {
// Star the post and add self to stars
starCount += 1
userIDsStarredBy[uid] = true
}
post["starCount"] = starCount as AnyObject?
post["userIDsStarredBy"] = userIDsStarredBy as AnyObject?
// Set value and report transaction success
currentData.value = post
return TransactionResult.success(withValue: currentData)
}
return TransactionResult.success(withValue: currentData)
}) { error, committed, snapshot in
if let error = error {
print(error.localizedDescription)
}
}
}
func onViewAppear() {
updateStars()
}
// remove all handlers when current view disappears
func onViewDisappear() {
if let refHandle = refHandle {
ref.child("posts").child(id).removeObserver(withHandle: refHandle)
}
}
func onDetailViewDisappear() {
if let refHandle = refHandle {
ref.child("post-comments").child(id).removeObserver(withHandle: refHandle)
}
}
}
|
apache-2.0
|
516da39e39d9fba1a1820895ecea7154
| 32.528205 | 95 | 0.647752 | 4.07352 | false | false | false | false |
cristov26/moviesApp
|
MoviesApp/MoviesApp/Presenter/DetailMovie/VideoCell.swift
|
1
|
2956
|
//
// VideoCell.swift
// MoviesApp
//
// Created by Cristian Tovar on 11/16/17.
// Copyright © 2017 Cristian Tovar. All rights reserved.
//
import UIKit
import Lottie
import Alamofire
class VideoCell: UITableViewCell {
@IBOutlet weak var iconError: UIImageView!
@IBOutlet weak var animationView: UIView!
@IBOutlet weak var playerView: YTPlayerView!
var lottieView = AnimationView()
var isLoaded = false
var loadedKey: String?
var videoKey: String?
var completionBlock: LottieCompletionBlock?
override func prepareForReuse() {
super.prepareForReuse()
iconError.isHidden = true
animationView.isHidden = false
playerView.isHidden = false
isLoaded = false
}
func loadVideo(VideoId: String) {
guard loadedKey != videoKey else {
animationView.isHidden = true
return
}
if lottieView.animation == nil {
let animation = Animation.named("YouTubeAnimation")
lottieView.animation = animation
lottieView.contentMode = .scaleAspectFit
lottieView.frame = CGRect(x: 0, y: 0, width: animationView.frame.width, height: animationView.frame.height)
animationView.addSubview(lottieView)
}
if lottieView.frame.width != animationView.frame.height {
lottieView.frame = CGRect(x: 0, y: 0, width: animationView.frame.width, height: animationView.frame.height)
}
if !(NetworkReachabilityManager()?.isReachable ?? false) {
animationView.isHidden = true
playerView.isHidden = true
iconError.isHidden = false
return
}
if completionBlock == nil {
completionBlock = { [weak self] finished in
self?.animationEnded(finished: finished)
}
}
lottieView.animationSpeed = 2
lottieView.play(fromProgress: 0,
toProgress: 1,
loopMode: LottieLoopMode.playOnce,
completion: completionBlock)
iconError.isHidden = true
if playerView.load(withVideoId: VideoId) {
playerView.delegate = self
} else {
lottieView.stop()
animationView.isHidden = true
iconError.isHidden = false
}
}
func animationEnded(finished: Bool, completion: LottieCompletionBlock? = nil) {
if finished && self.isLoaded {
animationView.isHidden = true
} else {
lottieView.play(fromProgress: 0,
toProgress: 1,
loopMode: LottieLoopMode.playOnce,
completion: completionBlock)
}
}
}
extension VideoCell: YTPlayerViewDelegate {
func playerViewDidBecomeReady(_ playerView: YTPlayerView) {
isLoaded = true
loadedKey = videoKey
}
}
|
mit
|
47b899d74c51f16e294e8202b0f2e4f2
| 31.472527 | 119 | 0.596616 | 5.059932 | false | false | false | false |
mmick66/kinieta
|
KinietaTests/ColorComponentsTests.swift
|
1
|
2049
|
//
// ColorComponentsTests.swift
// KinietaTests
//
// Created by Michael Michailidis on 19/10/2017.
// Copyright © 2017 Michael Michailidis. All rights reserved.
//
import XCTest
class ColorComponentsTests: XCTestCase {
let originalColor = UIColor(red:237.0 / 255.0, green: 99.0 / 255.0, blue: 102.0 / 255.0, alpha:1.00)
override func setUp() {
super.setUp()
}
override func tearDown() {
super.tearDown()
}
@discardableResult
func createDerivativeColor(space: UIColor.Components.Space) -> UIColor {
let data = originalColor.components(as: space)
return UIColor(components: data)
}
func testRGBColorConvertion() {
let derivativeColor = self.createDerivativeColor(space: .RGB)
XCTAssert(originalColor == derivativeColor, "Colors do not match")
}
func testHSBColorConvertion() {
let derivativeColor = self.createDerivativeColor(space: .HSB)
print("Compare:\n\t o-color: \"\(originalColor)\"\n\t d-color: \"\(derivativeColor)\"")
XCTAssert(originalColor.description == derivativeColor.description, "Colors do not match")
}
func testHLCValueExtraction() {
let (h,l,c,a) = self.originalColor.hlca
XCTAssert((h * LCHColor.MaxH) ~= 25.63104309046355, "Hue (\(h * LCHColor.MaxH)) != 25.63104309046355")
XCTAssert((l * LCHColor.MaxL) ~= 59.78697847134286, "Luminosity (\(l * LCHColor.MaxL)) != 59.78697847134286")
XCTAssert((c * LCHColor.MaxC) ~= 59.360754654915006, "Chroma (\(c * LCHColor.MaxC)) != 59.360754654915006")
XCTAssert(a == 1.0, "Colors do not match")
}
func testPerformanceExample() {
self.measure {
self.createDerivativeColor(space: .HLC)
}
}
}
infix operator ~=
func ~=(lhs:CGFloat, rhs:CGFloat) -> Bool {
return CGFloat(round(lhs * 10.0) / 10.0) == CGFloat(round(rhs * 10.0) / 10.0)
}
|
apache-2.0
|
b25415e11af6bb802e7df1a779267a48
| 28.257143 | 117 | 0.603516 | 3.785582 | false | true | false | false |
magnetsystems/message-samples-ios
|
QuickStart/QuickStart/UserRetrievalViewController.swift
|
1
|
3600
|
/*
* Copyright (c) 2015 Magnet Systems, Inc.
* 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 UIKit
import MagnetMax
class UserRetrievalViewController: UIViewController {
// MARK: Outlets
@IBOutlet weak var criteriaSegmentedControl: UISegmentedControl!
@IBOutlet weak var searchTextField: UITextField!
@IBOutlet weak var usersTableView: UITableView!
// MARK: public properties
var users : [MMUser] = []
// MARK: Overrides
override func viewDidLoad() {
super.viewDidLoad()
currentMode = .ByID
}
// MARK: Private implementations
private enum CurrentMode {
case ByID
case ByUserName
}
private var currentMode: CurrentMode = .ByID {
didSet {
switch currentMode {
case .ByID:
searchTextField.placeholder = "userID1, userID2, userID3"
searchTextField.text = MMUser.currentUser()?.userID
case .ByUserName:
searchTextField.placeholder = "userName1, userName2, userName3"
searchTextField.text = MMUser.currentUser()?.userName
}
}
}
// MARK: Actions
@IBAction func criteriaChanged() {
if criteriaSegmentedControl.selectedSegmentIndex == 0 {
currentMode = .ByID
} else if criteriaSegmentedControl.selectedSegmentIndex == 1 {
currentMode = .ByUserName
}
}
@IBAction func retrieveUsers(sender: UIBarButtonItem) {
if let searchString = searchTextField.text {
let values = searchString.characters.split(",").map { String($0).stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceCharacterSet()) }
switch currentMode {
case .ByID:
MMUser.usersWithUserIDs(values, success: { [weak self] users in
self?.users = users
self?.usersTableView.reloadData()
}, failure: { error in
print("[ERROR]: \(error.localizedDescription)")
})
case .ByUserName:
MMUser.usersWithUserNames(values, success: { [weak self] users in
self?.users = users
self?.usersTableView.reloadData()
}, failure: { error in
print("[ERROR]: \(error.localizedDescription)")
})
}
}
}
}
extension UserRetrievalViewController : UITableViewDataSource {
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return users.count
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("UserCellIdentifier", forIndexPath: indexPath)
let user = users[indexPath.row]
cell.textLabel?.text = user.userName
return cell
}
}
|
apache-2.0
|
da2e8524f5a32f52e7b8d98a35664d55
| 29.508475 | 151 | 0.609444 | 5.504587 | false | false | false | false |
cuappdev/podcast-ios
|
old/Podcast/FacebookEndpointRequests.swift
|
1
|
2433
|
//
// FacebookEndpointRequests.swift
// Podcast
//
// Created by Jack Thompson on 8/27/18.
// Copyright © 2018 Cornell App Development. All rights reserved.
//
import Foundation
import SwiftyJSON
class FetchFacebookFriendsEndpointRequest: EndpointRequest {
var pageSize: Int
var offset: Int
// returnFollowing: If true, return your friends sorted by the number of followers.
// If false, only return your friends that you are not following also sorted by the number of followers
var returnFollowing: Bool?
init(facebookAccessToken: String, pageSize: Int, offset: Int, returnFollowing: Bool?) {
self.offset = offset
self.pageSize = pageSize
self.returnFollowing = returnFollowing
super.init()
path = "/users/facebook/friends/"
httpMethod = .get
queryParameters = ["offset": offset, "max": pageSize]
if let following = returnFollowing {
queryParameters["return_following"] = following.description
}
headers = ["AccessToken": facebookAccessToken]
}
override func processResponseJSON(_ json: JSON) {
processedResponseValue = json["data"]["users"].map{ element in User(json: element.1) }
}
}
class SearchFacebookFriendsEndpointRequest: EndpointRequest {
var offset: Int
var max: Int
var query: String
init(facebookAccessToken: String, query: String, offset: Int, max: Int) {
self.query = query
self.offset = offset
self.max = max
super.init()
path = "/search/facebook/friends/\(query.addingPercentEncoding(withAllowedCharacters: .urlHostAllowed) ?? query)/"
httpMethod = .get
queryParameters = ["offset": offset, "max": max]
headers = ["AccessToken": facebookAccessToken]
}
override func processResponseJSON(_ json: JSON) {
processedResponseValue = json["data"]["users"].map{ element in User(json: element.1) }
}
}
class DismissFacebookFriendEndpointRequest: EndpointRequest {
// id of the friend we are dismissing
var facebookId: String
init(facebookAccessToken: String, facebookId: String) {
self.facebookId = facebookId
super.init()
path = "/users/facebook/friends/ignore/\(facebookId)/"
httpMethod = .post
headers = ["AccessToken": facebookAccessToken]
}
}
|
mit
|
2efe5434f9ecda6475bd5f7baf8388b6
| 30.584416 | 122 | 0.650082 | 4.75 | false | false | false | false |
eduarenas80/MarvelClient
|
Source/Entities/Entity.swift
|
2
|
2042
|
//
// Entity.swift
// MarvelClient
//
// Copyright (c) 2016 Eduardo Arenas <[email protected]>
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
import Foundation
import SwiftyJSON
public protocol JSONSerializable {
init(json: JSON)
}
public protocol Entity: JSONSerializable {
var id: Int { get }
var modified: NSDate? { get }
var resourceURI: String { get }
var thumbnail: Image { get }
}
public protocol EntitySummary: JSONSerializable {
var resourceURI: String { get }
var name: String { get }
var id: Int? { get }
}
public extension EntitySummary {
var id: Int? {
guard let url = NSURL(string: self.resourceURI) else {
return nil
}
guard let pathComponents = url.pathComponents else {
return nil
}
return Int(pathComponents.last!)
}
}
public enum EntityType: String {
case Characters = "characters"
case Comics = "comics"
case Creators = "creators"
case Events = "events"
case Series = "series"
case Stories = "stories"
}
|
mit
|
877fcd703b77cc2eab79c18cd8274ac5
| 30.415385 | 81 | 0.718903 | 4.108652 | false | false | false | false |
jpsim/Yams
|
Sources/Yams/Node.Mapping.swift
|
1
|
6928
|
//
// Node.Mapping.swift
// Yams
//
// Created by Norio Nomura on 2/24/17.
// Copyright (c) 2016 Yams. All rights reserved.
//
extension Node {
/// A mapping is the YAML equivalent of a `Dictionary`.
public struct Mapping {
private var pairs: [Pair<Node>]
/// This mapping's `Tag`.
public var tag: Tag
/// The style to use when emitting this `Mapping`.
public var style: Style
/// This mapping's `Mark`.
public var mark: Mark?
/// The style to use when emitting a `Mapping`.
public enum Style: UInt32 {
/// Let the emitter choose the style.
case any
/// The block mapping style.
case block
/// The flow mapping style.
case flow
}
/// Create a `Node.Mapping` using the specified parameters.
///
/// - parameter pairs: The array of `(Node, Node)` tuples to generate this mapping.
/// - parameter tag: This mapping's `Tag`.
/// - parameter style: The style to use when emitting this `Mapping`.
/// - parameter mark: This mapping's `Mark`.
public init(_ pairs: [(Node, Node)], _ tag: Tag = .implicit, _ style: Style = .any, _ mark: Mark? = nil) {
self.pairs = pairs.map { Pair($0.0, $0.1) }
self.tag = tag
self.style = style
self.mark = mark
}
}
/// Get or set the `Node.Mapping` value if this node is a `Node.mapping`.
public var mapping: Mapping? {
get {
if case let .mapping(mapping) = self {
return mapping
}
return nil
}
set {
if let newValue = newValue {
self = .mapping(newValue)
}
}
}
}
extension Node.Mapping: Comparable {
/// :nodoc:
public static func < (lhs: Node.Mapping, rhs: Node.Mapping) -> Bool {
return lhs.pairs < rhs.pairs
}
}
extension Node.Mapping: Equatable {
/// :nodoc:
public static func == (lhs: Node.Mapping, rhs: Node.Mapping) -> Bool {
return lhs.pairs == rhs.pairs && lhs.resolvedTag == rhs.resolvedTag
}
}
extension Node.Mapping: Hashable {
/// :nodoc:
public func hash(into hasher: inout Hasher) {
hasher.combine(pairs)
hasher.combine(resolvedTag)
}
}
extension Node.Mapping: ExpressibleByDictionaryLiteral {
/// :nodoc:
public init(dictionaryLiteral elements: (Node, Node)...) {
self.init(elements)
}
}
// MARK: - MutableCollection Conformance
extension Node.Mapping: MutableCollection {
/// :nodoc:
public typealias Element = (key: Node, value: Node)
// MARK: Sequence
/// :nodoc:
public func makeIterator() -> Array<Element>.Iterator {
return pairs.map(Pair.toTuple).makeIterator()
}
// MARK: Collection
/// The index type for this mapping.
public typealias Index = Array<Element>.Index
/// :nodoc:
public var startIndex: Index {
return pairs.startIndex
}
/// :nodoc:
public var endIndex: Index {
return pairs.endIndex
}
/// :nodoc:
public func index(after index: Index) -> Index {
return pairs.index(after: index)
}
/// :nodoc:
public subscript(index: Index) -> Element {
get {
return (key: pairs[index].key, value: pairs[index].value)
}
// MutableCollection
set {
pairs[index] = Pair(newValue.key, newValue.value)
}
}
}
extension Node.Mapping: TagResolvable {
static let defaultTagName = Tag.Name.map
}
// MARK: - Merge support
extension Node.Mapping {
func flatten() -> Node.Mapping {
var pairs = Array(self)
var merge = [(key: Node, value: Node)]()
var index = pairs.startIndex
while index < pairs.count {
let pair = pairs[index]
if pair.key.tag.name == .merge {
pairs.remove(at: index)
switch pair.value {
case .mapping(let mapping):
merge.append(contentsOf: mapping.flatten())
case let .sequence(sequence):
let submerge = sequence
.compactMap { $0.mapping.map { $0.flatten() } }
.reversed()
submerge.forEach {
merge.append(contentsOf: $0)
}
default:
break // TODO: Should raise error on other than mapping or sequence
}
} else if pair.key.tag.name == .value {
pair.key.tag.name = .str
index += 1
} else {
index += 1
}
}
return Node.Mapping(merge + pairs, tag, style)
}
}
// MARK: - Dictionary-like APIs
extension Node.Mapping {
/// This mapping's keys. Similar to `Dictionary.keys`.
public var keys: LazyMapCollection<Node.Mapping, Node> {
return lazy.map { $0.key }
}
/// This mapping's values. Similar to `Dictionary.values`.
public var values: LazyMapCollection<Node.Mapping, Node> {
return lazy.map { $0.value }
}
/// Set or get the `Node` for the specified string's `Node` representation.
public subscript(string: String) -> Node? {
get {
return self[Node(string, tag.copy(with: .implicit))]
}
set {
self[Node(string, tag.copy(with: .implicit))] = newValue
}
}
/// Set or get the specified `Node`.
public subscript(node: Node) -> Node? {
get {
return pairs.reversed().first(where: { $0.key == node })?.value
}
set {
if let newValue = newValue {
if let index = index(forKey: node) {
pairs[index] = Pair(pairs[index].key, newValue)
} else {
pairs.append(Pair(node, newValue))
}
} else {
if let index = index(forKey: node) {
pairs.remove(at: index)
}
}
}
}
/// Get the index of the specified `Node`, if it exists in the mapping.
public func index(forKey key: Node) -> Index? {
return pairs.reversed().firstIndex(where: { $0.key == key }).map({ pairs.index(before: $0.base) })
}
}
private struct Pair<Value: Comparable & Equatable>: Comparable, Equatable {
let key: Value
let value: Value
init(_ key: Value, _ value: Value) {
self.key = key
self.value = value
}
static func < (lhs: Pair<Value>, rhs: Pair<Value>) -> Bool {
return lhs.key < rhs.key
}
static func toTuple(pair: Pair) -> (key: Value, value: Value) {
return (key: pair.key, value: pair.value)
}
}
extension Pair: Hashable where Value: Hashable {}
|
mit
|
7bdc2931365f5b6aec9c9f0b29e5a44c
| 27.866667 | 114 | 0.537096 | 4.258144 | false | false | false | false |
larcus94/ImagePickerSheetController
|
ImagePickerSheetController/ImagePickerSheetController/Sheet/SheetCollectionViewCell.swift
|
2
|
4249
|
//
// SheetCollectionViewCell.swift
// ImagePickerSheetController
//
// Created by Laurin Brandner on 24/08/15.
// Copyright © 2015 Laurin Brandner. All rights reserved.
//
import UIKit
enum RoundedCorner {
case all(CGFloat)
case top(CGFloat)
case bottom(CGFloat)
case none
}
class SheetCollectionViewCell: UICollectionViewCell {
var backgroundInsets = UIEdgeInsets() {
didSet {
reloadMask()
reloadSeparator()
setNeedsLayout()
}
}
var roundedCorners = RoundedCorner.none {
didSet {
reloadMask()
}
}
var separatorVisible = false {
didSet {
reloadSeparator()
}
}
var separatorColor = UIColor.black {
didSet {
separatorView?.backgroundColor = separatorColor
}
}
var separatorHeight: CGFloat = 1 {
didSet {
setNeedsLayout()
}
}
fileprivate var separatorView: UIView?
override var isHighlighted: Bool {
didSet {
reloadBackgroundColor()
}
}
var highlightedBackgroundColor: UIColor = .clear {
didSet {
reloadBackgroundColor()
}
}
var normalBackgroundColor: UIColor = .clear {
didSet {
reloadBackgroundColor()
}
}
fileprivate var needsMasking: Bool {
guard backgroundInsets == UIEdgeInsets() else {
return true
}
switch roundedCorners {
case .none:
return false
default:
return true
}
}
// MARK: - Initialization
override init(frame: CGRect) {
super.init(frame: frame)
initialize()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
initialize()
}
fileprivate func initialize() {
layoutMargins = UIEdgeInsets()
}
// MARK: - Layout
override func layoutSubviews() {
super.layoutSubviews()
reloadMask()
separatorView?.frame = CGRect(x: bounds.minY, y: bounds.maxY - separatorHeight, width: bounds.width, height: separatorHeight)
}
// MARK: - Mask
fileprivate func reloadMask() {
if needsMasking && layer.mask == nil {
let maskLayer = CAShapeLayer()
maskLayer.frame = bounds
maskLayer.lineWidth = 0
maskLayer.fillColor = UIColor.black.cgColor
layer.mask = maskLayer
}
let layerMask = layer.mask as? CAShapeLayer
layerMask?.frame = bounds
layerMask?.path = maskPathWithRect(bounds.inset(by: backgroundInsets), roundedCorner: roundedCorners)
}
fileprivate func maskPathWithRect(_ rect: CGRect, roundedCorner: RoundedCorner) -> CGPath {
let radii: CGFloat
let corners: UIRectCorner
switch roundedCorner {
case .all(let value):
corners = .allCorners
radii = value
case .top(let value):
corners = [.topLeft, .topRight]
radii = value
case .bottom(let value):
corners = [.bottomLeft, .bottomRight]
radii = value
case .none:
return UIBezierPath(rect: rect).cgPath
}
return UIBezierPath(roundedRect: rect, byRoundingCorners: corners, cornerRadii: CGSize(width: radii, height: radii)).cgPath
}
// MARK: - Separator
fileprivate func reloadSeparator() {
if separatorVisible && backgroundInsets.bottom < separatorHeight {
if separatorView == nil {
let view = UIView()
view.backgroundColor = separatorColor
addSubview(view)
separatorView = view
}
}
else {
separatorView?.removeFromSuperview()
separatorView = nil
}
}
// MARK - Background
fileprivate func reloadBackgroundColor() {
backgroundColor = isHighlighted ? highlightedBackgroundColor : normalBackgroundColor
}
}
|
mit
|
9d8ed7db17ac9a29aff9db09ebd5d45a
| 23.554913 | 133 | 0.553908 | 5.679144 | false | false | false | false |
kstaring/swift
|
stdlib/public/SDK/SpriteKit/SpriteKit.swift
|
4
|
4110
|
//===----------------------------------------------------------------------===//
//
// 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
//
//===----------------------------------------------------------------------===//
@_exported import SpriteKit
import simd
// SpriteKit defines SKColor using a macro.
#if os(OSX)
public typealias SKColor = NSColor
#elseif os(iOS) || os(tvOS) || os(watchOS)
public typealias SKColor = UIColor
#endif
// this class only exists to allow AnyObject lookup of _copyImageData
// since that method only exists in a private header in SpriteKit, the lookup
// mechanism by default fails to accept it as a valid AnyObject call
@objc class _SpriteKitMethodProvider : NSObject {
override init() { _sanityCheckFailure("don't touch me") }
@objc func _copyImageData() -> NSData! { return nil }
}
@available(iOS, introduced: 10.0)
@available(OSX, introduced: 10.12)
@available(tvOS, introduced: 10.0)
@available(watchOS, introduced: 3.0)
extension SKWarpGeometryGrid {
/// Create a grid of the specified dimensions, source and destination positions.
///
/// Grid dimensions (columns and rows) refer to the number of faces in each dimension. The
/// number of vertices required for a given dimension is equal to (cols + 1) * (rows + 1).
///
/// SourcePositions are normalized (0.0 - 1.0) coordinates to determine the source content.
///
/// DestinationPositions are normalized (0.0 - 1.0) positional coordinates with respect to
/// the node's native size. Values outside the (0.0-1.0) range are perfectly valid and
/// correspond to positions outside of the native undistorted bounds.
///
/// Source and destination positions are provided in row-major order starting from the top-left.
/// For example the indices for a 2x2 grid would be as follows:
///
/// [0]---[1]---[2]
/// | | |
/// [3]---[4]---[5]
/// | | |
/// [6]---[7]---[8]
///
/// - Parameter columns: the number of columns to initialize the SKWarpGeometryGrid with
/// - Parameter rows: the number of rows to initialize the SKWarpGeometryGrid with
/// - Parameter sourcePositions: the source positions for the SKWarpGeometryGrid to warp from
/// - Parameter destinationPositions: the destination positions for SKWarpGeometryGrid to warp to
public convenience init(columns: Int, rows: Int, sourcePositions: [simd.float2] = [float2](), destinationPositions: [simd.float2] = [float2]()) {
let requiredElementsCount = (columns + 1) * (rows + 1)
switch (destinationPositions.count, sourcePositions.count) {
case (0, 0):
self.init(__columns: columns, rows: rows, sourcePositions: nil, destPositions: nil)
case (let dests, 0):
_precondition(dests == requiredElementsCount, "Mismatch found between rows/columns and positions.")
self.init(__columns: columns, rows: rows, sourcePositions: nil, destPositions: destinationPositions)
case (0, let sources):
_precondition(sources == requiredElementsCount, "Mismatch found between rows/columns and positions.")
self.init(__columns: columns, rows: rows, sourcePositions: sourcePositions, destPositions: nil)
case (let dests, let sources):
_precondition(dests == requiredElementsCount && sources == requiredElementsCount, "Mismatch found between rows/columns and positions.")
self.init(__columns: columns, rows: rows, sourcePositions: sourcePositions, destPositions: destinationPositions)
}
}
public func replacingBySourcePositions(positions source: [simd.float2]) -> SKWarpGeometryGrid {
return self.__replacingSourcePositions(source)
}
public func replacingByDestinationPositions(positions destination: [simd.float2]) -> SKWarpGeometryGrid {
return self.__replacingDestPositions(destination)
}
}
|
apache-2.0
|
6c2d20324f499534906225fe4a48ecf3
| 47.352941 | 147 | 0.684672 | 4.237113 | false | false | false | false |
pennlabs/penn-mobile-ios
|
PennMobile/Home/Fitness/Model/FitnessFacilityData.swift
|
1
|
1666
|
//
// FitnessFacilityData.swift
// PennMobile
//
// Created by dominic on 7/19/18.
// Copyright © 2018 PennLabs. All rights reserved.
//
import Foundation
class FitnessFacilityData {
static let shared = FitnessFacilityData()
fileprivate var schedules = [FitnessFacilityName: [FitnessSchedule]]()
func load(inputSchedules: FitnessSchedules) {
schedules = [FitnessFacilityName: [FitnessSchedule]]()
guard inputSchedules.schedules != nil else { return }
for schedule in inputSchedules.schedules! where schedule != nil {
if schedules[schedule!.name] != nil {
schedules[schedule!.name]?.append(schedule!)
} else {
schedules[schedule!.name] = [schedule!]
}
}
}
func getScheduleForToday(for venue: FitnessFacilityName) -> FitnessSchedule? {
guard schedules.keys.contains(venue) else { return nil }
return schedules[venue]!.first(where: { (schedule) -> Bool in
if let hours = schedule.hours.first {
return hours.start?.isToday ?? false
}
return false
})
}
func getActiveFacilities() -> [FitnessFacilityName?] {
var activeFacilities = [FitnessFacilityName]()
for (name, schedule) in schedules {
if schedule.contains(where: { (s) -> Bool in
return (s.hours.first?.start?.isToday ?? false)
}) {
activeFacilities.append(name)
}
}
return activeFacilities
}
func clearSchedules() {
schedules = [FitnessFacilityName: [FitnessSchedule]]()
}
}
|
mit
|
73d7ee5fa8691ffaff5fd03b43351c90
| 28.732143 | 82 | 0.596396 | 4.637883 | false | false | false | false |
Witcast/witcast-ios
|
Pods/Material/Sources/Frameworks/Motion/Sources/Extensions/Motion+CG.swift
|
1
|
7999
|
/*
* The MIT License (MIT)
*
* Copyright (C) 2017, Daniel Dahan and CosmicMind, Inc. <http://cosmicmind.com>.
* All rights reserved.
*
* Original Inspiration & Author
* Copyright (c) 2016 Luke Zhao <[email protected]>
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
import MetalKit
extension CGSize {
/// THe center point based on width and height.
var center: CGPoint {
return CGPoint(x: width / 2, y: height / 2)
}
/// Top left point based on the size.
var topLeft: CGPoint {
return .zero
}
/// Top right point based on the size.
var topRight: CGPoint {
return CGPoint(x: width, y: 0)
}
/// Bottom left point based on the size.
var bottomLeftPoint: CGPoint {
return CGPoint(x: 0, y: height)
}
/// Bottom right point based on the size.
var bottomRight: CGPoint {
return CGPoint(x: width, y: height)
}
/**
Retrieves the size based on a given CGAffineTransform.
- Parameter _ t: A CGAffineTransform.
- Returns: A CGSize.
*/
func transform(_ t: CGAffineTransform) -> CGSize {
return applying(t)
}
/**
Retrieves the size based on a given CATransform3D.
- Parameter _ t: A CGAffineTransform.
- Returns: A CGSize.
*/
func transform(_ t: CATransform3D) -> CGSize {
return applying(CATransform3DGetAffineTransform(t))
}
}
extension CGRect {
/// A center point based on the origin and size values.
var center: CGPoint {
return CGPoint(x: origin.x + size.width / 2, y: origin.y + size.height / 2)
}
/// The bounding box size based from from the frame's rect.
var bounds: CGRect {
return CGRect(origin: .zero, size: size)
}
/**
An initializer with a given point and size.
- Parameter center: A CGPoint.
- Parameter size: A CGSize.
*/
init(center: CGPoint, size: CGSize) {
self.init(x: center.x - size.width / 2, y: center.y - size.height / 2, width: size.width, height: size.height)
}
}
extension CGFloat {
/**
Calculates the limiting position to an area.
- Parameter _ a: A CGFloat.
- Parameter _ b: A CGFloat.
- Returns: A CGFloat.
*/
func clamp(_ a: CGFloat, _ b: CGFloat) -> CGFloat {
return self < a ? a : self > b ? b : self
}
}
extension CGPoint {
/**
Calculates a translation point based on the origin value.
- Parameter _ dx: A CGFloat.
- Parameter _ dy: A CGFloat.
- Returns: A CGPoint.
*/
func translate(_ dx: CGFloat, dy: CGFloat) -> CGPoint {
return CGPoint(x: x + dx, y: y + dy)
}
/**
Calculates a transform point based on a given CGAffineTransform.
- Parameter _ t: CGAffineTransform.
- Returns: A CGPoint.
*/
func transform(_ t: CGAffineTransform) -> CGPoint {
return applying(t)
}
/**
Calculates a transform point based on a given CATransform3D.
- Parameter _ t: CATransform3D.
- Returns: A CGPoint.
*/
func transform(_ t: CATransform3D) -> CGPoint {
return applying(CATransform3DGetAffineTransform(t))
}
/**
Calculates the distance between the CGPoint and given CGPoint.
- Parameter _ b: A CGPoint.
- Returns: A CGFloat.
*/
func distance(_ b: CGPoint) -> CGFloat {
return sqrt(pow(x - b.x, 2) + pow(y - b.y, 2))
}
}
/**
A handler for the (+) operator.
- Parameter left: A CGPoint.
- Parameter right: A CGPoint.
- Returns: A CGPoint.
*/
func +(left: CGPoint, right: CGPoint) -> CGPoint {
return CGPoint(x: left.x + right.x, y: left.y + right.y)
}
/**
A handler for the (-) operator.
- Parameter left: A CGPoint.
- Parameter right: A CGPoint.
- Returns: A CGPoint.
*/
func -(left: CGPoint, right: CGPoint) -> CGPoint {
return CGPoint(x: left.x - right.x, y: left.y - right.y)
}
/**
A handler for the (/) operator.
- Parameter left: A CGPoint.
- Parameter right: A CGFloat.
- Returns: A CGPoint.
*/
func /(left: CGPoint, right: CGFloat) -> CGPoint {
return CGPoint(x: left.x / right, y: left.y / right)
}
/**
A handler for the (/) operator.
- Parameter left: A CGPoint.
- Parameter right: A CGPoint.
- Returns: A CGPoint.
*/
func /(left: CGPoint, right: CGPoint) -> CGPoint {
return CGPoint(x: left.x / right.x, y: left.y / right.y)
}
/**
A handler for the (/) operator.
- Parameter left: A CGSize.
- Parameter right: A CGSize.
- Returns: A CGSize.
*/
func /(left: CGSize, right: CGSize) -> CGSize {
return CGSize(width: left.width / right.width, height: left.height / right.height)
}
/**
A handler for the (*) operator.
- Parameter left: A CGPoint.
- Parameter right: A CGFloat.
- Returns: A CGPoint.
*/
func *(left: CGPoint, right: CGFloat) -> CGPoint {
return CGPoint(x: left.x * right, y: left.y * right)
}
/**
A handler for the (*) operator.
- Parameter left: A CGPoint.
- Parameter right: A CGSize.
- Returns: A CGPoint.
*/
func *(left: CGPoint, right: CGSize) -> CGPoint {
return CGPoint(x: left.x * right.width, y: left.y * right.width)
}
/**
A handler for the (*) operator.
- Parameter left: A CGFloat.
- Parameter right: A CGPoint.
- Returns: A CGPoint.
*/
func *(left: CGFloat, right: CGPoint) -> CGPoint {
return right * left
}
/**
A handler for the (*) operator.
- Parameter left: A CGPoint.
- Parameter right: A CGPoint.
- Returns: A CGPoint.
*/
func *(left: CGPoint, right: CGPoint) -> CGPoint {
return CGPoint(x: left.x * right.x, y: left.y * right.y)
}
/**
A handler for the (*) prefix.
- Parameter left: A CGSize.
- Parameter right: A CGFloat.
- Returns: A CGSize.
*/
func *(left: CGSize, right: CGFloat) -> CGSize {
return CGSize(width: left.width * right, height: left.height * right)
}
/**
A handler for the (*) prefix.
- Parameter left: A CGSize.
- Parameter right: A CGSize.
- Returns: A CGSize.
*/
func *(left: CGSize, right: CGSize) -> CGSize {
return CGSize(width: left.width * right.width, height: left.height * right.width)
}
/**
A handler for the (==) operator.
- Parameter lhs: A CATransform3D.
- Parameter rhs: A CATransform3D.
- Returns: A Bool.
*/
func ==(lhs: CATransform3D, rhs: CATransform3D) -> Bool {
var lhs = lhs
var rhs = rhs
return memcmp(&lhs, &rhs, MemoryLayout<CATransform3D>.size) == 0
}
/**
A handler for the (!=) operator.
- Parameter lhs: A CATransform3D.
- Parameter rhs: A CATransform3D.
- Returns: A Bool.
*/
func !=(lhs: CATransform3D, rhs: CATransform3D) -> Bool {
return !(lhs == rhs)
}
/**
A handler for the (-) prefix.
- Parameter point: A CGPoint.
- Returns: A CGPoint.
*/
prefix func -(point: CGPoint) -> CGPoint {
return CGPoint.zero - point
}
/**
A handler for the (abs) function.
- Parameter _ p: A CGPoint.
- Returns: A CGPoint.
*/
func abs(_ p: CGPoint) -> CGPoint {
return CGPoint(x: abs(p.x), y: abs(p.y))
}
|
apache-2.0
|
ce704b47e09e0ca4b6504257268c8d22
| 26.023649 | 118 | 0.633704 | 3.699815 | false | false | false | false |
gavrix/ImageViewModel
|
Carthage/Checkouts/ReactiveSwift/Tests/ReactiveSwiftTests/ActionSpec.swift
|
1
|
6223
|
//
// ActionSpec.swift
// ReactiveSwift
//
// Created by Justin Spahr-Summers on 2014-12-11.
// Copyright (c) 2014 GitHub. All rights reserved.
//
import Foundation
import Result
import Nimble
import Quick
import ReactiveSwift
class ActionSpec: QuickSpec {
override func spec() {
describe("Action") {
var action: Action<Int, String, NSError>!
var enabled: MutableProperty<Bool>!
var executionCount = 0
var completedCount = 0
var values: [String] = []
var errors: [NSError] = []
var scheduler: TestScheduler!
let testError = NSError(domain: "ActionSpec", code: 1, userInfo: nil)
beforeEach {
executionCount = 0
completedCount = 0
values = []
errors = []
enabled = MutableProperty(false)
scheduler = TestScheduler()
action = Action(enabledIf: enabled) { number in
return SignalProducer { observer, disposable in
executionCount += 1
if number % 2 == 0 {
observer.send(value: "\(number)")
observer.send(value: "\(number)\(number)")
scheduler.schedule {
observer.sendCompleted()
}
} else {
scheduler.schedule {
observer.send(error: testError)
}
}
}
}
action.values.observeValues { values.append($0) }
action.errors.observeValues { errors.append($0) }
action.completed.observeValues { completedCount += 1 }
}
it("should be disabled and not executing after initialization") {
expect(action.isEnabled.value) == false
expect(action.isExecuting.value) == false
}
it("should error if executed while disabled") {
var receivedError: ActionError<NSError>?
var disabledErrorsTriggered = false
action.disabledErrors.observeValues {
disabledErrorsTriggered = true
}
action.apply(0).startWithFailed {
receivedError = $0
}
expect(receivedError).notTo(beNil())
expect(disabledErrorsTriggered) == true
if let error = receivedError {
let expectedError = ActionError<NSError>.disabled
expect(error == expectedError) == true
}
}
it("should enable and disable based on the given property") {
enabled.value = true
expect(action.isEnabled.value) == true
expect(action.isExecuting.value) == false
enabled.value = false
expect(action.isEnabled.value) == false
expect(action.isExecuting.value) == false
}
describe("completed") {
beforeEach {
enabled.value = true
}
it("should send a value whenever the producer completes") {
action.apply(0).start()
expect(completedCount) == 0
scheduler.run()
expect(completedCount) == 1
action.apply(2).start()
scheduler.run()
expect(completedCount) == 2
}
it("should not send a value when the producer fails") {
action.apply(1).start()
scheduler.run()
expect(completedCount) == 0
}
it("should not send a value when the producer is interrupted") {
let disposable = action.apply(0).start()
disposable.dispose()
scheduler.run()
expect(completedCount) == 0
}
it("should not send a value when the action is disabled") {
enabled.value = false
action.apply(0).start()
scheduler.run()
expect(completedCount) == 0
}
}
describe("execution") {
beforeEach {
enabled.value = true
}
it("should execute successfully") {
var receivedValue: String?
action.apply(0)
.assumeNoErrors()
.startWithValues {
receivedValue = $0
}
expect(executionCount) == 1
expect(action.isExecuting.value) == true
expect(action.isEnabled.value) == false
expect(receivedValue) == "00"
expect(values) == [ "0", "00" ]
expect(errors) == []
scheduler.run()
expect(action.isExecuting.value) == false
expect(action.isEnabled.value) == true
expect(values) == [ "0", "00" ]
expect(errors) == []
}
it("should execute with an error") {
var receivedError: ActionError<NSError>?
action.apply(1).startWithFailed {
receivedError = $0
}
expect(executionCount) == 1
expect(action.isExecuting.value) == true
expect(action.isEnabled.value) == false
scheduler.run()
expect(action.isExecuting.value) == false
expect(action.isEnabled.value) == true
expect(receivedError).notTo(beNil())
if let error = receivedError {
let expectedError = ActionError<NSError>.producerFailed(testError)
expect(error == expectedError) == true
}
expect(values) == []
expect(errors) == [ testError ]
}
}
describe("bindings") {
it("should execute successfully") {
var receivedValue: String?
let (signal, observer) = Signal<Int, NoError>.pipe()
action.values.observeValues { receivedValue = $0 }
action <~ signal
enabled.value = true
expect(executionCount) == 0
expect(action.isExecuting.value) == false
expect(action.isEnabled.value) == true
observer.send(value: 0)
expect(executionCount) == 1
expect(action.isExecuting.value) == true
expect(action.isEnabled.value) == false
expect(receivedValue) == "00"
expect(values) == [ "0", "00" ]
expect(errors) == []
scheduler.run()
expect(action.isExecuting.value) == false
expect(action.isEnabled.value) == true
expect(values) == [ "0", "00" ]
expect(errors) == []
}
}
}
describe("using a property as input") {
let echo: (Int) -> SignalProducer<Int, NoError> = SignalProducer.init(value:)
it("executes the action with the property's current value") {
let input = MutableProperty(0)
let action = Action(input: input, echo)
var values: [Int] = []
action.values.observeValues { values.append($0) }
input.value = 1
action.apply().start()
input.value = 2
action.apply().start()
input.value = 3
action.apply().start()
expect(values) == [1, 2, 3]
}
it("is disabled if the property is nil") {
let input = MutableProperty<Int?>(1)
let action = Action(input: input, echo)
expect(action.isEnabled.value) == true
input.value = nil
expect(action.isEnabled.value) == false
}
}
}
}
|
mit
|
37bbcc911502b7cac07f83b33dd41938
| 23.308594 | 80 | 0.629278 | 3.693175 | false | false | false | false |
loudnate/Loop
|
WatchApp Extension/Extensions/UIColor.swift
|
1
|
3090
|
//
// UIColor.swift
// Naterade
//
// Created by Nathan Racklyeft on 3/20/16.
// Copyright © 2016 Nathan Racklyeft. All rights reserved.
//
import UIKit
extension UIColor {
static let tintColor = UIColor(named: "tint")!
static let carbsColor = UIColor(named: "carbs")!
// Equivalent to carbsColor with alpha 0.14 on a black background
static let darkCarbsColor = UIColor(named: "carbs-dark")!
static let glucose = UIColor(named: "glucose")!
// Equivalent to glucoseColor with alpha 0.14 on a black background
static let darkGlucose = UIColor(named: "glucose-dark")!
static let insulin = UIColor(named: "insulin")!
static let darkInsulin = UIColor(named: "insulin-dark")!
static let overrideColor = UIColor(named: "workout")!
// Equivalent to workoutColor with alpha 0.14 on a black background
static let darkOverrideColor = UIColor(named: "workout-dark")!
static let disabledButtonColor = UIColor.gray
static let darkDisabledButtonColor = UIColor.disabledButtonColor.withAlphaComponent(0.14)
static let chartLabel = HIGWhiteColor()
static let chartNowLine = HIGWhiteColor().withAlphaComponent(0.2)
static let chartPlatter = HIGWhiteColorDark()
static let agingColor = HIGYellowColor()
static let staleColor = HIGRedColor()
// MARK: - HIG colors
// See: https://developer.apple.com/watch/human-interface-guidelines/visual-design/#color
private static func HIGPinkColor() -> UIColor {
return UIColor(red: 250 / 255, green: 17 / 255, blue: 79 / 255, alpha: 1)
}
private static func HIGPinkColorDark() -> UIColor {
return HIGPinkColor().withAlphaComponent(0.17)
}
private static func HIGRedColor() -> UIColor {
return UIColor(red: 1, green: 59 / 255, blue: 48 / 255, alpha: 1)
}
private static func HIGRedColorDark() -> UIColor {
return HIGRedColor().withAlphaComponent(0.17)
}
private static func HIGOrangeColor() -> UIColor {
return UIColor(red: 1, green: 149 / 255, blue: 0, alpha: 1)
}
private static func HIGOrangeColorDark() -> UIColor {
return HIGOrangeColor().withAlphaComponent(0.15)
}
private static func HIGYellowColor() -> UIColor {
return UIColor(red: 1, green: 230 / 255, blue: 32 / 255, alpha: 1)
}
private static func HIGYellowColorDark() -> UIColor {
return HIGYellowColor().withAlphaComponent(0.14)
}
private static func HIGGreenColor() -> UIColor {
return UIColor(red: 4 / 255, green: 222 / 255, blue: 113 / 255, alpha: 1)
}
private static func HIGGreenColorDark() -> UIColor {
return HIGGreenColor().withAlphaComponent(0.14)
}
private static func HIGWhiteColor() -> UIColor {
return UIColor(red: 242 / 255, green: 244 / 255, blue: 1, alpha: 1)
}
private static func HIGWhiteColorDark() -> UIColor {
// Equivalent to HIGWhiteColor().withAlphaComponent(0.14) on black
return UIColor(red: 33 / 255, green: 34 / 255, blue: 35 / 255, alpha: 1)
}
}
|
apache-2.0
|
ca08cd5ea912926ce4c841be29ef07fe
| 30.20202 | 93 | 0.666235 | 4.085979 | false | false | false | false |
Avtolic/ACAlertController
|
ACAlertControllerDemo/ACAlertControllerDemo/DemoViewController.swift
|
1
|
13671
|
//
// DemoViewController.swift
// ACAlertControllerDemo
//
// Created by Yury on 17/06/16.
// Copyright © 2016 Avtolic. All rights reserved.
//
import UIKit
class DemoViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
let button = UIButton(type: .system)
button.frame = CGRect(x: 10, y: 200, width: 330, height: 100)
button.setTitle("Normal", for: UIControlState())
button.setTitle("Highlighted", for: .highlighted)
button.backgroundColor = UIColor.yellow.withAlphaComponent(0.5)
view.addSubview(button)
// Do any additional setup after loading the view.
}
}
extension DemoViewController {
func createLabel(_ text: String?, textColor: UIColor = UIColor.black, color: UIColor = UIColor.clear) -> UILabel {
let label = UILabel()
label.text = text
label.numberOfLines = 0
label.font = UIFont.systemFont(ofSize: 15)
label.textColor = textColor
label.backgroundColor = color
label.textAlignment = .center
// label.sizeToFit()
return label
}
func createTextField() -> UITextField {
let textField = UITextField()
textField.placeholder = "Name"
textField.autocapitalizationType = .words
textField.returnKeyType = .done
textField.enablesReturnKeyAutomatically = true
textField.borderStyle = .line
textField.backgroundColor = UIColor.white
let width = NSLayoutConstraint(item: textField, attribute: .width, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 1, constant: 270)
width.priority = 995
width.isActive = true
return textField
}
@IBAction func newOne() {
let alert = ACAlertController()
for i in 1...3 {
alert.addItem(ItemCustomView.newCustomView(text1: "Some text \(i) here!", text2: "Some Text \(i) here also!!", text3: "Just \(i)!!!")!)
}
for _ in 1...1 {
alert.addItem(createLabel("Short text"))
alert.addItem(UIImageView(image: UIImage(named: "Details Icon")))
alert.addItem(UIImageView(image: UIImage(named: "Checklist Icon OK")))
alert.addItem(UIImageView(image: UIImage(named: "Details Icon")))
alert.addItem(createLabel("Мой дядя самых честных правил !!!! когда не в шутку занемог, он уважать себя заставил и лучше выдумать не мог."))
alert.addItem(UIImageView(image: UIImage(named: "Checklist Icon OK")))
}
for i in 1...3 {
let buttonView = ItemCustomView.newCustomView(text1: "Button text \(i) here!", text2: "Button Text \(i) here also!!", text3: "Just \(i)!!!")!
alert.addAction(ACAlertAction(view: buttonView, handler: { (_) in
print("Custom button \(i)")
}))
}
alert.addAction(ACAlertAction(view: UIImageView(image: UIImage(named: "Checklist Icon OK")), handler: { (_) in
print("Action Details")
}))
alert.addAction(ACAlertAction(view: UIImageView(image: UIImage(named: "Details Icon")), handler: { (_) in
print("Action Details")
}))
let historyImageView = UIImageView(image: UIImage(named: "Details Icon"))
historyImageView.setContentCompressionResistancePriority(995, for: .vertical)
historyImageView.setContentHuggingPriority(995, for: .vertical)
alert.addAction(ACAlertAction(view: historyImageView, handler: { (_) in
print("Action History")
}))
let action = ACAlertActionNative(title: "Disabled title", style: .default, handler: { (_) in
print("Disabled")
})
action.enabled = false
alert.addAction(action)
alert.addAction(ACAlertActionNative(title: "Destructive title", style: .destructive, handler: { (_) in
print("Destructive")
}))
alert.addAction(ACAlertActionNative(title: "A", style: .default, handler: { (_) in
print("Default")
}))
alert.addAction(ACAlertActionNative(title: "C", style: .cancel, handler: { (_) in
print("Cancel")
}))
present(alert, animated: true)
// view.addSubview(alert.view)
// NSLayoutConstraint(item: view, attribute: .centerX, relatedBy: .equal, toItem: alert.view, attribute: .centerX, multiplier: 1, constant: 0).isActive = true
// NSLayoutConstraint(item: view, attribute: .centerY, relatedBy: .equal, toItem: alert.view, attribute: .centerY, multiplier: 1, constant: 0).isActive = true
// let alert = ACAlertController(title: "Title", message: "Are you sure you want to Sign Out?")
//
// alert.addItem(createLabel("Short text"))
// alert.addItem(UIImageView(image: UIImage(named: "Checklist Icon OK")))
// alert.addItem(UIImageView(image: UIImage(named: "Import Icon")))
//
// var margins1 = alert.defaultItemsMargins
// margins1.bottom = 0
// var margins2 = alert.defaultItemsMargins
// margins2.top = 0
// margins2.right = 20
// alert.addItem(createTextField(), inset: margins1)
// alert.addItem(createTextField(), inset: margins2)
// alert.addItem(createTextField())
//
// alert.addItem(createLabel("Short text", textColor: UIColor.magenta, color: UIColor.yellow))
// alert.addItem(createLabel("Some not very short but quite long text here. Hello world!",
// textColor: UIColor.cyan, color: UIColor.orange))
// alert.addItem(createLabel("Some not very short but quite long text here. Hello world!",
// textColor: UIColor.magenta, color: UIColor.yellow))
//
// alert.addAction(ACAlertAction(view: UIImageView(image: UIImage(named: "Details Icon")), handler: { (_) in
// print("Action Details")
// }))
// let historyImageView = UIImageView(image: UIImage(named: "Checklist Icon OK"))
// historyImageView.setContentCompressionResistancePriority(995, for: .vertical)
// alert.addAction(ACAlertAction(view: historyImageView, handler: { (_) in
// print("Action History")
// }))
//
// let action = ACAlertActionNative(title: "Disabled title", style: .default, handler: { (_) in
// print("Disabled")
// })
// action.enabled = false
// alert.addAction(action)
//
// alert.addAction(ACAlertActionNative(title: "A", style: .default, handler: { (_) in
// print("Default")
// }))
// alert.addAction(ACAlertActionNative(title: "C", style: .cancel, handler: { (_) in
// print("Cancel")
// }))
// alert.addAction(ACAlertActionNative(title: "Destructive title", style: .destructive, handler: { (_) in
// print("Destructive")
// }))
//
// present(alert, animated: true){
// }
}
@IBAction func newTwo() {
}
@IBAction func newThree() {
}
@IBAction func newEdit() {
}
}
extension DemoViewController {
@IBAction func onOne() {
let alertController = UIAlertController(title: "", message: nil, preferredStyle: .alert)
// let yesAction = UIAlertAction(title: "Yes", style: .Default){ (action) in }
// alertController.addAction(yesAction)
// let alertController = UIAlertController(title: "Title Lorem Ipsum bla bla bla very long title Lorem Ipsum bla bla bla very long title", message: "Are you sure you want to Sign Out?", preferredStyle: .Alert)
// let yesAction = UIAlertAction(title: "Yes", style: .Default){ (action) in }
// alertController.addAction(yesAction)
present(alertController, animated: true) {}
}
@IBAction func onTwo() {
let alertController = UIAlertController(title: "Title", message: "Are you sure you want to Sign Out?", preferredStyle: .alert)
let noAction = UIAlertAction(title: "No", style: .cancel){ (action) in }
let yesAction = UIAlertAction(title: "Yes", style: .default){ (action) in }
alertController.addAction(noAction)
alertController.addAction(yesAction)
let alertView = alertController.view
alertView?.frame.origin = CGPoint(x: 100, y: 270)
view.addSubview(alertView!)
DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + Double(10) / Double(NSEC_PER_SEC)) {
print("ggg")
alertView?.frame.origin = CGPoint(x: 100, y: 270)
}
// presentViewController(alertController, animated: true) {}
}
@IBAction func onThree() {
let alertController = UIAlertController(title: "Title", message: "Are you sure you want to Sign Out?", preferredStyle: .alert)
let noAction = UIAlertAction(title: "No", style: .cancel){ (action) in print("No") }
let yesAction = UIAlertAction(title: "Yes", style: .default){ (action) in print("Yes") }
let destrAction = UIAlertAction(title: "Destructive", style: .destructive){ (action) in print("Destructive") }
let disableAction = UIAlertAction(title: "Destr", style: .default){ (action) in }
alertController.addAction(noAction)
alertController.addAction(yesAction)
alertController.addAction(destrAction)
// alertController.addAction(disableAction)
// for _ in 1...15 {
// let noAction = UIAlertAction(title: "No", style: .destructive){ (action) in print("No") }
// alertController.addAction(noAction)
// }
disableAction.isEnabled = false
// noAction.enabled = false
// yesAction.enabled = false
// destrAction.enabled = false
present(alertController, animated: true) {
}
}
@IBAction func onEdit() {
let alertController = UIAlertController(title: "Name the Song", message: "Song name not on the list?\nEnter it here.", preferredStyle: .alert)
alertController.addTextField { (textField) -> Void in
textField.placeholder = "Name"
textField.autocapitalizationType = .words
textField.returnKeyType = .done
textField.enablesReturnKeyAutomatically = true
}
alertController.addTextField { (textField) -> Void in
textField.placeholder = "Name 2"
textField.autocapitalizationType = .words
textField.returnKeyType = .done
textField.enablesReturnKeyAutomatically = true
}
for i in 1...30 {
alertController.addTextField { (textField) -> Void in
textField.placeholder = "Name \(i)"
textField.autocapitalizationType = .words
textField.returnKeyType = .done
textField.enablesReturnKeyAutomatically = true
}
}
let cancelAction = UIAlertAction(title: "Cancel", style: .cancel){ (action) in }
alertController.addAction(cancelAction)
let submitAction = UIAlertAction(title: "Submit", style: .default){ (action) in
if let field = alertController.textFields?.first, let text = field.text , !text.isEmpty {
print(text)
}
}
alertController.addAction(submitAction)
for _ in 1...15 {
let noAction = UIAlertAction(title: "No", style: .destructive){ (action) in print("No") }
alertController.addAction(noAction)
}
self.present(alertController, animated: true) {
// print(alertController.view.performSelector("recursiveDescription"))
// print(alertController.view.gestureRecognizers)
// alertController.view.removeGestureRecognizer(alertController.view.gestureRecognizers!.first!)
// let recognizer = alertController.view.gestureRecognizers!.first! as! UILongPressGestureRecognizer
// print(recognizer)
// print(recognizer.minimumPressDuration)
// print(recognizer.numberOfTapsRequired)
// print(recognizer.numberOfTouchesRequired)
// print(recognizer.allowableMovement)
// print(recognizer.cancelsTouchesInView)
// print(recognizer.delaysTouchesBegan)
// print(recognizer.delaysTouchesEnded)
//
// print(recognizer.delegate)
// let del = recognizer.delegate!
// if let _ = del.gestureRecognizer?(recognizer, shouldBeRequiredToFailBy: recognizer) {
// print("shouldBeRequiredToFailByGestureRecognizer")
// }
// if let _ = del.gestureRecognizer?(recognizer, shouldReceive: UIPress()) {
// print("shouldReceivePress")
// }
// if let _ = del.gestureRecognizer?(recognizer, shouldReceive: UITouch()) {
// print("shouldReceiveTouch")
// }
// if let _ = del.gestureRecognizer?(recognizer, shouldRecognizeSimultaneouslyWith: UIGestureRecognizer()) {
// print("shouldRecognizeSimultaneouslyWithGestureRecognizer")
// }
// if let _ = del.gestureRecognizer?(recognizer, shouldRequireFailureOf: recognizer) {
// print("shouldRequireFailureOfGestureRecognizer")
// }
// if let _ = del.gestureRecognizerShouldBegin?(recognizer) {
// print("gestureRecognizerShouldBegin")
// }
//
}
}
}
|
mit
|
c43fdfa7a8d88e46be71248458fdecb6
| 44.587248 | 216 | 0.614354 | 4.587977 | false | false | false | false |
sketchytech/Aldwych_JSON_Swift
|
Sources/JSONArray.swift
|
2
|
25431
|
//
// JSONArray.swift
// JSONParser
//
// Created by Anthony Levings on 23/03/2015.
//
import Foundation
// initialization of JSONArray type
public struct JSONArray:SequenceType {
//TODO: make restrictions work for nest dictionaries when changed after initialization
public var inheritRestrictions = true
public var restrictTypeChanges:Bool
public var anyValueIsNullable:Bool
// use dictionary with index as keys for position in array
private var stringDict:Dictionary<Int,String>?
private var numDict:Dictionary<Int,NSNumber>?
private var boolDict:Dictionary<Int,Bool>?
private var nullDict:Dictionary<Int,NSNull>?
// json cases
private var arrayDict:Dictionary<Int,JSONArray>?
private var dictDict:Dictionary<Int,JSONDictionary>?
public var count:Int {
var count = 0
if let n = stringDict?.count {
count += n
}
if let n = numDict?.count {
count += n
}
if let n = boolDict?.count {
count += n
}
if let n = nullDict?.count {
count += n
}
if let n = dictDict?.count {
count += n
}
if let n = arrayDict?.count {
count += n
}
return count
}
public init (restrictTypeChanges:Bool = true, anyValueIsNullable:Bool = true) {
self.anyValueIsNullable = anyValueIsNullable
self.restrictTypeChanges = restrictTypeChanges
}
public init (array:[AnyObject], handleBool:Bool = true, restrictTypeChanges:Bool = true, anyValueIsNullable:Bool = true) {
// AJL: replace with map?
self.anyValueIsNullable = anyValueIsNullable
self.restrictTypeChanges = restrictTypeChanges
for val in enumerate(array) {
if let v = val.element as? String {
if stringDict == nil {
self.stringDict = Dictionary<Int,String>()
}
stringDict![val.index] = v
}
else if let v = val.element as? NSNumber {
// test to see if a bool
if handleBool && v.isBoolNumber() {
if boolDict == nil {
boolDict = Dictionary<Int,Bool>()
}
if boolDict != nil {
boolDict![val.index] = Bool(v)
}
}
else {
if numDict == nil {
numDict = Dictionary<Int,NSNumber>()
}
if numDict != nil {
numDict![val.index] = v
}
}
}
else if let v = val.element as? NSNull {
if nullDict == nil {
self.nullDict = Dictionary<Int,NSNull>()
}
nullDict![val.index] = v
}
else if let v = val.element as? Dictionary<String, AnyObject> {
if dictDict == nil {
self.dictDict = Dictionary<Int,JSONDictionary>()
}
dictDict![val.index] = JSONDictionary(dict: v, handleBool:handleBool, restrictTypeChanges: restrictTypeChanges, anyValueIsNullable: anyValueIsNullable)
}
else if let v = val.element as? [AnyObject] {
if arrayDict == nil {
self.arrayDict = Dictionary<Int,JSONArray>()
}
arrayDict![val.index] = JSONArray(array: v, handleBool:handleBool, restrictTypeChanges: restrictTypeChanges, anyValueIsNullable: anyValueIsNullable)
}
}
}
public var array:[AnyObject] {
var arr = [AnyObject](count: self.count, repeatedValue: 0)
if stringDict != nil {
for (k,v) in stringDict! {
arr[k] = v
}
}
if numDict != nil {
for (k,v) in numDict! {
arr[k] = v
}
}
if boolDict != nil {
for (k,v) in boolDict! {
arr[k] = v
}
}
if nullDict != nil {
for (k,v) in nullDict! {
arr[k] = v
}
}
if dictDict != nil {
for (k,v) in dictDict! {
arr[k] = v.dictionary as [String:AnyObject]
}
}
if arrayDict != nil {
for (k,v) in arrayDict! {
arr[k] = v.array as [AnyObject]
}
}
return arr
}
public var nsArray:NSArray {
var arr = NSMutableArray(capacity: self.count)
if stringDict != nil {
for (k,v) in stringDict! {
arr[k] = v as NSString
}
}
if numDict != nil {
for (k,v) in numDict! {
arr[k] = v as NSNumber
}
}
if boolDict != nil {
for (k,v) in boolDict! {
arr[k] = v as Bool
}
}
if nullDict != nil {
for (k,v) in nullDict! {
arr[k] = v as NSNull
}
}
if dictDict != nil {
for (k,v) in dictDict! {
arr[k] = v.nsDictionary as NSDictionary
}
}
if arrayDict != nil {
for (k,v) in arrayDict! {
arr[k] = v.nsArray as NSArray
}
}
return arr
}
}
// JSON conform to SequenceType
extension JSONArray {
public typealias Generator = JSONArrayGenerator
public func generate() -> Generator {
// AJL: avoid strong capture of self?
let gen = Generator(arr: self)
return gen
}
}
extension JSONArray {
mutating func removeLast() {
let a = self.count-1
stringDict?.removeValueForKey(a)
numDict?.removeValueForKey(a)
boolDict?.removeValueForKey(a)
nullDict?.removeValueForKey(a)
arrayDict?.removeValueForKey(a)
dictDict?.removeValueForKey(a)
}
}
// methods for returning all strings, numbers, null from an array
extension JSONArray {
public func isStringArray() -> Bool {
if stringDict != nil && numDict == nil && nullDict == nil && arrayDict == nil && dictDict == nil {
return true
}
else {
return false
}
}
// returns all the values from the string dictionary
public func stringArray() -> [String]? {
if let v = stringDict?.values {
return map(v){$0}
}
return nil
}
public func containsStrings() -> Bool {
if stringDict != nil {
return true
}
return false
}
public func containsNull() -> Bool {
if nullDict != nil {
return true
}
return false
}
public func dictionaryArray() -> [JSONDictionary]? {
if let v = dictDict?.values {
return map(v){$0}
}
return nil
}
}
// getting and setting from subscripts
extension JSONArray {
public subscript (key:Int) -> String? {
get {
return stringDict?[key]
}
set(newValue) {
if stringDict?[key] != nil {
stringDict?[key] = newValue
}
else if nullDict?[key] != nil {
nullDict?.removeValueForKey(key)
if nullDict?.isEmpty == true {
nullDict = nil
}
// check to make sure there is a numDict and create one if not
if stringDict == nil {
stringDict = Dictionary<Int,String>()
}
stringDict?[key] = newValue
}
// the JSONArray type uses nil as an indicator of emptiness, so if the final value/key is removed then the dictionary should reset to nil
else if restrictTypeChanges == false {
numDict?.removeValueForKey(key)
if numDict?.isEmpty == true {
numDict = nil
}
boolDict?.removeValueForKey(key)
if boolDict?.isEmpty == true {
boolDict = nil
}
arrayDict?.removeValueForKey(key)
if arrayDict?.isEmpty == true {
arrayDict = nil
}
dictDict?.removeValueForKey(key)
if dictDict?.isEmpty == true {
dictDict = nil
}
// because nil is an indicator of emptiness, it might be the case that no stringDict exists, and so it must be created if this is the case
if stringDict == nil {
stringDict = Dictionary<Int,String>()
}
stringDict?[key] = newValue
}
}
}
public subscript (key:Int) -> NSNumber? {
get {
return numDict?[key]
}
set(newValue) {
if numDict?[key] != nil {
numDict?[key] = newValue
}
// if value starts as null, we assume it can be replaced, but there's no way of knowing what it can be replaced with so we must allow anything in the first instance
else if nullDict?[key] != nil {
nullDict?.removeValueForKey(key)
if nullDict?.isEmpty == true {
nullDict = nil
}
// check to make sure there is a numDict and create one if not
if numDict == nil {
numDict = Dictionary<Int,NSNumber>()
}
numDict?[key] = newValue
}
// if the restriction of changing types has been turned off then anything can be replaced
else if restrictTypeChanges == false {
stringDict?.removeValueForKey(key)
if stringDict?.isEmpty == true {
stringDict = nil
}
boolDict?.removeValueForKey(key)
if boolDict?.isEmpty == true {
boolDict = nil
}
arrayDict?.removeValueForKey(key)
if arrayDict?.isEmpty == true {
arrayDict = nil
}
dictDict?.removeValueForKey(key)
if dictDict?.isEmpty == true {
dictDict = nil
}
// check to make sure there is a numDict and create one if not
if numDict == nil {
numDict = Dictionary<Int,NSNumber>()
}
// add value to numDict
numDict?[key] = newValue
}
}
}
public subscript (key:Int) -> Bool? {
get {
return boolDict?[key]
}
set(newValue) {
if boolDict?[key] != nil {
boolDict?[key] = newValue
}
// if value starts as null, we assume it can be replaced, but there's no way of knowing what it can be replaced with so we must allow anything in the first instance
else if nullDict?[key] != nil {
nullDict?.removeValueForKey(key)
if nullDict?.isEmpty == true {
nullDict = nil
}
// check to make sure there is a numDict and create one if not
if boolDict == nil {
boolDict = Dictionary<Int,Bool>()
}
boolDict?[key] = newValue
}
// if the restriction of changing types has been turned off then anything can be replaced
else if restrictTypeChanges == false {
stringDict?.removeValueForKey(key)
if stringDict?.isEmpty == true {
stringDict = nil
}
numDict?.removeValueForKey(key)
if numDict?.isEmpty == true {
numDict = nil
}
arrayDict?.removeValueForKey(key)
if arrayDict?.isEmpty == true {
arrayDict = nil
}
dictDict?.removeValueForKey(key)
if dictDict?.isEmpty == true {
dictDict = nil
}
// check to make sure there is a numDict and create one if not
if boolDict == nil {
boolDict = Dictionary<Int,Bool>()
}
// add value to numDict
boolDict?[key] = newValue
}
}
}
public subscript (key:Int) -> NSNull? {
get {
return nullDict?[key]
}
set(newValue) {
if nullDict?[key] != nil {
nullDict?[key] = newValue
}
// any value is nullable
else if anyValueIsNullable == true {
numDict?.removeValueForKey(key)
if numDict?.isEmpty == true {
numDict = nil
}
stringDict?.removeValueForKey(key)
if stringDict?.isEmpty == true {
stringDict = nil
}
boolDict?.removeValueForKey(key)
if boolDict?.isEmpty == true {
boolDict = nil
}
arrayDict?.removeValueForKey(key)
if arrayDict?.isEmpty == true {
arrayDict = nil
}
dictDict?.removeValueForKey(key)
if dictDict?.isEmpty == true {
dictDict = nil
}
if nullDict == nil {
nullDict = Dictionary<Int,NSNull>()
}
nullDict?[key] = newValue
}
}
}
public subscript (key:Int) -> JSONArray? {
get {
var arrayD = self.arrayDict?[key]
if inheritRestrictions == true {
arrayD?.restrictTypeChanges = self.restrictTypeChanges
arrayD?.anyValueIsNullable = self.anyValueIsNullable
}
return arrayD
}
set(newValue) {
if arrayDict?[key] != nil {
arrayDict?[key] = newValue
}
else if nullDict?[key] != nil {
nullDict?.removeValueForKey(key)
if nullDict?.isEmpty == true {
nullDict = nil
}
// check to make sure there is a numDict and create one if not
if arrayDict == nil {
arrayDict = Dictionary<Int,JSONArray>()
}
arrayDict?[key] = newValue
}
else if restrictTypeChanges == false {
stringDict?.removeValueForKey(key)
if stringDict?.isEmpty == true {
stringDict = nil
}
arrayDict?.removeValueForKey(key)
if arrayDict?.isEmpty == true {
arrayDict = nil
}
boolDict?.removeValueForKey(key)
if boolDict?.isEmpty == true {
boolDict = nil
}
dictDict?.removeValueForKey(key)
if dictDict?.isEmpty == true {
dictDict = nil
}
// check to make sure there is a numDict and create one if not
if arrayDict == nil {
arrayDict = Dictionary<Int,JSONArray>()
}
// add value to numDict
arrayDict?[key] = newValue
}
}
}
public subscript (key:Int) -> JSONDictionary? {
get {
var dictD = self.dictDict?[key]
if inheritRestrictions == true {
dictD?.restrictTypeChanges = self.restrictTypeChanges
dictD?.anyValueIsNullable = self.anyValueIsNullable
}
return dictD
}
set(newValue) {
if dictDict?[key] != nil {
dictDict?[key] = newValue
}
else if nullDict?[key] != nil {
nullDict?.removeValueForKey(key)
if nullDict?.isEmpty == true {
nullDict = nil
}
dictDict?[key] = newValue
}
else if restrictTypeChanges == false {
stringDict?.removeValueForKey(key)
if stringDict?.isEmpty == true {
stringDict = nil
}
boolDict?.removeValueForKey(key)
if boolDict?.isEmpty == true {
boolDict = nil
}
arrayDict?.removeValueForKey(key)
if arrayDict?.isEmpty == true {
arrayDict = nil
}
numDict?.removeValueForKey(key)
if numDict?.isEmpty == true {
numDict = nil
}
// check to make sure there is a numDict and create one if not
if dictDict == nil {
dictDict = Dictionary<Int,JSONDictionary>()
}
// add value to numDict
dictDict?[key] = newValue
}
}
}
}
// add methods for dictionary, avoid accidental additions
extension JSONArray {
// Append method
public mutating func append(str:String) {
if stringDict == nil {
stringDict = Dictionary<Int,String>()
}
if stringDict != nil {
stringDict![self.count] = str
}
}
public mutating func append(num:NSNumber) {
if numDict == nil {
numDict = Dictionary<Int,NSNumber>()
}
if numDict != nil {
numDict![self.count] = num
}
}
public mutating func append(bool:Bool) {
if boolDict == nil {
boolDict = Dictionary<Int,Bool>()
}
if boolDict != nil {
boolDict![self.count] = bool
}
}
public mutating func append(null:NSNull) {
if nullDict == nil {
nullDict = Dictionary<Int,NSNull>()
}
if nullDict != nil {
nullDict![self.count] = null
}
}
public mutating func append(dict:JSONDictionary) {
if dictDict == nil {
dictDict = Dictionary<Int,JSONDictionary>()
}
if dictDict != nil {
dictDict![self.count] = dict
}
}
public mutating func append(arr:JSONArray) {
if arrayDict == nil {
arrayDict = Dictionary<Int,JSONArray>()
}
if arrayDict != nil {
arrayDict![self.count] = arr
}
}
}
extension JSONArray {
// extension to enable insert method
mutating func updatePositions(fromIndex:Int,by:Int = 1) {
if var strD = stringDict
{
// update stringDict
for (k,v) in strD {
if k >= fromIndex {
strD[k+by] = v
}
}
stringDict = strD
}
if var numD = numDict
{
// update numDict
for (k,v) in numD {
if k >= fromIndex {
numD[k+by] = v
}
}
numDict = numD
}
if var boolD = boolDict
{
// update boolDict
for (k,v) in boolD {
if k >= fromIndex {
boolD[k+by] = v
}
}
boolDict = boolD
}
if var nulD = nullDict
{
// update nullDict
for (k,v) in nulD {
if k >= fromIndex {
nulD[k+by] = v
}
}
nullDict = nulD
}
if var arrD = arrayDict
{
// update arrayDict
for (k,v) in arrD {
if k >= fromIndex {
arrD[k+by] = v
}
}
arrayDict = arrD
}
if var dictD = dictDict
{
// update dictDict
for (k,v) in dictD {
if k >= fromIndex {
dictD[k+by] = v
}
}
dictDict = dictD
}
}
public mutating func insert(str:String, atIndex:Int) {
if self.count-1 >= atIndex {
updatePositions(atIndex)
if stringDict == nil {
stringDict = Dictionary<Int,String>()
}
stringDict?[atIndex] = str
}
}
public mutating func insert(num:NSNumber, atIndex:Int) {
if self.count-1 >= atIndex {
updatePositions(atIndex)
if numDict == nil {
numDict = Dictionary<Int,NSNumber>()
}
numDict?[atIndex] = num
}
}
public mutating func insert(bool:Bool, atIndex:Int) {
if self.count-1 >= atIndex {
updatePositions(atIndex)
if boolDict == nil {
boolDict = Dictionary<Int,Bool>()
}
boolDict?[atIndex] = bool
}
}
public mutating func insert(null:NSNull, atIndex:Int) {
if self.count-1 >= atIndex {
updatePositions(atIndex)
if nullDict == nil {
nullDict = Dictionary<Int,NSNull>()
}
nullDict?[atIndex] = null
}
}
public mutating func insert(dict:JSONDictionary, atIndex:Int) {
if self.count-1 >= atIndex {
updatePositions(atIndex)
if dictDict == nil {
dictDict = Dictionary<Int,JSONDictionary>()
}
dictDict?[atIndex] = dict
}
}
public mutating func insert(arr:JSONArray, atIndex:Int) {
if self.count-1 >= atIndex {
updatePositions(atIndex)
if arrayDict == nil {
arrayDict = Dictionary<Int,JSONArray>()
}
arrayDict?[atIndex] = arr
}
}
// TODO: extend() method
// TODO: removeAtIndex(), etc. methods
}
// returning an instance of Value type
extension JSONArray {
public subscript (key:Int) -> Value? {
get {
if let a = stringDict?[key] {
return Value(a)
}
else if let a = numDict?[key] {
return Value(num:a)
}
else if let a = boolDict?[key] {
return Value(bool:a)
}
else if let a = nullDict?[key] {
return Value(a)
}
else if let a = dictDict?[key] {
return Value.JSONDictionaryType(a)
}
else if let a = arrayDict?[key] {
return Value.JSONArrayType(a)
}
return nil
}
}
}
// return JSON data
extension JSONArray {
public func jsonData(options:NSJSONWritingOptions = nil, error:NSErrorPointer = nil) -> NSData? {
return NSJSONSerialization.dataWithJSONObject(self.array, options: options, error: error)
}
public func stringify(options:NSJSONWritingOptions = nil, error:NSErrorPointer = nil) -> String? {
if let data = NSJSONSerialization.dataWithJSONObject(self.array, options: options, error: error) {
let count = data.length / sizeof(UInt8)
// create array of appropriate length:
var array = [UInt8](count: count, repeatedValue: 0)
// copy bytes into array
data.getBytes(&array, length:count * sizeof(UInt8))
return String(bytes: array, encoding: NSUTF8StringEncoding)
}
else {return nil }
}
}
// JSONArray Generator
public struct JSONArrayGenerator:GeneratorType {
// use dictionary with index as keys for position in array
private let arr:JSONArray
private var i:Int
init(arr:JSONArray) {
self.arr = arr
self.i = 0
}
mutating public func next() -> Value? {
if let v:Value? = arr[i] {
++i
return v
}
// reset value
i = 0
return nil
}
}
|
mit
|
bc1e7e3c8062d8a9bb7023306a0d3781
| 29.131517 | 180 | 0.455625 | 5.227338 | false | false | false | false |
avaidyam/Parrot
|
MochaUI/DroppableView.swift
|
1
|
10821
|
import AppKit
import Mocha
/* TODO: concludeDragOperation, wantsPeriodicDraggingUpdates, updateDraggingItemsForDrag. */
/* TODO: what if spring-loading a child window and deciding not to continue, and then un-spring? */
/* TODO: what if the acceptedTypes = [._fileURL] already? just short-circuit the verification? */
@objc public protocol DroppableViewDelegate {
@objc optional func dragging(state: DroppableView.DragState, for: NSDraggingInfo) -> NSDragOperation
@objc optional func dragging(phase: DroppableView.OperationPhase, for: NSDraggingInfo) -> Bool
@objc optional func springLoading(state: DroppableView.DragState, for: NSDraggingInfo) -> NSSpringLoadingOptions
@objc optional func springLoading(phase: DroppableView.SpringLoadingPhase, for: NSDraggingInfo)
}
public class DroppableView: NSView, NSSpringLoadingDestination /*NSDraggingDestination*/ {
@objc public enum DragState: Int {
case entered, updated, exited
}
@objc public enum OperationPhase: Int {
case preparing, performing
}
@objc public enum SpringLoadingPhase: Int {
case activated, deactivated
}
//
//
//
private lazy var baseLayer: CALayer = {
let layer = CALayer()
layer.frame = self.bounds
layer.autoresizingMask = [.layerWidthSizable, .layerHeightSizable]
layer.cornerRadius = 4.0
layer.opacity = 0.0
return layer
}()
private lazy var ringLayer: CALayer = {
let layer = CALayer()
layer.frame = self.bounds
layer.autoresizingMask = [.layerWidthSizable, .layerHeightSizable]
layer.borderWidth = 4.0
layer.cornerRadius = 4.0
layer.opacity = 0.0
return layer
}()
private lazy var blinkAnim: CAAnimation = {
let animation = CABasicAnimation(keyPath: "opacity")
animation.fromValue = 0.0
animation.toValue = 1.0
animation.duration = 0.1
animation.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionLinear)
animation.autoreverses = true
animation.repeatCount = 3
return animation
}()
private lazy var flashAnim: CAAnimation = {
let animation = CABasicAnimation(keyPath: "opacity")
animation.fromValue = 0.0
animation.toValue = 0.33
animation.duration = 0.05
animation.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionLinear)
animation.autoreverses = true
animation.repeatCount = 2
return animation
}()
// Conformance is split into DroppableView{Dragging, Operation}Delegate. Only one delegate may be provided though.
public var delegate: DroppableViewDelegate? = nil
/// Also accepts fileURLs whose UTI conforms to these types.
public var acceptedTypes: [NSPasteboard.PasteboardType] = [] {
didSet {
self.unregisterDraggedTypes()
self.registerForDraggedTypes(self.acceptedTypes + [._fileURL])
// register for the raw kUTTypes AND manually process fileURL types.
}
}
public var operation: NSDragOperation = .copy
public var allowsSpringLoading: Bool = false
public var tintColor: NSColor = NSColor.selectedMenuItemColor {
didSet {
self.needsDisplay = true
}
}
public var hapticResponse: Bool = true
public var sound: NSSound? = nil
private var currentDragState: DragState = .exited {
didSet {
self.needsDisplay = true
}
}
private var springLoadingState: DragState = .exited {
didSet {
self.needsDisplay = true
}
}
public var isEnabled: Bool = true
public var isHighlighted: Bool {
return !(self.currentDragState == .exited && self.springLoadingState == .exited)
}
//
//
//
public override init(frame frameRect: NSRect) {
super.init(frame: frameRect)
setup()
}
public required init?(coder: NSCoder) {
super.init(coder: coder)
setup()
}
private func setup() {
self.wantsLayer = true
self.layerContentsRedrawPolicy = .onSetNeedsDisplay
self.layer!.addSublayer(self.baseLayer)
self.layer!.addSublayer(self.ringLayer)
}
//
//
//
public override var allowsVibrancy: Bool { return true }
public override var wantsUpdateLayer: Bool { return true }
public override func updateLayer() {
self.baseLayer.backgroundColor = self.tintColor.cgColor
self.baseLayer.opacity = self.springLoadingState == .exited ? 0 : 0.33
self.ringLayer.borderColor = self.tintColor.cgColor
self.ringLayer.opacity = self.currentDragState == .exited ? 0 : 1
}
private func blink() {
self.ringLayer.opacity = 0.0
self.ringLayer.add(self.blinkAnim, forKey: "opacity")
self.currentDragState = .exited
self.needsDisplay = false // otherwise animation fails to run
self.sound?.play()
}
private func flash() {
self.baseLayer.opacity = 0.0
self.baseLayer.add(self.flashAnim, forKey: "opacity")
self.springLoadingState = .exited
self.needsDisplay = false // otherwise animation fails to run
}
//
//
//
public override var acceptsFirstResponder: Bool {
return false
}
public override func acceptsFirstMouse(for event: NSEvent?) -> Bool {
return false
}
public override func hitTest(_ point: NSPoint) -> NSView? {
return nil
}
//
//
//
public override func draggingEntered(_ sender: NSDraggingInfo) -> NSDragOperation {
let valid = self.isValid(sender)
self.currentDragState = valid ? .entered : .exited
if valid && self.hapticResponse {
NSHapticFeedbackManager.defaultPerformer.perform(.alignment, performanceTime: .drawCompleted)
}
return self.delegate?.dragging?(state: .entered, for: sender) ?? (valid ? self.operation : [])
}
public override func draggingUpdated(_ sender: NSDraggingInfo) -> NSDragOperation {
let valid = self.isValid(sender)
self.currentDragState = valid ? .updated : .exited
return self.delegate?.dragging?(state: .updated, for: sender) ?? (valid ? self.operation : [])
}
public override func draggingExited(_ sender: NSDraggingInfo?) {
if self.hapticResponse && sender != nil && self.isValid(sender!) {
NSHapticFeedbackManager.defaultPerformer.perform(.alignment, performanceTime: .drawCompleted)
}
self.currentDragState = .exited
_ = self.delegate?.dragging?(state: .exited, for: sender!) // FIXME!
}
public override func prepareForDragOperation(_ sender: NSDraggingInfo) -> Bool {
if let accepted = self.delegate?.dragging?(phase: .preparing, for: sender) {
if accepted {
self.currentDragState = .exited
}
return accepted
} else {
self.currentDragState = .exited
return false
}
}
public override func performDragOperation(_ sender: NSDraggingInfo) -> Bool {
if let accepted = self.delegate?.dragging?(phase: .performing, for: sender) {
if accepted {
self.blink()
if self.hapticResponse {
NSHapticFeedbackManager.defaultPerformer.perform(.levelChange, performanceTime: .drawCompleted)
}
} else {
self.currentDragState = .exited
}
return accepted
} else {
self.currentDragState = .exited
return false
}
}
public func springLoadingEntered(_ draggingInfo: NSDraggingInfo) -> NSSpringLoadingOptions {
return self.delegate?.springLoading?(state: .entered, for: draggingInfo) ?? (self.allowsSpringLoading ? .enabled : .disabled)
}
public func springLoadingUpdated(_ draggingInfo: NSDraggingInfo) -> NSSpringLoadingOptions {
return self.delegate?.springLoading?(state: .updated, for: draggingInfo) ?? (self.allowsSpringLoading ? .enabled : .disabled)
}
public func springLoadingExited(_ draggingInfo: NSDraggingInfo) {
_ = self.delegate?.springLoading?(state: .exited, for: draggingInfo)
}
public func springLoadingActivated(_ activated: Bool, draggingInfo: NSDraggingInfo) {
self.flash()
self.delegate?.springLoading?(phase: activated ? .activated : .deactivated, for: draggingInfo)
}
public func springLoadingHighlightChanged(_ draggingInfo: NSDraggingInfo) {
self.springLoadingState = draggingInfo.springLoadingHighlight == .none ? .exited : .entered
}
public override func draggingEnded(_ draggingInfo: NSDraggingInfo) {
self.currentDragState = .exited
self.springLoadingState = .exited
}
/// Performs a series of conformation validity checks on each pasteboard item.
/// This is necessary to allow both a "direct" UTI such as `public.image`
/// in addition to a file with an "indirect" UTI type (as above) which would normally
/// have the UTI of `public.file-url`. This does not allow for `public.url` types.
private func isValid(_ info: NSDraggingInfo) -> Bool {
for item in info.draggingPasteboard().pasteboardItems ?? [] {
if let _ = item.availableType(from: self.acceptedTypes) {
continue // a raw type is available, so don't process file-inferred types
} else if let _ = item.availableType(from: [._fileURL]) {
if let plist = item.propertyList(forType: ._fileURL),
let url = NSURL(pasteboardPropertyList: plist, ofType: ._fileURL),
let fileURL = url.filePathURL,
let type = (try? fileURL.resourceValues(forKeys: [.typeIdentifierKey]))?.typeIdentifier {
// we have an inference file type now instead of the public.file-url UTI...
for possible in self.acceptedTypes where !UTTypeConformsTo(type as CFString, possible.rawValue as CFString) {
return false // the file-inferred types did not match a real UTI type
}
} else {
return false // we couldn't extract the url filetype somehow
}
} else {
return false // no raw or file-inferred types were found
}
}
return true // every item conformed directly or through inferrence
}
}
|
mpl-2.0
|
ef27eb3079f189d65ebd9b1d03c64857
| 36.313793 | 133 | 0.628408 | 4.861186 | false | false | false | false |
xxxAIRINxxx/ViewPagerController
|
Sources/InfiniteScrollView.swift
|
1
|
16367
|
//
// InfiniteScrollView.swift
// ViewPagerController
//
// Created by xxxAIRINxxx on 2016/01/05.
// Copyright © 2016 xxxAIRINxxx. All rights reserved.
//
// @see : https://github.com/bteapot/BTInfiniteScrollView
import Foundation
import UIKit
public enum XPosition: Int {
case start
case middle
case end
}
public struct InfiniteItem {
let index : Int
let thickness : CGFloat
let view : UIView
public init(_ index: Int, _ thickness: CGFloat, _ view: UIView) {
self.index = index
self.thickness = thickness
self.view = view
}
}
public protocol InfiniteScrollViewDataSource: class {
func totalItemCount() -> Int
func viewForIndex(_ index: Int) -> UIView
func thicknessForIndex(_ index: Int) -> CGFloat
}
public protocol InfiniteScrollViewDelegate: class {
func updateContentOffset(_ delta: CGFloat)
func infiniteScrollViewWillBeginDecelerating(_ scrollView: UIScrollView)
func infiniteScrollViewWillBeginDragging(_ scrollView: UIScrollView)
func infinitScrollViewDidScroll(_ scrollView: UIScrollView)
func infiniteScrollViewDidEndCenterScrolling(_ item: InfiniteItem)
func infiniteScrollViewDidShowCenterItem(_ item: InfiniteItem)
}
public final class InfiniteScrollView: UIScrollView {
public weak var infiniteDataSource : InfiniteScrollViewDataSource!
public weak var infiniteDelegate : InfiniteScrollViewDelegate?
public fileprivate(set) var items : [InfiniteItem] = []
public var scrolling : Int = 0
fileprivate var lastReportedItemIndex : Int = Int.min
fileprivate var isUserScrolling = false
// MARK: - Constructor
override init(frame: CGRect) {
super.init(frame: frame)
self.commonInit()
}
required public init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
self.commonInit()
}
fileprivate func commonInit() {
self.delegate = self
self.autoresizesSubviews = false
self.bounces = false
self.showsHorizontalScrollIndicator = false
self.panGestureRecognizer.maximumNumberOfTouches = 1
}
// MARK: - Override
override public var frame: CGRect {
get { return super.frame }
set {
if newValue.isEmpty { return }
let bounds = self.bounds
let oldVisibleCenterX = bounds.origin.x + bounds.size.width / 2.0
super.frame = newValue
let newBounds = self.bounds
if newBounds.size.width * 5 > self.contentSize.width || newBounds.size.height < self.contentSize.height {
super.contentSize = CGSize(width: newBounds.width * 5, height: newBounds.size.height)
}
let newVisibleCenterX = newBounds.origin.x + newBounds.size.width / 2.0
let deltaX = oldVisibleCenterX - newVisibleCenterX
self.items = self.items.map(){ item in
item.view.frame.origin.x = item.view.frame.origin.x - deltaX
item.view.frame.size.height = newBounds.size.height
return item
}
}
}
public override func layoutSubviews() {
super.layoutSubviews()
guard self.infiniteDataSource.totalItemCount() > 0 else { return }
var bounds = self.bounds
let visible = bounds.size.width
if self.scrolling == 0 {
var delta = self.contentSize.width / 2 - bounds.midX
let allow = self.isPagingEnabled ? !self.isDecelerating : true
if allow && fabs(delta) > visible {
delta = visible * (delta > 0 ? 1 : -1)
self.delegate = nil
let contentOffset = self.contentOffset
self.contentOffset = CGPoint(x: contentOffset.x + delta, y: contentOffset.y)
self.delegate = self
bounds = self.bounds
self.items = self.items.map(){ item in
item.view.frame.origin.x += delta
return item
}
self.infiniteDelegate?.updateContentOffset(delta)
}
}
let minVisible = bounds.minX
let maxVisible = bounds.maxX
let lastItem = self.items.last
var index = 0
var endEdge: CGFloat = 0
if let _item = lastItem {
index = _item.index
endEdge = _item.view.frame.maxX
} else {
endEdge = self.placeNewItem(.middle, edge: 0, index: 0)
}
while (endEdge < maxVisible) {
index += 1
endEdge = self.placeNewItem(.end, edge: endEdge, index: index)
}
let firstItem = self.items.first
var startEdge: CGFloat = 0
if let _item = firstItem {
index = _item.index
startEdge = _item.view.frame.minX
}
while (startEdge > minVisible) {
index -= 1
startEdge = self.placeNewItem(.start, edge: startEdge, index: index)
}
if self.scrolling == 0 && self.items.count > 0 {
var lasted = self.items.last
while (lasted != nil && lasted!.view.frame.minX >= maxVisible) {
lasted!.view.removeFromSuperview()
self.items.removeLast()
lasted = self.items.last
}
var firsted = self.items.first
while (firsted != nil && firsted!.view.frame.maxX <= minVisible) {
firsted!.view.removeFromSuperview()
self.items.remove(at: 0)
firsted = self.items.first
}
}
if let _item = self.itemAtCenterPosition() {
if self.isUserScrolling { return }
if self.lastReportedItemIndex != _item.index {
self.lastReportedItemIndex = _item.index
self.infiniteDelegate?.infiniteScrollViewDidShowCenterItem(_item)
}
}
}
// MARK: - Public Functions
public func itemAtView(_ view: UIView) -> InfiniteItem? {
return self.items.filter() { item in return item.view === view }.first
}
public func itemAtIndex(_ index: Int) -> InfiniteItem? {
return self.items.filter() { item in return item.index == index }.first
}
public func updateItems(_ handler: ((InfiniteItem) -> InfiniteItem)) {
self.items = self.items.map(handler)
}
public func reset() {
self.subviews.forEach() { $0.removeFromSuperview() }
self.items.removeAll(keepingCapacity: true)
}
public func reloadViews() {
guard self.infiniteDataSource.totalItemCount() > 0 else { return }
if let _targetItem = self.itemAtCenterPosition() {
self.reloadView(.start, item: _targetItem, edge: _targetItem.view.frame.midX)
var previousItem = _targetItem
var item = self.itemAtIndex(previousItem.index + 1)
while (item != nil) {
self.reloadView(.end, item: item!, edge: previousItem.view.frame.maxX)
previousItem = item!
item = self.itemAtIndex(previousItem.index + 1)
}
previousItem = _targetItem
item = self.itemAtIndex(previousItem.index - 1)
while (item != nil) {
self.reloadView(.end, item: item!, edge: previousItem.view.frame.maxX)
previousItem = item!
item = self.itemAtIndex(previousItem.index - 1)
}
self.setNeedsLayout()
self.layoutIfNeeded()
}
}
public func reloadView(_ position: XPosition, item: InfiniteItem, edge: CGFloat) {
guard self.infiniteDataSource.totalItemCount() > 0 else { return }
let convertIndex = self.convertIndex(item.index)
let bounds = self.bounds
let thickness = CGFloat(ceilf(Float(self.infiniteDataSource.thicknessForIndex(convertIndex))))
let view = (self.infiniteDataSource.viewForIndex(convertIndex))
switch position {
case .start:
item.view.frame = CGRect(x: edge - thickness, y: 0, width: thickness, height: bounds.size.height)
case .middle:
item.view.frame = CGRect(x: edge - thickness / 2.0, y: 0, width: thickness, height: bounds.size.height)
case .end:
item.view.frame = CGRect(x: edge, y: 0, width: thickness, height: bounds.size.height)
}
item.view.removeFromSuperview()
self.addSubview(view)
}
public func resetWithIndex(_ index: Int) {
guard self.infiniteDataSource.totalItemCount() > 0 else { return }
if self.bounds.isEmpty { return }
self.reset()
_ = self.placeNewItem(.middle, edge: 0, index: index)
self.setNeedsLayout()
self.layoutIfNeeded()
}
public func itemAtCenterPosition() -> InfiniteItem? {
let bounds = self.bounds
let mark: CGFloat = bounds.midX
for item in self.items {
if item.view.frame.minX <= mark && item.view.frame.maxX >= mark {
return item
}
}
return nil
}
public func scrollToCenter(_ index: Int, offset: CGFloat, animated: Bool, animation: (() -> Void)?, completion: (() -> Void)?) {
guard self.infiniteDataSource.totalItemCount() > 0 else { return }
if self.bounds.isEmpty { return }
self.setNeedsLayout()
self.layoutIfNeeded()
var bounds = self.bounds
let visible = bounds.size.width
var targetItem = self.items.filter({item in return item.index == index }).first
if targetItem == nil {
let firstItem = self.items.first
let lastItem = self.items.last
let isStart = index < firstItem!.index
targetItem = self.createItem(index)
var newItems: [InfiniteItem] = []
newItems.append(targetItem!)
var gap: CGFloat = isStart ? (visible - targetItem!.thickness) / 2.0 + offset : (visible - targetItem!.thickness) / 2.0 - offset
var indexDelta = (isStart ? firstItem!.index - index : index - lastItem!.index) - 1
var gapItemIndex = index
while (indexDelta > 0 && gap >= 0) {
gapItemIndex += isStart ? 1 : -1
let item = self.createItem(gapItemIndex)
isStart ? newItems.append(item) : newItems.insert(item, at: 0)
gap -= item.thickness
indexDelta -= 1
}
if isStart {
var startEdge = firstItem!.view.frame.minX
var newItemIndex = newItems.count - 1
while newItemIndex >= 0 {
let item = newItems[newItemIndex]
item.view.frame = CGRect(x: startEdge - item.thickness, y: 0, width: item.thickness, height: bounds.size.height)
startEdge = item.view.frame.minX
self.addSubview(item.view)
self.items.insert(item, at: 0)
newItemIndex -= 1
}
} else {
var endEdge = firstItem!.view.frame.maxX
self.items = newItems.map() { item in
item.view.frame = CGRect(x: endEdge, y: 0, width: item.thickness, height: bounds.size.height)
endEdge = item.view.frame.maxX
self.addSubview(item.view)
return item
}
}
}
bounds = CGRect(
x: targetItem!.view.frame.minX - (bounds.size.width - targetItem!.thickness) / 2.0 + offset,
y: 0,
width: bounds.size.width,
height: bounds.size.height
)
self.scrolling += 1
self.setContentOffset(self.contentOffset, animated: false)
if animated {
UIView.animateKeyframes(withDuration: 0.25, delay: 0, options: .beginFromCurrentState, animations: {
self.bounds = bounds
animation?()
}, completion: { finished in
self.scrolling -= 1
self.setNeedsLayout()
self.layoutIfNeeded()
completion?()
})
} else {
self.bounds = bounds
self.scrolling -= 1
completion?()
}
}
public func scrollToCenter(_ index: Int, animated: Bool, animation: (() -> Void)?, completion: (() -> Void)?) {
self.scrollToCenter(index, offset: 0, animated: animated, animation: animation, completion: completion)
}
public func convertIndex(_ scrollViewIndex: Int) -> Int {
let total = self.infiniteDataSource.totalItemCount()
let currentIndex = scrollViewIndex >= 0 ? (scrollViewIndex % total) : (total - (-scrollViewIndex % total))
return currentIndex == total ? 0 : currentIndex
}
// MARK: - Private Functions
fileprivate func createItem(_ index: Int) -> InfiniteItem {
let convertIndex = self.convertIndex(index)
let bounds = self.bounds
let thickness = CGFloat(ceilf(Float(self.infiniteDataSource.thicknessForIndex(convertIndex))))
let view = self.infiniteDataSource.viewForIndex(convertIndex)
view.frame = CGRect(x: 0, y: 0, width: thickness, height: bounds.size.height)
return InfiniteItem(index, thickness, view)
}
fileprivate func placeNewItem(_ position: XPosition, edge: CGFloat, index: Int) -> CGFloat {
let item = self.createItem(index)
switch position {
case .start:
item.view.frame.origin.x = edge - item.thickness
self.addSubview(item.view)
self.items.insert(item, at: 0)
return item.view.frame.minX
case .middle:
item.view.frame.origin.x = bounds.origin.x + (bounds.size.width - item.thickness) / 2.0
self.addSubview(item.view)
self.items.append(item)
return item.view.frame.maxX
case .end:
item.view.frame.origin.x = edge
self.addSubview(item.view)
self.items.append(item)
return item.view.frame.maxX
}
}
}
// MARK: - Private UIScrollViewDelegate
extension InfiniteScrollView: UIScrollViewDelegate {
public func scrollViewWillBeginDecelerating(_ scrollView: UIScrollView) {
self.infiniteDelegate?.infiniteScrollViewWillBeginDecelerating(scrollView)
}
public func scrollViewWillBeginDragging(_ scrollView: UIScrollView) {
self.infiniteDelegate?.infiniteScrollViewWillBeginDragging(scrollView)
self.isUserScrolling = true
}
public func scrollViewDidScroll(_ scrollView: UIScrollView) {
self.infiniteDelegate?.infinitScrollViewDidScroll(scrollView)
}
public func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
self.isUserScrolling = false
if let _targetItem = self.itemAtCenterPosition() {
self.scrollToCenter(_targetItem.index, offset: 0, animated: true, animation: nil, completion: nil)
self.infiniteDelegate?.infiniteScrollViewDidEndCenterScrolling(_targetItem)
}
}
public func scrollViewDidEndDragging(_ scrollView: UIScrollView, willDecelerate decelerate: Bool) {
if decelerate { return }
self.isUserScrolling = false
if let _targetItem = self.itemAtCenterPosition() {
self.scrollToCenter(_targetItem.index, offset: 0, animated: true, animation: nil, completion: nil)
self.infiniteDelegate?.infiniteScrollViewDidEndCenterScrolling(_targetItem)
}
}
}
|
mit
|
0abe53590cab023d2756fdd8235b1ab9
| 34.655773 | 140 | 0.57094 | 4.882458 | false | false | false | false |
savelii/BSON
|
Sources/ExtendedJSON.swift
|
1
|
17200
|
//
// ExtendedJSON.swift
// BSON
//
// Created by Robbert Brandsma on 14-06-16.
//
//
import Foundation
extension Document {
/// All errors that can occur when parsing Extended JSON
public enum ExtendedJSONError : Error {
/// Invalid character at position
case invalidCharacter(position: String.CharacterView.Index)
/// -
case unexpectedEndOfInput
/// Expected a String at position at position
case stringExpected(position: String.CharacterView.Index)
/// Unable to parse the number at position
case numberParseError(position: String.CharacterView.Index)
/// Unable to parse the value at position
case unparseableValue(position: String.CharacterView.Index)
}
/// Converts the `Document` to the [MongoDB extended JSON](https://docs.mongodb.com/manual/reference/mongodb-extended-json/) format.
/// The data is converted to MongoDB extended JSON in strict mode.
///
/// - returns: The JSON string. Depending on the type of document, the top level object will either be an array or object.
public func makeExtendedJSON() -> String {
var str: String
if self.validatesAsArray() && isArray {
str = self.makeIterator().map { pair in
return pair.value.makeExtendedJSON()
}.reduce("[") { "\($0),\($1)" } + "]"
} else {
str = self.makeIterator().map { pair in
return "\"\(pair.key)\":\(pair.value.makeExtendedJSON())"
}.reduce("{") { "\($0),\($1)" } + "}"
}
if (str.characters.count > 2) {
str.remove(at: str.index(after: str.startIndex)) // remove the comma
}
return str
}
/// Parses the given JSON string as [MongoDB extended JSON](https://docs.mongodb.com/manual/reference/mongodb-extended-json/).
/// The data is parsed in strict mode.
///
/// - parameter json: The MongoDB extended JSON string. The top level object must be an array or object.
///
/// - throws: May throw any error that `Foundation.JSONSerialization` throws.
public init(extendedJSON json: String) throws {
let characters = json.characters
var position = characters.startIndex
/// Advances one position
func advance() {
position = characters.index(after: position)
}
/// Returns the character at the current position
///
/// - throws: Throws when the current character is out of bounds.
///
/// - returns: The character at the current position.
func c() throws -> Character {
if position < characters.endIndex {
return characters[position]
} else {
throw ExtendedJSONError.unexpectedEndOfInput
}
}
/// Increase the position to the first character found that is not whitespace.
///
/// - throws: Throws when a character is out of bounds.
func skipWhitespace() throws {
while true {
switch try c() {
case " ", "\n", "\t":
advance()
default:
return
}
}
}
/// Get the string at the current position.
/// After calling this, the position will be increased until the character after the closing ".
///
/// - throws: Can throw when a bounds error occurs.
///
/// - returns: The string
func getStringValue() throws -> String {
// If at the ", skip it
if try c() == "\"" {
// Advance, so we are at the start of the string:
advance()
}
// We will store the final string here:
var string = ""
characterLoop: while true {
let char = try c()
switch char {
case "\"": // This is the end of the string.
break characterLoop
case "\\": // Handle the escape sequence
if try checkLiteral("\\\"") { // Quotation mark, \"
string.append("\"")
continue characterLoop
} else if try checkLiteral("\\\\") { // Reverse solidus, \\
string.append("\\")
continue characterLoop
} else if try checkLiteral("\\r") { // Carriage return, \r
string.append("\r")
continue characterLoop
} else if try checkLiteral("\\n") { // Newline, \n
string.append("\n")
continue characterLoop
} else if try checkLiteral("\\/") { // Solidus, \/
string.append("/")
continue characterLoop
} else if try checkLiteral("\\b") { // Backspace, \b
string.append("\u{8}")
continue characterLoop
} else if try checkLiteral("\\f") { // Formfeed, \f
string.append("\u{c}")
continue characterLoop
} else if try checkLiteral("\\t") { // Horizontal tab, \t
string.append("\t")
continue characterLoop
} else if try checkLiteral("\\u") { // Unicode code, for example: \u000c or \u000C
// Get the four digits
guard json.distance(from: position, to: json.endIndex) >= 3 else {
string.append("\\u")
continue characterLoop
}
let unicodeEnd = json.index(position, offsetBy: 3)
let substr = json[position...unicodeEnd]
guard let code = Int(substr, radix: 16) else {
string.append("\\u")
continue characterLoop
}
guard let scalar = UnicodeScalar(code) else {
continue characterLoop
}
let character = Character(scalar)
string.append(character)
continue characterLoop
} else {
fallthrough
}
default:
string.append(char)
}
advance()
}
// Advance past the end of the string:
advance()
return string
}
/// Checks if the given literal is at the current position.
/// After calling this, the position will be after the literal if it was found, or unaltered if it wasn't.
///
/// - parameter value: The literal to check for.
///
/// - throws: Unexpected end of document
///
/// - returns: True when the literal is found, false otherwise.
func checkLiteral(_ value: String) throws -> Bool {
let endIndex = json.index(position, offsetBy: value.characters.count)
if endIndex > json.endIndex {
return false
}
let remaining = json[position..<json.endIndex]
if remaining.hasPrefix(value) {
position = json.index(position, offsetBy: value.characters.count)
return true
}
return false
}
/// Parse the object at array at the current position. After calling this, the position will be after the end of the object or array.
func parseObjectOrArray() throws -> BSONPrimitive? {
// This will be the document we're working with
// There may be whitespace before the start of the object or array
try skipWhitespace()
// Check if this is an array or object
let isArray: Bool
switch try c() {
case "{":
isArray = false
case "[":
isArray = true
default:
throw ExtendedJSONError.invalidCharacter(position: position)
}
var document = isArray ? Document(array: []) : Document()
// Advance past the starting character
advance()
// Loop over the characters until we get to the end
valueFindLoop: while true {
// We are now after the value. Skip whitespace, and then determine the next action.
try skipWhitespace()
switch try c() {
case "}":
guard !isArray else {
throw ExtendedJSONError.invalidCharacter(position: position)
}
advance()
break valueFindLoop
case "]":
guard isArray else {
throw ExtendedJSONError.invalidCharacter(position: position)
}
advance()
break valueFindLoop
case ",":
advance()
default:
break
}
// Whitespace, whitespace everywhere!
try skipWhitespace()
// Get the key, which may be the current index in the case of an array, or a string.
let key: String? = isArray ? nil : try getStringValue()
// We are now after the key, so we should skip whitespace again.
try skipWhitespace()
// In case of an object, the next character should be a colon (:)
if !isArray {
guard try c() == ":" else {
throw ExtendedJSONError.invalidCharacter(position: position)
}
advance()
try skipWhitespace()
}
// We are now at the start of the value. We will now get the value and type identifier.
let value: ValueConvertible?
switch try c() {
case "\"":
// This is a string
value = try getStringValue()
case "{", "[":
// This is an object or array
value = try parseObjectOrArray()
case "-", "0", "1", "2", "3", "4", "5", "6", "7", "8", "9":
// TODO: support these e+24 numbers
let numberStart = position
let numberCharacters = ["-", "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "."]
while numberCharacters.contains(String(try c())) {
advance()
}
let numberString = json[numberStart..<position]
// Determine the type: default to int32(or int64 if needed), but if it contains a ., double
if numberString.contains(".") {
guard let number = Double(numberString) else {
throw ExtendedJSONError.numberParseError(position: numberStart)
}
value = number
} else {
if let number = Int32(numberString) {
value = number
} else {
guard let number = Int64(numberString) else {
throw ExtendedJSONError.numberParseError(position: numberStart)
}
value = number
}
}
case _ where try checkLiteral("true"):
value = true
case _ where try checkLiteral("false"):
value = false
case _ where try checkLiteral("null"):
value = Null()
default:
throw ExtendedJSONError.unparseableValue(position: position)
}
if let value = value {
// All the information to be able to append to the document is now ready:
if let key = key, !isArray {
document.append(value, forKey: key)
} else {
document.append(value)
}
}
}
subParser: if !isArray {
// If this document is one of the extended JSON types, we should return the parsed value instead of an array or document.
let count = document.count
// For performance reasons, only do this if the count is 1 or 2, and only if the first key starts with a $.
guard (count == 1 || count == 2) && document.keys[0].hasPrefix("$") else {
break subParser
}
if count == 1 {
if let hex = document["$oid"] as String? {
// ObjectID
return try ObjectId(hex)
} else if let dateString = document["$date"] as String? {
// DateTime
return parseISO8601(from: dateString)
} else if let code = document["$code"] as String? {
return JavascriptCode(code)
} else if let numberString = document["$numberLong"] as String? {
guard let number = Int64(numberString) else {
break subParser
}
return number
} else if document["$minKey"] as Int? == 1 {
return MinKey()
} else if document["$maxKey"] as Int? == 1 {
return MaxKey()
} else if let timestamp = document["$timestamp"] as Document?, let t = timestamp["t"] as Int32?, let i = timestamp["i"] as Int32? {
return Timestamp(increment: i, timestamp: t)
}
} else if count == 2 {
if let base64 = document["$binary"] as String?, let hexSubtype = document["$type"] as String? {
// Binary
guard hexSubtype.characters.count > 2 else {
break subParser
}
guard let data = Data(base64Encoded: base64), let subtypeInt = UInt8(hexSubtype[hexSubtype.index(hexSubtype.startIndex, offsetBy: 2)..<hexSubtype.endIndex], radix: 16) else {
break subParser
}
let subtype = Binary.Subtype(rawValue: subtypeInt)
#if os(Linux)
var byteBuffer = [UInt8](repeating: 0, count: data.count)
data.copyBytes(to: &byteBuffer, count: byteBuffer.count)
return Binary(data: byteBuffer, withSubtype: subtype)
#else
return Binary(data: Array<UInt8>(data), withSubtype: subtype)
#endif
} else if let pattern = document["$regex"] as String?, let options = document["$options"] as String? {
// RegularExpression
#if swift(>=3.1)
return try? NSRegularExpression(pattern: pattern, options: regexOptions(fromString: options))
#else
return try? RegularExpression(pattern: pattern, options: regexOptions(fromString: options))
#endif
} else if let code = document["$code"] as String?, let scope = document["$scope"] as Document? {
// JS with scope
return JavascriptCode(code, withScope: scope)
}
}
}
return document
}
guard let jsonVal = try parseObjectOrArray()?.documentValue else {
throw ExtendedJSONError.unexpectedEndOfInput
}
self.init(data: jsonVal.bytes)
}
}
|
mit
|
687e270beed9fe39596c0df7988bf3b1
| 41.679901 | 198 | 0.456628 | 5.862304 | false | false | false | false |
february29/Learning
|
swift/Fch_Contact/Pods/RxSwift/RxSwift/Schedulers/Internal/DispatchQueueConfiguration.swift
|
37
|
3749
|
//
// DispatchQueueConfiguration.swift
// RxSwift
//
// Created by Krunoslav Zaher on 7/23/16.
// Copyright © 2016 Krunoslav Zaher. All rights reserved.
//
import Dispatch
import struct Foundation.TimeInterval
struct DispatchQueueConfiguration {
let queue: DispatchQueue
let leeway: DispatchTimeInterval
}
private func dispatchInterval(_ interval: Foundation.TimeInterval) -> DispatchTimeInterval {
precondition(interval >= 0.0)
// TODO: Replace 1000 with something that actually works
// NSEC_PER_MSEC returns 1000000
return DispatchTimeInterval.milliseconds(Int(interval * 1000.0))
}
extension DispatchQueueConfiguration {
func schedule<StateType>(_ state: StateType, action: @escaping (StateType) -> Disposable) -> Disposable {
let cancel = SingleAssignmentDisposable()
queue.async {
if cancel.isDisposed {
return
}
cancel.setDisposable(action(state))
}
return cancel
}
func scheduleRelative<StateType>(_ state: StateType, dueTime: Foundation.TimeInterval, action: @escaping (StateType) -> Disposable) -> Disposable {
let deadline = DispatchTime.now() + dispatchInterval(dueTime)
let compositeDisposable = CompositeDisposable()
let timer = DispatchSource.makeTimerSource(queue: queue)
#if swift(>=4.0)
timer.schedule(deadline: deadline, leeway: leeway)
#else
timer.scheduleOneshot(deadline: deadline, leeway: leeway)
#endif
// TODO:
// This looks horrible, and yes, it is.
// It looks like Apple has made a conceputal change here, and I'm unsure why.
// Need more info on this.
// It looks like just setting timer to fire and not holding a reference to it
// until deadline causes timer cancellation.
var timerReference: DispatchSourceTimer? = timer
let cancelTimer = Disposables.create {
timerReference?.cancel()
timerReference = nil
}
timer.setEventHandler(handler: {
if compositeDisposable.isDisposed {
return
}
_ = compositeDisposable.insert(action(state))
cancelTimer.dispose()
})
timer.resume()
_ = compositeDisposable.insert(cancelTimer)
return compositeDisposable
}
func schedulePeriodic<StateType>(_ state: StateType, startAfter: TimeInterval, period: TimeInterval, action: @escaping (StateType) -> StateType) -> Disposable {
let initial = DispatchTime.now() + dispatchInterval(startAfter)
var timerState = state
let timer = DispatchSource.makeTimerSource(queue: queue)
#if swift(>=4.0)
timer.schedule(deadline: initial, repeating: dispatchInterval(period), leeway: leeway)
#else
timer.scheduleRepeating(deadline: initial, interval: dispatchInterval(period), leeway: leeway)
#endif
// TODO:
// This looks horrible, and yes, it is.
// It looks like Apple has made a conceputal change here, and I'm unsure why.
// Need more info on this.
// It looks like just setting timer to fire and not holding a reference to it
// until deadline causes timer cancellation.
var timerReference: DispatchSourceTimer? = timer
let cancelTimer = Disposables.create {
timerReference?.cancel()
timerReference = nil
}
timer.setEventHandler(handler: {
if cancelTimer.isDisposed {
return
}
timerState = action(timerState)
})
timer.resume()
return cancelTimer
}
}
|
mit
|
1014b55310d81fda03df0800f88797c7
| 32.464286 | 164 | 0.635272 | 5.256662 | false | false | false | false |
IdeasOnCanvas/Callisto
|
Callisto/UnitTestMessage.swift
|
1
|
1765
|
//
// UnitTestMessage.swift
// Callisto
//
// Created by Patrick Kladek on 07.06.17.
// Copyright © 2017 IdeasOnCanvas. All rights reserved.
//
import Cocoa
final class UnitTestMessage: Codable {
let method: String
let assertType: String
let explanation: String
init?(message: String) {
guard let xRange = (message.range(of: "✗")) else { return nil }
let validMessage = message[xRange.lowerBound...]
let components = validMessage.components(separatedBy: CharacterSet(charactersIn: ",-"))
guard components.count >= 3 else { return nil }
self.method = String(components[0].dropFirst(2))
self.assertType = components[1].trim()
self.explanation = components[2].trim().strippingLocalInfos.condenseWhitespace()
}
}
extension UnitTestMessage: CustomStringConvertible {
var description: String {
return "\(self.method), \(self.assertType) - \(self.explanation)"
}
}
extension UnitTestMessage: Hashable {
static func == (left: UnitTestMessage, right: UnitTestMessage) -> Bool {
return
left.method == right.method &&
left.assertType == right.assertType &&
left.explanation == right.explanation
}
func hash(into hasher: inout Hasher) {
hasher.combine(self.method)
hasher.combine(self.assertType)
hasher.combine(self.explanation)
}
}
private extension String {
/// Deletes informations like: <__NSArrayM: 0x60000184dfb0>
/// Before: "*** Collection <__NSArrayM: 0x60000184dfb0> was mutated while being enumerated."
/// After "*** Collection was mutated while being enumerated."
var strippingLocalInfos: String {
return self.trim(from: "<", to: ">")
}
}
|
mit
|
6db198eb89227e405f9df8ad1ccca97c
| 27.885246 | 97 | 0.652667 | 4.175355 | false | true | false | false |
moonrailgun/OpenCode
|
OpenCode/Classes/Tool/Ping/Controller/PingDetailController.swift
|
1
|
3294
|
//
// PingDetailController.swift
// OpenCode
//
// Created by 陈亮 on 16/7/6.
// Copyright © 2016年 moonrailgun. All rights reserved.
//
import UIKit
import SwiftyJSON
import FSLineChart
class PingDetailController: UIViewController {
var hostAddress:String?
var timer:NSTimer?
var pingResult:[JSON] = []
let lineChartView:FSLineChart = FSLineChart(frame: CGRectMake(0,200,UIScreen.mainScreen().bounds.width,60))
var lineChartData:[Int] = []
let currentTimeView:UILabel = UILabel(frame: CGRectMake((UIScreen.mainScreen().bounds.width - 60) / 2,150,60,30))
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
self.view.backgroundColor = UIColor.whiteColor()
let currentTimeDesc = UILabel(frame: CGRectMake((UIScreen.mainScreen().bounds.width - 180) / 2,120,180,30))
currentTimeDesc.text = "当前延时(ms):"
currentTimeDesc.font = UIFont.systemFontOfSize(14)
currentTimeDesc.textAlignment = .Center
self.view.addSubview(currentTimeDesc)
currentTimeView.text = "0"
currentTimeView.textAlignment = .Center
currentTimeView.font = UIFont.systemFontOfSize(30)
self.view.addSubview(currentTimeView)
lineChartView.setChartData(lineChartData)
self.view.addSubview(lineChartView)
self.timer = NSTimer.scheduledTimerWithTimeInterval(2, target: self, selector: #selector(self.ping), userInfo: nil, repeats: true)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
override func viewDidAppear(animated: Bool) {
if(timer != nil){
startPing()
}
}
override func viewDidDisappear(animated: Bool) {
if(timer != nil){
stopPing()
}
}
func startPing(){
self.timer?.fire()
}
func stopPing(){
self.timer?.invalidate()
}
func ping() {
if let address = hostAddress{
SimplePingHelper.start(address, target: self, selector: #selector(self.pingResult(_:)))
}
}
func pingResult(object:AnyObject){
let result = JSON(object)
pingResult.append(result)
if(result["status"] == true){
//ping到
let time = result["time"].int! > 2 ? 2 : result["time"].int!
print("\(time)ms")
currentTimeView.text = String(time)
self.lineChartData.append(time)
}else{
//没有
print(result["error"])
self.lineChartData.append(2)
}
self.lineChartView.clearChartData()
self.lineChartView.setChartData(self.lineChartData)
self.lineChartView.animationDuration = 0
}
/*
// 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.
}
*/
}
|
gpl-2.0
|
2771d574c06beb5c136826a38a49fa46
| 30.171429 | 138 | 0.624809 | 4.622881 | false | false | false | false |
skerkewitz/SwignalR
|
SwignalR/Classes/Hubs/HubInvocation.swift
|
1
|
3091
|
//
// HubInvocation.swift
// SignalR
//
// Created by Alex Billingsley on 11/7/11.
// Copyright (c) 2011 DyKnow LLC. (http://dyknow.com/)
// Created by Stefan Kerkewitz on 28/02/2017.
//
// 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 `SRHubInvocation` object defines the interface for invoking methods on the SignalR Client using a Hubs
* implementation
*/
internal struct SRHubInvocation: SRDeserializable, SRSerializable {
static let kCallbackId = "I"
static let kHub = "H"
static let kMethod = "M"
static let kArgs = "A"
static let kState = "S"
let callbackId: String?
/** The `NSString` object corresponding to the hub to preform an invocation on */
let hub: String
/** The `NSString` object corresponding to the method to invoke on the hub */
let method: String
/** The `NSMutableArray` object corresponding to the arguments to be passed as part of the invocation */
let args: [Any]?
/** The `NSMutableDictionary` object corresponding to the client state */
let state: [String:Any]?
init(name: String, method: String, args: [Any]?, callbackId: String, state: [String: Any]) {
self.hub = name
self.method = method
self.args = args
self.callbackId = callbackId
self.state = state
}
init(dictionary dict: [String: Any]) {
self.callbackId = dict[SRHubInvocation.kCallbackId] as? String
self.hub = dict[SRHubInvocation.kHub] as! String
self.method = dict[SRHubInvocation.kMethod] as! String
self.args = dict[SRHubInvocation.kArgs] as? [Any]
self.state = dict[SRHubInvocation.kState] as? [String:Any]
}
func proxyForJson() -> [String: Any] {
var dict = [String: Any]()
dict[SRHubInvocation.kCallbackId] = self.callbackId
dict[SRHubInvocation.kHub] = self.hub
dict[SRHubInvocation.kMethod] = self.method
dict[SRHubInvocation.kArgs] = self.args
dict[SRHubInvocation.kState] = self.state
return dict
}
}
|
mit
|
332ee65a874dcf045f6d301b248e4de5
| 38.126582 | 116 | 0.695891 | 4.083223 | false | false | false | false |
dehesa/Metal
|
shaders/Sources/Common/MathUtils.swift
|
1
|
1624
|
import Foundation
import simd
extension float4x4 {
init(scaleBy s: Float) {
self.init(SIMD4<Float>(s, 0, 0, 0),
SIMD4<Float>(0, s, 0, 0),
SIMD4<Float>(0, 0, s, 0),
SIMD4<Float>(0, 0, 0, 1))
}
init(rotationAbout axis: SIMD3<Float>, by angleRadians: Float) {
let x = axis.x, y = axis.y, z = axis.z
let c = cosf(angleRadians)
let s = sinf(angleRadians)
let t = 1 - c
self.init(SIMD4<Float>( t * x * x + c, t * x * y + z * s, t * x * z - y * s, 0),
SIMD4<Float>( t * x * y - z * s, t * y * y + c, t * y * z + x * s, 0),
SIMD4<Float>( t * x * z + y * s, t * y * z - x * s, t * z * z + c, 0),
SIMD4<Float>( 0, 0, 0, 1))
}
init(translationBy t: SIMD3<Float>) {
self.init(SIMD4<Float>( 1, 0, 0, 0),
SIMD4<Float>( 0, 1, 0, 0),
SIMD4<Float>( 0, 0, 1, 0),
SIMD4<Float>(t[0], t[1], t[2], 1))
}
init(perspectiveProjectionFov fovRadians: Float, aspectRatio aspect: Float, nearZ: Float, farZ: Float) {
let yScale = 1 / tan(fovRadians * 0.5)
let xScale = yScale / aspect
let zRange = farZ - nearZ
let zScale = -(farZ + nearZ) / zRange
let wzScale = -2 * farZ * nearZ / zRange
let xx = xScale
let yy = yScale
let zz = zScale
let zw = Float(-1)
let wz = wzScale
self.init(SIMD4<Float>(xx, 0, 0, 0),
SIMD4<Float>( 0, yy, 0, 0),
SIMD4<Float>( 0, 0, zz, zw),
SIMD4<Float>( 0, 0, wz, 1))
}
}
|
mit
|
d0993b737c5673cff9076072aa9aae25
| 32.833333 | 106 | 0.465517 | 2.874336 | false | false | false | false |
oceanfive/swift
|
swift_two/swift_two/Classes/Model/HYRetweetedStatusFrame.swift
|
1
|
2125
|
//
// HYRetweetedStatusFrame.swift
// swift_two
//
// Created by ocean on 16/6/21.
// Copyright © 2016年 ocean. All rights reserved.
//
import UIKit
class HYRetweetedStatusFrame: NSObject {
var nameLabelFrame: CGRect?
var textLabelFrame: CGRect?
var frame: CGRect?
var status = HYStatuses() {
willSet(newValue){
let tempStatus = newValue
//nameLabelFrame
let tempNameText = "@\((tempStatus.retweeted_status?.user?.name)!)" as NSString
let nameLabelSize = tempNameText.boundingRectWithSize(CGSizeMake(kScreenW, CGFloat.max), options: NSStringDrawingOptions.UsesLineFragmentOrigin, attributes: [NSFontAttributeName:kHomeCellRetweetedNameLabelFont], context: nil).size
let nameLabelX: CGFloat = 10.0
let nameLabelY: CGFloat = 10.0
let nameLabelW: CGFloat = nameLabelSize.width
let nameLabelH: CGFloat = nameLabelSize.height
nameLabelFrame = CGRectMake(nameLabelX, nameLabelY, nameLabelW, nameLabelH)
//textFrame
let tempString = (tempStatus.retweeted_status?.text)! as NSString
let size = tempString.boundingRectWithSize(CGSizeMake(kScreenW - 20.0, CGFloat.max), options: NSStringDrawingOptions.UsesLineFragmentOrigin, attributes: [NSFontAttributeName: kHomeCellRetweetedTextLabelFont], context: nil).size
let textLabelX: CGFloat = nameLabelX
let textLabelY: CGFloat = CGRectGetMaxY(nameLabelFrame!) + 10.0
let textLabelW: CGFloat = size.width
let textLabelH: CGFloat = size.height
textLabelFrame = CGRectMake(textLabelX, textLabelY, textLabelW, textLabelH)
//MARK: - 待确定??!!这里先设置为0,通过父控件来修改尺寸
frame = CGRectMake(0, 0, kScreenW, CGRectGetMaxY(textLabelFrame!) + 10.0)
}
// didSet(oldValue){
//
//
// }
//
}
}
|
mit
|
87ffc651c216facc4c096c3570ef6ce6
| 31.40625 | 242 | 0.608968 | 4.938095 | false | false | false | false |
Ajunboys/actor-platform
|
actor-apps/app-ios/Actor/Controllers/Settings/SettingsViewController.swift
|
24
|
15795
|
//
// Copyright (c) 2015 Actor LLC. <https://actor.im>
//
import UIKit
import MobileCoreServices
class SettingsViewController: AATableViewController {
// MARK: -
// MARK: Private vars
private let UserInfoCellIdentifier = "UserInfoCellIdentifier"
private let TitledCellIdentifier = "TitledCellIdentifier"
private let TextCellIdentifier = "TextCellIdentifier"
private var tableData: UATableData!
private let uid: Int
private var user: AMUserVM?
private var binder = Binder()
private var phones: JavaUtilArrayList?
// MARK: -
// MARK: Constructors
init() {
uid = Int(MSG.myUid())
super.init(style: UITableViewStyle.Plain)
var title = "";
if (MainAppTheme.tab.showText) {
title = NSLocalizedString("TabSettings", comment: "Settings Title")
}
tabBarItem = UITabBarItem(title: title,
image: MainAppTheme.tab.createUnselectedIcon("ic_settings_outline"),
selectedImage: MainAppTheme.tab.createSelectedIcon("ic_settings_filled"))
if (!MainAppTheme.tab.showText) {
tabBarItem.imageInsets = UIEdgeInsetsMake(6, 0, -6, 0);
}
}
required init(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
// MARK: -
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = MainAppTheme.list.bgColor
edgesForExtendedLayout = UIRectEdge.Top
automaticallyAdjustsScrollViewInsets = false
user = MSG.getUserWithUid(jint(uid))
tableView.separatorStyle = UITableViewCellSeparatorStyle.None
tableView.backgroundColor = MainAppTheme.list.backyardColor
tableView.clipsToBounds = false
tableView.tableFooterView = UIView()
tableData = UATableData(tableView: tableView)
tableData.registerClass(UserPhotoCell.self, forCellReuseIdentifier: UserInfoCellIdentifier)
tableData.registerClass(TitledCell.self, forCellReuseIdentifier: TitledCellIdentifier)
tableData.registerClass(TextCell.self, forCellReuseIdentifier: TextCellIdentifier)
tableData.tableScrollClosure = { (tableView: UITableView) -> () in
self.applyScrollUi(tableView)
}
// Avatar
var profileInfoSection = tableData.addSection(autoSeparator: true)
.setFooterHeight(15)
profileInfoSection.addCustomCell { (tableView, indexPath) -> UITableViewCell in
var cell: UserPhotoCell = tableView.dequeueReusableCellWithIdentifier(self.UserInfoCellIdentifier, forIndexPath: indexPath) as! UserPhotoCell
cell.contentView.superview?.clipsToBounds = false
if self.user != nil {
cell.setUsername(self.user!.getNameModel().get())
}
self.applyScrollUi(tableView, cell: cell)
return cell
}.setHeight(avatarHeight)
// Nick
profileInfoSection
.addCustomCell { (tableView, indexPath) -> UITableViewCell in
var cell: TitledCell = tableView.dequeueReusableCellWithIdentifier(self.TitledCellIdentifier, forIndexPath: indexPath) as! TitledCell
cell.enableNavigationIcon()
if let nick = self.user!.getNickModel().get() {
cell.setTitle(localized("ProfileUsername"), content: "@\(nick)")
cell.setAction(false)
} else {
cell.setTitle(localized("ProfileUsername"), content: localized("SettingsUsernameNotSet"))
cell.setAction(true)
}
return cell
}
.setHeight(55)
.setAction { () -> () in
self.textInputAlert("SettingsUsernameTitle", content: self.user!.getNickModel().get(), action: "AlertSave", tapYes: { (nval) -> () in
var nNick: String? = nval.trim()
if nNick?.size() == 0 {
nNick = nil
}
self.execute(MSG.editMyNickCommandWithNick(nNick))
})
}
var about = self.user!.getAboutModel().get()
if about == nil {
about = localized("SettingsAboutNotSet")
}
var aboutCell = profileInfoSection
.addTextCell(localized("ProfileAbout"), text: about)
.setEnableNavigation(true)
if self.user!.getAboutModel().get() == nil {
aboutCell.setIsAction(true)
}
aboutCell.setAction { () -> () in
var text = self.user!.getAboutModel().get()
if text == nil {
text = ""
}
var controller = EditTextController(title: localized("SettingsChangeAboutTitle"), actionTitle: localized("NavigationSave"), content: text, completition: { (newText) -> () in
var updatedText: String? = newText.trim()
if updatedText?.size() == 0 {
updatedText = nil
}
self.execute(MSG.editMyAboutCommandWithNick(updatedText))
})
var navigation = AANavigationController(rootViewController: controller)
self.presentViewController(navigation, animated: true, completion: nil)
}
// Phones
profileInfoSection
.addCustomCells(55, countClosure: { () -> Int in
if (self.phones != nil) {
return Int(self.phones!.size())
}
return 0
}) { (tableView, index, indexPath) -> UITableViewCell in
var cell: TitledCell = tableView.dequeueReusableCellWithIdentifier(self.TitledCellIdentifier, forIndexPath: indexPath) as! TitledCell
if let phone = self.phones!.getWithInt(jint(index)) as? AMUserPhone {
cell.setTitle(phone.getTitle(), content: "+\(phone.getPhone())")
}
return cell
}.setAction { (index) -> () in
var phoneNumber = (self.phones?.getWithInt(jint(index)).getPhone())!
var hasPhone = UIApplication.sharedApplication().canOpenURL(NSURL(string: "tel://")!)
if (!hasPhone) {
UIPasteboard.generalPasteboard().string = "+\(phoneNumber)"
self.alertUser("NumberCopied")
} else {
self.showActionSheet(["CallNumber", "CopyNumber"],
cancelButton: "AlertCancel",
destructButton: nil,
sourceView: self.view,
sourceRect: self.view.bounds,
tapClosure: { (index) -> () in
if (index == 0) {
UIApplication.sharedApplication().openURL(NSURL(string: "tel://+\(phoneNumber)")!)
} else if index == 1 {
UIPasteboard.generalPasteboard().string = "+\(phoneNumber)"
self.alertUser("NumberCopied")
}
})
}
}
// Profile
var topSection = tableData.addSection(autoSeparator: true)
topSection.setHeaderHeight(15)
topSection.setFooterHeight(15)
// Profile: Set Photo
topSection.addActionCell("SettingsSetPhoto", actionClosure: { () -> () in
var hasCamera = UIImagePickerController.isSourceTypeAvailable(UIImagePickerControllerSourceType.Camera)
self.showActionSheet(hasCamera ? ["PhotoCamera", "PhotoLibrary"] : ["PhotoLibrary"],
cancelButton: "AlertCancel",
destructButton: self.user!.getAvatarModel().get() != nil ? "PhotoRemove" : nil,
sourceView: self.view,
sourceRect: self.view.bounds,
tapClosure: { (index) -> () in
if index == -2 {
self.confirmUser("PhotoRemoveGroupMessage",
action: "PhotoRemove",
cancel: "AlertCancel",
sourceView: self.view,
sourceRect: self.view.bounds,
tapYes: { () -> () in
MSG.removeMyAvatar()
})
} else if index >= 0 {
let takePhoto: Bool = (index == 0) && hasCamera
self.pickAvatar(takePhoto, closure: { (image) -> () in
MSG.changeOwnAvatar(image)
})
}
})
})
// Profile: Set Name
topSection.addActionCell("SettingsChangeName", actionClosure: { () -> () in
var alertView = UIAlertView(title: nil,
message: NSLocalizedString("SettingsEditHeader", comment: "Title"),
delegate: nil,
cancelButtonTitle: NSLocalizedString("AlertCancel", comment: "Cancel Title"))
alertView.addButtonWithTitle(NSLocalizedString("AlertSave", comment: "Save Title"))
alertView.alertViewStyle = UIAlertViewStyle.PlainTextInput
alertView.textFieldAtIndex(0)!.autocapitalizationType = UITextAutocapitalizationType.Words
alertView.textFieldAtIndex(0)!.text = self.user!.getNameModel().get()
alertView.textFieldAtIndex(0)?.keyboardAppearance = MainAppTheme.common.isDarkKeyboard ? UIKeyboardAppearance.Dark : UIKeyboardAppearance.Light
alertView.tapBlock = { (alertView, buttonIndex) -> () in
if (buttonIndex == 1) {
let textField = alertView.textFieldAtIndex(0)!
if count(textField.text) > 0 {
self.execute(MSG.editMyNameCommandWithName(textField.text))
}
}
}
alertView.show()
})
// Settings
var actionsSection = tableData.addSection(autoSeparator: true)
.setHeaderHeight(15)
.setFooterHeight(15)
// Settings: Notifications
actionsSection.addNavigationCell("SettingsNotifications", actionClosure: { () -> () in
self.navigateNext(SettingsNotificationsViewController(), removeCurrent: false)
})
// Settings: Privacy
actionsSection.addNavigationCell("SettingsSecurity", actionClosure: { () -> () in
self.navigateNext(SettingsPrivacyViewController(), removeCurrent: false)
})
// Support
var supportSection = tableData.addSection(autoSeparator: true)
.setHeaderHeight(15)
.setFooterHeight(15)
// Support: Ask Question
supportSection.addNavigationCell("SettingsAskQuestion", actionClosure: { () -> () in
self.execute(MSG.findUsersCommandWithQuery("75551234567"), successBlock: { (val) -> Void in
var user:AMUserVM!
if let users = val as? IOSObjectArray {
if Int(users.length()) > 0 {
if let tempUser = users.objectAtIndex(0) as? AMUserVM {
user = tempUser
}
}
}
self.navigateDetail(ConversationViewController(peer: AMPeer.userWithInt(user.getId())))
}, failureBlock: { (val) -> Void in
// TODO: Implement
})
})
// Support: Ask Question
supportSection.addNavigationCell("SettingsAbout", actionClosure: { () -> () in
UIApplication.sharedApplication().openURL(NSURL(string: "https://actor.im")!)
})
// Support: App version
var version = NSBundle.mainBundle().infoDictionary!["CFBundleShortVersionString"] as! String
supportSection.addCommonCell()
.setContent(NSLocalizedString("SettingsVersion", comment: "Version").stringByReplacingOccurrencesOfString("{version}", withString: version, options: NSStringCompareOptions.allZeros, range: nil))
.setStyle(.Hint)
// Bind
tableView.reloadData()
binder.bind(user!.getNameModel()!, closure: { (value: String?) -> () in
if value == nil {
return
}
if let cell = self.tableView.cellForRowAtIndexPath(NSIndexPath(forItem: 0, inSection: 0)) as? UserPhotoCell {
cell.setUsername(value!)
}
})
binder.bind(user!.getAboutModel(), closure: { (value: String?) -> () in
var about = self.user!.getAboutModel().get()
if about == nil {
about = localized("SettingsAboutNotSet")
aboutCell.setIsAction(true)
} else {
aboutCell.setIsAction(false)
}
aboutCell.setContent(localized("ProfileAbout"), text: about)
self.tableView.reloadRowsAtIndexPaths([NSIndexPath(forRow: 2, inSection: 0)], withRowAnimation: UITableViewRowAnimation.Automatic)
})
binder.bind(user!.getNickModel(), closure: { (value: String?) -> () in
self.tableView.reloadRowsAtIndexPaths([NSIndexPath(forRow: 1, inSection: 0)], withRowAnimation: UITableViewRowAnimation.Automatic)
})
binder.bind(MSG.getOwnAvatarVM().getUploadState(), valueModel2: user!.getAvatarModel()) { (upload: AMAvatarUploadState?, avatar: AMAvatar?) -> () in
if let cell = self.tableView.cellForRowAtIndexPath(NSIndexPath(forItem: 0, inSection: 0)) as? UserPhotoCell {
if (upload != nil && upload!.isUploading().boolValue) {
cell.userAvatarView.bind(self.user!.getNameModel().get(), id: jint(self.uid), fileName: upload?.getDescriptor())
cell.setProgress(true)
} else {
cell.userAvatarView.bind(self.user!.getNameModel().get(), id: jint(self.uid), avatar: avatar, clearPrev: false)
cell.setProgress(false)
}
}
}
binder.bind(user!.getPresenceModel(), closure: { (presence: AMUserPresence?) -> () in
var presenceText = MSG.getFormatter().formatPresence(presence, withSex: self.user!.getSex())
if presenceText != nil {
if let cell = self.tableView.cellForRowAtIndexPath(NSIndexPath(forItem: 0, inSection: 0)) as? UserPhotoCell {
cell.setPresence(presenceText)
}
}
})
binder.bind(user!.getPhonesModel(), closure: { (phones: JavaUtilArrayList?) -> () in
if phones != nil {
self.phones = phones
self.tableView.reloadData()
}
})
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
MSG.onProfileOpenWithUid(jint(uid))
MainAppTheme.navigation.applyStatusBar()
navigationController?.navigationBar.shadowImage = UIImage()
applyScrollUi(tableView)
}
override func viewWillDisappear(animated: Bool) {
super.viewWillDisappear(animated)
MSG.onProfileClosedWithUid(jint(uid))
navigationController?.navigationBar.lt_reset()
}
}
|
mit
|
877aa2deb613a7366396dc8ff2d47154
| 42.155738 | 206 | 0.556695 | 5.530462 | false | false | false | false |
jeffreybergier/WaterMe2
|
WaterMe/Frameworks/Store/Store/PurchaseController.swift
|
1
|
3090
|
//
// PurchaseController.swift
// WaterMeStore
//
// Created by Jeffrey Bergier on 13/1/18.
// Copyright © 2017 Saturday Apps.
//
// This file is part of WaterMe. Simple Plant Watering Reminders for iOS.
//
// WaterMe is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// WaterMe is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with WaterMe. If not, see <http://www.gnu.org/licenses/>.
//
import XCGLogger
import StoreKit
internal let log = XCGLogger.default
public class PurchaseController {
private let purchaser = Purchaser()
public var transactionsInFlightUpdated: (() -> Void)?
private var transactionsInFlight: [InFlightTransaction] = []
public init?() {
guard SKPaymentQueue.canMakePayments() else { return nil }
self.purchaser.transactionsUpdated = { [unowned self] inFlights in
self.transactionsInFlight += inFlights
self.transactionsInFlightUpdated?()
}
}
public func nextTransactionForPresentingToUser() -> InFlightTransaction? {
return self.transactionsInFlight.popLast()
}
public func buy(product: SKProduct) {
self.purchaser.buy(product: product)
}
public func finish(inFlight: InFlightTransaction) {
self.purchaser.finish(inFlight: inFlight)
}
public func fetchTipJarProducts(completion: @escaping (TipJarProducts?) -> Void) {
let requester = TipJarProductRequester()
requester.fetchTipJarProducts() { result in
_ = requester // capture the requester here so its not released and deallocated mid-flight
completion(result)
}
}
}
internal class Purchaser: NSObject, SKPaymentTransactionObserver {
internal var transactionsUpdated: (([InFlightTransaction]) -> Void)?
override init() {
super.init()
SKPaymentQueue.default().add(self)
}
internal func buy(product: SKProduct) {
let payment = SKPayment(product: product)
SKPaymentQueue.default().add(payment)
}
internal func finish(inFlight: InFlightTransaction) {
SKPaymentQueue.default().finishTransaction(inFlight.transaction)
}
private func finish(transaction: SKPaymentTransaction) {
SKPaymentQueue.default().finishTransaction(transaction)
}
internal func paymentQueue(_ queue: SKPaymentQueue, updatedTransactions transactions: [SKPaymentTransaction]) {
let (inFlight, _, readyToBeFinished) = InFlightTransaction.process(transactions: transactions)
readyToBeFinished.forEach({ self.finish(transaction: $0) })
self.transactionsUpdated?(inFlight)
}
}
|
gpl-3.0
|
d02f5f2765ca2010d480549b20164648
| 32.576087 | 115 | 0.700227 | 4.556047 | false | false | false | false |
krzysztofzablocki/Sourcery
|
SourceryTests/Parsing/FileParserSpec.swift
|
1
|
58577
|
import Quick
import Nimble
import PathKit
#if SWIFT_PACKAGE
import Foundation
@testable import SourceryLib
#else
@testable import Sourcery
#endif
@testable import SourceryFramework
@testable import SourceryRuntime
class FileParserSpec: QuickSpec {
// swiftlint:disable function_body_length
override func spec() {
describe("Parser") {
describe("parse") {
func parse(_ code: String, parseDocumentation: Bool = false) -> [Type] {
guard let parserResult = try? makeParser(for: code, parseDocumentation: parseDocumentation).parse() else { fail(); return [] }
return parserResult.types
}
describe("regression files") {
it("doesnt crash on localized strings") {
let templatePath = Stubs.errorsDirectory + Path("localized-error.swift")
guard let content = try? templatePath.read(.utf8) else { return fail() }
_ = parse(content)
}
}
context("given it has sourcery annotations") {
it("extract annotations from extensions properly") {
let result = parse(
"""
// sourcery: forceMockPublisher
public extension AnyPublisher {}
"""
)
let annotations: [String: NSObject] = [
"forceMockPublisher": NSNumber(value: true)
]
expect(result.first?.annotations).to(equal(
annotations
))
}
it("extracts annotation block") {
let annotations = [
["skipEquality": NSNumber(value: true)],
["skipEquality": NSNumber(value: true), "extraAnnotation": NSNumber(value: Float(2))],
[:]
]
let expectedVariables = (1...3)
.map { Variable(name: "property\($0)", typeName: TypeName(name: "Int"), annotations: annotations[$0 - 1], definedInTypeName: TypeName(name: "Foo")) }
let expectedType = Class(name: "Foo", variables: expectedVariables, annotations: ["skipEquality": NSNumber(value: true)])
let result = parse("""
// sourcery:begin: skipEquality
class Foo {
var property1: Int
// sourcery: extraAnnotation = 2
var property2: Int
// sourcery:end
var property3: Int
}
""")
expect(result).to(equal([expectedType]))
}
it("extracts file annotation block") {
let annotations: [[String: NSObject]] = [
["fileAnnotation": NSNumber(value: true), "skipEquality": NSNumber(value: true)],
["fileAnnotation": NSNumber(value: true), "skipEquality": NSNumber(value: true), "extraAnnotation": NSNumber(value: Float(2))],
["fileAnnotation": NSNumber(value: true)]
]
let expectedVariables = (1...3)
.map { Variable(name: "property\($0)", typeName: TypeName(name: "Int"), annotations: annotations[$0 - 1], definedInTypeName: TypeName(name: "Foo")) }
let expectedType = Class(name: "Foo", variables: expectedVariables, annotations: ["fileAnnotation": NSNumber(value: true), "skipEquality": NSNumber(value: true)])
let result = parse("// sourcery:file: fileAnnotation\n" +
"// sourcery:begin: skipEquality\n\n\n\n" +
"class Foo {\n" +
" var property1: Int\n\n\n" +
" // sourcery: extraAnnotation = 2\n" +
" var property2: Int\n\n" +
" // sourcery:end\n" +
" var property3: Int\n" +
"}")
expect(result.first).to(equal(expectedType))
}
}
context("given struct") {
it("extracts properly") {
expect(parse("struct Foo { }"))
.to(equal([
Struct(name: "Foo", accessLevel: .internal, isExtension: false, variables: [])
]))
}
it("extracts import correctly") {
let expectedStruct = Struct(name: "Foo", accessLevel: .internal, isExtension: false, variables: [])
expectedStruct.imports = [
Import(path: "SimpleModule"),
Import(path: "SpecificModule.ClassName")
]
expect(parse("""
import SimpleModule
import SpecificModule.ClassName
struct Foo {}
""").first)
.to(equal(expectedStruct))
}
it("extracts properly with access information") {
expect(parse("public struct Foo { }"))
.to(equal([
Struct(name: "Foo", accessLevel: .public, isExtension: false, variables: [], modifiers: [Modifier(name: "public")])
]))
}
it("extracts properly with access information for extended types via extension") {
let foo = Struct(name: "Foo", accessLevel: .public, isExtension: false, variables: [], modifiers: [Modifier(name: "public")])
expect(parse(
"""
public struct Foo { }
public extension Foo {
struct Boo {}
}
"""
).last)
.to(equal(
Struct(name: "Boo", parent: foo, accessLevel: .public, isExtension: false, variables: [], modifiers: [])
))
}
it("extracts generic struct properly") {
expect(parse("struct Foo<Something> { }"))
.to(equal([
Struct(name: "Foo", isGeneric: true)
]))
}
it("extracts instance variables properly") {
expect(parse("struct Foo { var x: Int }"))
.to(equal([
Struct(name: "Foo", accessLevel: .internal, isExtension: false, variables: [Variable(name: "x", typeName: TypeName(name: "Int"), accessLevel: (read: .internal, write: .internal), isComputed: false, definedInTypeName: TypeName(name: "Foo"))])
]))
}
it("extracts instance variables with custom accessors properly") {
expect(parse("struct Foo { public private(set) var x: Int }"))
.to(equal([
Struct(name: "Foo", accessLevel: .internal, isExtension: false, variables: [
Variable(
name: "x",
typeName: TypeName(name: "Int"),
accessLevel: (read: .public, write: .private),
isComputed: false,
modifiers: [
Modifier(name: "public"),
Modifier(name: "private", detail: "set")
],
definedInTypeName: TypeName(name: "Foo"))
])
]))
}
it("extracts multi-line instance variables definitions properly") {
let defaultValue =
"""
[
"This isn't the simplest to parse",
// Especially with interleaved comments
"but we can deal with it",
// pretty well
"or so we hope"
]
"""
expect(parse(
"""
struct Foo {
var complicatedArray = \(defaultValue)
}
"""
))
.to(equal([
Struct(name: "Foo", accessLevel: .internal, isExtension: false, variables: [
Variable(
name: "complicatedArray",
typeName: TypeName(
name: "[String]",
array: ArrayType(name: "[String]",
elementTypeName: TypeName(name: "String")
),
generic: GenericType(name: "Array", typeParameters: [.init(typeName: TypeName(name: "String"))])
),
accessLevel: (read: .internal, write: .internal),
isComputed: false,
defaultValue: defaultValue,
definedInTypeName: TypeName(name: "Foo")
)])
]))
}
it("extracts instance variables with property setters properly") {
expect(parse(
"""
struct Foo {
var array = [Int]() {
willSet {
print("new value \\(newValue)")
}
}
}
"""
))
.to(equal([
Struct(name: "Foo", accessLevel: .internal, isExtension: false, variables: [
Variable(
name: "array",
typeName: TypeName(
name: "[Int]",
array: ArrayType(name: "[Int]",
elementTypeName: TypeName(name: "Int")
),
generic: GenericType(name: "Array", typeParameters: [.init(typeName: TypeName(name: "Int"))])
),
accessLevel: (read: .internal, write: .internal),
isComputed: false,
defaultValue: "[Int]()",
definedInTypeName: TypeName(name: "Foo")
)])
]))
}
it("extracts computed variables properly") {
expect(parse("struct Foo { var x: Int { return 2 } }"))
.to(equal([
Struct(name: "Foo", accessLevel: .internal, isExtension: false, variables: [
Variable(name: "x", typeName: TypeName(name: "Int"), accessLevel: (read: .internal, write: .none), isComputed: true, isStatic: false, definedInTypeName: TypeName(name: "Foo"))
])
]))
}
it("extracts class variables properly") {
expect(parse("struct Foo { static var x: Int { return 2 }; class var y: Int = 0 }"))
.to(equal([
Struct(name: "Foo", accessLevel: .internal, isExtension: false, variables: [
Variable(name: "x",
typeName: TypeName(name: "Int"),
accessLevel: (read: .internal, write: .none),
isComputed: true,
isStatic: true,
modifiers: [
Modifier(name: "static")
],
definedInTypeName: TypeName(name: "Foo")),
Variable(name: "y",
typeName: TypeName(name: "Int"),
accessLevel: (read: .internal, write: .internal),
isComputed: false,
isStatic: true,
defaultValue: "0",
modifiers: [
Modifier(name: "class")
],
definedInTypeName: TypeName(name: "Foo"))
])
]))
}
context("given nested struct") {
it("extracts properly from body") {
let innerType = Struct(name: "Bar", accessLevel: .internal, isExtension: false, variables: [])
expect(parse("struct Foo { struct Bar { } }"))
.to(equal([
Struct(name: "Foo", accessLevel: .internal, isExtension: false, variables: [], containedTypes: [innerType]),
innerType
]))
}
}
}
context("given class") {
it("extracts variables properly") {
expect(parse("class Foo { var x: Int }"))
.to(equal([
Class(name: "Foo", accessLevel: .internal, isExtension: false, variables: [Variable(name: "x", typeName: TypeName(name: "Int"), accessLevel: (read: .internal, write: .internal), isComputed: false, definedInTypeName: TypeName(name: "Foo"))])
]))
}
it("extracts inherited types properly") {
expect(parse("class Foo: TestProtocol, AnotherProtocol {}").first(where: { $0.name == "Foo" }))
.to(equal(
Class(name: "Foo", accessLevel: .internal, isExtension: false, variables: [], inheritedTypes: ["TestProtocol", "AnotherProtocol"])
))
}
it("extracts annotations correctly") {
let expectedType = Class(name: "Foo", accessLevel: .internal, isExtension: false, variables: [], inheritedTypes: ["TestProtocol"])
expectedType.annotations["firstLine"] = NSNumber(value: true)
expectedType.annotations["thirdLine"] = NSNumber(value: 4543)
expect(parse("// sourcery: thirdLine = 4543\n/// comment\n// sourcery: firstLine\nclass Foo: TestProtocol { }"))
.to(equal([expectedType]))
}
it("extracts documentation correctly") {
let expectedType = Class(name: "Foo", accessLevel: .internal, isExtension: false, variables: [], inheritedTypes: ["TestProtocol"])
expectedType.annotations["thirdLine"] = NSNumber(value: 4543)
expectedType.documentation = ["doc", "comment", "baz"]
expect(parse("/// doc\n// sourcery: thirdLine = 4543\n/// comment\n// firstLine\n///baz\nclass Foo: TestProtocol { }", parseDocumentation: true))
.to(equal([expectedType]))
}
}
context("given typealias") {
func parse(_ code: String) -> FileParserResult {
guard let parserResult = try? makeParser(for: code).parse() else { fail(); return FileParserResult(path: nil, module: nil, types: [], functions: [], typealiases: []) }
return parserResult
}
context("given global typealias") {
it("extracts global typealiases properly") {
expect(parse("typealias GlobalAlias = Foo; class Foo { typealias FooAlias = Int; class Bar { typealias BarAlias = Int } }").typealiases)
.to(equal([
Typealias(aliasName: "GlobalAlias", typeName: TypeName(name: "Foo"))
]))
}
it("extracts typealiases for inner types") {
expect(parse("typealias GlobalAlias = Foo.Bar;").typealiases)
.to(equal([
Typealias(aliasName: "GlobalAlias", typeName: TypeName(name: "Foo.Bar"))
]))
}
it("extracts typealiases of other typealiases") {
expect(parse("typealias Foo = Int; typealias Bar = Foo").typealiases)
.to(contain([
Typealias(aliasName: "Foo", typeName: TypeName(name: "Int")),
Typealias(aliasName: "Bar", typeName: TypeName(name: "Foo"))
]))
}
it("extracts typealias for tuple") {
let typealiase = parse("typealias GlobalAlias = (Foo, Bar)").typealiases.first
expect(typealiase)
.to(equal(
Typealias(aliasName: "GlobalAlias",
typeName: TypeName(name: "(Foo, Bar)", tuple: TupleType(name: "(Foo, Bar)", elements: [.init(name: "0", typeName: .init("Foo")), .init(name: "1", typeName: .init("Bar"))]))
)
))
}
it("extracts typealias for closure") {
expect(parse("typealias GlobalAlias = (Int) -> (String)").typealiases)
.to(equal([
Typealias(aliasName: "GlobalAlias", typeName: TypeName(name: "(Int) -> String", closure: ClosureType(name: "(Int) -> String", parameters: [.init(typeName: TypeName(name: "Int"))], returnTypeName: TypeName(name: "String"))))
]))
}
it("extracts typealias for void closure") {
let parsed = parse("typealias GlobalAlias = () -> ()").typealiases.first
let expected = Typealias(aliasName: "GlobalAlias", typeName: TypeName(name: "() -> ()", closure: ClosureType(name: "() -> ()", parameters: [], returnTypeName: TypeName(name: "()"))))
expect(parsed).to(equal(expected))
}
it("extracts private typealias") {
expect(parse("private typealias GlobalAlias = () -> ()").typealiases)
.to(equal([
Typealias(aliasName: "GlobalAlias", typeName: TypeName(name: "() -> ()", closure: ClosureType(name: "() -> ()", parameters: [], returnTypeName: TypeName(name: "()"))), accessLevel: .private)
]))
}
}
context("given local typealias") {
it("extracts local typealiases properly") {
let foo = Type(name: "Foo")
let bar = Type(name: "Bar", parent: foo)
let fooBar = Type(name: "FooBar", parent: bar)
let types = parse("class Foo { typealias FooAlias = String; struct Bar { typealias BarAlias = Int; struct FooBar { typealias FooBarAlias = Float } } }").types
let fooAliases = types.first?.typealiases
let barAliases = types.first?.containedTypes.first?.typealiases
let fooBarAliases = types.first?.containedTypes.first?.containedTypes.first?.typealiases
expect(fooAliases).to(equal(["FooAlias": Typealias(aliasName: "FooAlias", typeName: TypeName(name: "String"), parent: foo)]))
expect(barAliases).to(equal(["BarAlias": Typealias(aliasName: "BarAlias", typeName: TypeName(name: "Int"), parent: bar)]))
expect(fooBarAliases).to(equal(["FooBarAlias": Typealias(aliasName: "FooBarAlias", typeName: TypeName(name: "Float"), parent: fooBar)]))
}
}
}
context("given a protocol composition") {
context("when used as typeName") {
it("is extracted correctly as return type") {
let expectedFoo = Method(name: "foo()", selectorName: "foo", returnTypeName: TypeName(name: "ProtocolA & ProtocolB", isProtocolComposition: true), definedInTypeName: TypeName(name: "Foo"))
expectedFoo.returnType = ProtocolComposition(name: "ProtocolA & Protocol B")
let expectedFooOptional = Method(name: "fooOptional()", selectorName: "fooOptional", returnTypeName: TypeName(name: "(ProtocolA & ProtocolB)", isOptional: true, isProtocolComposition: true), definedInTypeName: TypeName(name: "Foo"))
expectedFooOptional.returnType = ProtocolComposition(name: "ProtocolA & Protocol B")
let methods = parse("""
protocol Foo {
func foo() -> ProtocolA & ProtocolB
func fooOptional() -> (ProtocolA & ProtocolB)?
}
""")[0].methods
expect(methods[0]).to(equal(expectedFoo))
expect(methods[1]).to(equal(expectedFooOptional))
}
}
context("of two protocols") {
it("extracts protocol composition for typealias with ampersand") {
expect(parse("typealias Composition = Foo & Bar; protocol Foo {}; protocol Bar {}"))
.to(contain([
ProtocolComposition(name: "Composition", inheritedTypes: ["Foo", "Bar"], composedTypeNames: [TypeName(name: "Foo"), TypeName(name: "Bar")])
]))
expect(parse("private typealias Composition = Foo & Bar; protocol Foo {}; protocol Bar {}"))
.to(contain([
ProtocolComposition(name: "Composition", accessLevel: .private, inheritedTypes: ["Foo", "Bar"], composedTypeNames: [TypeName(name: "Foo"), TypeName(name: "Bar")])
]))
}
}
context("of three protocols") {
it("extracts protocol composition for typealias with ampersand") {
expect(parse("typealias Composition = Foo & Bar & Baz; protocol Foo {}; protocol Bar {}; protocol Baz {}"))
.to(contain([
ProtocolComposition(name: "Composition", inheritedTypes: ["Foo", "Bar", "Baz"], composedTypeNames: [TypeName(name: "Foo"), TypeName(name: "Bar"), TypeName(name: "Baz")])
]))
}
it("extracts protocol composition for typealias with ampersand") {
expect(parse("typealias Composition = Foo & Bar & Baz; protocol Foo {}; protocol Bar {}; protocol Baz {}"))
.to(contain([
ProtocolComposition(name: "Composition", inheritedTypes: ["Foo", "Bar", "Baz"], composedTypeNames: [TypeName(name: "Foo"), TypeName(name: "Bar"), TypeName(name: "Baz")])
]))
}
}
context("of a protocol and a class") {
it("extracts protocol composition for typealias with ampersand") {
expect(parse("typealias Composition = Foo & Bar; protocol Foo {}; class Bar {}"))
.to(contain([
ProtocolComposition(name: "Composition", inheritedTypes: ["Foo", "Bar"], composedTypeNames: [TypeName(name: "Foo"), TypeName(name: "Bar")])
]))
}
}
context("given local protocol composition") {
it("extracts local protocol compositions properly") {
let foo = Type(name: "Foo")
let bar = Type(name: "Bar", parent: foo)
let types = parse("protocol P {}; class Foo { typealias FooComposition = Bar & P; class Bar { typealias BarComposition = FooBar & P; class FooBar {} } }")
let fooType = types.first(where: { $0.name == "Foo" })
let fooComposition = fooType?.containedTypes.first
let barComposition = fooType?.containedTypes.last?.containedTypes.first
expect(fooComposition).to(equal(
ProtocolComposition(name: "FooComposition", parent: foo, inheritedTypes: ["Bar", "P"], composedTypeNames: [TypeName(name: "Bar"), TypeName(name: "P")])))
expect(barComposition).to(equal(
ProtocolComposition(name: "BarComposition", parent: bar, inheritedTypes: ["FooBar", "P"], composedTypeNames: [TypeName(name: "FooBar"), TypeName(name: "P")])))
}
}
}
context("given enum") {
it("extracts empty enum properly") {
expect(parse("enum Foo { }"))
.to(equal([
Enum(name: "Foo", accessLevel: .internal, isExtension: false, inheritedTypes: [], cases: [])
]))
}
it("extracts cases properly") {
expect(parse("enum Foo { case optionA; case optionB }"))
.to(equal([
Enum(name: "Foo", accessLevel: .internal, isExtension: false, inheritedTypes: [], cases: [EnumCase(name: "optionA"), EnumCase(name: "optionB")])
]))
}
it("extracts cases with special names") {
expect(parse("""
enum Foo {
case `default`
case `for`(something: Int, else: Float, `default`: Bool)
}
"""))
.to(equal([
Enum(name: "Foo", accessLevel: .internal, isExtension: false, inheritedTypes: [], cases: [
EnumCase(name: "`default`"),
EnumCase(name: "`for`", associatedValues:
[
AssociatedValue(name: "something", typeName: TypeName(name: "Int")),
AssociatedValue(name: "else", typeName: TypeName(name: "Float")),
AssociatedValue(name: "`default`", typeName: TypeName(name: "Bool"))
])])
]))
}
it("extracts multi-byte cases properly") {
expect(parse("enum JapaneseEnum {\ncase アイウエオ\n}"))
.to(equal([
Enum(name: "JapaneseEnum", cases: [EnumCase(name: "アイウエオ")])
]))
}
context("given enum cases annotations") {
it("extracts cases with annotations properly") {
expect(parse("""
enum Foo {
// sourcery:begin: block
// sourcery: first, second=\"value\"
case optionA(/* sourcery: first, second = \"value\" */Int)
// sourcery: third
case optionB
case optionC
// sourcery:end
}
"""))
.to(equal([
Enum(name: "Foo", cases: [
EnumCase(name: "optionA", associatedValues: [
AssociatedValue(name: nil, typeName: TypeName(name: "Int"), annotations: [
"first": NSNumber(value: true),
"second": "value" as NSString,
"block": NSNumber(value: true)
])
], annotations: [
"block": NSNumber(value: true),
"first": NSNumber(value: true),
"second": "value" as NSString
]
),
EnumCase(name: "optionB", annotations: [
"block": NSNumber(value: true),
"third": NSNumber(value: true)
]
),
EnumCase(name: "optionC", annotations: [
"block": NSNumber(value: true)
])
])
]))
}
it("extracts cases with inline annotations properly") {
expect(parse("""
enum Foo {
//sourcery:begin: block
/* sourcery: first, second = \"value\" */ case optionA(/* sourcery: first, second = \"value\" */Int);
/* sourcery: third */ case optionB
case optionC
//sourcery:end
}
""").first)
.to(equal(
Enum(name: "Foo", cases: [
EnumCase(name: "optionA", associatedValues: [
AssociatedValue(name: nil, typeName: TypeName(name: "Int"), annotations: [
"first": NSNumber(value: true),
"second": "value" as NSString,
"block": NSNumber(value: true)
])
], annotations: [
"block": NSNumber(value: true),
"first": NSNumber(value: true),
"second": "value" as NSString
]),
EnumCase(name: "optionB", annotations: [
"block": NSNumber(value: true),
"third": NSNumber(value: true)
]),
EnumCase(name: "optionC", annotations: [
"block": NSNumber(value: true)
])
])
))
}
it("extracts one line cases with inline annotations properly") {
expect(parse("""
enum Foo {
//sourcery:begin: block
case /* sourcery: first, second = \"value\" */ optionA(Int), /* sourcery: third, fourth = \"value\" */ optionB, optionC
//sourcery:end
}
""").first)
.to(equal(
Enum(name: "Foo", cases: [
EnumCase(name: "optionA", associatedValues: [
AssociatedValue(name: nil, typeName: TypeName(name: "Int"), annotations: [
"block": NSNumber(value: true)
])
], annotations: [
"block": NSNumber(value: true),
"first": NSNumber(value: true),
"second": "value" as NSString
]),
EnumCase(name: "optionB", annotations: [
"block": NSNumber(value: true),
"third": NSNumber(value: true),
"fourth": "value" as NSString
]),
EnumCase(name: "optionC", annotations: [
"block": NSNumber(value: true)
])
])
))
}
it("extracts cases with annotations and computed variables properly") {
expect(parse("""
enum Foo {
// sourcery: var
var first: Int { return 0 }
// sourcery: first, second=\"value\"
case optionA(Int)
// sourcery: var
var second: Int { return 0 }
// sourcery: third
case optionB
case optionC }
""").first)
.to(equal(
Enum(name: "Foo", cases: [
EnumCase(name: "optionA", associatedValues: [
AssociatedValue(name: nil, typeName: TypeName(name: "Int"))
], annotations: [
"first": NSNumber(value: true),
"second": "value" as NSString
]),
EnumCase(name: "optionB", annotations: [
"third": NSNumber(value: true)
]),
EnumCase(name: "optionC")
], variables: [
Variable(name: "first", typeName: TypeName(name: "Int"), accessLevel: (.internal, .none), isComputed: true, annotations: [ "var": NSNumber(value: true) ], definedInTypeName: TypeName(name: "Foo")),
Variable(name: "second", typeName: TypeName(name: "Int"), accessLevel: (.internal, .none), isComputed: true, annotations: [ "var": NSNumber(value: true) ], definedInTypeName: TypeName(name: "Foo"))
])
))
}
}
it("extracts associated value annotations properly") {
let result = parse("""
enum Foo {
case optionA(
// sourcery: first
// sourcery: second, third = "value"
Int)
case optionB
}
""")
expect(result)
.to(equal([
Enum(name: "Foo",
cases: [
EnumCase(name: "optionA", associatedValues: [
AssociatedValue(name: nil, typeName: TypeName(name: "Int"), annotations: ["first": NSNumber(value: true), "second": NSNumber(value: true), "third": "value" as NSString])
]),
EnumCase(name: "optionB")
])
]))
}
it("extracts associated value inline annotations properly") {
let result = parse("enum Foo {\n case optionA(/* sourcery: annotation*/Int)\n case optionB }")
expect(result)
.to(equal([
Enum(name: "Foo",
cases: [
EnumCase(name: "optionA", associatedValues: [
AssociatedValue(name: nil, typeName: TypeName(name: "Int"), annotations: ["annotation": NSNumber(value: true)])
]),
EnumCase(name: "optionB")
])
]))
}
it("extracts variables properly") {
expect(parse("enum Foo { var x: Int { return 1 } }"))
.to(equal([
Enum(name: "Foo", accessLevel: .internal, isExtension: false, inheritedTypes: [], cases: [], variables: [Variable(name: "x", typeName: TypeName(name: "Int"), accessLevel: (.internal, .none), isComputed: true, definedInTypeName: TypeName(name: "Foo"))])
]))
}
context("given enum without rawType") {
it("extracts inherited types properly") {
expect(parse("enum Foo: SomeProtocol { case optionA }; protocol SomeProtocol {}"))
.to(equal([
Enum(name: "Foo", accessLevel: .internal, isExtension: false, inheritedTypes: ["SomeProtocol"], rawTypeName: nil, cases: [EnumCase(name: "optionA")]),
Protocol(name: "SomeProtocol")
]))
}
}
it("extracts enums with custom values") {
expect(parse("""
enum Foo: String {
case optionA = "Value"
}
"""))
.to(equal([
Enum(name: "Foo", accessLevel: .internal, isExtension: false, inheritedTypes: ["String"], cases: [EnumCase(name: "optionA", rawValue: "Value")])
]))
expect(parse("""
enum Foo: Int {
case optionA = 2
}
"""))
.to(equal([
Enum(name: "Foo", accessLevel: .internal, isExtension: false, inheritedTypes: ["Int"], cases: [EnumCase(name: "optionA", rawValue: "2")])
]))
expect(parse("""
enum Foo: Int {
case optionA = -1
case optionB = 0
}
"""))
.to(equal([
Enum(
name: "Foo",
accessLevel: .internal,
isExtension: false,
inheritedTypes: ["Int"],
cases: [
EnumCase(name: "optionA", rawValue: "-1"),
EnumCase(name: "optionB", rawValue: "0")
])
]))
}
it("extracts enums without rawType") {
let expectedEnum = Enum(name: "Foo", accessLevel: .internal, isExtension: false, inheritedTypes: [], cases: [EnumCase(name: "optionA")])
expect(parse("enum Foo { case optionA }")).to(equal([expectedEnum]))
}
it("extracts enums with associated types") {
expect(parse("enum Foo { case optionA(Observable<Int, Int>); case optionB(Int, named: Float, _: Int); case optionC(dict: [String: String]) }"))
.to(equal([
Enum(name: "Foo", accessLevel: .internal, isExtension: false, inheritedTypes: [], cases:
[
EnumCase(name: "optionA", associatedValues: [
AssociatedValue(localName: nil, externalName: nil, typeName: TypeName(name: "Observable<Int, Int>", generic: GenericType(
name: "Observable", typeParameters: [
GenericTypeParameter(typeName: TypeName(name: "Int")),
GenericTypeParameter(typeName: TypeName(name: "Int"))
])))
]),
EnumCase(name: "optionB", associatedValues: [
AssociatedValue(localName: nil, externalName: "0", typeName: TypeName(name: "Int")),
AssociatedValue(localName: "named", externalName: "named", typeName: TypeName(name: "Float")),
AssociatedValue(localName: nil, externalName: "2", typeName: TypeName(name: "Int"))
]),
EnumCase(name: "optionC", associatedValues: [
AssociatedValue(localName: "dict", externalName: nil, typeName: TypeName(name: "[String: String]", dictionary: DictionaryType(name: "[String: String]", valueTypeName: TypeName(name: "String"), keyTypeName: TypeName(name: "String")), generic: GenericType(name: "Dictionary", typeParameters: [GenericTypeParameter(typeName: TypeName(name: "String")), GenericTypeParameter(typeName: TypeName(name: "String"))])))
])
])
]))
}
it("extracts enums with indirect cases") {
expect(parse("enum Foo { case optionA; case optionB; indirect case optionC(Foo) }"))
.to(equal([
Enum(name: "Foo", accessLevel: .internal, isExtension: false, inheritedTypes: [], cases:
[
EnumCase(name: "optionA", indirect: false),
EnumCase(name: "optionB"),
EnumCase(name: "optionC", associatedValues: [AssociatedValue(typeName: TypeName(name: "Foo"))], indirect: true)
])
]))
expect(parse("""
enum Foo {
/// Option A
case optionA
/// Option B
case optionB
/// Option C
indirect case optionC(Foo)
}
""", parseDocumentation: true))
.to(equal([
Enum(name: "Foo", accessLevel: .internal, isExtension: false, inheritedTypes: [], cases:
[
EnumCase(name: "optionA", documentation: ["Option A"], indirect: false),
EnumCase(name: "optionB", documentation: ["Option B"]),
EnumCase(name: "optionC", associatedValues: [AssociatedValue(typeName: TypeName(name: "Foo"))], documentation: ["Option C"], indirect: true)
])
]))
}
it("extracts enums with Void associated type") {
expect(parse("enum Foo { case optionA(Void); case optionB(Void) }"))
.to(equal([
Enum(name: "Foo", accessLevel: .internal, isExtension: false, inheritedTypes: [], cases:
[
EnumCase(name: "optionA", associatedValues: [AssociatedValue(typeName: TypeName(name: "Void"))]),
EnumCase(name: "optionB", associatedValues: [AssociatedValue(typeName: TypeName(name: "Void"))])
])
]))
}
it("extracts default values for associated values") {
expect(parse("enum Foo { case optionA(Int = 1, named: Float = 42.0, _: Bool = false); case optionB(Bool = true) }"))
.to(equal([
Enum(name: "Foo", accessLevel: .internal, isExtension: false, inheritedTypes: [], cases:
[
EnumCase(name: "optionA", associatedValues: [
AssociatedValue(localName: nil, externalName: "0", typeName: TypeName(name: "Int"), defaultValue: "1"),
AssociatedValue(localName: "named", externalName: "named", typeName: TypeName(name: "Float"), defaultValue: "42.0"),
AssociatedValue(localName: nil, externalName: "2", typeName: TypeName(name: "Bool"), defaultValue: "false")
]),
EnumCase(name: "optionB", associatedValues: [
AssociatedValue(localName: nil, externalName: nil, typeName: TypeName(name: "Bool"), defaultValue: "true")
])
])
]))
}
}
context("given protocol") {
it("extracts generic requirements properly") {
expect(parse(
"""
protocol SomeGenericProtocol: GenericProtocol {}
"""
).first).to(equal(
Protocol(name: "SomeGenericProtocol", inheritedTypes: ["GenericProtocol"])
))
expect(parse(
"""
protocol SomeGenericProtocol: GenericProtocol where LeftType == RightType {}
"""
).first).to(equal(
Protocol(
name: "SomeGenericProtocol",
inheritedTypes: ["GenericProtocol"],
genericRequirements: [
GenericRequirement(leftType: .init(name: "LeftType"), rightType: .init(typeName: .init("RightType")), relationship: .equals)
])
))
expect(parse(
"""
protocol SomeGenericProtocol: GenericProtocol where LeftType: RightType {}
"""
).first).to(equal(
Protocol(
name: "SomeGenericProtocol",
inheritedTypes: ["GenericProtocol"],
genericRequirements: [
GenericRequirement(leftType: .init(name: "LeftType"), rightType: .init(typeName: .init("RightType")), relationship: .conformsTo)
])
))
expect(parse(
"""
protocol SomeGenericProtocol: GenericProtocol where LeftType == RightType, LeftType2: RightType2 {}
"""
).first).to(equal(
Protocol(
name: "SomeGenericProtocol",
inheritedTypes: ["GenericProtocol"],
genericRequirements: [
GenericRequirement(leftType: .init(name: "LeftType"), rightType: .init(typeName: .init("RightType")), relationship: .equals),
GenericRequirement(leftType: .init(name: "LeftType2"), rightType: .init(typeName: .init("RightType2")), relationship: .conformsTo)
])
))
}
it("extracts empty protocol properly") {
expect(parse("protocol Foo { }"))
.to(equal([
Protocol(name: "Foo")
]))
}
it("does not consider protocol variables as computed") {
expect(parse("protocol Foo { var some: Int { get } }"))
.to(equal([
Protocol(name: "Foo", variables: [Variable(name: "some", typeName: TypeName(name: "Int"), accessLevel: (.internal, .none), isComputed: false, definedInTypeName: TypeName(name: "Foo"))])
]))
}
it("does consider type variables as computed when they are, even if they adhere to protocol") {
expect(parse("protocol Foo { var some: Int { get }\nvar some2: Int { get } }\nclass Bar: Foo { var some: Int { return 2 }\nvar some2: Int { get { return 2 } } }").first(where: { $0.name == "Bar" }))
.to(equal(
Class(name: "Bar", variables: [
Variable(name: "some", typeName: TypeName(name: "Int"), accessLevel: (.internal, .none), isComputed: true, definedInTypeName: TypeName(name: "Bar")),
Variable(name: "some2", typeName: TypeName(name: "Int"), accessLevel: (.internal, .none), isComputed: true, definedInTypeName: TypeName(name: "Bar"))
], inheritedTypes: ["Foo"])
))
}
it("does not consider type variables as computed when they aren't, even if they adhere to protocol and have didSet blocks") {
expect(parse("protocol Foo { var some: Int { get } }\nclass Bar: Foo { var some: Int { didSet { } }").first(where: { $0.name == "Bar" }))
.to(equal(
Class(name: "Bar", variables: [Variable(name: "some", typeName: TypeName(name: "Int"), accessLevel: (.internal, .internal), isComputed: false, definedInTypeName: TypeName(name: "Bar"))], inheritedTypes: ["Foo"])
))
}
it("sets members access level to protocol access level") {
func assert(_ accessLevel: AccessLevel, line: UInt = #line) {
expect(line: line, parse("\(accessLevel) protocol Foo { var some: Int { get }; func foo() -> Void }"))
.to(equal([
Protocol(name: "Foo", accessLevel: accessLevel, variables: [Variable(name: "some", typeName: TypeName(name: "Int"), accessLevel: (accessLevel, .none), isComputed: false, definedInTypeName: TypeName(name: "Foo"))], methods: [Method(name: "foo()", selectorName: "foo", returnTypeName: TypeName(name: "Void"), throws: false, rethrows: false, accessLevel: accessLevel, definedInTypeName: TypeName(name: "Foo"))], modifiers: [Modifier(name: "\(accessLevel)")])
]))
}
assert(.private)
assert(.internal)
assert(.private)
}
}
}
}
}
}
|
mit
|
f7dacfb05774e6e43a66afcf3d5244ba
| 60.768987 | 491 | 0.3749 | 6.696055 | false | false | false | false |
calkinssean/woodshopBMX
|
WoodshopBMX/Pods/Charts/Charts/Classes/Charts/BarChartView.swift
|
7
|
5806
|
//
// BarChartView.swift
// Charts
//
// Created by Daniel Cohen Gindi on 4/3/15.
//
// Copyright 2015 Daniel Cohen Gindi & Philipp Jahoda
// A port of MPAndroidChart for iOS
// Licensed under Apache License 2.0
//
// https://github.com/danielgindi/ios-charts
//
import Foundation
import CoreGraphics
/// Chart that draws bars.
public class BarChartView: BarLineChartViewBase, BarChartDataProvider
{
/// flag that enables or disables the highlighting arrow
private var _drawHighlightArrowEnabled = false
/// if set to true, all values are drawn above their bars, instead of below their top
private var _drawValueAboveBarEnabled = true
/// if set to true, a grey area is drawn behind each bar that indicates the maximum value
private var _drawBarShadowEnabled = false
internal override func initialize()
{
super.initialize()
renderer = BarChartRenderer(dataProvider: self, animator: _animator, viewPortHandler: _viewPortHandler)
_xAxisRenderer = ChartXAxisRendererBarChart(viewPortHandler: _viewPortHandler, xAxis: _xAxis, transformer: _leftAxisTransformer, chart: self)
self.highlighter = BarChartHighlighter(chart: self)
_xAxis._axisMinimum = -0.5
}
internal override func calcMinMax()
{
super.calcMinMax()
guard let data = _data else { return }
let barData = data as! BarChartData
// increase deltax by 1 because the bars have a width of 1
_xAxis.axisRange += 0.5
// extend xDelta to make space for multiple datasets (if ther are one)
_xAxis.axisRange *= Double(data.dataSetCount)
let groupSpace = barData.groupSpace
_xAxis.axisRange += Double(barData.xValCount) * Double(groupSpace)
_xAxis._axisMaximum = _xAxis.axisRange - _xAxis._axisMinimum
}
/// - returns: the Highlight object (contains x-index and DataSet index) of the selected value at the given touch point inside the BarChart.
public override func getHighlightByTouchPoint(pt: CGPoint) -> ChartHighlight?
{
if _data === nil
{
Swift.print("Can't select by touch. No data set.")
return nil
}
return self.highlighter?.getHighlight(x: Double(pt.x), y: Double(pt.y))
}
/// - returns: the bounding box of the specified Entry in the specified DataSet. Returns null if the Entry could not be found in the charts data.
public func getBarBounds(e: BarChartDataEntry) -> CGRect
{
guard let
set = _data?.getDataSetForEntry(e) as? IBarChartDataSet
else { return CGRectNull }
let barspace = set.barSpace
let y = CGFloat(e.value)
let x = CGFloat(e.xIndex)
let barWidth: CGFloat = 0.5
let spaceHalf = barspace / 2.0
let left = x - barWidth + spaceHalf
let right = x + barWidth - spaceHalf
let top = y >= 0.0 ? y : 0.0
let bottom = y <= 0.0 ? y : 0.0
var bounds = CGRect(x: left, y: top, width: right - left, height: bottom - top)
getTransformer(set.axisDependency).rectValueToPixel(&bounds)
return bounds
}
public override var lowestVisibleXIndex: Int
{
let step = CGFloat(_data?.dataSetCount ?? 0)
let div = (step <= 1.0) ? 1.0 : step + (_data as! BarChartData).groupSpace
var pt = CGPoint(x: _viewPortHandler.contentLeft, y: _viewPortHandler.contentBottom)
getTransformer(ChartYAxis.AxisDependency.Left).pixelToValue(&pt)
return Int((pt.x <= CGFloat(chartXMin)) ? 0.0 : (pt.x / div) + 1.0)
}
public override var highestVisibleXIndex: Int
{
let step = CGFloat(_data?.dataSetCount ?? 0)
let div = (step <= 1.0) ? 1.0 : step + (_data as! BarChartData).groupSpace
var pt = CGPoint(x: _viewPortHandler.contentRight, y: _viewPortHandler.contentBottom)
getTransformer(ChartYAxis.AxisDependency.Left).pixelToValue(&pt)
return Int((pt.x >= CGFloat(chartXMax)) ? CGFloat(chartXMax) / div : (pt.x / div))
}
// MARK: Accessors
/// flag that enables or disables the highlighting arrow
public var drawHighlightArrowEnabled: Bool
{
get { return _drawHighlightArrowEnabled; }
set
{
_drawHighlightArrowEnabled = newValue
setNeedsDisplay()
}
}
/// if set to true, all values are drawn above their bars, instead of below their top
public var drawValueAboveBarEnabled: Bool
{
get { return _drawValueAboveBarEnabled; }
set
{
_drawValueAboveBarEnabled = newValue
setNeedsDisplay()
}
}
/// if set to true, a grey area is drawn behind each bar that indicates the maximum value
public var drawBarShadowEnabled: Bool
{
get { return _drawBarShadowEnabled; }
set
{
_drawBarShadowEnabled = newValue
setNeedsDisplay()
}
}
// MARK: - BarChartDataProbider
public var barData: BarChartData? { return _data as? BarChartData }
/// - returns: true if drawing the highlighting arrow is enabled, false if not
public var isDrawHighlightArrowEnabled: Bool { return drawHighlightArrowEnabled }
/// - returns: true if drawing values above bars is enabled, false if not
public var isDrawValueAboveBarEnabled: Bool { return drawValueAboveBarEnabled }
/// - returns: true if drawing shadows (maxvalue) for each bar is enabled, false if not
public var isDrawBarShadowEnabled: Bool { return drawBarShadowEnabled }
}
|
apache-2.0
|
8b8195f9bf51bf9a4c97fd5a6b44c8c9
| 33.772455 | 149 | 0.628832 | 4.992261 | false | false | false | false |
ZeroFengLee/CmdBluetooth
|
CmdBluetooth/CmdBluetoothCore/CmdConnecter.swift
|
1
|
4067
|
//
// CmdConnecter.swift
// CmdBluetooth
//
// Created by Zero on 16/8/4.
// Copyright © 2016年 Zero. All rights reserved.
//
import Foundation
import CoreBluetooth
class CmdConnecter: CentralManagerConnectionDelegate {
typealias SuccessHandle = ((_ central: CBCentralManager, _ peripheral: CBPeripheral) -> Void)
typealias FailHandle = ((_ error: NSError?) -> Void)
var centralManager: CBCentralManager?
var discovery: CmdDiscovery?
var parser: CmdParserSession?
var autoConnect = false
fileprivate var connectTimer: Timer?
fileprivate var successHandle: SuccessHandle?
fileprivate var failHandle: FailHandle?
fileprivate var lastPeripheral: CBPeripheral?
fileprivate var isCancel = false
/**
no central manager, discovery -> return false
*/
func connectWithDuration(_ duration: TimeInterval, connectSuccess: SuccessHandle?, failHandle:FailHandle?) -> Bool {
guard let centralManager = self.centralManager, let discovery = self.discovery else {
return false
}
self.successHandle = connectSuccess
self.failHandle = failHandle
invalidateTimer()
connectTimer = Timer.scheduledTimer(timeInterval: duration, target: self, selector: #selector(CmdConnecter.timeOut), userInfo: nil, repeats: false)
if let lastPeripheral = lastPeripheral {
self.cancel(centralManager, peripheral: lastPeripheral)
}
centralManager.connect(discovery.peripheral, options: nil)
return true
}
func connectLastPeripheral() {
if let centralManager = centralManager, let lastPeripheral = lastPeripheral {
centralManager.connect(lastPeripheral, options: nil)
}
}
func disConnect() {
guard let discovery = self.discovery else { return }
self.cancel(centralManager, peripheral: discovery.peripheral)
}
//MARK: CentralManagerConnectionDelegate
func centralManager(_ central: CBCentralManager, didConnectPeripheral peripheral: CBPeripheral) {
NotificationCenter.default.post(name: Notification.Name(rawValue: CmdConnectStateNotify), object: true)
self.lastPeripheral = peripheral
self.invalidateTimer()
guard let parser = self.parser else { return }
parser.isFree = true
parser.connected = true
parser.peripheral = peripheral
parser.startRetrivePeripheral{ [weak self] () in
guard let `self` = self else { return }
self.successHandle?(central, peripheral)
}
}
func centralManager(_ central: CBCentralManager, didFailToConnectPeripheral peripheral: CBPeripheral, error: NSError?) {
if let failHandle = self.failHandle {
failHandle(error)
}
}
func centralManager(_ central: CBCentralManager, didDisconnectPeripheral peripheral: CBPeripheral, error: NSError?) {
NotificationCenter.default.post(name: Notification.Name(rawValue: CmdConnectStateNotify), object: false)
parser?.connected = false
if isCancel {
self.lastPeripheral = nil
isCancel = false
return
}
if autoConnect {
central.connect(peripheral, options: nil)
}
}
//MARK: Private Method
@objc fileprivate func timeOut() {
if let failHandle = self.failHandle {
let timeoutError = NSError(domain: "com.zero.ble", code: -1008, userInfo: ["msg" : "connect timeout"])
failHandle(timeoutError)
}
self.disConnect()
}
fileprivate func cancel(_ central: CBCentralManager?, peripheral: CBPeripheral?) {
isCancel = true
self.invalidateTimer()
if let centralManager = centralManager, let peripheral = peripheral {
centralManager.cancelPeripheralConnection(peripheral)
}
}
fileprivate func invalidateTimer() {
connectTimer?.invalidate()
self.connectTimer = nil
}
}
|
mit
|
d84ac100f661846024c188c572b0eea9
| 34.649123 | 155 | 0.658465 | 5.170483 | false | false | false | false |
Takanu/Pelican
|
Sources/Pelican/API/Types/Chat/ChatMember.swift
|
1
|
3593
|
//
// ChatMember.swift
// Pelican
//
// Created by Takanu Kyriako on 31/08/2017.
//
import Foundation
/**
Defines the status of a chat member, in a group.
*/
public enum ChatMemberStatus: String, Codable {
case creator = "creator", administrator, member, restricted, left, kicked
}
/**
Contains information about one member of a chat.
*/
public struct ChatMember: Codable {
// BASIC INFORMATION
/// Information about the user.
public var user: User
/// The member's status in the chat.
public var status: ChatMemberStatus
/// The date when restrictions will be lifted for this user (if their `status` is "restricted"), in unix time.
public var restrictedUntilDate: Int?
/// If true, the bot is able to edit administrator priviliges of that user.
public var isEditable: Bool?
// ADMINISTRATOR PRIVILEGES
/// If true, this administrator can change the chat title, chat photo and other settings.
public var canChangeInfo: Bool?
/// If true, this administrator can post in the channel (applies to channels only).
public var canPostChannelMessages: Bool?
/// If true, this administrator can edit the messages of other users and pin messages (applies to channels only).
public var canEditChannelMessages: Bool?
/// If true, this administrator can delete messages that other users have posted to the chat.
public var canDeleteMessages: Bool?
/// If true, this administrator can invite new users to the chat.
public var canInviteUsers: Bool?
/// If true, this administrator can restrict, ban or unban chat members.
public var canRestrictMembers: Bool?
/// If true, this administrator can pin messages.
public var canPinMessages: Bool?
/**
If true, this administrator can add new administrators with a subset of his own privileges or demote administrators that he has promoted, directly or indirectly (promoted by administrators that were appointed by the user).
*/
public var canPromoteMembers: Bool?
// MEMBER RESTRICTIONS
/// If true, the user can send text messages, contacts, locations and venues to the chat.
public var canSendMessages: Bool?
/// If true, the user can send audio files, documents, photos, videos, video notes and voice notes. For this to be true, `canSendMessages` must also be true.
public var canSendMediaMessages: Bool?
/// If true, the user can send animations, games, stickers as well as use inline bots. For this to be true, 'canSendMediaMessages' must also be true.
public var canSendOtherMessages: Bool?
/// If true, the user may add web page previews to his messages. For this to be true, 'canSendOtherMessages' must also be true.
public var canAddWebPagePreviews: Bool?
/// Coding keys to map values when Encoding and Decoding.
enum CodingKeys: String, CodingKey {
case user
case status
case restrictedUntilDate = "until_date"
case isEditable = "can_be_edited"
case canChangeInfo = "can_change_info"
case canPostChannelMessages = "can_post_messages"
case canEditChannelMessages = "can_edit_messages"
case canDeleteMessages = "can_delete_messages"
case canInviteUsers = "can_invite_users"
case canRestrictMembers = "can_restrict_members"
case canPinMessages = "can_pin_messages"
case canPromoteMembers = "can_promote_members"
case canSendMessages = "can_send_messages"
case canSendMediaMessages = "can_send_media_messages"
case canSendOtherMessages = "can_send_other_messages"
case canAddWebPagePreviews = "can_add_web_page_previews"
}
public init(user: User, status: ChatMemberStatus) {
self.user = user
self.status = status
}
}
|
mit
|
8128b36b387c1101337731a3fade7e4c
| 32.579439 | 223 | 0.744225 | 3.802116 | false | false | false | false |
Shannon-Yang/SYNetworking
|
SYNetworkingTests/Request/SYNetworkingCacheRequest.swift
|
1
|
1019
|
//
// SYNetworkingCacheRequest.swift
// SYNetworking
//
// Created by Shannon Yang on 2017/2/4.
// Copyright © 2017年 Hangzhou Yunti Technology Co. Ltd. All rights reserved.
//
import Foundation
import Alamofire
import ObjectMapper
import SwiftyJSON
import SYNetworking
class SYNetworkingCacheRequest: SYDataRequest {
let requestUrlString: String
let method: HTTPMethod
let parameters: [String : Any]?
init(requestUrlString: String, method: HTTPMethod = .post, parameters: [String : Any]? = nil) {
self.requestUrlString = requestUrlString
self.method = method
self.parameters = parameters
super.init()
}
override var requestURLString: String {
return self.requestUrlString
}
override var requestMethod: HTTPMethod {
return self.method
}
override var requestParameters: [String : Any]? {
return self.parameters
}
override var cacheTimeInSeconds: Int {
return 1000
}
}
|
mit
|
cbe8ca586baab9f5b5c163c757bfaf2f
| 22.090909 | 99 | 0.669291 | 4.618182 | false | false | false | false |
Rhumbix/SwiftyPaperTrail
|
SwiftyPaperTrail/DefaultLoggerFactory+Extensions.swift
|
1
|
1285
|
//
// DefaultLoggerFactory+Extensions.swift
// SwiftyPaperTrail
//
// Created by Mark Eschbach on 1/2/17.
// Copyright © 2017 Rhumbix, Inc. All rights reserved.
//
import SwiftyLogger
public extension LoggerFactory {
public func addSyslog( to host : String, tcp port : Int ) -> LoggerFactory {
guard let realPort = UInt16(exactly: port) else {
fatalError("Port given \(port) is outside of TCP port range")
}
let target = SwiftyPaperTrail.withTCP(to: host, at: realPort)
self.addTarget(target)
return self
}
public func addSyslog( to host : String, tls port : Int ) -> LoggerFactory {
guard let realPort = UInt16(exactly: port) else {
fatalError("Port given \(port) is outside of TCP port range")
}
let target = SwiftyPaperTrail.withTLSoverTCP(to: host, at: realPort)
self.addTarget(target)
return self
}
public func addSyslog( to host : String, udp port : Int ) -> LoggerFactory {
guard let realPort = UInt16(exactly: port) else {
fatalError("Port given \(port) is outside of UDP port range")
}
let target = SwiftyPaperTrail.withUDP(to: host, at: realPort)
self.addTarget(target)
return self
}
}
|
mit
|
6a95d582f0ed0600e0b72d59650d8d1b
| 32.789474 | 80 | 0.633178 | 3.962963 | false | false | false | false |
adelinofaria/Buildasaur
|
Buildasaur/BranchWatchingViewController.swift
|
2
|
3775
|
//
// BranchWatchingViewController.swift
// Buildasaur
//
// Created by Honza Dvorsky on 23/05/2015.
// Copyright (c) 2015 Honza Dvorsky. All rights reserved.
//
import Foundation
import AppKit
import BuildaGitServer
import BuildaUtils
class BranchWatchingViewController: NSViewController, NSTableViewDelegate, NSTableViewDataSource {
//these two must be set before viewDidLoad by its presenting view controller
var syncer: HDGitHubXCBotSyncer!
var watchedBranchNames: Set<String>!
private var branches: [Branch] = []
@IBOutlet weak var branchActivityIndicator: NSProgressIndicator!
@IBOutlet weak var branchesTableView: NSTableView!
override func viewDidLoad() {
super.viewDidLoad()
assert(self.syncer != nil, "Syncer has not been set")
self.watchedBranchNames = Set(self.syncer.watchedBranchNames)
}
override func viewWillAppear() {
super.viewWillAppear()
self.fetchBranches { (branches, error) -> () in
if let error = error {
UIUtils.showAlertWithError(error)
}
self.branchesTableView.reloadData()
}
}
func fetchBranches(completion: ([Branch]?, NSError?) -> ()) {
self.branchActivityIndicator.startAnimation(nil)
let repoName = self.syncer.localSource.githubRepoName()!
self.syncer.github.getBranchesOfRepo(repoName, completion: { (branches, error) -> () in
NSOperationQueue.mainQueue().addOperationWithBlock({ () -> Void in
if let branches = branches {
self.branches = branches
}
completion(branches, error)
self.branchActivityIndicator.stopAnimation(nil)
})
})
}
@IBAction func cancelTapped(sender: AnyObject) {
self.dismissController(nil)
}
@IBAction func doneTapped(sender: AnyObject) {
//save the now-selected watched branches to the syncer
self.syncer.watchedBranchNames = Array(self.watchedBranchNames)
StorageManager.sharedInstance.saveSyncers() //think of a better way to force saving
self.dismissController(nil)
}
//MARK: branches table view
func numberOfRowsInTableView(tableView: NSTableView) -> Int {
if tableView == self.branchesTableView {
return self.branches.count
}
return 0
}
func tableView(tableView: NSTableView, objectValueForTableColumn tableColumn: NSTableColumn?, row: Int) -> AnyObject? {
if tableView == self.branchesTableView {
switch tableColumn!.identifier {
case "name":
let branch = self.branches[row]
return branch.name
case "enabled":
let branch = self.branches[row]
return self.watchedBranchNames.contains(branch.name)
default:
return nil
}
}
return nil
}
@IBAction func branchesTableViewRowCheckboxTapped(sender: AnyObject) {
//toggle selection in model
let branch = self.branches[self.branchesTableView.selectedRow]
let branchName = branch.name
//see if we are checking or unchecking
let previouslyEnabled = self.watchedBranchNames.contains(branchName)
if previouslyEnabled {
//disable
self.watchedBranchNames.remove(branchName)
} else {
//enable
self.watchedBranchNames.insert(branchName)
}
}
}
|
mit
|
af5008d34bcd7f7eb159459b01f69755
| 29.699187 | 123 | 0.596291 | 5.576071 | false | false | false | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.