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
cpageler93/ConsulSwift
Tests/ConsulSwiftTests/ConsulHealthTests.swift
1
5151
// // ConsulHealthTests.swift // ConsulSwiftTests // // Created by Christoph Pageler on 20.06.17. // import XCTest @testable import ConsulSwift class ConsulHealthTests: XCTestCase { override func setUp() { super.setUp() // Put setup code here. This method is called before the invocation of each test method in the class. } override func tearDown() { // Put teardown code here. This method is called after the invocation of each test method in the class. super.tearDown() } static var allTests = [ ("test2HealthChecksForNode", test2HealthChecksForNode), ("test2HealthChecksForNodeAsync", test2HealthChecksForNodeAsync), ("test2HealthNodesForService", test2HealthNodesForService), ("test2HealthNodesForServiceAsync", test2HealthNodesForServiceAsync), ("testHealthListChecksInState", testHealthListChecksInState), ("testHealthListChecksInStateAync", testHealthListChecksInStateAync) ] func test2HealthChecksForNode() { let consul = Consul() let agentMembers = consul.agentMembers() switch agentMembers { case .success(let agentMembers): if let firstNode = agentMembers.first { let healthChecks = consul.healthChecksFor(node: firstNode.name) switch healthChecks { case .success(let healthChecks): XCTAssertGreaterThanOrEqual(healthChecks.count, 1) case .failure(let error): XCTAssertNil(error) } } else { XCTFail() } case .failure(let error): XCTAssertNil(error) } } func test2HealthChecksForNodeAsync() { let consul = Consul() let agentMembers = consul.agentMembers() let expectation = self.expectation(description: "healthCkecksForNode") switch agentMembers { case .success(let agentMembers): if let firstNode = agentMembers.first { consul.healthChecksFor(node: firstNode.name, completion: { healthChecks in switch healthChecks { case .success(let healthChecks): XCTAssertGreaterThanOrEqual(healthChecks.count, 1) case .failure(let error): XCTAssertNil(error) } expectation.fulfill() }) } else { XCTFail() } case .failure(let error): XCTAssertNil(error) } self.waitForExpectations(timeout: 15, handler: nil) } func test2HealthNodesForService() { let consul = Consul() let service = Consul.AgentServiceInput(name: "myTestService") service.tags = ["superImportant"] consul.agentRegisterService(service) let healthNodes = consul.healthNodesFor(service: "myTestService", tag: "superImportant") switch healthNodes { case .success(let healthNodes): XCTAssertGreaterThanOrEqual(healthNodes.count, 1) case .failure(let error): XCTAssertNil(error) } consul.agentDeregisterService("myTestService") } func test2HealthNodesForServiceAsync() { let consul = Consul() let expectation = self.expectation(description: "healthCkecksForNode") let service = Consul.AgentServiceInput(name: "myTestService") service.tags = ["superImportant"] consul.agentRegisterService(service) consul.healthNodesFor(service: "myTestService", tag: "superImportant") { healthNodes in switch healthNodes { case .success(let healthNodes): XCTAssertGreaterThanOrEqual(healthNodes.count, 1) case .failure(let error): XCTAssertNil(error) } consul.agentDeregisterService("myTestService") expectation.fulfill() } self.waitForExpectations(timeout: 15, handler: nil) } func testHealthListChecksInState() { let consul = Consul() let checks = consul.healthListChecksInState(.passing) switch checks { case .success(let checks): XCTAssertGreaterThanOrEqual(checks.count, 1) case .failure(let error): XCTAssertNil(error) } } func testHealthListChecksInStateAync() { let consul = Consul() let expectation = self.expectation(description: "healthChecksInState") consul.healthListChecksInState(.passing) { checks in switch checks { case .success(let checks): XCTAssertGreaterThanOrEqual(checks.count, 1) case .failure(let error): XCTAssertNil(error) } expectation.fulfill() } self.waitForExpectations(timeout: 15, handler: nil) } }
mit
f5b4728d6dd9ce854be4365482e12f17
33.57047
111
0.584935
4.933908
false
true
false
false
banjun/NorthLayout
Classes/VFL.swift
1
4887
import Foundation import CoreGraphics #if os(iOS) import UIKit #else import AppKit #endif extension VFL { /// decompose visual format into both side of edge connections and a middle remainder format string func edgeDecomposed(format: String) -> String { // strip decomposed edge connections // we do not generate a format string from parsed VFL, for some reliability // instead, use a knowledge that first `[` and last `]` separate edge connections let decomposed = format .drop {$0 != "["} .reversed().drop {$0 != "]"}.reversed() switch orientation { case .h: return "H:" + decomposed case .v: return "V:" + decomposed } } } extension VFL.SimplePredicate { func value(_ metrics: [String: CGFloat]) -> CGFloat? { switch self { case let .metricName(n): return metrics[n] case let .positiveNumber(v): return v } } } extension VFL.Constant { func value(_ metrics: [String: CGFloat]) -> CGFloat? { switch self { case let .metricName(n): return metrics[n] case let .number(v): return v } } } extension VFL.Priority { func value(_ metrics: [String: CGFloat]) -> CGFloat? { switch self { case let .metricName(n): return metrics[n] case let .number(v): return v } } } extension VFL.PredicateList { /// returns constraints: `lhs (==|<=|>=) rhs + constant` @discardableResult func constraints<T>(lhs: NSLayoutAnchor<T>, rhs: NSLayoutAnchor<T>, metrics: [String: CGFloat]) -> [NSLayoutConstraint] { let cs: [NSLayoutConstraint] switch self { case let .simplePredicate(p): guard let constant = p.value(metrics) else { return [] } cs = [lhs.constraint(equalTo: rhs, constant: constant)] case let .predicateListWithParens(predicates): cs = predicates.compactMap { p in guard case let .constant(c) = p.objectOfPredicate else { return nil } // NOTE: For the objectOfPredicate production, viewName is acceptable only if the subject of the predicate is the width or height of a view guard let constant = c.value(metrics) else { return nil } let constraint: NSLayoutConstraint switch p.relation { case .eq?, nil: constraint = lhs.constraint(equalTo: rhs, constant: constant) case .le?: constraint = lhs.constraint(lessThanOrEqualTo: rhs, constant: constant) case .ge?: constraint = lhs.constraint(greaterThanOrEqualTo: rhs, constant: constant) } _ = p.priority?.value(metrics).map {constraint.priority = LayoutPriority(rawValue: Float($0))} return constraint } } cs.forEach {$0.isActive = true} return cs } } protocol Anchorable { var leftAnchor: NSLayoutXAxisAnchor { get } var rightAnchor: NSLayoutXAxisAnchor { get } var topAnchor: NSLayoutYAxisAnchor { get } var bottomAnchor: NSLayoutYAxisAnchor { get } } extension View: Anchorable {} extension LayoutGuide: Anchorable {} extension VFL.Bound { private func anchorable(for view: View) -> Anchorable { switch self { case .superview: return view case .layoutMargin: #if os(iOS) || os(tvOS) guard #available(iOS 11, tvOS 11, *) else { // in iOS 10, reading layoutMarginsGuide when frame.size is zero and autolayout disabled // has side-effect causing layoutMargins not to work with margins. // workaround: simply enclose by setting false/true let prev = view.translatesAutoresizingMaskIntoConstraints if view.frame.size == .zero { view.translatesAutoresizingMaskIntoConstraints = false } let r = view.layoutMarginsGuide view.translatesAutoresizingMaskIntoConstraints = prev return r } return view.layoutMarginsGuide #else // macOS cannot support layout margins. silently fall back to superview. return view #endif } } func leftAnchor(for view: View) -> NSLayoutXAxisAnchor { return anchorable(for: view).leftAnchor } func rightAnchor(for view: View) -> NSLayoutXAxisAnchor { return anchorable(for: view).rightAnchor } func topAnchor(for view: View) -> NSLayoutYAxisAnchor { return anchorable(for: view).topAnchor } func bottomAnchor(for view: View) -> NSLayoutYAxisAnchor { return anchorable(for: view).bottomAnchor } }
mit
154648cfa1d2127bb7d2fce6786885bb
34.671533
225
0.593616
4.961421
false
false
false
false
NutdanaiVankrua/iOSSwift
iOSSwiftGuidelines/AppDelegate.swift
1
4636
// // AppDelegate.swift // iOSSwiftGuidelines // // Created by NutdanaiV Macbook Pro on 1/29/2560 BE. // Copyright © 2560 NutdanaiV Macbook Pro. All rights reserved. // import UIKit import CoreData @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { // Override point for customization after application launch. return true } func applicationWillResignActive(_ application: UIApplication) { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. 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 active state; here you can undo many of the changes made on entering the background. } func applicationDidBecomeActive(_ application: UIApplication) { // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. } func applicationWillTerminate(_ application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. // Saves changes in the application's managed object context before the application terminates. self.saveContext() } // MARK: - Core Data stack lazy var persistentContainer: NSPersistentContainer = { /* The persistent container for the application. This implementation creates and returns a container, having loaded the store for the application to it. This property is optional since there are legitimate error conditions that could cause the creation of the store to fail. */ let container = NSPersistentContainer(name: "iOSSwiftGuidelines") container.loadPersistentStores(completionHandler: { (storeDescription, error) in if let error = error as NSError? { // Replace this implementation with code to handle the error appropriately. // fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. /* Typical reasons for an error here include: * The parent directory does not exist, cannot be created, or disallows writing. * The persistent store is not accessible, due to permissions or data protection when the device is locked. * The device is out of space. * The store could not be migrated to the current model version. Check the error message to determine what the actual problem was. */ fatalError("Unresolved error \(error), \(error.userInfo)") } }) return container }() // MARK: - Core Data Saving support func saveContext () { let context = persistentContainer.viewContext if context.hasChanges { do { try context.save() } catch { // Replace this implementation with code to handle the error appropriately. // fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. let nserror = error as NSError fatalError("Unresolved error \(nserror), \(nserror.userInfo)") } } } }
mit
21e3c81a65ba1d9b08cfdd95f33a71be
48.83871
285
0.688026
5.815558
false
false
false
false
wikimedia/wikipedia-ios
Wikipedia/Code/TalkPageViewController+FindInPage.swift
1
6335
import Foundation extension TalkPageViewController { // MARK: - Overrides override var canBecomeFirstResponder: Bool { return findInPageState.keyboardBar != nil } override var inputAccessoryView: UIView? { return findInPageState.keyboardBar } // MARK: - Presentation fileprivate func createFindInPageViewIfNecessary() { guard findInPageState.keyboardBar == nil else { return } let keyboardBar = FindAndReplaceKeyboardBar.wmf_viewFromClassNib()! keyboardBar.delegate = self keyboardBar.apply(theme: theme) findInPageState.keyboardBar = keyboardBar } func showFindInPage() { createFindInPageViewIfNecessary() becomeFirstResponder() findInPageState.keyboardBar?.show() } func hideFindInPage(releaseKeyboardBar: Bool = false) { findInPageState.reset(viewModel.topics) findInPageState.keyboardBar?.hide() rethemeVisibleCells() resignFirstResponder() if releaseKeyboardBar { findInPageState.keyboardBar = nil } } var isShowingFindInPage: Bool { return findInPageState.keyboardBar?.isVisible ?? false } // MARK: - Scroll to Element private func scrollToFindInPageResultRect() { if let scrollingToIndexPath = scrollingToIndexPath, let scrollingToResult = scrollingToResult { if let scrollingToCommentViewModel = scrollingToCommentViewModel { if let commentView = talkPageCell(indexPath: scrollingToIndexPath)?.commentViewForViewModel(scrollingToCommentViewModel) { if let targetFrame = commentView.frameForHighlight(result: scrollingToResult) { talkPageView.collectionView.scrollRectToVisible(targetFrame, animated: true) } } } else { if let talkPageCell = talkPageCell(indexPath: scrollingToIndexPath) { if let targetFrame = talkPageCell.topicView.frameForHighlight(result: scrollingToResult) { talkPageView.collectionView.scrollRectToVisible(targetFrame, animated: true) } } } } scrollingToIndexPath = nil scrollingToResult = nil scrollingToCommentViewModel = nil rethemeVisibleCells() } func scrollToFindInPageResult(_ result: TalkPageFindInPageSearchController.SearchResult?) { guard let result = result else { return } switch result.location { case .topicTitle(topicIndex: let index, topicIdentifier: _): let indexPath = IndexPath(row: index, section: 0) scrollingToIndexPath = indexPath scrollingToResult = result if talkPageView.collectionView.indexPathsForVisibleItems.contains(indexPath) { scrollToFindInPageResultRect() } else { talkPageView.collectionView.scrollToItem(at: indexPath, at: .top, animated: false) scrollToFindInPageResultRect() } case .topicLeadComment(topicIndex: let index, replyIdentifier: _), .topicOtherContent(topicIndex: let index): let indexPath = IndexPath(row: index, section: 0) scrollingToIndexPath = indexPath scrollingToResult = result if talkPageView.collectionView.indexPathsForVisibleItems.contains(indexPath) { scrollToFindInPageResultRect() } else { talkPageView.collectionView.scrollToItem(at: indexPath, at: .top, animated: false) scrollToFindInPageResultRect() } case .reply(topicIndex: let topicIndex, topicIdentifier: _, replyIndex: let replyIndex, replyIdentifier: _): let topicViewModel = viewModel.topics[topicIndex] let commentViewModel = topicViewModel.replies[replyIndex] let indexPath = IndexPath(row: topicIndex, section: 0) scrollingToIndexPath = indexPath scrollingToResult = result scrollingToCommentViewModel = commentViewModel if talkPageView.collectionView.indexPathsForVisibleItems.contains(indexPath) { scrollToFindInPageResultRect() } else { talkPageView.collectionView.scrollToItem(at: indexPath, at: .top, animated: false) scrollToFindInPageResultRect() } } } private func talkPageCell(indexPath: IndexPath) -> TalkPageCell? { talkPageView.collectionView.layoutIfNeeded() return talkPageView.collectionView.cellForItem(at: indexPath) as? TalkPageCell } } extension TalkPageViewController: FindAndReplaceKeyboardBarDelegate { func keyboardBar(_ keyboardBar: FindAndReplaceKeyboardBar, didChangeSearchTerm searchTerm: String?) { guard let searchTerm else { return } findInPageState.search(term: searchTerm, in: viewModel.topics, traitCollection: traitCollection, theme: theme) rethemeVisibleCells() } func keyboardBarDidTapClose(_ keyboardBar: FindAndReplaceKeyboardBar) { hideFindInPage() } func keyboardBarDidTapClear(_ keyboardBar: FindAndReplaceKeyboardBar) { findInPageState.reset(viewModel.topics) rethemeVisibleCells() } func keyboardBarDidTapPrevious(_ keyboardBar: FindAndReplaceKeyboardBar) { findInPageState.previous() viewModel.topics.forEach { $0.activeHighlightResult = findInPageState.selectedMatch } scrollToFindInPageResult(findInPageState.selectedMatch) } func keyboardBarDidTapNext(_ keyboardBar: FindAndReplaceKeyboardBar?) { findInPageState.next() viewModel.topics.forEach { $0.activeHighlightResult = findInPageState.selectedMatch } scrollToFindInPageResult(findInPageState.selectedMatch) } func keyboardBarDidTapReturn(_ keyboardBar: FindAndReplaceKeyboardBar) { keyboardBarDidTapNext(keyboardBar) } func keyboardBarDidTapReplace(_ keyboardBar: FindAndReplaceKeyboardBar, replaceText: String, replaceType: ReplaceType) {} }
mit
95eeee2ebd867434aaac6608dd1a3fbb
36.264706
138
0.657143
5.785388
false
false
false
false
loudnate/xDripG5
CGMBLEKit/Messages/AuthChallengeRxMessage.swift
1
557
// // AuthChallengeRxMessage.swift // xDrip5 // // Created by Nathan Racklyeft on 11/22/15. // Copyright © 2015 Nathan Racklyeft. All rights reserved. // import Foundation struct AuthChallengeRxMessage: TransmitterRxMessage { let isAuthenticated: Bool let isBonded: Bool init?(data: Data) { guard data.count >= 3 else { return nil } guard data.starts(with: .authChallengeRx) else { return nil } isAuthenticated = data[1] == 0x1 isBonded = data[2] == 0x1 } }
mit
28dfffe558fe488dd2e2f016e076dfce
18.857143
59
0.606115
3.888112
false
false
false
false
rmuhamedgaliev/IsoWorld
IsoWorld/IsoWorld/Models/UserScore.swift
1
907
// // UserScore.swift // IsoWorld // // Created by rmuhamedgaliev on 06/05/16. // Copyright © 2016 Rinat Muhamedgaliev. All rights reserved. // import Foundation import SpriteKit class UserNode: SKSpriteNode { var userObj: UserScore? } class UserScore { dynamic var name: String = "" dynamic var score: Int = 0 dynamic var me: Bool = false dynamic var time: Int = 0 init() {} init(name: String, score: Int, time: Int, me: Bool) { self.name = name self.score = score self.me = me self.time = time } init(fromDictionary dictionary: NSDictionary) { if let name = dictionary["name"] as? String { self.name = name } if let score = dictionary["score"] as? Int { self.score = score } if let me = dictionary["me"] as? Bool { self.me = me } if let time = dictionary["time"] as? Int { self.time = time } } }
mit
1d543d449381a137619574ab892e4c48
16.764706
62
0.610375
3.406015
false
false
false
false
mitchtreece/Spider
Spider/Classes/Async/UISpider+Async.swift
1
2481
// // UISpider+Async.swift // Spider-Web // // Created by Mitch Treece on 1/26/22. // import Foundation @available(iOS 13, *) @available(macOS 12, *) public extension UISpider where T: ImageView { /// Fetches a remote _or_ cached image for a given URL, then assigns it to the current image view. /// - parameter url: The image's URL. /// - parameter placeholder: A placeholder image to assign to the current image view while the image is being fetched; _defaults to nil_. /// - parameter cacheImage: Flag indicating if the fetched image should be cached; _defaults to true_. /// - returns: An optional image result. /// /// The caller is responsible for assigning the image to the image view. func setImage(_ url: URLRepresentable, placeholder: Image? = nil, cacheImage: Bool = true) async -> (Image?, Bool) { await withCheckedContinuation { c in setImage(url, placeholder: placeholder, cacheImage: cacheImage) { image, fromCache, error in c.resume(returning: (image, fromCache)) } } } /// Fetches a remote _or_ cached image for a given URL, then assigns it to the current image view. /// - parameter url: The image's URL. /// - parameter placeholder: A placeholder image to assign to the current image view while the image is being fetched; _defaults to nil_. /// - parameter cacheImage: Flag indicating if the fetched image should be cached; _defaults to true_. /// - returns: An image result. /// /// The caller is responsible for assigning the image to the image view. func setImageThrowing(_ url: URLRepresentable, placeholder: Image? = nil, cacheImage: Bool = true) async throws -> (Image, Bool) { try await withCheckedThrowingContinuation { c in setImage(url, placeholder: placeholder, cacheImage: cacheImage) { image, fromCache, error in if let error = error { c.resume(throwing: error) return } else if let image = image { c.resume(returning: (image, fromCache)) return } c.resume(throwing: ErrorType.invalidImage) } } } }
mit
0566afabc70d704acc1a83262a15f910
37.169231
141
0.572753
5.07362
false
false
false
false
Johnykutty/JSONModeller
JSONModellerTests/StringExtensionTests.swift
1
2383
// // StringExtensionTests.swift // JSONModeller // // Created by Johnykutty Mathew on 06/06/15. // Copyright (c) 2015 Johnykutty Mathew. All rights reserved. // import Cocoa import XCTest class StringExtensionTests: XCTestCase { override func setUp() { super.setUp() // Put setup code here. This method is called before the invocation of each test method in the class. } override func tearDown() { // Put teardown code here. This method is called after the invocation of each test method in the class. super.tearDown() } func testSubStringFrom() { let string = "test" let expectedResult = "est" let actualResult = string.substring(from:1) XCTAssertEqual(expectedResult, actualResult, "testSubStringFrom failed for lowercase string") let string2 = "TEST" let expectedResult2 = "EST" let actualResult2 = string2.substring(from:1) XCTAssertEqual(expectedResult, actualResult, "testSubStringFrom failed for uppercase string") } func testSubStringTo() { let string = "Test" let expectedResult = "Te" let actualResult = string.substring(to:2) XCTAssertEqual(expectedResult, actualResult, "testSubStringTo failed for lowercase string") let string2 = "TEST" let expectedResult2 = "TE" let actualResult2 = string2.substring(to:2) XCTAssertEqual(expectedResult2, actualResult2, "testSubStringTo failed for failed for uppercase string") } func testfirstLetterLowered() { let string = "Test" let expectedResult = "test" let actualResult = string.firstLetterLoweredString() XCTAssertEqual(expectedResult, actualResult, "firstLetterLowerdString failed for lowecase string") let string2 = "TEST" let expectedResult2 = "tEST" let actualResult2 = string2.firstLetterLoweredString() XCTAssertEqual(expectedResult2, actualResult2, "firstLetterLowerdString failed for uppercase string") } func testfirstLetterLoweredForSingleLetter() { let string = "T" let expectedResult = "t" let actualResult = string.firstLetterLoweredString() XCTAssertEqual(expectedResult, actualResult, "firstLetterLowerdString failed for lsingle lettor string") } }
mit
4716927428888a251726fd153cdc00c0
34.567164
112
0.67478
4.833671
false
true
false
false
IntertechInc/uicollectionview-tutorial
CollectionViewCustomLayout/TimeEntryCollectionLayout.swift
1
5412
// // TimeEntryCollectionLayout.swift // CollectionViewCustomLayout // // Created by Ryan Harvey on 8/30/15. // Copyright (c) 2015 Intertech. All rights reserved. // import UIKit class TimeEntryCollectionLayout: UICollectionViewLayout { private var cellAttributes = [NSIndexPath: UICollectionViewLayoutAttributes]() private var headerAttributes = [NSIndexPath: UICollectionViewLayoutAttributes]() private var contentSize: CGSize? private let numberOfVisibleDays = 7 private let headerWidth = CGFloat(80) private let verticalDividerWidth = CGFloat(2) private let horizontalDividerHeight = CGFloat(2) var days: [day] = [] { didSet { invalidateLayout() } } override func prepareLayout() { if (collectionView == nil) { return } // 1: Clear the cache cellAttributes.removeAll() headerAttributes.removeAll() // 2: Calculate the height of a row let availableHeight = collectionView!.bounds.height - collectionView!.contentInset.top - collectionView!.contentInset.bottom - CGFloat(numberOfVisibleDays - 1) * horizontalDividerHeight let rowHeight = availableHeight / CGFloat(numberOfVisibleDays) // 3: Calculate the width available for time entry cells let itemsWidth = collectionView!.bounds.width - collectionView!.contentInset.left - collectionView!.contentInset.right - headerWidth; var rowY: CGFloat = 0 // 4: For each day for (dayIndex, day) in days.enumerate() { // 4.1: Find the Y coordinate of the row rowY = CGFloat(dayIndex) * (rowHeight + horizontalDividerHeight) // 4.2: Generate and store layout attributes header cell let headerIndexPath = NSIndexPath(forItem: 0, inSection: dayIndex) let headerCellAttributes = UICollectionViewLayoutAttributes( forSupplementaryViewOfKind: UICollectionElementKindSectionHeader, withIndexPath: headerIndexPath) headerAttributes[headerIndexPath] = headerCellAttributes headerCellAttributes.frame = CGRectMake(0, rowY, headerWidth, rowHeight) // 4.3: Get the total number of hours for the day let hoursInDay = day.entries.reduce(0) { (h, e) in h + e.hours } // Set the initial X position for time entry cells var cellX = headerWidth // 4.4: For each time entry in day for (entryIndex, entry) in day.entries.enumerate() { // 4.4.1: Get the width of the cell var cellWidth = CGFloat(Double(entry.hours) / Double(hoursInDay)) * itemsWidth // Leave some empty space to form the vertical divider cellWidth -= verticalDividerWidth cellX += verticalDividerWidth // 4.4.3: Generate and store layout attributes for the cell let cellIndexPath = NSIndexPath(forItem: entryIndex, inSection: dayIndex) let timeEntryCellAttributes = UICollectionViewLayoutAttributes(forCellWithIndexPath: cellIndexPath) cellAttributes[cellIndexPath] = timeEntryCellAttributes timeEntryCellAttributes.frame = CGRectMake(cellX, rowY, cellWidth, rowHeight) // Update cellX to the next starting position cellX += cellWidth } } // 5: Store the complete content size let maxY = rowY + rowHeight contentSize = CGSizeMake(collectionView!.bounds.width, maxY) print("collectionView size = \(NSStringFromCGSize(collectionView!.bounds.size))") print("contentSize = \(NSStringFromCGSize(contentSize!))") } override func collectionViewContentSize() -> CGSize { if contentSize != nil { return contentSize! } return CGSize.zero } override func layoutAttributesForElementsInRect(rect: CGRect) -> [UICollectionViewLayoutAttributes]? { var attributes = [UICollectionViewLayoutAttributes]() for attribute in headerAttributes.values { if CGRectIntersectsRect(attribute.frame, rect) { attributes.append(attribute) } } for attribute in cellAttributes.values { if CGRectIntersectsRect(attribute.frame, rect) { attributes.append(attribute) } } print("layoutAttributesForElementsInRect rect = \(NSStringFromCGRect(rect)), returned \(attributes.count) attributes") return attributes } override func layoutAttributesForItemAtIndexPath(indexPath: NSIndexPath) -> UICollectionViewLayoutAttributes? { return cellAttributes[indexPath] } override func layoutAttributesForSupplementaryViewOfKind( elementKind: String, atIndexPath indexPath: NSIndexPath) -> UICollectionViewLayoutAttributes? { return headerAttributes[indexPath] } }
mit
0add3ac8477dbd4b6cc806397affb1ce
35.574324
126
0.60643
6.013333
false
false
false
false
sosaucily/yelpclient
yelpclient/ViewController.swift
1
4572
// // ViewController.swift // yelpclient // // Created by Jesse Smith on 9/20/14. // Copyright (c) 2014 Jesse Smith. All rights reserved. // import UIKit class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate, UISearchBarDelegate, FilterTableDelegate { var client: YelpClient! // You can register for Yelp API keys here: http://www.yelp.com/developers/manage_api_keys let yelpConsumerKey = "BeBsBEuYUeHESjJ-gB-3Mw" let yelpConsumerSecret = "1t3Nw-VC0kwAJRK0NQskWV6Pk9o" let yelpToken = "WKnNK35JBfL5uIuKKMQBigb75WB6xZKH" let yelpTokenSecret = "190x3RR1Be_xmB8t5z-4AD8Mjq4" @IBOutlet weak var resultsTableView: UITableView! var businesses: [Restaurant] = [Restaurant]() let searchBarTop: UISearchBar = UISearchBar() var term: String = "" var categories: String = "" var sortMetric: Int = 0 required init(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. self.resultsTableView.estimatedRowHeight = 200 self.resultsTableView.rowHeight = UITableViewAutomaticDimension self.searchBarTop.delegate = self self.searchDisplayController?.displaysSearchBarInNavigationBar = true; self.navigationItem.titleView = self.searchBarTop client = YelpClient(consumerKey: yelpConsumerKey, consumerSecret: yelpConsumerSecret, accessToken: yelpToken, accessSecret: yelpTokenSecret) self.doSearch() } func doSearch() { client.searchWithTerm(self.term, categories: self.categories, sortBy: self.sortMetric, success: { (operation: AFHTTPRequestOperation!, responseObject: AnyObject!) -> Void in self.businesses = [] var dictArray = responseObject["businesses"] as? NSArray for biz in dictArray! { var biz = biz as NSDictionary var res = Restaurant(dataDict: biz) self.businesses.append(res) } self.resultsTableView.reloadData() }) { (operation: AFHTTPRequestOperation!, error: NSError!) -> Void in println(error) } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return businesses.count } func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { self.navigationController?.navigationBar.endEditing(true) } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = resultsTableView.dequeueReusableCellWithIdentifier("yelpcell") as YelpCellTableViewCell let biz = businesses[indexPath.row] let location = biz.location cell.nameLabel.text = "\(indexPath.row+1). \(biz.name)" cell.dollarsLabel.text = "$$" var cats = biz.categories cell.categoriesLabel.text = ", ".join(cats.map({ "\($0)" })) cell.addressLabel.text = "\(location!)" if (!biz.image_url.isEmpty) { cell.imageIcon.setImageWithURL(NSURL(string: biz.image_url)) } if (!biz.rating_img_url.isEmpty) { cell.ratingImage.setImageWithURL(NSURL(string: biz.rating_img_url)) } return cell } func searchBarSearchButtonClicked(searchBar: UISearchBar){ self.term = searchBar.text self.doSearch() } func searchBar(searchBar: UISearchBar, textDidChange searchText: String) { if (searchText == "") { self.term = "" self.doSearch() } } func returnSearchParams(searchParams: SearchResults) { var list: [String] = [] if (searchParams.thai) { list.append("thai") } if (searchParams.chinese) { list.append("chinese") } if (searchParams.italian) { list.append("italian") } if (searchParams.mexican) { list.append("mexican") } self.sortMetric = searchParams.sortMetric self.categories = ",".join(list) self.doSearch() } }
mit
eb62bd06200dca65d2c88b10f847d3ce
32.372263
181
0.622266
4.708548
false
false
false
false
nicksweet/Clink
Clink/Classes/DefaultPeerManager.swift
1
1474
// // DefaultPeerManager.swift // Clink // // Created by Nick Sweet on 7/13/17. // import Foundation public class DefaultPeerManager: ClinkPeerManager { public func createPeer(withId peerId: String) { let peer = Clink.DefaultPeer(id: peerId) UserDefaults.standard.set(peer.toDict(), forKey: peer.id) var savedPeerIds = UserDefaults.standard.stringArray(forKey: savedPeerIdsDefaultsKey) ?? [] if savedPeerIds.index(of: peer.id) == nil { savedPeerIds.append(peer.id) UserDefaults.standard.set(savedPeerIds, forKey: savedPeerIdsDefaultsKey) } } public func update(value: Any, forKey key: String, ofPeerWithId peerId: String) { guard let peer: Clink.DefaultPeer = self.getPeer(withId: peerId) else { return } peer[key] = value UserDefaults.standard.set(peer.toDict(), forKey: peer.id) } public func getPeer<T: ClinkPeer>(withId peerId: String) -> T? { guard let peerDict = UserDefaults.standard.dictionary(forKey: peerId) else { return nil } return Clink.DefaultPeer(dict: peerDict) as? T } public func getKnownPeerIds() -> [Clink.PeerId] { return UserDefaults.standard.stringArray(forKey: savedPeerIdsDefaultsKey) ?? [] } public func delete(peerWithId peerId: String) { UserDefaults.standard.removeObject(forKey: peerId) } }
mit
3f9bacfca2d7eb0ece3f0019e9f2c469
31.043478
99
0.63772
4.360947
false
false
false
false
LYM-mg/MGDYZB
MGDYZB/MGDYZB/Class/Main/Controller/MGNavController.swift
1
4266
// // MGNavController.swift // MGDYZB // // Created by ming on 16/10/25. // Copyright © 2016年 ming. All rights reserved. // import UIKit fileprivate func < <T : Comparable>(lhs: T?, rhs: T?) -> Bool { switch (lhs, rhs) { case let (l?, r?): return l < r case (nil, _?): return true default: return false } } fileprivate func > <T : Comparable>(lhs: T?, rhs: T?) -> Bool { switch (lhs, rhs) { case let (l?, r?): return l > r default: return rhs < lhs } } class MGNavController: UINavigationController { override func viewDidLoad() { super.viewDidLoad() /* // 1.获取系统的Pop手势 guard let systemGes = interactivePopGestureRecognizer else { return } // 2.获取target/action // 2.1.利用运行时机制查看所有的属性名称 var count : UInt32 = 0 let ivars = class_copyIvarList(UIGestureRecognizer.self, &count)! for i in 0..<count { let ivar = ivars[Int(i)] let name = ivar_getName(ivar) print(String(cString: name!)) } */ // 0.设置导航栏的颜色 setUpNavAppearance () // 1.创建Pan手势 let target = navigationController?.interactivePopGestureRecognizer?.delegate let pan = UIPanGestureRecognizer(target: target, action: Selector(("handleNavigationTransition:"))) pan.delegate = self self.view.addGestureRecognizer(pan) // 2.禁止系统的局部返回手势 navigationController?.interactivePopGestureRecognizer?.isEnabled = false self.delegate = self } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } // MARK: - 拦截Push操作 override func pushViewController(_ viewController: UIViewController, animated: Bool) { // 这里判断是否进入push视图 if (self.childViewControllers.count > 0) { let backBtn = UIButton(image: #imageLiteral(resourceName: "back"), highlightedImage: #imageLiteral(resourceName: "backBarButtonItem"), title: "返回",target: self, action: #selector(MGNavController.backClick)) // 设置按钮内容左对齐 backBtn.contentHorizontalAlignment = UIControlContentHorizontalAlignment.left; // 内边距 backBtn.contentEdgeInsets = UIEdgeInsetsMake(0, -10, 0, 0); viewController.navigationItem.leftBarButtonItem = UIBarButtonItem(customView: backBtn) // 隐藏要push的控制器的tabbar viewController.hidesBottomBarWhenPushed = true } super.pushViewController(viewController, animated: animated) } @objc fileprivate func backClick() { popViewController(animated: true) } } extension MGNavController : UIGestureRecognizerDelegate{ func gestureRecognizerShouldBegin(_ gestureRecognizer: UIGestureRecognizer) -> Bool { ///判断是否是根控制器 if self.childViewControllers.count == 1 { return false } return true } } extension MGNavController { fileprivate func setUpNavAppearance () { let navBar = UINavigationBar.appearance() if(Double(UIDevice.current.systemVersion)) > 8.0 { navBar.isTranslucent = true } else { self.navigationBar.isTranslucent = true } navBar.tintColor = UIColor(red: 1, green: 1, blue: 1, alpha: 1.00) navBar.titleTextAttributes = [NSForegroundColorAttributeName:UIColor.white,NSFontAttributeName:UIFont.boldSystemFont(ofSize: 18)] } } extension MGNavController: UINavigationControllerDelegate { func navigationController(_ navigationController: UINavigationController, willShow viewController: UIViewController, animated: Bool) { if viewController is LiveViewController { navigationController.navigationBar.barTintColor = UIColor.yellow }else { navigationController.navigationBar.barTintColor = UIColor.orange } } }
mit
b649feedc092befc12516dc824cdc485
30.851563
218
0.627177
5.07721
false
false
false
false
Den-Ree/InstagramAPI
src/InstagramAPI/InstagramAPI/Example/ViewControllers/Location/LocationRecentViewController.swift
2
2985
// // LocationRecentViewController.swift // InstagramAPI // // Created by Admin on 06.06.17. // Copyright © 2017 ConceptOffice. All rights reserved. // import UIKit private let reuseIdentifier = "locationRecentCell" class LocationRecentViewController: UICollectionViewController { var locationParameter: InstagramLocationRouter.RecentMediaParameter? fileprivate var dataSource: [InstagramMedia?] = [] fileprivate let kMaxPhotosInRaw = 4 fileprivate let kPhotosSpacing: CGFloat = 1.0 override func viewDidLoad() { super.viewDidLoad() let router = InstagramLocationRouter.getRecentMedia(locationParameter!) InstagramClient().send(router, completion: { ( media: InstagramArrayResponse<InstagramMedia>?, error: Error?) in if error == nil { self.dataSource = (media?.data)! self.collectionView?.reloadData() } }) self.collectionView!.register(UICollectionViewCell.self, forCellWithReuseIdentifier: reuseIdentifier) } } extension LocationRecentViewController { // MARK: UICollectionViewDataSource override func numberOfSections(in collectionView: UICollectionView) -> Int { return 1 } override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return dataSource.count } override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCell(withReuseIdentifier: reuseIdentifier, for: indexPath) as! LocationRecentCell let media = dataSource[indexPath.row] cell.imageView.af_setImage(withURL: (media?.image.lowResolution.url)!) return cell } } extension LocationRecentViewController: UICollectionViewDelegateFlowLayout { // Mark: UICollectionViewDelegateFlowLayout func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize { let screenWidth = UIScreen.main.bounds.width let photoWidth = floor(screenWidth / CGFloat(kMaxPhotosInRaw) - kPhotosSpacing / CGFloat(kMaxPhotosInRaw) * kPhotosSpacing) return CGSize(width: photoWidth, height: photoWidth) } func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumInteritemSpacingForSectionAt section: Int) -> CGFloat { return kPhotosSpacing } func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat { return kPhotosSpacing } func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets { return UIEdgeInsetsMake(0, 0, kPhotosSpacing * 2, 0) } }
mit
53a7cab9a1845747f480d88e642b6bb8
38.786667
175
0.743968
5.619586
false
false
false
false
CoreAnimationAsSwift/WZHQZhiBo
ZhiBo/ZhiBo/Tools/NetworkTools.swift
1
775
// // NetworkTools.swift // ZhiBo // // Created by mac on 16/10/31. // Copyright © 2016年 mac. All rights reserved. // import UIKit import Alamofire enum MethodType :String { case GET = "GET" case POST = "POST" } class NetworkTools { class func requestData(_ type:MethodType,urlString:String,parameters:[String:Any]? = nil,completion:@escaping (_ result:Any?)->()) { let method = type == .GET ? HTTPMethod.get : HTTPMethod.post Alamofire.request(urlString, method: method, parameters: parameters).responseJSON { (response) in guard let result = response.result.value else { print(response.result.error!) return } completion(result) } } }
mit
2c6a9106700c9257de4e9d516880d944
26.571429
136
0.601036
4.288889
false
false
false
false
MessageKit/MessageKit
Sources/Views/TypingBubble.swift
1
5326
// MIT License // // Copyright (c) 2017-2019 MessageKit // // 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 /// A subclass of `UIView` that mimics the iMessage typing bubble open class TypingBubble: UIView { // MARK: Lifecycle public override init(frame: CGRect) { super.init(frame: frame) setupSubviews() } public required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) setupSubviews() } // MARK: Open // MARK: - Properties open var isPulseEnabled = true open override var backgroundColor: UIColor? { set { [contentBubble, cornerBubble, tinyBubble].forEach { $0.backgroundColor = newValue } } get { contentBubble.backgroundColor } } // MARK: - Animation Layers open var contentPulseAnimationLayer: CABasicAnimation { let animation = CABasicAnimation(keyPath: "transform.scale") animation.fromValue = 1 animation.toValue = 1.04 animation.duration = 1 animation.repeatCount = .infinity animation.autoreverses = true return animation } open var circlePulseAnimationLayer: CABasicAnimation { let animation = CABasicAnimation(keyPath: "transform.scale") animation.fromValue = 1 animation.toValue = 1.1 animation.duration = 0.5 animation.repeatCount = .infinity animation.autoreverses = true return animation } open func setupSubviews() { addSubview(tinyBubble) addSubview(cornerBubble) addSubview(contentBubble) contentBubble.addSubview(typingIndicator) backgroundColor = .incomingMessageBackground } // MARK: - Layout open override func layoutSubviews() { super.layoutSubviews() // To maintain the iMessage like bubble the width:height ratio of the frame // must be close to 1.65 // In order to prevent NaN crash when assigning the frame of the contentBubble guard bounds.width > 0, bounds.height > 0 else { return } let ratio = bounds.width / bounds.height let extraRightInset = bounds.width - 1.65 / ratio * bounds.width let tinyBubbleRadius: CGFloat = bounds.height / 6 tinyBubble.frame = CGRect( x: 0, y: bounds.height - tinyBubbleRadius, width: tinyBubbleRadius, height: tinyBubbleRadius) let cornerBubbleRadius = tinyBubbleRadius * 2 let offset: CGFloat = tinyBubbleRadius / 6 cornerBubble.frame = CGRect( x: tinyBubbleRadius - offset, y: bounds.height - (1.5 * cornerBubbleRadius) + offset, width: cornerBubbleRadius, height: cornerBubbleRadius) let contentBubbleFrame = CGRect( x: tinyBubbleRadius + offset, y: 0, width: bounds.width - (tinyBubbleRadius + offset) - extraRightInset, height: bounds.height - (tinyBubbleRadius + offset)) let contentBubbleFrameCornerRadius = contentBubbleFrame.height / 2 contentBubble.frame = contentBubbleFrame contentBubble.layer.cornerRadius = contentBubbleFrameCornerRadius let insets = UIEdgeInsets( top: offset, left: contentBubbleFrameCornerRadius / 1.25, bottom: offset, right: contentBubbleFrameCornerRadius / 1.25) typingIndicator.frame = contentBubble.bounds.inset(by: insets) } // MARK: - Animation API open func startAnimating() { defer { isAnimating = true } guard !isAnimating else { return } typingIndicator.startAnimating() if isPulseEnabled { contentBubble.layer.add(contentPulseAnimationLayer, forKey: AnimationKeys.pulse) [cornerBubble, tinyBubble].forEach { $0.layer.add(circlePulseAnimationLayer, forKey: AnimationKeys.pulse) } } } open func stopAnimating() { defer { isAnimating = false } guard isAnimating else { return } typingIndicator.stopAnimating() [contentBubble, cornerBubble, tinyBubble].forEach { $0.layer.removeAnimation(forKey: AnimationKeys.pulse) } } // MARK: Public public private(set) var isAnimating = false // MARK: - Subviews /// The indicator used to display the typing animation. public let typingIndicator = TypingIndicator() public let contentBubble = UIView() public let cornerBubble = BubbleCircle() public let tinyBubble = BubbleCircle() // MARK: Private private enum AnimationKeys { static let pulse = "typingBubble.pulse" } }
mit
39d2d6e2d39ee93d0b646b0d1c0b7612
29.786127
113
0.713106
4.498311
false
false
false
false
Matt-gale/EasyRegistration
EasyRegistrationIOS/EasyRegistrationIOS/SignUpViewController.swift
1
7465
// // SignUpViewController.swift // EasyRegistrationIOS // // Created by Ye He on 19/7/17. // // import UIKit class SignUpViewController: UIViewController { @IBOutlet weak var emailTF: UITextField! @IBOutlet weak var passwordTF: UITextField! var emailBorder = CAShapeLayer() var passwordBorder = CAShapeLayer() var emailTick = CAShapeLayer() var passwordTick = CAShapeLayer() let borderColor = UIColor(red: 31 / 255.0, green: 163 / 255.0, blue: 224 / 255.0, alpha: 1.0).cgColor let width = CGFloat(2.0) override func viewDidLoad() { super.viewDidLoad() setupTextFieldBorders() setupTickLayers() } private func setupTextFieldBorders() { setupBorder(for: emailTF, shapeLayer: emailBorder) setupBorder(for: passwordTF, shapeLayer: passwordBorder) } private func setupBorder(for textField: UITextField, shapeLayer: CAShapeLayer) { let borderPath = getBorderPath(of : textField) shapeLayer.path = borderPath.cgPath shapeLayer.strokeEnd = 0.0 shapeLayer.strokeColor = borderColor shapeLayer.fillColor = borderColor shapeLayer.lineWidth = 2.0 textField.layer.addSublayer(shapeLayer) } private func getBorderPath(of textField: UITextField) -> UIBezierPath { let borderPath = UIBezierPath() let yPos = textField.bounds.size.height - width let start = CGPoint(x: 0, y: yPos) let end = CGPoint(x: textField.bounds.size.width, y: yPos) borderPath.move(to: start) borderPath.addLine(to: end) return borderPath } private func setupTickLayers() { setupTickLayer(for: emailTF, shapeLayer: emailTick) setupTickLayer(for: passwordTF, shapeLayer: passwordTick) } private func setupTickLayer(for textField: UITextField, shapeLayer: CAShapeLayer) { let tickPath = getTickPath(of: textField) shapeLayer.path = tickPath.cgPath shapeLayer.strokeColor = borderColor shapeLayer.fillColor = UIColor.clear.cgColor shapeLayer.lineWidth = 2.0 shapeLayer.strokeEnd = 0.0 textField.layer.addSublayer(shapeLayer) } private func getTickPath(of textField: UITextField) -> UIBezierPath { let tickPath = UIBezierPath() let spaceToRight = CGFloat(5.0) let halfTickHeight = CGFloat(5.0) let xPos = textField.bounds.size.width - spaceToRight - halfTickHeight * 3 let yPos = (textField.bounds.size.height - width) / 2 let start = CGPoint(x: xPos, y: yPos) let end = CGPoint(x: xPos + halfTickHeight, y: yPos + halfTickHeight) let end2 = CGPoint(x: xPos + halfTickHeight * 3, y: yPos - halfTickHeight) tickPath.move(to: start) tickPath.addLine(to: end) tickPath.addLine(to: end2) return tickPath } @IBAction func switchToLoginVC(_ sender: UIButton) { let rootVC = UIApplication.shared.delegate!.window!!.rootViewController! as! TransitionViewController rootVC.transitionToLoginVC() } @IBAction func emailValueChanged(_ sender: UITextField) { NSObject.cancelPreviousPerformRequests(withTarget: self, selector: #selector(self.recheckEmail(sender:)), object: sender) self.perform(#selector(self.recheckEmail(sender:)), with: sender, afterDelay: 0.5) } @IBAction func passwordValueChanged(_ sender: UITextField) { NSObject.cancelPreviousPerformRequests(withTarget: self, selector: #selector(self.recheckPassword(sender:)), object: sender) self.perform(#selector(self.recheckPassword(sender:)), with: sender, afterDelay: 0.5) } @objc private func recheckEmail(sender: UITextField) { emailTick.removeAllAnimations() guard let text = sender.text, !text.isEmpty else { // implicit animation emailTick.strokeEnd = 0.0 return } setupTickAnimation(for: emailTick) } @objc private func recheckPassword(sender: UITextField) { guard let text = sender.text, !text.isEmpty else { // implicit animation passwordTick.strokeEnd = 0.0 return } setupTickAnimation(for: passwordTick) } private func setupTickAnimation(for tickLayer: CAShapeLayer) { tickLayer.removeAllAnimations() CATransaction.begin() CATransaction.setDisableActions(true) let animation = CABasicAnimation(keyPath: "strokeEnd") animation.fromValue = 0.0 animation.toValue = 1.0 animation.duration = 0.3 tickLayer.strokeEnd = 1.0 tickLayer.add(animation, forKey: "drawTickAnimation") CATransaction.commit() } @IBAction func emailTFFocused(_ sender: UITextField) { setupFocusAnimation(for: emailBorder) } @IBAction func emailTFUnfocused(_ sender: UITextField) { setupUnFocusAnimation(for: emailBorder) } @IBAction func passwordTFFocused(_ sender: UITextField) { setupFocusAnimation(for: passwordBorder) } @IBAction func passwordTFUnfocused(_ sender: UITextField) { setupUnFocusAnimation(for: passwordBorder) } // start or remove 'focus' animation for the border of a text field depends on whether previous animations are finished private func setupFocusAnimation(for borderLayer: CAShapeLayer) { CATransaction.begin() CATransaction.setDisableActions(true) let withdrawAni = borderLayer.animation(forKey: "withdrawLineAnimation") let drawAni = borderLayer.animation(forKey: "drawLineAnimation") if drawAni == nil && withdrawAni == nil { borderLayer.strokeStart = 0.0 let animation = CABasicAnimation(keyPath: "strokeEnd") animation.fromValue = 0.0 animation.toValue = 1.0 animation.duration = 0.5 borderLayer.strokeEnd = 1.0 borderLayer.add(animation, forKey: "drawLineAnimation") } else { borderLayer.removeAllAnimations() borderLayer.strokeStart = 0.0 borderLayer.strokeEnd = 1.0 } CATransaction.commit() } // start or remove 'unfocus' animation of the border of a text field depends on whether previous animations are finished private func setupUnFocusAnimation(for borderLayer: CAShapeLayer) { CATransaction.begin() CATransaction.setDisableActions(true) let withdrawAni = borderLayer.animation(forKey: "withdrawLineAnimation") let drawAni = borderLayer.animation(forKey: "drawLineAnimation") if drawAni == nil && withdrawAni == nil { let animation = CABasicAnimation(keyPath: "strokeStart") animation.fromValue = 0.0 animation.toValue = 1.0 animation.duration = 0.5 borderLayer.strokeStart = 1.0 borderLayer.add(animation, forKey: "withdrawLineAnimation") } else { borderLayer.removeAllAnimations() borderLayer.strokeStart = 1.0 } CATransaction.commit() } }
gpl-3.0
9790f660a4d4ebb782e6a763399edf9f
33.883178
132
0.631882
4.937169
false
false
false
false
zitao0322/ShopCar
Shoping_Car/Pods/RxCocoa/RxCocoa/Common/DelegateProxyType.swift
9
11461
// // DelegateProxyType.swift // RxCocoa // // Created by Krunoslav Zaher on 6/15/15. // Copyright © 2015 Krunoslav Zaher. All rights reserved. // import Foundation #if !RX_NO_MODULE import RxSwift #endif /** `DelegateProxyType` protocol enables using both normal delegates and Rx observable sequences with views that can have only one delegate/datasource registered. `Proxies` store information about observers, subscriptions and delegates for specific views. Type implementing `DelegateProxyType` should never be initialized directly. To fetch initialized instance of type implementing `DelegateProxyType`, `proxyForObject` method should be used. This is more or less how it works. +-------------------------------------------+ | | | UIView subclass (UIScrollView) | | | +-----------+-------------------------------+ | | Delegate | | +-----------v-------------------------------+ | | | Delegate proxy : DelegateProxyType +-----+----> Observable<T1> | , UIScrollViewDelegate | | +-----------+-------------------------------+ +----> Observable<T2> | | | +----> Observable<T3> | | | forwards events | | to custom delegate | | v +-----------v-------------------------------+ | | | Custom delegate (UIScrollViewDelegate) | | | +-------------------------------------------+ Since RxCocoa needs to automagically create those Proxys ..and because views that have delegates can be hierarchical UITableView : UIScrollView : UIView .. and corresponding delegates are also hierarchical UITableViewDelegate : UIScrollViewDelegate : NSObject .. and sometimes there can be only one proxy/delegate registered, every view has a corresponding delegate virtual factory method. In case of UITableView / UIScrollView, there is extension UIScrollView { public func rx_createDelegateProxy() -> RxScrollViewDelegateProxy { return RxScrollViewDelegateProxy(parentObject: self) } .... and override in UITableView extension UITableView { public override func rx_createDelegateProxy() -> RxScrollViewDelegateProxy { .... */ public protocol DelegateProxyType : AnyObject { /** Creates new proxy for target object. */ static func createProxyForObject(object: AnyObject) -> AnyObject /** Returns assigned proxy for object. - parameter object: Object that can have assigned delegate proxy. - returns: Assigned delegate proxy or `nil` if no delegate proxy is assigned. */ static func assignedProxyFor(object: AnyObject) -> AnyObject? /** Assigns proxy to object. - parameter object: Object that can have assigned delegate proxy. - parameter proxy: Delegate proxy object to assign to `object`. */ static func assignProxy(proxy: AnyObject, toObject object: AnyObject) /** Returns designated delegate property for object. Objects can have multiple delegate properties. Each delegate property needs to have it's own type implementing `DelegateProxyType`. - parameter object: Object that has delegate property. - returns: Value of delegate property. */ static func currentDelegateFor(object: AnyObject) -> AnyObject? /** Sets designated delegate property for object. Objects can have multiple delegate properties. Each delegate property needs to have it's own type implementing `DelegateProxyType`. - parameter toObject: Object that has delegate property. - parameter delegate: Delegate value. */ static func setCurrentDelegate(delegate: AnyObject?, toObject object: AnyObject) /** Returns reference of normal delegate that receives all forwarded messages through `self`. - returns: Value of reference if set or nil. */ func forwardToDelegate() -> AnyObject? /** Sets reference of normal delegate that receives all forwarded messages through `self`. - parameter forwardToDelegate: Reference of delegate that receives all messages through `self`. - parameter retainDelegate: Should `self` retain `forwardToDelegate`. */ func setForwardToDelegate(forwardToDelegate: AnyObject?, retainDelegate: Bool) } @available(*, deprecated=2.5, renamed="DelegateProxyType.proxyForObject", message="You can just use normal static protocol extension. E.g. `RxScrollViewDelegateProxy.proxyForObject`") public func proxyForObject<P: DelegateProxyType>(type: P.Type, _ object: AnyObject) -> P { return P.proxyForObject(object) } extension DelegateProxyType { /** Returns existing proxy for object or installs new instance of delegate proxy. - parameter object: Target object on which to install delegate proxy. - returns: Installed instance of delegate proxy. extension UISearchBar { public var rx_delegate: DelegateProxy { return RxSearchBarDelegateProxy.proxyForObject(self) } public var rx_text: ControlProperty<String> { let source: Observable<String> = self.rx_delegate.observe(#selector(UISearchBarDelegate.searchBar(_:textDidChange:))) ... } } */ public static func proxyForObject(object: AnyObject) -> Self { MainScheduler.ensureExecutingOnScheduler() let maybeProxy = Self.assignedProxyFor(object) as? Self let proxy: Self if maybeProxy == nil { proxy = Self.createProxyForObject(object) as! Self Self.assignProxy(proxy, toObject: object) assert(Self.assignedProxyFor(object) === proxy) } else { proxy = maybeProxy! } let currentDelegate: AnyObject? = Self.currentDelegateFor(object) if currentDelegate !== proxy { proxy.setForwardToDelegate(currentDelegate, retainDelegate: false) Self.setCurrentDelegate(proxy, toObject: object) assert(Self.currentDelegateFor(object) === proxy) assert(proxy.forwardToDelegate() === currentDelegate) } return proxy } /** Sets forward delegate for `DelegateProxyType` associated with a specific object and return disposable that can be used to unset the forward to delegate. Using this method will also make sure that potential original object cached selectors are cleared and will report any accidental forward delegate mutations. - parameter forwardDelegate: Delegate object to set. - parameter retainDelegate: Retain `forwardDelegate` while it's being set. - parameter onProxyForObject: Object that has `delegate` property. - returns: Disposable object that can be used to clear forward delegate. */ public static func installForwardDelegate(forwardDelegate: AnyObject, retainDelegate: Bool, onProxyForObject object: AnyObject) -> Disposable { weak var weakForwardDelegate: AnyObject? = forwardDelegate let proxy = Self.proxyForObject(object) assert(proxy.forwardToDelegate() === nil, "This is a feature to warn you that there is already a delegate (or data source) set somewhere previously. The action you are trying to perform will clear that delegate (data source) and that means that some of your features that depend on that delegate (data source) being set will likely stop working.\n" + "If you are ok with this, try to set delegate (data source) to `nil` in front of this operation.\n" + " This is the source object value: \(object)\n" + " This this the original delegate (data source) value: \(proxy.forwardToDelegate()!)\n" + "Hint: Maybe delegate was already set in xib or storyboard and now it's being overwritten in code.\n") proxy.setForwardToDelegate(forwardDelegate, retainDelegate: retainDelegate) // refresh properties after delegate is set // some views like UITableView cache `respondsToSelector` Self.setCurrentDelegate(nil, toObject: object) Self.setCurrentDelegate(proxy, toObject: object) assert(proxy.forwardToDelegate() === forwardDelegate, "Setting of delegate failed") return AnonymousDisposable { MainScheduler.ensureExecutingOnScheduler() let delegate: AnyObject? = weakForwardDelegate assert(delegate == nil || proxy.forwardToDelegate() === delegate, "Delegate was changed from time it was first set. Current \(proxy.forwardToDelegate()), and it should have been \(proxy)") proxy.setForwardToDelegate(nil, retainDelegate: retainDelegate) } } } extension ObservableType { func subscribeProxyDataSourceForObject<P: DelegateProxyType>(object: AnyObject, dataSource: AnyObject, retainDataSource: Bool, binding: (P, Event<E>) -> Void) -> Disposable { let proxy = P.proxyForObject(object) let disposable = P.installForwardDelegate(dataSource, retainDelegate: retainDataSource, onProxyForObject: object) let subscription = self.asObservable() .catchError { error in bindingErrorToInterface(error) return Observable.empty() } // source can never end, otherwise it would release the subscriber, and deallocate the data source .concat(Observable.never()) .subscribe { [weak object] (event: Event<E>) in MainScheduler.ensureExecutingOnScheduler() if let object = object { assert(proxy === P.currentDelegateFor(object), "Proxy changed from the time it was first set.\nOriginal: \(proxy)\nExisting: \(P.currentDelegateFor(object))") } binding(proxy, event) switch event { case .Error(let error): bindingErrorToInterface(error) disposable.dispose() case .Completed: disposable.dispose() default: break } } return CompositeDisposable(subscription, disposable) } }
mit
9ba0728ea8fcf31021552f782025100b
40.226619
358
0.584119
6.141479
false
false
false
false
jozsef-vesza/MVVMExample
MVVMExample/Infrastructure/BindingExtensions.swift
1
742
// // BindingExtensions.swift // MVVMExample // // Created by József Vesza on 15/12/14. // Copyright (c) 2014 Jozsef Vesza. All rights reserved. // import Foundation public class Bindable<T> { typealias Listener = T -> Void var listener: Listener? var value: T { didSet { if let listener = listener { listener(value) } } } init(_ v: T) { value = v } public func bind(listener: Listener?) { self.listener = listener } public func bindAndFire(listener: Listener?) { self.listener = listener if let listener = self.listener { listener(value) } } }
mit
a68bb5fdbc5704c5345bf67a2af3b43e
17.55
57
0.520918
4.333333
false
false
false
false
wangwugang1314/weiBoSwift
weiBoSwift/weiBoSwift/Classes/Home/View/YBHomeCellCenterView.swift
1
3701
// // YBHomeCellCenterView.swift // weiBoSwift // // Created by MAC on 15/12/2. // Copyright © 2015年 MAC. All rights reserved. // import UIKit class YBHomeCellCenterView: UIView { // MARK: - 属性 var dataModel: YBWeiBoModel? { didSet { // 设置图片数据 collectionView.dataModel = dataModel // 判断是不是转发微薄 if let retween = dataModel?.retweeted_status { // 转发微薄 let ret = retween as! YBWeiBoModel // 设置textView textView.text = ret.text constraintTop?.constant = 5 backgroundColor = UIColor(white: 0, alpha: 0.1) }else{ // 原创微薄 textView.text = "" constraintTop?.constant = 0 backgroundColor = UIColor.whiteColor() } let collSize = collectionView.countCollectionSize() // 设置collectionView大小 constraintW?.constant = collSize.width constraintH?.constant = collSize.height constraintViewBottom?.constant = dataModel?.imageURLs.count == 0 ? 0 : 5 } } /// 约束 /// collection的约束 var constraintW: NSLayoutConstraint? var constraintH: NSLayoutConstraint? var constraintTop: NSLayoutConstraint? /// self的约束 var constraintViewBottom: NSLayoutConstraint? // MARK: - 构造方法 override init(frame: CGRect) { super.init(frame: frame) // 准备UI prepareUI() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } // MARK: - 准备UI private func prepareUI(){ // 文本视图 addSubview(textView) textView.mas_makeConstraints { (mask) -> Void in mask.top.mas_equalTo()(self.mas_top).offset()(5) mask.left.mas_equalTo()(self.mas_left).offset()(5) mask.width.mas_equalTo()(UIScreen.width() - 20) } // 图片 addSubview(collectionView) collectionView.translatesAutoresizingMaskIntoConstraints = false addConstraint(NSLayoutConstraint(item: collectionView, attribute: NSLayoutAttribute.Left, relatedBy: .Equal, toItem: self, attribute: .Left, multiplier: 1, constant: 10)) constraintW = NSLayoutConstraint(item: collectionView, attribute: .Width, relatedBy: NSLayoutRelation.Equal, toItem: nil, attribute: NSLayoutAttribute.NotAnAttribute, multiplier: 1, constant: 0) constraintH = NSLayoutConstraint(item: collectionView, attribute: .Height, relatedBy: NSLayoutRelation.Equal, toItem: nil, attribute: NSLayoutAttribute.NotAnAttribute, multiplier: 1, constant: 0) constraintTop = NSLayoutConstraint(item: collectionView, attribute: .Top, relatedBy: NSLayoutRelation.Equal, toItem: textView, attribute: NSLayoutAttribute.Bottom, multiplier: 1, constant: 0) // 底边 constraintViewBottom = NSLayoutConstraint(item: self, attribute: NSLayoutAttribute.Bottom, relatedBy: .Equal, toItem: collectionView, attribute: .Bottom, multiplier: 1, constant: 5) addConstraints([constraintW!, constraintH!, constraintTop!, constraintViewBottom!]) // 底边 } // MARK: - 懒加载 /// 文本 private lazy var textView: UILabel = { let view = UILabel() view.numberOfLines = 0 view.font = UIFont.systemFontOfSize(16) return view }() /// 图片 private lazy var collectionView: YBHomeCellImageCollectionView = { let view = YBHomeCellImageCollectionView() return view }() }
apache-2.0
d9ceb313680e7eb86144916c655b6935
36.978723
203
0.628852
4.890411
false
false
false
false
igormatyushkin014/Sensitive
Sensitive/SensitiveDemo/ViewControllers/Main/MainViewController.swift
1
1733
// // MainViewController.swift // SensitiveDemo // // Created by Igor Matyushkin on 09.11.15. // Copyright © 2015 Igor Matyushkin. All rights reserved. // import UIKit import Sensitive class MainViewController: UIViewController { // MARK: Class variables & properties // MARK: Class methods // MARK: Initializers // MARK: Deinitializer deinit { } // MARK: Outlets @IBOutlet fileprivate weak var circleView: CircleView! // MARK: Variables & properties fileprivate let colors: [UIColor] = [ .green, .yellow, .orange, .white ] fileprivate var indexOfCurrentColor: Int? // MARK: Public methods override func viewDidLoad() { super.viewDidLoad() // Initialize circle view self.circleView.onTap .handle { (tapGestureRecognizer) in if (self.indexOfCurrentColor == nil) || (self.indexOfCurrentColor! >= self.colors.count - 1) { self.indexOfCurrentColor = 0 } else { self.indexOfCurrentColor = self.indexOfCurrentColor! + 1 } let colorForCircleView = self.colors[self.indexOfCurrentColor!] self.circleView.backgroundColor = colorForCircleView } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } override var prefersStatusBarHidden : Bool { return true } // MARK: Private methods // MARK: Actions // MARK: Protocol methods }
mit
e1b05273fd6637c2157c534b963dfba5
22.093333
110
0.569861
5.296636
false
false
false
false
JesusAntonioGil/MemeMe2.0
MemeMe2/Controllers/MemeTable/MemeTableViewController.swift
1
2417
// // MemeTableViewController.swift // MemeMe2 // // Created by Jesus Antonio Gil on 24/3/16. // Copyright © 2016 Jesus Antonio Gil. All rights reserved. // import UIKit class MemeTableViewController: UIViewController { @IBOutlet weak var tableView: UITableView! @IBOutlet weak var addButton: UIBarButtonItem! //Injected var storageHelperProtocol: StorageHelperProtocol! var controllerAssembly: ControllerAssembly! //MARK: LIFE CYCLE override func viewDidLoad() { super.viewDidLoad() } override func viewDidAppear(animated: Bool) { super.viewDidAppear(animated) tableView.reloadData() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } //MARK: ACTIONS @IBAction func onAddImageButtonTap(sender: AnyObject) { let generateNavigationController: UINavigationController = controllerAssembly.generateNavigationController() as! UINavigationController navigationController?.presentViewController(generateNavigationController, animated: true, completion: nil) } } extension MemeTableViewController: UITableViewDelegate { func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat { return 90.0 } } extension MemeTableViewController: UITableViewDataSource { func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return storageHelperProtocol.memes.count } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell: MemeTableViewCell = tableView.dequeueReusableCellWithIdentifier("MemeTableViewCell", forIndexPath: indexPath) as! MemeTableViewCell cell.memeObject = storageHelperProtocol.memes[indexPath.row] return cell } func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { tableView.deselectRowAtIndexPath(indexPath, animated: true) let detailViewController: DetailViewController = controllerAssembly.detailViewController() as! DetailViewController detailViewController.memeObject = storageHelperProtocol.memes[indexPath.row] navigationController?.pushViewController(detailViewController, animated: true) } }
mit
c8ad6d008e890291c10dd985e46b9442
28.108434
149
0.722682
5.950739
false
false
false
false
mtgto/GPM
GPM/Kanban.swift
1
663
// // Kanban.swift // GPM // // Created by mtgto on 2016/09/18. // Copyright © 2016 mtgto. All rights reserved. // import Cocoa class Kanban: Hashable, Equatable { let owner: String let repo: String let number: Int var cards: [(GitHubProject.Column, [GitHubProject.Card])] = [] init(owner: String, repo: String, number: Int) { self.owner = owner self.repo = repo self.number = number } var hashValue: Int { return "\(owner)/\(repo)/\(number)".hashValue } } func ==(lhs: Kanban, rhs: Kanban) -> Bool { return lhs.owner == rhs.owner && lhs.repo == rhs.repo && lhs.number == rhs.number }
mit
ebd1fd610aaefe7d7b90ce585ed4d8d4
21.066667
85
0.598187
3.447917
false
false
false
false
SwiftORM/Postgres-StORM
Sources/PostgresStORM/Insert.swift
1
2491
// // Insert.swift // PostgresStORM // // Created by Jonathan Guthrie on 2016-09-24. // // import StORM import PerfectLogger /// Performs insert functions as an extension to the main class. extension PostgresStORM { /// Insert function where the suppled data is in [(String, Any)] format. @discardableResult public func insert(_ data: [(String, Any)]) throws -> Any { var keys = [String]() var vals = [String]() for i in data { keys.append(i.0) vals.append(String(describing: i.1)) } do { return try insert(cols: keys, params: vals) } catch { LogFile.error("Error: \(error)", logFile: "./StORMlog.txt") throw StORMError.error("\(error)") } } /// Insert function where the suppled data is in [String: Any] format. public func insert(_ data: [String: Any]) throws -> Any { var keys = [String]() var vals = [String]() for i in data.keys { keys.append(i.lowercased()) vals.append(data[i] as! String) } do { return try insert(cols: keys, params: vals) } catch { LogFile.error("Error: \(error)", logFile: "./StORMlog.txt") throw StORMError.error("\(error)") } } /// Insert function where the suppled data is in matching arrays of columns and parameter values. public func insert(cols: [String], params: [Any]) throws -> Any { let (idname, _) = firstAsKey() do { return try insert(cols: cols, params: params, idcolumn: idname) } catch { LogFile.error("Error: \(error)", logFile: "./StORMlog.txt") throw StORMError.error("\(error)") } } /// Insert function where the suppled data is in matching arrays of columns and parameter values, as well as specifying the name of the id column. public func insert(cols: [String], params: [Any], idcolumn: String) throws -> Any { var paramString = [String]() var substString = [String]() for i in 0..<params.count { paramString.append(String(describing: params[i])) substString.append("$\(i+1)") } //"\"" + columns.joined(separator: "\",\"") + "\"" let colsjoined = "\"" + cols.joined(separator: "\",\"") + "\"" let str = "INSERT INTO \(self.table()) (\(colsjoined.lowercased())) VALUES(\(substString.joined(separator: ","))) RETURNING \"\(idcolumn.lowercased())\"" do { let response = try exec(str, params: paramString) return parseRows(response)[0].data[idcolumn.lowercased()]! } catch { LogFile.error("Error: \(error)", logFile: "./StORMlog.txt") self.error = StORMError.error("\(error)") throw error } } }
apache-2.0
b98049f0e3d9c3b0773f0e214f54689d
26.373626
155
0.645524
3.389116
false
false
false
false
youngsoft/TangramKit
TangramKit/TangramKit.swift
1
13385
// // TangramKit.swift // TangramKit // // Created by 欧阳大哥 on 16/10/28. // Copyright (c) 2015年 YoungSoft. All rights reserved. // Email: [email protected] // QQ: 156355113 // QQ群: 178573773 // Github: https://github.com/youngsoft/TangramKit forSwift // Github: https://github.com/youngsoft/MyLinearLayout forObjective-C // HomePage: http://www.jianshu.com/users/3c9287519f58 // HomePage: http://blog.csdn.net/yangtiang // /* The MIT License (MIT) Copyright (c) 2016 YoungSoft 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. */ /* 感谢TangramKit的共同开发者,没有他们的帮忙我无法准时的完成这件事情,他们之中有我的同事,也有共同的兴趣爱好者。他们是: 闫涛: github: https://github.com/taoyan homepage: http://blog.csdn.net/u013928640 张光凯 github: https://github.com/loveNoodles homepage: http://blog.csdn.net/u011597585 周杰: github: https://github.com/MineJ 阳光不锈: github: https://github.com/towik */ //Current version is 1.4.2, please open: https://github.com/youngsoft/TangramKit/blob/master/CHANGELOG.md to show the changes. import Foundation import UIKit /// 布局视图方向的枚举类型定义。用来指定布局内子视图的整体排列布局方向。 /// /// - vert: 垂直方向,布局视图内所有子视图整体从上到下排列布局。 /// - horz: 水平方向,布局视图内所有子视图整体从左到右排列布局。 public enum TGOrientation { /// 垂直方向,布局视图内所有子视图整体从上到下排列布局。 case vert /// 水平方向,布局视图内所有子视图整体从左到右排列布局。 case horz } /// 视图的可见性枚举类型定义。用来指定视图是否在布局中可见,他是对hidden属性的扩展设置 /// /// - visible: 视图可见,等价于hidden = false /// - invisible: 视图隐藏,等价于hidden = true, 但是会在父布局视图中占位空白区域 /// - gone: 视图隐藏,等价于hidden = true, 但是不会在父视图中占位空白区域 public enum TGVisibility { /// 视图可见,等价于hidden = false case visible /// 视图隐藏,等价于hidden = true, 但是会在父布局视图中占位空白区域 case invisible /// 视图隐藏,等价于hidden = true, 但是不会在父视图中占位空白区域 case gone } /// 布局视图内所有子视图的停靠方向和填充拉伸属性以及对齐方式的枚举类型定义。 /// /// - 所谓停靠方向就是指子视图停靠在布局视图中水平方向和垂直方向的位置。水平方向一共有左、水平中心、右、窗口水平中心四个位置,垂直方向一共有上、垂直中心、下、窗口垂直中心四个位置。 /// - 所谓填充拉伸属性就是指子视图的尺寸填充或者子视图的间距拉伸满整个布局视图。一共有水平宽度、垂直高度两种尺寸填充,水平间距、垂直间距两种间距拉伸。 /// - 所谓对齐方式就是指多个子视图之间的对齐位置。水平方向一共有左、水平居中、右、左右两端对齐四种对齐方式,垂直方向一共有上、垂直居中、下、向下两端对齐四种方式。 /// /// 在布局基类中有一个gravity属性用来表示布局内所有子视图的停靠方向和填充拉伸属性;在流式布局中有一个arrangedGravity属性用来表示布局内每排子视图的对齐方式。 public struct TGGravity : OptionSet { public let rawValue :Int public init(rawValue: Int) {self.rawValue = rawValue} /// 默认值,不停靠、不填充、不对齐。 public static let none = TGGravity(rawValue:0) /// 水平方向 public struct horz { /// 左边停靠或者左对齐 public static let left = TGGravity(rawValue:1) /// 水平中心停靠或者水平居中对齐 public static let center = TGGravity(rawValue:2) /// 右边停靠或者右对齐 public static let right = TGGravity(rawValue:4) /// 窗口水平中心停靠,表示在屏幕窗口的水平中心停靠 public static let windowCenter = TGGravity(rawValue: 8) /// 水平间距拉伸,并且头尾部分的间距是0, 如果只有一个子视图则变为左边停靠 public static let between = TGGravity(rawValue: 16) /// 头部对齐,对于阿拉伯国家来说是和Right等价的,对于非阿拉伯国家则是和Left等价的 public static let leading = TGGravity(rawValue: 32) /// 尾部对齐,对于阿拉伯国家来说是和Left等价的,对于非阿拉伯国家则是和Right等价的 public static let trailing = TGGravity(rawValue:64) /// 水平间距环绕拉伸,并且头尾部分为其他部分间距的一半, 如果只有一个子视图则变为水平居中停靠 public static let around = TGGravity(rawValue: 128) /// 水平间距等分拉伸,并且头尾部分和其他部分间距的一样, 如果只有一个子视图则变为水平居中停靠 public static let among:TGGravity = [horz.between, horz.around] /// 水平宽度填充 public static let fill:TGGravity = [horz.left, horz.center, horz.right] /// 水平掩码,用来获取水平方向的枚举值 public static let mask = TGGravity(rawValue:0xFF00) } /// 垂直方向 public struct vert { /// 上边停靠或者上对齐 public static let top = TGGravity(rawValue:1 << 8) /// 垂直中心停靠或者垂直居中对齐 public static let center = TGGravity(rawValue:2 << 8) /// 下边停靠或者下边对齐 public static let bottom = TGGravity(rawValue:4 << 8) /// 窗口垂直中心停靠,表示在屏幕窗口的垂直中心停靠 public static let windowCenter = TGGravity(rawValue:8 << 8) /// 垂直间距拉伸,并且头尾部分的间距是0, 如果只有一个子视图则变为上边停靠 public static let between = TGGravity(rawValue: 16 << 8) /// 垂直高度填充 public static let fill:TGGravity = [vert.top, vert.center, vert.bottom] /// 基线对齐,只支持水平线性布局,指定基线对齐必须要指定出一个基线标准的子视图 public static let baseline = TGGravity(rawValue: 32 << 8) /// 垂直间距环绕拉伸,并且头尾部分为其他部分间距的一半, 如果只有一个子视图则变为垂直居中停靠 public static let around = TGGravity(rawValue: 64 << 8) /// 垂直间距等分拉伸,并且头尾部分和其他部分间距的一样, 如果只有一个子视图则变为垂直居中停靠 public static let among:TGGravity = [vert.between, vert.around] /// 垂直掩码,用来获取垂直方向的枚举值 public static let mask = TGGravity(rawValue:0x00FF) } /// 整体居中 public static let center:TGGravity = [horz.center, vert.center] /// 全部填充 public static let fill:TGGravity = [horz.fill, vert.fill] /// 全部拉伸 public static let between:TGGravity = [horz.between, vert.between] public static let around:TGGravity = [horz.around, vert.around] public static let among:TGGravity = [horz.among, vert.among] } public func &(left: TGGravity, right: TGGravity) -> TGGravity { return TGGravity(rawValue: left.rawValue & right.rawValue) } public func >(left: TGGravity, right: TGGravity) -> Bool { return left.rawValue > right.rawValue } /// 停靠对齐的生效策略,主要用于流式布局中的最后一行。 /// /// - no: 不做任何停靠对齐 /// - always: 总是停靠对齐 /// - auto: 自动使用前面的停靠对齐策略 public enum TGGravityPolicy { case no case always case auto } /// 用来设置当线性布局中的子视图的尺寸大于线性布局的尺寸时的子视图的压缩策略枚举类型定义。请参考线性布局的tg_shrinkType属性的定义。 public struct TGSubviewsShrinkType : OptionSet { public let rawValue :Int public init(rawValue: Int) {self.rawValue = rawValue} //压缩策略 /// 不压缩,默认是这个值 public static let none = TGSubviewsShrinkType(rawValue:0) /// 平均压缩。 public static let average = TGSubviewsShrinkType(rawValue:1) /// 比例压缩。 public static let weight = TGSubviewsShrinkType(rawValue:2) /// 自动压缩。这个属性只有在水平线性布局里面并且只有2个子视图的宽度等于.wrap时才有用。这个属性主要用来实现左右两个子视图根据自身内容来进行缩放,以便实现最佳的宽度空间利用 public static let auto = TGSubviewsShrinkType(rawValue:4) //压缩模式 /// 尺寸压缩 public static let size = TGSubviewsShrinkType(rawValue:0) /// 间距压缩 public static let space = TGSubviewsShrinkType(rawValue:16) } /// 位置和尺寸的比重对象,表示位置或尺寸的值是相对值。也就是尺寸或者位置的百分比值。 /// /// 比如tg_width.equal(20%) 表示子视图的宽度是父视图的20%的比例。 /// 请使用 数字% 方法来使用TGWeight类型的值。 public struct TGWeight:Any { //常用的比重值。 /// 0比重,表示不占用任何位置和尺寸。 public static let zeroWeight = TGWeight(0) private var _value:CGFloat = 0 public init(_ value:Int8) { _value = CGFloat(value) } public init(_ value:Int16) { _value = CGFloat(value) } public init(_ value:Int32) { _value = CGFloat(value) } public init(_ value:Int64) { _value = CGFloat(value) } public init(_ value:Int) { _value = CGFloat(value) } public init(_ value:UInt) { _value = CGFloat(value) } public init(_ value:Double) { _value = CGFloat(value) } public init (_ value:Float) { _value = CGFloat(value) } public init(_ value:CGFloat) { _value = value } public init(_ value:TGWeight) { _value = value._value } internal var rawValue:CGFloat{ get { return _value; } set { _value = newValue } } } extension TGWeight:Equatable { } public func !=(lhs: TGWeight, rhs: TGWeight) -> Bool { return lhs.rawValue != rhs.rawValue } public func ==(lhs: TGWeight, rhs: TGWeight) -> Bool { return lhs.rawValue == rhs.rawValue } public func +=( lhs:inout TGWeight, rhs:TGWeight) { lhs.rawValue += rhs.rawValue } public func -=( lhs:inout TGWeight, rhs:TGWeight) { lhs.rawValue -= rhs.rawValue } public func +(lhs:TGWeight, rhs:TGWeight) ->TGWeight { return TGWeight(lhs.rawValue + rhs.rawValue) } //比重对象的快捷使用方式。 postfix operator % // TGWeight(100) <==> 100% public postfix func %(val:CGFloat) ->TGWeight { return TGWeight(val) } public postfix func %(val:Int) ->TGWeight { return TGWeight(val) } /// 设置当将布局视图嵌入到UIScrollView以及其派生类时对UIScrollView的contentSize的调整设置模式的枚举类型定义。 /// 当将一个布局视图作为子视图添加到UIScrollView或者其派生类时(UITableView,UICollectionView除外)系统会自动调整和计算并设置其中的contentSize值。您可以使用布局视图的属性tg_adjustScrollViewContentSizeMode来进行设置定义的枚举值。 /// /// - auto: 自动调整,在添加到UIScrollView之前(UITableView, UICollectionView除外)。如果值被设置auto则自动会变化yes。如果值被设置为no则不进行任何调整 /// - no: 不会调整contentSize /// - yes: 一定会调整contentSize public enum TGAdjustScrollViewContentSizeMode { /// 自动调整,在添加到UIScrollView之前(UITableView, UICollectionView除外)。如果值被设置auto则自动会变化yes。如果值被设置为no则不进行任何调整 case auto /// 不会调整contentSize case no /// 一定会调整contentSize case yes }
mit
fe5f2d0d837ec0439062681073aa4a8c
26.838983
158
0.676104
3.050139
false
false
false
false
ddimitrov90/EverliveSDK
Tests/Pods/EverliveSDK/EverliveSDK/EVReflectionExtensions.swift
2
4630
// // EVReflectionExtensions.swift // EverliveSwift // // Created by Dimitar Dimitrov on 3/2/16. // Copyright © 2016 ddimitrov. All rights reserved. // import Foundation import EVReflection extension EVReflection { public class func prepareCreateObjectString(theObject: NSObject, performKeyCleanup:Bool = true) -> String { var (dict,_) = EVReflection.toDictionary(theObject) dict = fixPropertyNames(dict) let skippedProps: Set<String> = ((theObject as? DataItem)?.getSkippedProperties())! dict = removeSkippedProperties(dict, skippedProps: skippedProps) dict = convertDictionaryForJsonSerialization(dict) var result: String = "" do { let jsonData = try NSJSONSerialization.dataWithJSONObject(dict , options: .PrettyPrinted) if let jsonString = NSString(data:jsonData, encoding:NSUTF8StringEncoding) { result = jsonString as String } } catch { } return result } public class func prepareUpdateObjectString(theObject: NSObject, changedProperties: Set<String>, performKeyCleanup:Bool = true) -> NSDictionary { var (dict,_) = EVReflection.toDictionary(theObject) dict = removeNonModifiedProps(dict, changedProps: changedProperties) let skippedProps: Set<String> = ((theObject as? DataItem)?.getSkippedProperties())! dict = removeSkippedProperties(dict, skippedProps: skippedProps) dict = convertDictionaryForJsonSerialization(dict) return dict } private class func removeNonModifiedProps(dict: NSDictionary, changedProps: Set<String>) -> NSDictionary { let newProperties = NSMutableDictionary() for (key, _) in dict { if((changedProps.indexOf(key as! String)) != nil){ var newKey: String = key as! String; newKey.replaceRange(newKey.startIndex...newKey.startIndex, with: String(newKey[newKey.startIndex]).capitalizedString) newProperties[newKey] = dict[key as! String] } } return newProperties } private class func removeSkippedProperties(dict: NSDictionary, skippedProps: Set<String>) -> NSDictionary { let newProperties = NSMutableDictionary() for (key, _) in dict { if((skippedProps.indexOf(key as! String)) == nil){ newProperties[key as! String] = dict[key as! String] } } return newProperties } private class func fixPropertyNames(dict: NSDictionary) -> NSDictionary { let newProperties = NSMutableDictionary() for (key, _) in dict { var newKey: String = key as! String; newKey.replaceRange(newKey.startIndex...newKey.startIndex, with: String(newKey[newKey.startIndex]).capitalizedString) newProperties[newKey] = dict[key as! String] } return newProperties } private class func convertDictionaryForJsonSerialization(dict: NSDictionary) -> NSDictionary { for (key, value) in dict { dict.setValue(convertValueForJsonSerialization(value), forKey: key as! String) } return dict } private class func convertValueForJsonSerialization(value : AnyObject) -> AnyObject { switch(value) { case let stringValue as NSString: return stringValue case let numberValue as NSNumber: return numberValue case let nullValue as NSNull: return nullValue case let arrayValue as NSArray: let tempArray: NSMutableArray = NSMutableArray() for value in arrayValue { tempArray.addObject(convertValueForJsonSerialization(value)) } return tempArray case let date as NSDate: return (getDateFormatter().stringFromDate(date) ?? "") case let ok as NSDictionary: return convertDictionaryForJsonSerialization(ok) default: NSLog("ERROR: Unexpected type while converting value for JsonSerialization") return "\(value)" } } private static var dateFormatter: NSDateFormatter? = nil private class func getDateFormatter() -> NSDateFormatter { if let formatter = dateFormatter { return formatter } let formatter = NSDateFormatter() formatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'" formatter.timeZone = NSTimeZone(forSecondsFromGMT: 0) formatter.locale = NSLocale(localeIdentifier: "en_US_POSIX") return formatter } }
mit
c7236ce0a56bbd3d9dadfb4f6fd76603
39.973451
149
0.645064
5.092409
false
false
false
false
mkaply/firefox-ios
Client/Frontend/Browser/TabDisplayManager.swift
5
20293
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ import Foundation import Shared import Storage extension UIGestureRecognizer { func cancel() { if isEnabled { isEnabled = false isEnabled = true } } } // MARK: Delegate for animation completion notifications. enum TabAnimationType { case addTab case removedNonLastTab case removedLastTab case updateTab case moveTab } protocol TabDisplayCompletionDelegate: AnyObject { func completedAnimation(for: TabAnimationType) } // MARK: - @objc protocol TabSelectionDelegate: AnyObject { func didSelectTabAtIndex(_ index: Int) } protocol TopTabCellDelegate: AnyObject { func tabCellDidClose(_ cell: UICollectionViewCell) } protocol TabDisplayer: AnyObject { typealias TabCellIdentifer = String var tabCellIdentifer: TabCellIdentifer { get set } func focusSelectedTab() func cellFactory(for cell: UICollectionViewCell, using tab: Tab) -> UICollectionViewCell } class TabDisplayManager: NSObject { var performingChainedOperations = false var dataStore = WeakList<Tab>() var operations = [(TabAnimationType, (() -> Void))]() weak var tabDisplayCompletionDelegate: TabDisplayCompletionDelegate? fileprivate let tabManager: TabManager fileprivate let collectionView: UICollectionView fileprivate weak var tabDisplayer: TabDisplayer? private let tabReuseIdentifer: String var searchedTabs: [Tab]? var searchActive: Bool { return searchedTabs != nil } private var tabsToDisplay: [Tab] { if let searchedTabs = searchedTabs { // tabs can be deleted while a search is active. Make sure the tab still exists in the tabmanager before displaying return searchedTabs.filter({ tabManager.tabs.contains($0) }) } return self.isPrivate ? tabManager.privateTabs : tabManager.normalTabs } private(set) var isPrivate = false // Sigh. Dragging on the collection view is either an 'active drag' where the item is moved, or // that the item has been long pressed on (and not moved yet), and this gesture recognizer has been triggered var isDragging: Bool { return collectionView.hasActiveDrag || isLongPressGestureStarted } fileprivate var isLongPressGestureStarted: Bool { var started = false collectionView.gestureRecognizers?.forEach { recognizer in if let _ = recognizer as? UILongPressGestureRecognizer, recognizer.state == .began || recognizer.state == .changed { started = true } } return started } @discardableResult fileprivate func cancelDragAndGestures() -> Bool { let isActive = collectionView.hasActiveDrag || isLongPressGestureStarted collectionView.cancelInteractiveMovement() // Long-pressing a cell to initiate dragging, but not actually moving the cell, will not trigger the collectionView's internal 'interactive movement' vars/funcs, and cancelInteractiveMovement() will not work. The gesture recognizer needs to be cancelled in this case. collectionView.gestureRecognizers?.forEach { $0.cancel() } return isActive } init(collectionView: UICollectionView, tabManager: TabManager, tabDisplayer: TabDisplayer, reuseID: String) { self.collectionView = collectionView self.tabDisplayer = tabDisplayer self.tabManager = tabManager self.isPrivate = tabManager.selectedTab?.isPrivate ?? false self.tabReuseIdentifer = reuseID super.init() tabManager.addDelegate(self) register(self, forTabEvents: .didLoadFavicon, .didChangeURL) tabsToDisplay.forEach { self.dataStore.insert($0) } collectionView.reloadData() } func togglePrivateMode(isOn: Bool, createTabOnEmptyPrivateMode: Bool) { guard isPrivate != isOn else { return } isPrivate = isOn UserDefaults.standard.set(isPrivate, forKey: "wasLastSessionPrivate") TelemetryWrapper.recordEvent(category: .action, method: .tap, object: .privateBrowsingButton, extras: ["is-private": isOn.description] ) searchedTabs = nil refreshStore() if createTabOnEmptyPrivateMode { //if private tabs is empty and we are transitioning to it add a tab if tabManager.privateTabs.isEmpty && isPrivate { tabManager.addTab(isPrivate: true) } } let tab = mostRecentTab(inTabs: tabsToDisplay) ?? tabsToDisplay.last if let tab = tab { tabManager.selectTab(tab) } } // The collection is showing this Tab as selected func indexOfCellDrawnAsPreviouslySelectedTab(currentlySelected: Tab) -> IndexPath? { for i in 0..<collectionView.numberOfItems(inSection: 0) { if let cell = collectionView.cellForItem(at: IndexPath(row: i, section: 0)) as? TopTabCell, cell.selectedTab { if let tab = dataStore.at(i), tab != currentlySelected { return IndexPath(row: i, section: 0) } else { return nil } } } return nil } func searchTabsAnimated() { let isUnchanged = (tabsToDisplay.count == dataStore.count) && tabsToDisplay.zip(dataStore).reduce(true) { $0 && $1.0 === $1.1 } if !tabsToDisplay.isEmpty && isUnchanged { return } operations.removeAll() dataStore.removeAll() tabsToDisplay.forEach { self.dataStore.insert($0) } // animates the changes collectionView.reloadSections(IndexSet(integer: 0)) } func refreshStore(evenIfHidden: Bool = false) { operations.removeAll() dataStore.removeAll() tabsToDisplay.forEach { self.dataStore.insert($0) } collectionView.reloadData() if evenIfHidden { // reloadData() will reset the data for the collection view, // but if called when offscreen it will not render properly, // unless reloadItems is explicitly called on each item. // Avoid calling with evenIfHidden=true, as it can cause a blink effect as the cell is updated. // The cause of the blinking effect is unknown (and unusual). var indexPaths = [IndexPath]() for i in 0..<collectionView.numberOfItems(inSection: 0) { indexPaths.append(IndexPath(item: i, section: 0)) } collectionView.reloadItems(at: indexPaths) } tabDisplayer?.focusSelectedTab() } // The user has tapped the close button or has swiped away the cell func closeActionPerformed(forCell cell: UICollectionViewCell) { if isDragging { return } guard let index = collectionView.indexPath(for: cell)?.item, let tab = dataStore.at(index) else { return } tabManager.removeTabAndUpdateSelectedIndex(tab) } private func recordEventAndBreadcrumb(object: TelemetryWrapper.EventObject, method: TelemetryWrapper.EventMethod) { let isTabTray = tabDisplayer as? TabTrayControllerV1 != nil let eventValue = isTabTray ? TelemetryWrapper.EventValue.tabTray : TelemetryWrapper.EventValue.topTabs TelemetryWrapper.recordEvent(category: .action, method: method, object: object, value: eventValue) } // When using 'Close All', hide all the tabs so they don't animate their deletion individually func hideDisplayedTabs( completion: @escaping () -> Void) { let cells = collectionView.visibleCells UIView.animate(withDuration: 0.2, animations: { cells.forEach { $0.alpha = 0 } }, completion: { _ in cells.forEach { $0.alpha = 1 $0.isHidden = true } completion() }) } } extension TabDisplayManager: UICollectionViewDataSource { @objc func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return dataStore.count } @objc func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let tab = dataStore.at(indexPath.row)! let cell = collectionView.dequeueReusableCell(withReuseIdentifier: self.tabReuseIdentifer, for: indexPath) assert(tabDisplayer != nil) if let tabCell = tabDisplayer?.cellFactory(for: cell, using: tab) { return tabCell } else { return cell } } @objc func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView { guard let view = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: "HeaderFooter", for: indexPath) as? TopTabsHeaderFooter else { return UICollectionReusableView() } view.arrangeLine(kind) return view } } extension TabDisplayManager: TabSelectionDelegate { func didSelectTabAtIndex(_ index: Int) { guard let tab = dataStore.at(index) else { return } if tabsToDisplay.firstIndex(of: tab) != nil { tabManager.selectTab(tab) } TelemetryWrapper.recordEvent(category: .action, method: .press, object: .tab) } } @available(iOS 11.0, *) extension TabDisplayManager: UIDropInteractionDelegate { func dropInteraction(_ interaction: UIDropInteraction, canHandle session: UIDropSession) -> Bool { // Prevent tabs from being dragged and dropped onto the "New Tab" button. if let localDragSession = session.localDragSession, let item = localDragSession.items.first, let _ = item.localObject as? Tab { return false } return session.canLoadObjects(ofClass: URL.self) } func dropInteraction(_ interaction: UIDropInteraction, sessionDidUpdate session: UIDropSession) -> UIDropProposal { return UIDropProposal(operation: .copy) } func dropInteraction(_ interaction: UIDropInteraction, performDrop session: UIDropSession) { recordEventAndBreadcrumb(object: .url, method: .drop) _ = session.loadObjects(ofClass: URL.self) { urls in guard let url = urls.first else { return } self.tabManager.addTab(URLRequest(url: url), isPrivate: self.isPrivate) } } } extension TabDisplayManager: UICollectionViewDragDelegate { // This is called when the user has long-pressed on a cell, please note that `collectionView.hasActiveDrag` is not true // until the user's finger moves. This problem is mitigated by checking the collectionView for activated long press gesture recognizers. func collectionView(_ collectionView: UICollectionView, itemsForBeginning session: UIDragSession, at indexPath: IndexPath) -> [UIDragItem] { guard let tab = dataStore.at(indexPath.item) else { return [] } // Get the tab's current URL. If it is `nil`, check the `sessionData` since // it may be a tab that has not been restored yet. var url = tab.url if url == nil, let sessionData = tab.sessionData { let urls = sessionData.urls let index = sessionData.currentPage + urls.count - 1 if index < urls.count { url = urls[index] } } // Don't store the URL in the item as dragging a tab near the screen edge will prompt to open Safari with the URL let itemProvider = NSItemProvider() recordEventAndBreadcrumb(object: .tab, method: .drag) let dragItem = UIDragItem(itemProvider: itemProvider) dragItem.localObject = tab return [dragItem] } } @available(iOS 11.0, *) extension TabDisplayManager: UICollectionViewDropDelegate { func collectionView(_ collectionView: UICollectionView, performDropWith coordinator: UICollectionViewDropCoordinator) { guard collectionView.hasActiveDrag, let destinationIndexPath = coordinator.destinationIndexPath, let dragItem = coordinator.items.first?.dragItem, let tab = dragItem.localObject as? Tab, let sourceIndex = dataStore.index(of: tab) else { return } recordEventAndBreadcrumb(object: .tab, method: .drop) coordinator.drop(dragItem, toItemAt: destinationIndexPath) self.tabManager.moveTab(isPrivate: self.isPrivate, fromIndex: sourceIndex, toIndex: destinationIndexPath.item) _ = dataStore.remove(tab) dataStore.insert(tab, at: destinationIndexPath.item) let start = IndexPath(row: sourceIndex, section: 0) let end = IndexPath(row: destinationIndexPath.item, section: 0) updateWith(animationType: .moveTab) { [weak self] in self?.collectionView.moveItem(at: start, to: end) } } func collectionView(_ collectionView: UICollectionView, dropSessionDidUpdate session: UIDropSession, withDestinationIndexPath destinationIndexPath: IndexPath?) -> UICollectionViewDropProposal { guard let localDragSession = session.localDragSession, let item = localDragSession.items.first, let _ = item.localObject as? Tab else { return UICollectionViewDropProposal(operation: .forbidden) } return UICollectionViewDropProposal(operation: .move, intent: .insertAtDestinationIndexPath) } } extension TabDisplayManager: TabEventHandler { private func updateCellFor(tab: Tab, selectedTabChanged: Bool) { let selectedTab = tabManager.selectedTab updateWith(animationType: .updateTab) { [weak self] in guard let index = self?.dataStore.index(of: tab) else { return } var items = [IndexPath]() items.append(IndexPath(row: index, section: 0)) if selectedTabChanged { self?.tabDisplayer?.focusSelectedTab() // Check if the selected tab has changed. This method avoids relying on the state of the "previous" selected tab, // instead it iterates the displayed tabs to see which appears selected. // See also `didSelectedTabChange` for more info on why this is a good approach. if let selectedTab = selectedTab, let previousSelectedIndex = self?.indexOfCellDrawnAsPreviouslySelectedTab(currentlySelected: selectedTab) { items.append(previousSelectedIndex) } } for item in items { if let cell = self?.collectionView.cellForItem(at: item), let tab = self?.dataStore.at(item.row) { let isSelected = (item.row == index && tab == self?.tabManager.selectedTab) if let tabCell = cell as? TabCell { tabCell.configureWith(tab: tab, is: isSelected) } else if let tabCell = cell as? TopTabCell { tabCell.configureWith(tab: tab, isSelected: isSelected) } } } } } func tab(_ tab: Tab, didLoadFavicon favicon: Favicon?, with: Data?) { updateCellFor(tab: tab, selectedTabChanged: false) } func tab(_ tab: Tab, didChangeURL url: URL) { updateCellFor(tab: tab, selectedTabChanged: false) } } extension TabDisplayManager: TabManagerDelegate { func tabManager(_ tabManager: TabManager, didSelectedTabChange selected: Tab?, previous: Tab?, isRestoring: Bool) { cancelDragAndGestures() if let selected = selected { // A tab can be re-selected during deletion let changed = selected != previous updateCellFor(tab: selected, selectedTabChanged: changed) } // Rather than using 'previous' Tab to deselect, just check if the selected tab is different, and update the required cells. // The refreshStore() cancels pending operations are reloads data, so we don't want functions that rely on // any assumption of previous state of the view. Passing a previous tab (and relying on that to redraw the previous tab as unselected) would be making this assumption about the state of the view. } func tabManager(_ tabManager: TabManager, didAddTab tab: Tab, isRestoring: Bool) { if isRestoring { return } if cancelDragAndGestures() { refreshStore() return } if tab.isPrivate != self.isPrivate { return } updateWith(animationType: .addTab) { [weak self] in if let me = self, let index = me.tabsToDisplay.firstIndex(of: tab) { me.dataStore.insert(tab, at: index) me.collectionView.insertItems(at: [IndexPath(row: index, section: 0)]) } } } func tabManager(_ tabManager: TabManager, didRemoveTab tab: Tab, isRestoring: Bool) { if cancelDragAndGestures() { refreshStore() return } let type = tabManager.normalTabs.isEmpty ? TabAnimationType.removedLastTab : TabAnimationType.removedNonLastTab updateWith(animationType: type) { [weak self] in guard let removed = self?.dataStore.remove(tab) else { return } self?.collectionView.deleteItems(at: [IndexPath(row: removed, section: 0)]) } } /* Function to take operations off the queue recursively, and perform them (i.e. performBatchUpdates) in sequence. If this func is called while it (or performBatchUpdates) is running, it returns immediately. The `refreshStore()` function will clear the queue and reload data, and the view will instantly match the tab manager. Therefore, don't put operations on the queue that depend on previous operations on the queue. In these cases, just check the current state on-demand in the operation (for example, don't assume that a previous tab is selected because that was the previous operation in queue). For app events where each operation should be animated for the user to see, performedChainedOperations() is the one to use, and for bulk updates where it is ok to just redraw the entire view with the latest state, use `refreshStore()`. */ private func performChainedOperations() { guard !performingChainedOperations, let (type, operation) = operations.popLast() else { return } performingChainedOperations = true collectionView.performBatchUpdates({ [weak self] in // Baseline animation speed is 1.0, which is too slow, this (odd) code sets it to 3x self?.collectionView.forFirstBaselineLayout.layer.speed = 3.0 operation() }, completion: { [weak self] (done) in self?.performingChainedOperations = false self?.tabDisplayCompletionDelegate?.completedAnimation(for: type) self?.performChainedOperations() }) } private func updateWith(animationType: TabAnimationType, operation: (() -> Void)?) { if let op = operation { operations.insert((animationType, op), at: 0) } performChainedOperations() } func tabManagerDidRestoreTabs(_ tabManager: TabManager) { cancelDragAndGestures() refreshStore() // Need scrollToCurrentTab and not focusTab; these exact params needed to focus (without using async dispatch). (tabDisplayer as? TopTabsViewController)?.scrollToCurrentTab(false, centerCell: true) } func tabManagerDidAddTabs(_ tabManager: TabManager) { cancelDragAndGestures() } func tabManagerDidRemoveAllTabs(_ tabManager: TabManager, toast: ButtonToast?) { cancelDragAndGestures() } }
mpl-2.0
eb2971a3009b20716a268a511313850c
39.586
275
0.654462
5.103873
false
false
false
false
franciscocgoncalves/FastCapture
FastCapture/Keys.swift
1
1412
// // Keys.swift // FastCapture // // Created by Francisco Gonçalves on 22/04/15. // Copyright (c) 2015 Francisco Gonçalves. All rights reserved. // import Cocoa class Keys: NSObject { let keysValuesDict: NSDictionary var _anonymousClientId: String? var anonymousClientId: String { get { if _anonymousClientId == nil { _anonymousClientId = keysValuesDict.objectForKey("anonymousClientId") as? String } return _anonymousClientId! } } var _authenticatedClientId: String? var authenticatedClientId: String { get { if _authenticatedClientId == nil { _authenticatedClientId = keysValuesDict.objectForKey("authenticatedClientId") as? String } return _authenticatedClientId! } } var _authenticatedSecret: String? var authenticatedSecret: String { get { if _authenticatedSecret == nil { _authenticatedSecret = keysValuesDict.objectForKey("authenticatedSecret") as? String } return _authenticatedSecret! } } override init() { let keyValuesPath = NSBundle.mainBundle().pathForResource("Keys", ofType: "plist")! keysValuesDict = NSDictionary(contentsOfFile: keyValuesPath as String)! } }
mit
5055867d45e90e1c0da7c42d47d400d4
26.647059
104
0.594326
5.108696
false
false
false
false
briceZhao/ZXRefresh
ZXRefreshExample/ZXRefreshExample/BaseViewController.swift
1
2355
// // BaseViewController.swift // ZXRefreshExample // // Created by briceZhao on 2017/8/17. // Copyright © 2017年 chengyue. All rights reserved. // import UIKit class BaseViewController: UITableViewController { var models = ["1、你若安好,便是晴天。", "2、人生没有彩排,每一天都是现场直播。", "3、我们走得太快,灵魂都跟不上了。", "4、人生就像一杯茶,不会苦一辈子,但总会苦一阵子。", "5、人生如果错了方向,停止就是进步。", "6、理想很丰满,现实很骨感。", "7、男人一有钱就变坏,女人一边坏就有钱。", "8、择一城终老,遇一人白首。", "9、低头要有勇气,抬头要有底气。", "10、愿得一人心,白首不分离。", "11、一个人炫耀什么,说明内心缺少什么。", "12、试金可以用火,试女人可以用金,试男人可以用女人。", "13、时间就像一张网,你撒在哪里,你的收获就在哪里。", "14、学习要加,骄傲要减,机会要乘,懒惰要除。", "15、如果你简单,这个世界就对你简单。"] override func viewDidLoad() { super.viewDidLoad() self.tableView.tableFooterView = UIView(frame: CGRect.zero) self.view.backgroundColor = UIColor.lightGray } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return models.count } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { var cell = tableView.dequeueReusableCell(withIdentifier: "cell") if cell == nil { cell = UITableViewCell(style: .default, reuseIdentifier: "cell") } cell?.textLabel?.text = "\(models[(indexPath as NSIndexPath).row])" return cell! } override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { return 44.0 } deinit{ print("Deinit of \(NSStringFromClass(type(of: self)))") } }
mit
e9b7de6aabbab06d25b389a21f20c4be
29.915254
109
0.555921
3.334552
false
false
false
false
iandundas/HotTakeRealm
HotTakeRealmTests/RealmDatasourceTests.swift
1
12100
// // RealmDatasourceTests.swift // ReactiveKitSwappableDatasource // // Created by Ian Dundas on 05/06/2016. // Copyright © 2016 IanDundas. All rights reserved. // import UIKit import XCTest import RealmSwift import ReactiveKit import Nimble import HotTakeCore import Bond @testable import HotTakeRealm class RealmDatasourceTests: XCTestCase { var emptyRealm: Realm! var nonEmptyRealm: Realm! var bag: DisposeBag! var datasource: RealmDataSource<Cat>! override func setUp() { super.setUp() bag = DisposeBag() nonEmptyRealm = try! Realm(configuration: Realm.Configuration(inMemoryIdentifier: UUID().uuidString)) emptyRealm = try! Realm(configuration: Realm.Configuration(inMemoryIdentifier: UUID().uuidString)) try! nonEmptyRealm.write { nonEmptyRealm.add(Cat(value: ["name" : "Cat A", "miceEaten": 0])) } } override func tearDown() { bag.dispose() emptyRealm = nil nonEmptyRealm = nil datasource = nil super.tearDown() } func testInitialNotificationIsReceived(){ datasource = RealmDataSource<Cat>(items: nonEmptyRealm.objects(Cat.self)) let firstEvent = ChangesetProperty(nil) let secondEvent = ChangesetProperty(nil) datasource.mutations().element(at: 0).bind(to: firstEvent).dispose(in: bag) datasource.mutations().element(at: 1).bind(to: secondEvent).dispose(in: bag) expect(firstEvent.value?.change).to(equal(ObservableArrayChange.reset)) expect(secondEvent.value?.change).to(beNil()) } func testInsertEventIsReceived(){ datasource = RealmDataSource<Cat>(items: emptyRealm.objects(Cat.self)) let secondEvent = ChangesetProperty(nil) datasource.mutations().element(at: 1).bind(to: secondEvent).dispose(in: bag) let thirdEvent = ChangesetProperty(nil) datasource.mutations().element(at: 2).bind(to: thirdEvent).dispose(in: bag) let fourthEvent = ChangesetProperty(nil) datasource.mutations().element(at: 3).bind(to: fourthEvent).dispose(in: bag) try! emptyRealm.write { emptyRealm.add(Cat(value: ["name" : "Mr Cow"])) } expect(secondEvent.value?.change).toEventually(equal(ObservableArrayChange.beginBatchEditing), timeout:2) expect(thirdEvent.value?.change).toEventually(equal(ObservableArrayChange.inserts([0]))) expect(fourthEvent.value?.change).toEventually(equal(ObservableArrayChange.endBatchEditing)) } func testDeleteEventIsReceived(){ datasource = RealmDataSource<Cat>(items: nonEmptyRealm.objects(Cat.self)) let secondEvent = ChangesetProperty(nil) datasource.mutations().element(at: 1).bind(to: secondEvent).dispose(in: bag) let thirdEvent = ChangesetProperty(nil) datasource.mutations().element(at: 2).bind(to: thirdEvent).dispose(in: bag) let fourthEvent = ChangesetProperty(nil) datasource.mutations().element(at: 3).bind(to: fourthEvent).dispose(in: bag) try! nonEmptyRealm.write { datasource.items().forEach(nonEmptyRealm.delete) } expect(secondEvent.value?.change).toEventually(equal(ObservableArrayChange.beginBatchEditing)) expect(thirdEvent.value?.change).toEventually(equal(ObservableArrayChange.deletes([0]))) expect(fourthEvent.value?.change).toEventually(equal(ObservableArrayChange.endBatchEditing)) } func testBasicInsertBindingWhereObserverIsBoundBeforeInsert() { datasource = RealmDataSource<Cat>(items:emptyRealm.objects(Cat.self)) let firstEvent = ChangesetProperty(nil) datasource.mutations().element(at:0).bind(to: firstEvent) let thirdEvent = ChangesetProperty(nil) datasource.mutations().element(at:2).bind(to: thirdEvent) try! emptyRealm.write { emptyRealm.add(Cat(value: ["name" : "Mr Cow"])) } expect(firstEvent.value?.source).toEventually(beEmpty()) expect(thirdEvent.value?.source).toEventually(haveCount(1)) expect(thirdEvent.value?.change).toEventually(equal(ObservableArrayChange.inserts([0]))) } func testBasicInsertBindingWhereObserverIsBoundAfterInsertWithoutDelay() { datasource = RealmDataSource<Cat>(items:emptyRealm.objects(Cat.self)) try! emptyRealm.write { emptyRealm.add(Cat(value: ["name" : "Mr Cow"])) } let firstEvent = ChangesetProperty(nil) datasource.mutations().element(at:0).bind(to: firstEvent) let secondEvent = ChangesetProperty(nil) datasource.mutations().element(at:1).bind(to: secondEvent) expect(firstEvent.value?.source).toEventually(haveCount(1), timeout: 2) expect(firstEvent.value?.change).toEventually(equal(ObservableArrayChange.reset)) expect(secondEvent.value).toEventually(beNil(), timeout: 2) } func testBasicInsertBindingWhereObserverIsBoundAfterInsertWithADelay() { datasource = RealmDataSource<Cat>(items:emptyRealm.objects(Cat.self)) try! emptyRealm.write { emptyRealm.add(Cat(value: ["name" : "Mr Cow"])) } let firstEvent = ChangesetProperty(nil) let thirdEvent = ChangesetProperty(nil) DispatchQueue.main.asyncAfter(deadline: .now() + 1) { self.datasource.mutations().element(at:0).bind(to: firstEvent) self.datasource.mutations().element(at:1).bind(to: thirdEvent) } expect(firstEvent.value?.source).toEventually(haveCount(1), timeout: 2) expect(firstEvent.value?.change).toEventually(equal(ObservableArrayChange.reset)) expect(thirdEvent.value).toEventually(beNil(), timeout: 2) } func testBasicInsertBindingWhereObserverIsBoundBeforeInsertAndAnItemIsAlreadyAdded() { datasource = RealmDataSource<Cat>(items:nonEmptyRealm.objects(Cat.self)) let firstEvent = ChangesetProperty(nil) datasource.mutations().element(at:0).bind(to: firstEvent) let thirdEvent = ChangesetProperty(nil) datasource.mutations().element(at:2).bind(to: thirdEvent) try! nonEmptyRealm.write { nonEmptyRealm.add(Cat(value: ["name" : "Mr Cow"])) } expect(firstEvent.value?.source).toEventually(haveCount(1), timeout: 2) expect(firstEvent.value?.change).toEventually(equal(ObservableArrayChange.reset)) expect(thirdEvent.value?.change).toEventually(equal(ObservableArrayChange.inserts([1])), timeout: 2) expect(thirdEvent.value?.source).toEventually(haveCount(2), timeout: 2) } func testBasicInsertBindingWhereObserverIsBoundAfterInsertWithoutDelayAndAnItemIsAlreadyAdded() { datasource = RealmDataSource<Cat>(items:nonEmptyRealm.objects(Cat.self)) try! nonEmptyRealm.write { nonEmptyRealm.add(Cat(value: ["name" : "Mr Cow"])) } let firstEvent = ChangesetProperty(nil) datasource.mutations().element(at:0).bind(to: firstEvent) let thirdEvent = ChangesetProperty(nil) datasource.mutations().element(at:1).bind(to: thirdEvent) expect(firstEvent.value?.source).toEventually(haveCount(2), timeout: 2) expect(firstEvent.value?.change).toEventually(equal(ObservableArrayChange.reset)) expect(thirdEvent.value).toEventually(beNil(), timeout: 2) } func testBasicInsertBindingWhereObserverIsBoundAfterInsertWithADelayAndAnItemIsAlreadyAdded() { datasource = RealmDataSource<Cat>(items:nonEmptyRealm.objects(Cat.self)) try! nonEmptyRealm.write { nonEmptyRealm.add(Cat(value: ["name" : "Mr Cow"])) } let firstEvent = ChangesetProperty(nil) let thirdEvent = ChangesetProperty(nil) DispatchQueue.main.asyncAfter(deadline: .now() + 1) { self.datasource.mutations().element(at:0).bind(to: firstEvent) self.datasource.mutations().element(at:1).bind(to: thirdEvent) } expect(firstEvent.value?.source).toEventually(haveCount(2), timeout: 2) expect(firstEvent.value?.change).toEventually(equal(ObservableArrayChange.reset)) expect(thirdEvent.value).toEventually(beNil(), timeout: 2) } func testBasicDeleteWhereDatasourceIsEmptyWhenObservingAfterwards() { datasource = RealmDataSource<Cat>(items:nonEmptyRealm.objects(Cat.self)) try! nonEmptyRealm.write { datasource.items().forEach(nonEmptyRealm.delete) } let firstEvent = ChangesetProperty(nil) let secondEvent = ChangesetProperty(nil) self.datasource.mutations().element(at:0).bind(to: firstEvent) self.datasource.mutations().element(at:1).bind(to: secondEvent) expect(firstEvent.value?.source).toEventually(haveCount(0), timeout: 2) expect(firstEvent.value?.change).toEventually(equal(ObservableArrayChange.reset)) expect(secondEvent.value).toEventually(beNil(), timeout: 2) } func testBasicDeleteWhereDatasourceEmptiesAfterObservingOnSameThread() { datasource = RealmDataSource<Cat>(items:nonEmptyRealm.objects(Cat.self)) let firstEvent = ChangesetProperty(nil) self.datasource.mutations().element(at:0).bind(to: firstEvent) let thirdEvent = ChangesetProperty(nil) self.datasource.mutations().element(at:2).bind(to: thirdEvent) try! nonEmptyRealm.write { datasource.items().forEach(nonEmptyRealm.delete) } expect(firstEvent.value?.source).toEventually(haveCount(1), timeout: 2) expect(firstEvent.value?.change).toEventually(equal(ObservableArrayChange.reset)) expect(thirdEvent.value?.change).toEventually(equal(ObservableArrayChange.deletes([0]))) } func testBasicDeleteWhereDatasourceEmptiesAfterObservingBeforehand() { datasource = RealmDataSource<Cat>(items:nonEmptyRealm.objects(Cat.self)) let firstChangeset = ChangesetProperty(nil) self.datasource.mutations().element(at: 0).bind(to: firstChangeset) let thirdChangeset = ChangesetProperty(nil) self.datasource.mutations().element(at: 2).bind(to: thirdChangeset) try! nonEmptyRealm.write { datasource.items().forEach(nonEmptyRealm.delete) } expect(firstChangeset.value?.source).to(haveCount(1)) expect(thirdChangeset.value?.source).toEventually(haveCount(0)) expect(thirdChangeset.value?.change).toEventually(equal(ObservableArrayChange.deletes([0]))) } func testBasicUpdateWhereDatasourceIsObservingBeforehandAfterDelay() { datasource = RealmDataSource<Cat>(items:nonEmptyRealm.objects(Cat.self)) let firstEvent = ChangesetProperty(nil) self.datasource.mutations().element(at:0).bind(to: firstEvent) let thirdEvent = ChangesetProperty(nil) self.datasource.mutations().element(at:2).bind(to: thirdEvent) DispatchQueue.main.asyncAfter(deadline: .now() + 1) { let item = self.datasource.items()[0] try! self.nonEmptyRealm.write { item.name = "new name" } } expect(firstEvent.value?.source).toEventually(haveCount(1), timeout: 2) expect(firstEvent.value?.change).toEventually(equal(ObservableArrayChange.reset)) expect(thirdEvent.value?.source).toEventually(haveCount(1), timeout: 2) expect(thirdEvent.value?.change).to(equal(ObservableArrayChange.updates([0]))) } }
mit
3fd0b41ea98c1b848610731b5f7b7f1c
38.410423
113
0.65617
4.586429
false
true
false
false
2794129697/-----mx
CoolXuePlayer/QQUserInfo.swift
1
2775
// // QQUserInfo.swift // CoolXuePlayer // // Created by lion-mac on 15/7/14. // Copyright (c) 2015年 lion-mac. All rights reserved. // import UIKit class QQUserInfo: NSObject { var nickname:String = "" var is_lost:Int = 0 var gender:String = "" var province:String = "" var city:String = "" var vip:Int = 0 var is_yellow_vip:Int = 0 var yellow_vip_level:Int = 0 var is_yellow_year_vip:Int = 0 var figureurl:String = "" //30 var figureurl_qq_1:String = "" //40 var figureurl_1:String = "" //50 var figureurl_2:String = "" //100 var level:Int = 0 init(dictQQUser: NSDictionary) { super.init() self.setQQUserInfo(dictQQUser) } func setQQUserInfo(dictQQUser:NSDictionary){ var nickname:String! = dictQQUser["nickname"] as? String var is_lost:Int! = dictQQUser["is_lost"] as? Int var gender:String! = dictQQUser["gender"] as? String var province:String! = dictQQUser["province"] as? String var city:String! = dictQQUser["city"] as? String var vip:Int! = dictQQUser["vip"] as? Int var is_yellow_vip:Int! = dictQQUser["is_yellow_vip"] as? Int var yellow_vip_level:Int! = dictQQUser["yellow_vip_level"] as? Int var is_yellow_year_vip:Int! = dictQQUser["is_yellow_year_vip"] as? Int var figureurl:String! = dictQQUser["figureurl"] as? String var figureurl_qq_1:String! = dictQQUser["figureurl_qq_1"] as? String var figureurl_1:String! = dictQQUser["figureurl_qq_1"] as? String var figureurl_2:String! = dictQQUser["figureurl_qq_1"] as? String var level:Int! = dictQQUser["figureurl_qq_1"] as? Int self.nickname = (nickname != nil) ? nickname : self.nickname self.is_lost = (is_lost != nil) ? is_lost : self.is_lost self.gender = (gender != nil) ? gender : self.gender self.province = (province != nil) ? province : self.province self.city = (city != nil) ? city : self.city self.vip = (vip != nil) ? vip : self.vip self.is_yellow_vip = (is_yellow_vip != nil) ? is_yellow_vip : self.is_yellow_vip self.yellow_vip_level = (yellow_vip_level != nil) ? yellow_vip_level : self.yellow_vip_level self.is_yellow_year_vip = (is_yellow_year_vip != nil) ? is_yellow_year_vip : self.is_yellow_year_vip self.figureurl = (figureurl != nil) ? figureurl : self.figureurl self.figureurl_qq_1 = (figureurl_qq_1 != nil) ? figureurl_qq_1 : self.figureurl_qq_1 self.figureurl_1 = (figureurl_1 != nil) ? figureurl_1 : self.figureurl_1 self.figureurl_2 = (figureurl_2 != nil) ? figureurl_2 : self.figureurl_2 self.level = (level != nil) ? level : self.level } }
lgpl-3.0
2f4685d30a54e0947d05785707f0fb0d
43.725806
108
0.613776
3.180046
false
false
false
false
emraz/ERAlertController
ERAlertController/ERAlertController.swift
1
3588
// // ERAlertController.swift // ERAlertController // // Created by Mohammad Hasan on 2/16/17. // Copyright © 2017 Matrix Solution. All rights reserved. // import UIKit class ERAlertController: NSObject { class func showAlert(_ title : String, message: String, isCancel: Bool, okButtonTitle: String, cancelButtonTitle: String, completion: ((Bool)->())?) { let alertController = AlertController(title: title, message: message, preferredStyle: .alert) let okButton = UIAlertAction(title: okButtonTitle, style: .default) { action -> Void in if completion != nil { completion!(true) } } alertController.addAction(okButton) if isCancel { let cancelButton = UIAlertAction(title: cancelButtonTitle, style: .cancel){ action -> Void in if completion != nil { completion!(false) } } alertController.addAction(cancelButton) } alertController.present(animated: true, completion: nil) } class func showAlertWithTextInput(title:String? = nil, subtitle:String? = nil, actionTitle:String? = "Add", cancelTitle:String? = "Cancel", inputPlaceholder:String? = nil, inputKeyboardType:UIKeyboardType = UIKeyboardType.default, cancelHandler: ((UIAlertAction) -> Swift.Void)? = nil, actionHandler: ((_ text: String?) -> Void)? = nil) { let alertController = AlertController(title: title, message: subtitle, preferredStyle: .alert) alertController.addTextField { (textField:UITextField) in textField.placeholder = inputPlaceholder textField.keyboardType = inputKeyboardType } alertController.addAction(UIAlertAction(title: actionTitle, style: .default, handler: { (action:UIAlertAction) in guard let textField = alertController.textFields?.first else { actionHandler?(nil) return } actionHandler?(textField.text) })) alertController.addAction(UIAlertAction(title: cancelTitle, style: .cancel, handler: cancelHandler)) alertController.present(animated: true, completion: nil) } } private var windows: [String:UIWindow] = [:] extension UIWindowScene { static var focused: UIWindowScene? { return UIApplication.shared.connectedScenes .first { $0.activationState == .foregroundActive && $0 is UIWindowScene } as? UIWindowScene } } class AlertController: UIAlertController { var wid: String? func present(animated: Bool, completion: (() -> Void)?) { guard let window = UIWindowScene.focused.map(UIWindow.init(windowScene:)) else { return } window.rootViewController = UIViewController() window.windowLevel = .alert + 1 window.makeKeyAndVisible() window.rootViewController!.present(self, animated: animated, completion: completion) wid = UUID().uuidString windows[wid!] = window } open override func viewDidDisappear(_ animated: Bool) { super.viewDidDisappear(animated) if let wid = wid { windows[wid] = nil } } }
apache-2.0
af9a06a26fd81741ee940a3ce3b0ad64
35.602041
154
0.576526
5.595944
false
false
false
false
yanagiba/swift-ast
Tests/LexerTests/RoleTests.swift
2
7092
/* Copyright 2016 Ryuichi Intellectual Property and the Yanagiba project contributors 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 XCTest @testable import Lexer fileprivate func role(of content: String) -> Role { let scanner = Scanner(content: content) return scanner.scan().role } class RoleTests: XCTestCase { func testEmptyContent() { XCTAssertEqual(role(of: ""), .eof) } func testLineFeed() { XCTAssertEqual(role(of: "\n"), .lineFeed) } func testCarriageReturn() { XCTAssertEqual(role(of: "\r"), .carriageReturn) } func testLeftParen() { XCTAssertEqual(role(of: "("), .leftParen) } func testRightParen() { XCTAssertEqual(role(of: ")"), .rightParen) } func testLeftBrace() { XCTAssertEqual(role(of: "{"), .leftBrace) } func testRightBrace() { XCTAssertEqual(role(of: "}"), .rightBrace) } func testLeftSquare() { XCTAssertEqual(role(of: "["), .leftSquare) } func testRightSquare() { XCTAssertEqual(role(of: "]"), .rightSquare) } func testPeriod() { XCTAssertEqual(role(of: "."), .period) XCTAssertEqual(role(of: ".a"), .period) XCTAssertEqual(role(of: ".."), .dotOperatorHead) } func testComma() { XCTAssertEqual(role(of: ","), .comma) } func testColon() { XCTAssertEqual(role(of: ":"), .colon) } func testSemicolon() { XCTAssertEqual(role(of: ";"), .semi) } func testEqual() { XCTAssertEqual(role(of: "="), .equal) XCTAssertEqual(role(of: "=>"), .operatorHead) XCTAssertEqual(role(of: "=&"), .operatorHead) } func testAt() { XCTAssertEqual(role(of: "@"), .at) } func testHash() { XCTAssertEqual(role(of: "#"), .hash) } func testAmp() { XCTAssertEqual(role(of: "&"), .amp) XCTAssertEqual(role(of: "&="), .operatorHead) XCTAssertEqual(role(of: "&&"), .operatorHead) } func testMinus() { XCTAssertEqual(role(of: "-"), .operatorHead) XCTAssertEqual(role(of: "-="), .operatorHead) XCTAssertEqual(role(of: "->"), .arrow) XCTAssertEqual(role(of: "-<"), .operatorHead) XCTAssertEqual(role(of: "-1"), .minus) XCTAssertEqual(role(of: "-0"), .minus) XCTAssertEqual(role(of: "-9"), .minus) } func testBacktick() { XCTAssertEqual(role(of: "`"), .backtick) } func testBackslash() { XCTAssertEqual(role(of: "\\"), .backslash) } func testDollar() { XCTAssertEqual(role(of: "$"), .dollar) } func testDoubleQuote() { XCTAssertEqual(role(of: "\""), .doubleQuote) } func testExclaim() { XCTAssertEqual(role(of: "!"), .exclaim) XCTAssertEqual(role(of: "!="), .operatorHead) XCTAssertEqual(role(of: "!~"), .operatorHead) } func testQuestion() { XCTAssertEqual(role(of: "?"), .question) XCTAssertEqual(role(of: "?="), .operatorHead) XCTAssertEqual(role(of: "?!"), .operatorHead) } func testLessThan() { XCTAssertEqual(role(of: "<"), .lessThan) XCTAssertEqual(role(of: "<<"), .operatorHead) XCTAssertEqual(role(of: "<>"), .operatorHead) } func testGreaterThan() { XCTAssertEqual(role(of: ">"), .greaterThan) XCTAssertEqual(role(of: ">>"), .operatorHead) XCTAssertEqual(role(of: "><"), .operatorHead) } func testUnderscore() { XCTAssertEqual(role(of: "_"), .underscore) XCTAssertEqual(role(of: "_id"), .identifierHead) XCTAssertEqual(role(of: "_6"), .identifierHead) } func testSlash() { XCTAssertEqual(role(of: "/"), .operatorHead) XCTAssertEqual(role(of: "/>"), .operatorHead) XCTAssertEqual(role(of: "/\\"), .operatorHead) XCTAssertEqual(role(of: "//"), .singleLineCommentHead) XCTAssertEqual(role(of: "////"), .singleLineCommentHead) XCTAssertEqual(role(of: "/*"), .multipleLineCommentHead) XCTAssertEqual(role(of: "/**"), .multipleLineCommentHead) XCTAssertEqual(role(of: "/*//"), .multipleLineCommentHead) } func testAsterisk() { XCTAssertEqual(role(of: "*"), .operatorHead) XCTAssertEqual(role(of: "*="), .operatorHead) XCTAssertEqual(role(of: "*/"), .multipleLineCommentTail) } func testDigits() { for d in 0...9 { XCTAssertEqual(role(of: String(d)), .digit) } } func testSpaces() { for s in [" ", "\t", "\0", "\u{000b}", "\u{000c}"] { XCTAssertEqual(role(of: s), .space) } } func testOperatorHeads() { // Note: the folowings have been tested elsewhere: // "/", "=", "-", "!", "?", "*", "<", ">", "&" for oh in ["+", "%", "|", "^", "~", "\u{3009}"] { XCTAssertEqual(role(of: oh), .operatorHead) } } func testOperatorBody() { for ob in ["\u{E01DA}", "\u{E01EE}"] { XCTAssertEqual(role(of: ob), .operatorBody) } } func testIdentifierHeads() { // Note: the folowings have been tested elsewhere: // "_" for ih in ["A", "Z", "a", "z", "\u{3006}", "\u{EFFFC}"] { XCTAssertEqual(role(of: ih), .identifierHead) } } func testIdentifierBody() { // Note: the folowings have been tested elsewhere: // "0", "9" for ib in ["\u{FE20}", "\u{1DC7}"] { XCTAssertEqual(role(of: ib), .identifierBody) } } func testStartOfHeading() { XCTAssertEqual(role(of: "\u{1}"), .unknown) } static var allTests = [ ("testEmptyContent", testEmptyContent), ("testLineFeed", testLineFeed), ("testCarriageReturn", testCarriageReturn), ("testLeftParen", testLeftParen), ("testRightParen", testRightParen), ("testLeftBrace", testLeftBrace), ("testRightBrace", testRightBrace), ("testLeftSquare", testLeftSquare), ("testRightSquare", testRightSquare), ("testPeriod", testPeriod), ("testComma", testComma), ("testColon", testColon), ("testSemicolon", testSemicolon), ("testEqual", testEqual), ("testAt", testAt), ("testHash", testHash), ("testAmp", testAmp), ("testMinus", testMinus), ("testBacktick", testBacktick), ("testBackslash", testBackslash), ("testDollar", testDollar), ("testDoubleQuote", testDoubleQuote), ("testExclaim", testExclaim), ("testQuestion", testQuestion), ("testLessThan", testLessThan), ("testGreaterThan", testGreaterThan), ("testUnderscore", testUnderscore), ("testSlash", testSlash), ("testAsterisk", testAsterisk), ("testDigits", testDigits), ("testSpaces", testSpaces), ("testOperatorHeads", testOperatorHeads), ("testOperatorBody", testOperatorBody), ("testIdentifierHeads", testIdentifierHeads), ("testIdentifierBody", testIdentifierBody), ("testStartOfHeading", testStartOfHeading), ] }
apache-2.0
46c378f8d21e24b5b43307194c22977c
26.382239
85
0.626199
3.796574
false
true
false
false
lxcid/ListDiff
Tests/ListDiffTests/ListDiffStressTests/ListDiffStressTests.swift
1
4126
import XCTest import UIKit @testable import ListDiff private let collectionSize = 100 private let iterationsCount = 50 final class ListDiffStressTests: XCTestCase { func test_listDiff_doesNotCrashUICollectionView_duringStressCollectionChanges() { let expectations = (0..<iterationsCount).map { expectation(description: "async expectation of iteration \($0)") } performTests(expectations: expectations) waitForExpectations(timeout: 60) } // MARK: - Private private func performTests(expectations: [XCTestExpectation]) { performTest( index: 0, expectations: expectations, previousCellDataList: [] ) } private func performTest( index: Int, expectations: [XCTestExpectation], previousCellDataList: [CellData]) { guard index < expectations.count else { return } autoreleasepool { print("testing iteration \(index)") let cellDataGenerator = CellDataGenerator() // Given let cellDataGeneratorResult: CellDataGeneratorResult if index == 0 { cellDataGeneratorResult = cellDataGenerator .generateCellData(count: collectionSize) } else { cellDataGeneratorResult = cellDataGenerator .performRandomActionsOnCellData( previousCellDataList, minimumCountAfterActions: collectionSize / 10, maximumCountAfterActions: collectionSize * 10 ) } print(" from \(cellDataGeneratorResult.from.count), to: \(cellDataGeneratorResult.to.count).") print(" deletes \(cellDataGeneratorResult.deletes), " + "inserts: \(cellDataGeneratorResult.inserts), " + "moves \(cellDataGeneratorResult.moves), " + "updates: \(cellDataGeneratorResult.updates)." ) // When let collectionViewUpdater = CollectionViewUpdater() collectionViewUpdater.updateCollectionView( from: cellDataGeneratorResult.from, to: cellDataGeneratorResult.to, completion: { [weak self] result in // Then switch result { case let .exception(exception): XCTFail("Failed to update collection view using ListDiff. exception: \(exception)") print("__________________________________________________") case let .success(visibleCellDataList, expectedCellDataList): XCTAssert( visibleCellDataList.count == expectedCellDataList.count, "Update the layout to fit all cells in the screen" ) let zippedCellDataLists = zip(visibleCellDataList, expectedCellDataList) for (index, (visibleCellData, expectedCellData)) in zippedCellDataLists.enumerated() { XCTAssert( visibleCellData == expectedCellData, "visible cell data and expected cell data are not in sync at index: \(index)" ) } } print("") collectionViewUpdater.cleanUp() expectations[index].fulfill() DispatchQueue.main.async { self?.performTest( index: index + 1, expectations: expectations, previousCellDataList: cellDataGeneratorResult.to ) } } ) } } }
mit
da40e7de2da65f14038514217a89e286
38.673077
110
0.499273
6.633441
false
true
false
false
jeanetienne/Speller
Sources/CodeWordCollection.swift
2
1754
// // CodeWordCollection.swift // Speller // // Created by Jean-Étienne on 13/11/16. // Copyright © 2016 Jean-Étienne. All rights reserved. // import Foundation /// A `CodeWordCollection` represents a collection of all the code words /// matching a spelled character. Often the collection only contains one code /// word public final class CodeWordCollection { /// The first code word of the collection public var mainCodeWord: String { return codeWords[0] } /// The other code words of the collection public var secondaryCodeWords: [String] { return Array(codeWords.dropFirst(1)) } var codeWords: [String] = [] init(codeWord: String) { codeWords = [codeWord] } init(codeWords: [String]) { self.codeWords = codeWords } } extension CodeWordCollection: Equatable { public static func ==(lhs: CodeWordCollection, rhs: CodeWordCollection) -> Bool { return lhs.codeWords == rhs.codeWords } } extension CodeWordCollection: ExpressibleByStringLiteral { convenience public init(stringLiteral value: StringLiteralType) { self.init(codeWord: value) } convenience public init(extendedGraphemeClusterLiteral value: StringLiteralType) { self.init(codeWord: value) } convenience public init(unicodeScalarLiteral value: StringLiteralType) { self.init(codeWord: value) } } extension CodeWordCollection: ExpressibleByArrayLiteral { convenience public init(arrayLiteral elements: String...) { self.init(codeWords: elements) } } extension CodeWordCollection: CustomDebugStringConvertible { public var debugDescription: String { return codeWords.debugDescription } }
mit
16ee0a2089f0f0ece8ee75cbde59ad5b
22.039474
86
0.692176
4.399497
false
false
false
false
DanijelHuis/HDAugmentedReality
HDAugmentedReality/Classes/External/CameraView.swift
1
7120
// // CameraView.swift // HDAugmentedRealityDemo // // Created by Danijel Huis on 18/12/2016. // Copyright © 2016 Danijel Huis. All rights reserved. // import UIKit import AVFoundation /** UIView with video preview layer. Call startRunning/stopRunning to start/stop capture session. Use createCaptureSession to check if cameraView can be initialized correctly. */ open class CameraView: UIView { /// Media type, set it before adding to superview. open var mediaType: AVMediaType = AVMediaType.video /// Capture device position, set it before adding to superview. open var devicePosition: AVCaptureDevice.Position = AVCaptureDevice.Position.back /// Video gravitry for videoPreviewLayer, set it before adding to superview. open var videoGravity: AVLayerVideoGravity = AVLayerVideoGravity.resizeAspectFill open var isSessionCreated = false fileprivate var videoPreviewLayer: AVCaptureVideoPreviewLayer? fileprivate var captureSession: AVCaptureSession? //========================================================================================================================================================== //MARK: UIView overrides //========================================================================================================================================================== open override func layoutSubviews() { super.layoutSubviews() self.layoutUi() } fileprivate func layoutUi() { self.videoPreviewLayer?.frame = self.bounds } //========================================================================================================================================================== //MARK: Main logic //========================================================================================================================================================== /// Starts running capture session open func startRunning() { #if targetEnvironment(simulator) self.backgroundColor = UIColor.darkGray #endif //print("CameraView: Called startRunning before added to subview") self.captureSession?.startRunning() } /// Stops running capture session open func stopRunning() { self.captureSession?.stopRunning() } /// Creates capture session and video preview layer, destroySessionAndVideoPreviewLayer is called. @discardableResult open func createSessionAndVideoPreviewLayer() -> (session: AVCaptureSession?, error: CameraViewError?) { self.destroySessionAndVideoPreviewLayer() //===== Capture session let captureSessionResult = CameraView.createCaptureSession(withMediaType: self.mediaType, position: self.devicePosition) guard captureSessionResult.error == nil, let session = captureSessionResult.session else { print("CameraView: Cannot create capture session, use createCaptureSession method to check if device is capable for augmented reality.") return captureSessionResult } self.captureSession = session //===== View preview layer let videoPreviewLayer = AVCaptureVideoPreviewLayer(session: session) videoPreviewLayer.videoGravity = self.videoGravity self.layer.insertSublayer(videoPreviewLayer, at: 0) self.videoPreviewLayer = videoPreviewLayer self.isSessionCreated = true return captureSessionResult } /// Stops running and destroys capture session, removes and destroys video preview layer. open func destroySessionAndVideoPreviewLayer() { self.stopRunning() self.videoPreviewLayer?.removeFromSuperlayer() self.videoPreviewLayer = nil self.captureSession = nil self.isSessionCreated = false } open func setVideoOrientation(_ orientation: UIInterfaceOrientation) { if self.videoPreviewLayer?.connection?.isVideoOrientationSupported != nil { if let videoOrientation = AVCaptureVideoOrientation(rawValue: Int(orientation.rawValue)) { self.videoPreviewLayer?.connection?.videoOrientation = videoOrientation } } } //========================================================================================================================================================== //MARK: Utilities //========================================================================================================================================================== /// Tries to find video device and add video input to it. open class func createCaptureSession(withMediaType mediaType: AVMediaType, position: AVCaptureDevice.Position) -> (session: AVCaptureSession?, error: CameraViewError?) { var error: CameraViewError? var captureSession: AVCaptureSession? let captureDevice = AVCaptureDevice.default(.builtInWideAngleCamera, for: mediaType, position: position) if let captureDevice = captureDevice { // Get video input device var captureDeviceInput: AVCaptureDeviceInput? do { captureDeviceInput = try AVCaptureDeviceInput(device: captureDevice) } catch let deviceError { error = CameraViewError.deviceInput(underlyingError: deviceError) captureDeviceInput = nil } if let captureDeviceInput = captureDeviceInput, error == nil { let session = AVCaptureSession() if session.canAddInput(captureDeviceInput) { session.addInput(captureDeviceInput) } else { error = CameraViewError.addVideoInput } captureSession = session } else { error = CameraViewError.createCaptureDeviceInput } } else { error = CameraViewError.backVideoDeviceNotFount } return (session: captureSession, error: error) } open func inputDevice() -> AVCaptureDevice? { guard let inputs = self.captureSession?.inputs else { return nil } var inputDevice: AVCaptureDevice? = nil for input in inputs { if let input = input as? AVCaptureDeviceInput { inputDevice = input.device break } } return inputDevice } } public enum CameraViewError: Error { case deviceInput(underlyingError: Error) case addVideoInput case createCaptureDeviceInput case backVideoDeviceNotFount }
mit
12dea2768920463b90f5121d6fc03129
37.274194
171
0.534204
7.097707
false
false
false
false
radazzouz/firefox-ios
Client/Frontend/Browser/TabLocationView.swift
1
13071
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ import Foundation import UIKit import Shared import SnapKit import XCGLogger private let log = Logger.browserLogger protocol TabLocationViewDelegate { func tabLocationViewDidTapLocation(_ tabLocationView: TabLocationView) func tabLocationViewDidLongPressLocation(_ tabLocationView: TabLocationView) func tabLocationViewDidTapReaderMode(_ tabLocationView: TabLocationView) /// - returns: whether the long-press was handled by the delegate; i.e. return `false` when the conditions for even starting handling long-press were not satisfied @discardableResult func tabLocationViewDidLongPressReaderMode(_ tabLocationView: TabLocationView) -> Bool func tabLocationViewLocationAccessibilityActions(_ tabLocationView: TabLocationView) -> [UIAccessibilityCustomAction]? } struct TabLocationViewUX { static let HostFontColor = UIColor.black static let BaseURLFontColor = UIColor.gray static let BaseURLPitch = 0.75 static let HostPitch = 1.0 static let LocationContentInset = 8 static let Themes: [String: Theme] = { var themes = [String: Theme]() var theme = Theme() theme.URLFontColor = UIColor.lightGray theme.hostFontColor = UIColor.white theme.backgroundColor = UIConstants.PrivateModeLocationBackgroundColor themes[Theme.PrivateMode] = theme theme = Theme() theme.URLFontColor = BaseURLFontColor theme.hostFontColor = HostFontColor theme.backgroundColor = UIColor.white themes[Theme.NormalMode] = theme return themes }() } class TabLocationView: UIView { var delegate: TabLocationViewDelegate? var longPressRecognizer: UILongPressGestureRecognizer! var tapRecognizer: UITapGestureRecognizer! dynamic var baseURLFontColor: UIColor = TabLocationViewUX.BaseURLFontColor { didSet { updateTextWithURL() } } dynamic var hostFontColor: UIColor = TabLocationViewUX.HostFontColor { didSet { updateTextWithURL() } } var url: URL? { didSet { let wasHidden = lockImageView.isHidden lockImageView.isHidden = url?.scheme != "https" if wasHidden != lockImageView.isHidden { UIAccessibilityPostNotification(UIAccessibilityLayoutChangedNotification, nil) } updateTextWithURL() setNeedsUpdateConstraints() } } var readerModeState: ReaderModeState { get { return readerModeButton.readerModeState } set (newReaderModeState) { if newReaderModeState != self.readerModeButton.readerModeState { let wasHidden = readerModeButton.isHidden self.readerModeButton.readerModeState = newReaderModeState readerModeButton.isHidden = (newReaderModeState == ReaderModeState.unavailable) if wasHidden != readerModeButton.isHidden { UIAccessibilityPostNotification(UIAccessibilityLayoutChangedNotification, nil) } UIView.animate(withDuration: 0.1, animations: { () -> Void in if newReaderModeState == ReaderModeState.unavailable { self.readerModeButton.alpha = 0.0 } else { self.readerModeButton.alpha = 1.0 } self.setNeedsUpdateConstraints() self.layoutIfNeeded() }) } } } lazy var placeholder: NSAttributedString = { let placeholderText = NSLocalizedString("Search or enter address", comment: "The text shown in the URL bar on about:home") return NSAttributedString(string: placeholderText, attributes: [NSForegroundColorAttributeName: UIColor.gray]) }() lazy var urlTextField: UITextField = { let urlTextField = DisplayTextField() self.longPressRecognizer.delegate = self urlTextField.addGestureRecognizer(self.longPressRecognizer) self.tapRecognizer.delegate = self urlTextField.addGestureRecognizer(self.tapRecognizer) // Prevent the field from compressing the toolbar buttons on the 4S in landscape. urlTextField.setContentCompressionResistancePriority(250, for: UILayoutConstraintAxis.horizontal) urlTextField.attributedPlaceholder = self.placeholder urlTextField.accessibilityIdentifier = "url" urlTextField.accessibilityActionsSource = self urlTextField.font = UIConstants.DefaultChromeFont return urlTextField }() fileprivate lazy var lockImageView: UIImageView = { let lockImageView = UIImageView(image: UIImage(named: "lock_verified.png")) lockImageView.isHidden = true lockImageView.isAccessibilityElement = true lockImageView.contentMode = UIViewContentMode.center lockImageView.accessibilityLabel = NSLocalizedString("Secure connection", comment: "Accessibility label for the lock icon, which is only present if the connection is secure") return lockImageView }() fileprivate lazy var readerModeButton: ReaderModeButton = { let readerModeButton = ReaderModeButton(frame: CGRect.zero) readerModeButton.isHidden = true readerModeButton.addTarget(self, action: #selector(TabLocationView.SELtapReaderModeButton), for: .touchUpInside) readerModeButton.addGestureRecognizer(UILongPressGestureRecognizer(target: self, action: #selector(TabLocationView.SELlongPressReaderModeButton(_:)))) readerModeButton.isAccessibilityElement = true readerModeButton.accessibilityLabel = NSLocalizedString("Reader View", comment: "Accessibility label for the Reader View button") readerModeButton.accessibilityCustomActions = [UIAccessibilityCustomAction(name: NSLocalizedString("Add to Reading List", comment: "Accessibility label for action adding current page to reading list."), target: self, selector: #selector(TabLocationView.SELreaderModeCustomAction))] return readerModeButton }() override init(frame: CGRect) { super.init(frame: frame) longPressRecognizer = UILongPressGestureRecognizer(target: self, action: #selector(TabLocationView.SELlongPressLocation(_:))) tapRecognizer = UITapGestureRecognizer(target: self, action: #selector(TabLocationView.SELtapLocation(_:))) addSubview(urlTextField) addSubview(lockImageView) addSubview(readerModeButton) lockImageView.snp.makeConstraints { make in make.leading.centerY.equalTo(self) make.width.equalTo(self.lockImageView.intrinsicContentSize.width + CGFloat(TabLocationViewUX.LocationContentInset * 2)) } readerModeButton.snp.makeConstraints { make in make.trailing.centerY.equalTo(self) make.width.equalTo(self.readerModeButton.intrinsicContentSize.width + CGFloat(TabLocationViewUX.LocationContentInset * 2)) } } override var accessibilityElements: [Any]? { get { return [lockImageView, urlTextField, readerModeButton].filter { !$0.isHidden } } set { super.accessibilityElements = newValue } } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func updateConstraints() { urlTextField.snp.remakeConstraints { make in make.top.bottom.equalTo(self) if lockImageView.isHidden { make.leading.equalTo(self).offset(TabLocationViewUX.LocationContentInset) } else { make.leading.equalTo(self.lockImageView.snp.trailing) } if readerModeButton.isHidden { make.trailing.equalTo(self).offset(-TabLocationViewUX.LocationContentInset) } else { make.trailing.equalTo(self.readerModeButton.snp.leading) } } super.updateConstraints() } func SELtapReaderModeButton() { delegate?.tabLocationViewDidTapReaderMode(self) } func SELlongPressReaderModeButton(_ recognizer: UILongPressGestureRecognizer) { if recognizer.state == UIGestureRecognizerState.began { delegate?.tabLocationViewDidLongPressReaderMode(self) } } func SELlongPressLocation(_ recognizer: UITapGestureRecognizer) { if recognizer.state == UIGestureRecognizerState.began { delegate?.tabLocationViewDidLongPressLocation(self) } } func SELtapLocation(_ recognizer: UITapGestureRecognizer) { delegate?.tabLocationViewDidTapLocation(self) } func SELreaderModeCustomAction() -> Bool { return delegate?.tabLocationViewDidLongPressReaderMode(self) ?? false } fileprivate func updateTextWithURL() { if let httplessURL = url?.absoluteDisplayString, let baseDomain = url?.baseDomain { // Highlight the base domain of the current URL. let attributedString = NSMutableAttributedString(string: httplessURL) let nsRange = NSRange(location: 0, length: httplessURL.characters.count) attributedString.addAttribute(NSForegroundColorAttributeName, value: baseURLFontColor, range: nsRange) attributedString.colorSubstring(baseDomain, withColor: hostFontColor) attributedString.addAttribute(UIAccessibilitySpeechAttributePitch, value: NSNumber(value: TabLocationViewUX.BaseURLPitch), range: nsRange) attributedString.pitchSubstring(baseDomain, withPitch: TabLocationViewUX.HostPitch) urlTextField.attributedText = attributedString } else { // If we're unable to highlight the domain, just use the URL as is. if let host = url?.host, AppConstants.MOZ_PUNYCODE { urlTextField.text = url?.absoluteString.replacingOccurrences(of: host, with: host.asciiHostToUTF8()) } else { urlTextField.text = url?.absoluteString } } } } extension TabLocationView: UIGestureRecognizerDelegate { func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldRecognizeSimultaneouslyWith otherGestureRecognizer: UIGestureRecognizer) -> Bool { return true } func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldBeRequiredToFailBy otherGestureRecognizer: UIGestureRecognizer) -> Bool { // If the longPressRecognizer is active, fail all other recognizers to avoid conflicts. return gestureRecognizer == longPressRecognizer } } extension TabLocationView: AccessibilityActionsSource { func accessibilityCustomActionsForView(_ view: UIView) -> [UIAccessibilityCustomAction]? { if view === urlTextField { return delegate?.tabLocationViewLocationAccessibilityActions(self) } return nil } } extension TabLocationView: Themeable { func applyTheme(_ themeName: String) { guard let theme = TabLocationViewUX.Themes[themeName] else { log.error("Unable to apply unknown theme \(themeName)") return } baseURLFontColor = theme.URLFontColor! hostFontColor = theme.hostFontColor! backgroundColor = theme.backgroundColor } } private class ReaderModeButton: UIButton { override init(frame: CGRect) { super.init(frame: frame) setImage(UIImage(named: "reader.png"), for: UIControlState()) setImage(UIImage(named: "reader_active.png"), for: UIControlState.selected) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } var _readerModeState: ReaderModeState = ReaderModeState.unavailable var readerModeState: ReaderModeState { get { return _readerModeState } set (newReaderModeState) { _readerModeState = newReaderModeState switch _readerModeState { case .available: self.isEnabled = true self.isSelected = false case .unavailable: self.isEnabled = false self.isSelected = false case .active: self.isEnabled = true self.isSelected = true } } } } private class DisplayTextField: UITextField { weak var accessibilityActionsSource: AccessibilityActionsSource? override var accessibilityCustomActions: [UIAccessibilityCustomAction]? { get { return accessibilityActionsSource?.accessibilityCustomActionsForView(self) } set { super.accessibilityCustomActions = newValue } } fileprivate override var canBecomeFirstResponder: Bool { return false } }
mpl-2.0
e9a83b257355dccb67544712bd6db3ec
39.846875
289
0.683498
5.982151
false
false
false
false
tutsplus/watchOS-WatchConnectivity-Background-StarterProject
WatchConnectivity Introduction WatchKit Extension/InterfaceController.swift
1
2192
// // InterfaceController.swift // WatchConnectivity Introduction WatchKit Extension // // Created by Davis Allie on 25/08/2015. // Copyright © 2015 tutsplus. All rights reserved. // import WatchKit import Foundation import WatchConnectivity class InterfaceController: WKInterfaceController { @IBOutlet var table: WKInterfaceTable! let dateFormatter = NSDateFormatter() var items: [NSDictionary] = [] override func awakeWithContext(context: AnyObject?) { super.awakeWithContext(context) dateFormatter.dateFormat = "EEEE" } override func willActivate() { // This method is called when watch view controller is about to be visible to user super.willActivate() self.items.removeAll() if let newItems = NSUserDefaults.standardUserDefaults().objectForKey("items") as? [NSDictionary] { self.items = newItems self.table.setNumberOfRows(self.items.count, withRowType: "BasicRow") for i in 0..<self.items.count { if let row = self.table.rowControllerAtIndex(items.count-1) as? TableRow { let date = self.items[i]["date"] as! NSDate row.mainTitle.setText("\(date)") row.subtitle.setText(self.items[i]["day"] as? String) } } } } override func didDeactivate() { // This method is called when watch view controller is no longer visible super.didDeactivate() } @IBAction func addItem() { let date = NSDate() let item = ["date": date, "day": dateFormatter.stringFromDate(date)] self.items.append(item) print(self.items) if self.items.count == 1 { self.table.setNumberOfRows(1, withRowType: "BasicRow") } else { self.table.insertRowsAtIndexes(NSIndexSet(index: items.count-1), withRowType: "BasicRow") } if let row = self.table.rowControllerAtIndex(items.count-1) as? TableRow { row.mainTitle.setText("\(date)") row.subtitle.setText(item["day"] as? String) } } }
bsd-2-clause
6b5989f207d0a58708439f2a0a2030be
32.19697
106
0.607029
4.783843
false
false
false
false
prebid/prebid-mobile-ios
PrebidMobileTests/RenderingTests/Tests/PBMMRAIDControllerTest_Base.swift
1
7046
/*   Copyright 2018-2021 Prebid.org, 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 XCTest @testable import PrebidMobile class PBMMRAIDControllerTest_Base: XCTestCase, PBMCreativeViewDelegate { let timeout: TimeInterval = 1 var serverConnection: ServerConnection! var transaction: PBMTransaction! var mockHtmlCreative: MockPBMHTMLCreative! var mockCreativeModel: MockPBMCreativeModel! var mockEventTracker: MockPBMAdModelEventTracker! var mockModalManager: MockModalManager! var mockWebView: MockPBMWebView! var mockViewController: MockViewController! var MRAIDController: PBMMRAIDController! override func setUp() { super.setUp() self.mockViewController = MockViewController() //Set up MockServer self.serverConnection = ServerConnection(userAgentService: MockUserAgentService()) self.serverConnection.protocolClasses.append(MockServerURLProtocol.self) //Set up creative model self.mockCreativeModel = MockPBMCreativeModel(adConfiguration: AdConfiguration()) self.mockCreativeModel.width = 320 self.mockCreativeModel.height = 50 self.mockCreativeModel.html = "test" self.mockEventTracker = MockPBMAdModelEventTracker(creativeModel: self.mockCreativeModel, serverConnection: self.serverConnection) self.mockCreativeModel.eventTracker = self.mockEventTracker //Set up HTML Creative self.mockModalManager = MockModalManager() self.mockWebView = MockPBMWebView() self.mockHtmlCreative = MockPBMHTMLCreative( creativeModel: self.mockCreativeModel, transaction:UtilitiesForTesting.createEmptyTransaction(), webView: self.mockWebView, sdkConfiguration: Prebid.mock ) self.mockHtmlCreative.creativeViewDelegate = self self.mockHtmlCreative.modalManager = self.mockModalManager //Simulate creativeFactory self.mockHtmlCreative.setupView() //Simulate PBMBannerView.creativeReadyForImmediateDisplay: //Add the view to the "PBMBannerView" (in this case, the viewController's view) //Then call creative.display guard let creativeView = self.mockHtmlCreative.view else { XCTFail("No View") return } self.mockViewController.view.addSubview(creativeView) self.mockHtmlCreative.display(withRootViewController: self.mockViewController) } override func tearDown() { // Put teardown code here. This method is called after the invocation of each test method in the class. self.mockHtmlCreative = nil self.mockCreativeModel = nil self.mockModalManager = nil self.mockWebView = nil self.serverConnection = nil super.tearDown() } // MARK: - CreativeViewDelegate var creativeInterstitialDidLeaveAppHandler: PBMCreativeViewDelegateHandler? func creativeInterstitialDidLeaveApp(_ creative: PBMAbstractCreative) { self.creativeInterstitialDidLeaveAppHandler?(creative) } var creativeInterstitialDidCloseHandler: PBMCreativeViewDelegateHandler? func creativeInterstitialDidClose(_ creative: PBMAbstractCreative) { self.creativeInterstitialDidCloseHandler?(creative) } var creativeClickthroughDidCloseHandler: PBMCreativeViewDelegateHandler? func creativeClickthroughDidClose(_ creative: PBMAbstractCreative) { self.creativeClickthroughDidCloseHandler?(creative) } var creativeReadyToReimplantHandler: PBMCreativeViewDelegateHandler? func creativeReady(toReimplant creative: PBMAbstractCreative) { self.creativeReadyToReimplantHandler?(creative) } var creativeMraidDidCollapseHandler: PBMCreativeViewDelegateHandler? func creativeMraidDidCollapse(_ creative: PBMAbstractCreative) { self.creativeMraidDidCollapseHandler?(creative) } var creativeMraidDidExpandHandler: PBMCreativeViewDelegateHandler? func creativeMraidDidExpand(_ creative: PBMAbstractCreative) { self.creativeMraidDidExpandHandler?(creative) } var creativeDidCompleteHandler: PBMCreativeViewDelegateHandler? func creativeDidComplete(_ creative: PBMAbstractCreative) { self.creativeDidCompleteHandler?(creative) } var creativeWasClickedHandler: ((PBMAbstractCreative) -> Void)? func creativeWasClicked(_ creative: PBMAbstractCreative) { self.creativeWasClickedHandler?(creative) } func videoCreativeDidComplete(_ creative: PBMAbstractCreative) {} func creativeDidDisplay(_ creative: PBMAbstractCreative) {} func creativeViewWasClicked(_ creative: PBMAbstractCreative) {} func creativeFullScreenDidFinish(_ creative: PBMAbstractCreative) {} // MARK: - Utilities /** Setup an expectation and associated, mocked `PBMWebView` to fulfill that expectation. - parameters: - shouldFulfill: Whether or not the expecation is expected to fulfill - message: If `shouldFulfill`, the error message to check against - action: If `shouldFulfill`, the action to check against */ func mraidErrorExpectation(shouldFulfill: Bool, message expectedMessage: String? = nil, action expectedAction: PBMMRAIDAction? = nil, file: StaticString = #file, line: UInt = #line) { let exp = self.expectation(description: "Should \(shouldFulfill ? "" : "not ")call webview with an MRAID error") exp.isInverted = !shouldFulfill self.mockWebView.mock_MRAID_error = { (actualMessage, actualAction) in if shouldFulfill { PBMAssertEq(actualMessage, expectedMessage, file: file, line: line) PBMAssertEq(actualAction, expectedAction, file: file, line: line) } exp.fulfill() } } func createLoader(connection: ServerConnectionProtocol) -> PBMCreativeFactoryDownloadDataCompletionClosure { let result: PBMCreativeFactoryDownloadDataCompletionClosure = {url, completionBlock in let downloader = PBMDownloadDataHelper(serverConnection:connection) downloader.downloadData(for: url, completionClosure: { (data:Data?, error:Error?) in completionBlock(data,error) }) } return result } }
apache-2.0
5e7a1edf94b67ba9923deab410593aa2
40.875
187
0.705188
5.513323
false
false
false
false
glock45/swifter
Sources/Swifter/DemoServer.swift
1
5880
// // DemoServer.swift // Swifter // // Copyright (c) 2014-2016 Damian Kołakowski. All rights reserved. // #if os(Linux) import Glibc #else import Foundation #endif public func demoServer(_ publicDir: String) -> HttpServer { print(publicDir) let server = HttpServer() server["/shared/:path"] = shareFilesFromDirectory(publicDir) server["/files/:path"] = directoryBrowser("/") server["/"] = scopes { html { body { ul(server.routes) { service in li { a { href = service; inner = service } } } } } } server["/magic"] = { .ok(.html("You asked for " + $0.path)) } server["/test/:param1/:param2"] = { r in scopes { html { body { h3 { inner = "Address: \(r.address)" } h3 { inner = "Url: \(r.path)" } h3 { inner = "Method: \(r.method)" } h3 { inner = "Query:" } table(r.queryParams) { param in tr { td { inner = param.0 } td { inner = param.1 } } } h3 { inner = "Headers:" } table(r.headers) { header in tr { td { inner = header.0 } td { inner = header.1 } } } h3 { inner = "Route params:" } table(r.params) { param in tr { td { inner = param.0 } td { inner = param.1 } } } } } }(r) } server.GET["/upload"] = scopes { html { body { form { method = "POST" action = "/upload" enctype = "multipart/form-data" input { name = "my_file1"; type = "file" } input { name = "my_file2"; type = "file" } input { name = "my_file3"; type = "file" } button { type = "submit" inner = "Upload" } } } } } server.POST["/upload"] = { r in var response = "" for multipart in r.parseMultiPartFormData() { response += "Name: \(multipart.name) File name: \(multipart.fileName) Size: \(multipart.body.count)<br>" } return HttpResponse.ok(.html(response)) } server.GET["/login"] = scopes { html { head { script { src = "http://cdn.staticfile.org/jquery/2.1.4/jquery.min.js" } stylesheet { href = "http://cdn.staticfile.org/twitter-bootstrap/3.3.0/css/bootstrap.min.css" } } body { h3 { inner = "Sign In" } form { method = "POST" action = "/login" fieldset { input { placeholder = "E-mail"; name = "email"; type = "email"; autofocus = "" } input { placeholder = "Password"; name = "password"; type = "password"; autofocus = "" } a { href = "/login" button { type = "submit" inner = "Login" } } } } javascript { src = "http://cdn.staticfile.org/twitter-bootstrap/3.3.0/js/bootstrap.min.js" } } } } server.POST["/login"] = { r in let formFields = r.parseUrlencodedForm() return HttpResponse.ok(.html(formFields.map({ "\($0.0) = \($0.1)" }).joined(separator: "<br>"))) } server["/demo"] = scopes { html { body { center { h2 { inner = "Hello Swift" } img { src = "https://devimages.apple.com.edgekey.net/swift/images/swift-hero_2x.png" } } } } } server["/raw"] = { r in return HttpResponse.raw(200, "OK", ["XXX-Custom-Header": "value"], { try? $0.write([UInt8]("test".utf8)) }) } server["/redirect"] = { r in return .movedPermanently("http://www.google.com") } server["/long"] = { r in var longResponse = "" for k in 0..<1000 { longResponse += "(\(k)),->" } return .ok(.html(longResponse)) } server["/wildcard/*/test/*/:param"] = { r in return .ok(.html(r.path)) } server["/stream"] = { r in return HttpResponse.raw(200, "OK", nil, { w in for i in 0...100 { try? w.write([UInt8]("[chunk \(i)]".utf8)) } }) } server["/websocket-echo"] = websocket({ (session, text) in session.writeText(text) }, { (session, binary) in session.writeBinary(binary) }) server.notFoundHandler = { r in return .movedPermanently("https://github.com/404") } server.middleware.append { r in print("Middleware:\(r.method) \(r.path)") return nil } return server }
bsd-3-clause
6e9410fb00de911d81a2badf28f72214
28.84264
116
0.376935
4.741129
false
false
false
false
phimage/CallbackURLKit
Sources/Extensions.swift
1
4153
// // Extensions.swift // CallbackURLKit /* The MIT License (MIT) Copyright (c) 2017 Eric Marchand (phimage) Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ import Foundation // MARK: String extension String { var toQueryDictionary: [String: String] { var result: [String: String] = [String: String]() let pairs: [String] = self.components(separatedBy: "&") for pair in pairs { let comps: [String] = pair.components(separatedBy: "=") if comps.count >= 2 { let key = comps[0] let value = comps.dropFirst().joined(separator: "=") result[key.queryDecode] = value.queryDecode } } return result } var queryEncodeRFC3986: String { let generalDelimitersToEncode = ":#[]@" // does not include "?" or "/" due to RFC 3986 - Section 3.4 let subDelimitersToEncode = "!$&'()*+,;=" var allowedCharacterSet = CharacterSet.urlQueryAllowed allowedCharacterSet.remove(charactersIn: generalDelimitersToEncode + subDelimitersToEncode) return self.addingPercentEncoding(withAllowedCharacters: allowedCharacterSet) ?? self } var queryEncode: String { return self.addingPercentEncoding(withAllowedCharacters: CharacterSet.urlQueryAllowed) ?? self } var queryDecode: String { return self.removingPercentEncoding ?? self } } // MARK: Dictionary extension Dictionary { var queryString: String { var parts = [String]() for (key, value) in self { let keyString = "\(key)".queryEncodeRFC3986 let valueString = "\(value)".queryEncodeRFC3986 let query = "\(keyString)=\(valueString)" parts.append(query) } return parts.joined(separator: "&") as String } fileprivate func join(_ other: Dictionary) -> Dictionary { var joinedDictionary = Dictionary() for (key, value) in self { joinedDictionary.updateValue(value, forKey: key) } for (key, value) in other { joinedDictionary.updateValue(value, forKey: key) } return joinedDictionary } init(_ pairs: [Element]) { self.init() for (k, v) in pairs { self[k] = v } } } func +<K, V> (left: [K: V], right: [K: V]) -> [K: V] { return left.join(right) } // MARK: NSURLComponents extension URLComponents { var queryDictionary: [String: String] { get { guard let query = self.query else { return [:] } return query.toQueryDictionary } set { if newValue.isEmpty { self.query = nil } else { self.percentEncodedQuery = newValue.queryString } } } fileprivate mutating func addToQuery(_ add: String) { if let query = self.percentEncodedQuery { self.percentEncodedQuery = query + "&" + add } else { self.percentEncodedQuery = add } } } func &= (left: inout URLComponents, right: String) { left.addToQuery(right) }
mit
4585e1ac9fb7b9da0553c6d661071243
30.946154
108
0.632073
4.790081
false
false
false
false
the-blue-alliance/the-blue-alliance-ios
the-blue-alliance-ios/View Controllers/Teams/Team/TeamViewController.swift
1
9240
import BFRImageViewer import CoreData import Firebase import MyTBAKit import Photos import TBAData import TBAKit import UIKit class TeamViewController: HeaderContainerViewController, Observable { private(set) var team: Team private let pasteboard: UIPasteboard? private let photoLibrary: PHPhotoLibrary? private let statusService: StatusService private let urlOpener: URLOpener private let operationQueue = OperationQueue() private let teamHeaderView: TeamHeaderView override var headerView: UIView { return teamHeaderView } private(set) var infoViewController: TeamInfoViewController private(set) var eventsViewController: TeamEventsViewController private(set) var mediaViewController: TeamMediaCollectionViewController private var activity: NSUserActivity? override var subscribableModel: MyTBASubscribable { return team } private var year: Int? { didSet { if let year = year { eventsViewController.year = year mediaViewController.year = year fetchTeaMedia(year: year) } updateInterface() } } // MARK: - Observable typealias ManagedType = Team lazy var contextObserver: CoreDataContextObserver<Team> = { return CoreDataContextObserver(context: persistentContainer.viewContext) }() // MARK: Init init(team: Team, pasteboard: UIPasteboard? = nil, photoLibrary: PHPhotoLibrary? = nil, statusService: StatusService, urlOpener: URLOpener, myTBA: MyTBA, dependencies: Dependencies) { self.team = team self.pasteboard = pasteboard self.photoLibrary = photoLibrary self.statusService = statusService self.urlOpener = urlOpener self.year = TeamViewController.latestYear(currentSeason: statusService.currentSeason, years: team.yearsParticipated, in: dependencies.persistentContainer.viewContext) self.teamHeaderView = TeamHeaderView(TeamHeaderViewModel(team: team, year: year)) infoViewController = TeamInfoViewController(team: team, urlOpener: urlOpener, dependencies: dependencies) eventsViewController = TeamEventsViewController(team: team, year: year, dependencies: dependencies) mediaViewController = TeamMediaCollectionViewController(team: team, year: year, pasteboard: pasteboard, photoLibrary: photoLibrary, urlOpener: urlOpener, dependencies: dependencies) super.init( viewControllers: [infoViewController, eventsViewController, mediaViewController], navigationTitle: team.teamNumberNickname, navigationSubtitle: year?.description ?? "----", segmentedControlTitles: ["Info", "Events", "Media"], myTBA: myTBA, dependencies: dependencies ) eventsViewController.delegate = self mediaViewController.delegate = self teamHeaderView.yearButton.addTarget(self, action: #selector(showSelectYear), for: .touchUpInside) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } // MARK: - View Lifecycle override func viewDidLoad() { super.viewDidLoad() navigationController?.setupSplitViewLeftBarButtonItem(viewController: self) setupObservers() activity = team.userActivity } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) errorRecorder.log("Team: %@", [team.key]) } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) activity?.becomeCurrent() } override func viewWillDisappear(_ animated: Bool) { super.viewWillDisappear(animated) operationQueue.cancelAllOperations() } override func viewDidDisappear(_ animated: Bool) { super.viewDidDisappear(animated) activity?.resignCurrent() } // MARK: - Private private func setupObservers() { contextObserver.observeObject(object: team, state: .updated) { [weak self] (team, _) in guard let self = self else { return } guard let context = team.managedObjectContext else { fatalError("No context for Team.") } if self.year == nil { self.year = TeamViewController.latestYear( currentSeason: self.statusService.currentSeason, years: team.yearsParticipated, in: context ) } else { self.updateInterface() } } } private static func latestYear(currentSeason: Int, years: [Int]?, in context: NSManagedObjectContext) -> Int? { if let years = years, !years.isEmpty { // Limit default year set to be <= currentSeason let latestYear = years.first! if latestYear > currentSeason, years.count > 1 { // Find the next year before the current season return years.first(where: { $0 <= currentSeason }) } else { // Otherwise, the first year is fine (for new teams) return years.first } } return nil } private func updateInterface() { teamHeaderView.viewModel = TeamHeaderViewModel(team: team, year: year) navigationSubtitle = year?.description ?? "----" } private func fetchTeaMedia(year: Int) { var mediaOperation: TBAKitOperation! mediaOperation = tbaKit.fetchTeamMedia(key: team.key, year: year, completion: { [self] (result, notModified) in guard case .success(let media) = result, !notModified else { return } let context = persistentContainer.newBackgroundContext() context.performChangesAndWait({ let team = context.object(with: self.team.objectID) as! Team team.insert(media, year: year) }, saved: { [unowned self] in self.tbaKit.storeCacheHeaders(mediaOperation) }, errorRecorder: errorRecorder) }) operationQueue.addOperation(mediaOperation) } @objc private func showSelectYear() { guard let yearsParticipated = team.yearsParticipated, !yearsParticipated.isEmpty else { return } let selectTableViewController = SelectTableViewController<TeamViewController>(current: year, options: yearsParticipated, dependencies: dependencies) selectTableViewController.title = "Select Year" selectTableViewController.delegate = self let nav = UINavigationController(rootViewController: selectTableViewController) nav.modalPresentationStyle = .formSheet nav.navigationItem.rightBarButtonItem = UIBarButtonItem(barButtonSystemItem: .done, target: self, action: #selector(dismissSelectYear)) navigationController?.present(nav, animated: true, completion: nil) } @objc private func dismissSelectYear() { navigationController?.dismiss(animated: true, completion: nil) } } extension TeamViewController: SelectTableViewControllerDelegate { typealias OptionType = Int func optionSelected(_ option: Int) { year = option } func titleForOption(_ option: Int) -> String { return String(option) } } extension TeamViewController: EventsViewControllerDelegate { func eventSelected(_ event: Event) { let teamAtEventViewController = TeamAtEventViewController(team: team, event: event, myTBA: myTBA, pasteboard: pasteboard, photoLibrary: photoLibrary, statusService: statusService, urlOpener: urlOpener, dependencies: dependencies) self.navigationController?.pushViewController(teamAtEventViewController, animated: true) } } extension TeamViewController: TeamMediaCollectionViewControllerDelegate { func mediaSelected(_ media: TeamMedia) { if let imageViewController = TeamMediaImageViewController.forMedia(media: media) { DispatchQueue.main.async { self.present(imageViewController, animated: true) } } } } class TeamMediaImageViewController: BFRImageViewController { public static func forMedia(media: TeamMedia, peek: Bool = false) -> TeamMediaImageViewController? { // TODO: Support showing multiple images var imageViewController: TeamMediaImageViewController? if let image = media.image { let images = [image] imageViewController = peek ? TeamMediaImageViewController(forPeekWithImageSource: images) : TeamMediaImageViewController(imageSource: images) } else if let url = media.imageDirectURL { let urls = [url] imageViewController = peek ? TeamMediaImageViewController(forPeekWithImageSource: urls) : TeamMediaImageViewController(imageSource: urls) } imageViewController?.modalPresentationStyle = .fullScreen imageViewController?.showDoneButtonOnLeft = false return imageViewController } }
mit
a02707e3981120007c70ebc0b66e0124
33.867925
237
0.663745
5.448113
false
false
false
false
ahyattdev/OrangeIRC
OrangeIRC Core/ServerManager.swift
1
4918
// This file of part of the Swift IRC client framework OrangeIRC Core. // // Copyright © 2016 Andrew Hyatt // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. import Foundation /// Designed to manage a set of servers for an application. This is optional and /// not required to user `Server` but it handles the tasks of loading and saving /// data so you may find it useful. /// /// It is designed to be a singleton and it loads the server data when it is /// initialized. open class ServerManager : ServerDelegate { /// Shared instance public static let shared = ServerManager() /// The servers managed by the server manager internal(set) open var servers: [Server]! private init() { loadData() } /// Paths to store data for servers. Can be customized as needed, /// defaults to servers.plist in the Documents Directory. open var dataPath = FileManager.default.urls( for: .documentDirectory, in: .userDomainMask)[0].appendingPathComponent("servers.plist") /// The delegate for every server. open var serverDelegate: ServerDelegate? /// Servers for which the client is currently registered with. open var registeredServers: [Server] { var regServers = [Server]() for server in servers { if server.isRegistered { regServers.append(server) } } return regServers } /// Creates a server with UTF-8 encoding and adds it to the save data. /// /// - Parameters: /// - host: Server hostname /// - port: Server port /// - nickname: Client preferred nickname /// - username: Client username /// - realname: Client real name /// - password: Server password, optional /// - Returns: A created server that is in the save data open func addServer(host: String, port: Int, nickname: String, username: String, realname: String, password: String? = nil) -> Server { let server = Server(host: host, port: port, nickname: nickname, username: username, realname: realname, encoding: String.Encoding.utf8) // Set the password if one was provided if let password = password { server.password = password } servers.append(server) server.delegate = self server.connect() saveData() NotificationCenter.default.post(name: Notifications.serverCreated, object: server) NotificationCenter.default.post(name: Notifications.serverDataChanged, object: nil) // Returned so additional configuration can be done return server } /// Load client data from `dataPath`. open func loadData() { guard let loadedServers = NSKeyedUnarchiver.unarchiveObject(withFile: dataPath.path) else { // Initialize the file servers = [Server]() saveData() return } servers = loadedServers as? [Server] for server in servers { server.delegate = self if server.autoJoin && !server.isConnectingOrRegistering && !server.isConnected { server.connect() } } } /// Saves the client data to `dataPath`. open func saveData() { NSKeyedArchiver.archiveRootObject(servers, toFile: dataPath.path) } /// Deletes a server. Also handles disconnecting from it and removing it /// from the saved data. /// /// - Parameter server: The server to delete open func delete(server: Server) { server.disconnect() server.delegate = nil for i in 0 ..< servers.count { if servers[i] == server { servers.remove(at: i) break } } for room in server.rooms { NotificationCenter.default.post(name: Notifications.roomDeleted, object: room) NotificationCenter.default.post(name: Notifications.roomDataChanged, object: nil) } NotificationCenter.default.post(name: Notifications.serverDeleted, object: server) NotificationCenter.default.post(name: Notifications.serverDataChanged, object: nil) saveData() } }
apache-2.0
619f46fff38d92acc085f0756790afc7
34.890511
143
0.631483
4.858696
false
false
false
false
kickstarter/ios-oss
Library/ViewModels/MessageThreadsViewModel.swift
1
5981
import KsApi import Prelude import ReactiveSwift public protocol MessageThreadsViewModelInputs { /// Call when the mailbox chooser button is pressed. func mailboxButtonPressed() /// Call with the project whose message threads we are viewing. If no project or refTag is given, then use /// `nil`. func configureWith(project: Project?, refTag: RefTag?) /// Call when pull-to-refresh is invoked. func refresh() /// Call when the search button is pressed. func searchButtonPressed() /// Call when the user has selected a mailbox to switch to. func switchTo(mailbox: Mailbox) /// Call when the view loads. func viewDidLoad() /// Call when a new row is displayed. func willDisplayRow(_ row: Int, outOf totalRows: Int) } public protocol MessageThreadsViewModelOutputs { /// Emits a boolean that determines if the empty state is visible. var emptyStateIsVisible: Signal<Bool, Never> { get } /// Emits when we should go to the search messages screen. var goToSearch: Signal<(), Never> { get } /// Emits a boolean that determines if the footer loading view is hidden. var loadingFooterIsHidden: Signal<Bool, Never> { get } /// Emits a string of the mailbox we are currently viewing. var mailboxName: Signal<String, Never> { get } /// Emits an array of message threads to be displayed. var messageThreads: Signal<[MessageThread], Never> { get } /// Emits when the refresh control should end refreshing. var refreshControlEndRefreshing: Signal<(), Never> { get } /// Emits when an action sheet should be displayed that allows the user to choose mailboxes. var showMailboxChooserActionSheet: Signal<(), Never> { get } } public protocol MessageThreadsViewModelType { var inputs: MessageThreadsViewModelInputs { get } var outputs: MessageThreadsViewModelOutputs { get } } public final class MessageThreadsViewModel: MessageThreadsViewModelType, MessageThreadsViewModelInputs, MessageThreadsViewModelOutputs { public init() { let isCloseToBottom = self.willDisplayRowProperty.signal.skipNil() .filter { _, total in total > 1 } .map { row, total in row >= total - 3 } .skipRepeats() .filter { isClose in isClose } .ignoreValues() let mailbox = Signal.merge( self.switchToMailbox.signal.skipNil(), self.viewDidLoadProperty.signal.mapConst(.inbox) ) let requestFirstPageWith = Signal.merge( mailbox, mailbox.takeWhen(self.refreshProperty.signal) ) let (messageThreads, isLoading, _, _) = paginate( requestFirstPageWith: requestFirstPageWith, requestNextPageWhen: isCloseToBottom, clearOnNewRequest: true, valuesFromEnvelope: { $0.messageThreads }, cursorFromEnvelope: { $0.urls.api.moreMessageThreads }, requestFromParams: { [project = configDataProperty.producer.map { $0?.project }] mailbox in project.take(first: 1) .promoteError(ErrorEnvelope.self) .flatMap { project in AppEnvironment.current.apiService.fetchMessageThreads(mailbox: mailbox, project: project) } }, requestFromCursor: { AppEnvironment.current.apiService.fetchMessageThreads(paginationUrl: $0) } ) self.mailboxName = mailbox.map { switch $0 { case .inbox: return Strings.messages_navigation_inbox() case .sent: return Strings.messages_navigation_sent() } } self.messageThreads = messageThreads self.refreshControlEndRefreshing = isLoading.filter(isFalse).ignoreValues() self.emptyStateIsVisible = Signal.merge( self.messageThreads.filter { !$0.isEmpty }.mapConst(false), self.messageThreads.takeWhen(isLoading.filter(isFalse)).filter { $0.isEmpty }.mapConst(true) ).skipRepeats() self.loadingFooterIsHidden = Signal.merge([ self.viewDidLoadProperty.signal.take(first: 1).mapConst(false), isCloseToBottom.mapConst(false), mailbox.mapConst(false), isLoading.filter(isFalse).mapConst(true) ]).skipRepeats() self.showMailboxChooserActionSheet = self.mailboxButtonPressedProperty.signal self.goToSearch = self.searchButtonPressedProperty.signal } fileprivate let mailboxButtonPressedProperty = MutableProperty(()) public func mailboxButtonPressed() { self.mailboxButtonPressedProperty.value = () } fileprivate let configDataProperty = MutableProperty<ConfigData?>(nil) public func configureWith(project: Project?, refTag: RefTag?) { self.configDataProperty.value = ConfigData(project: project, refTag: refTag) } fileprivate let refreshProperty = MutableProperty(()) public func refresh() { self.refreshProperty.value = () } fileprivate let searchButtonPressedProperty = MutableProperty(()) public func searchButtonPressed() { self.searchButtonPressedProperty.value = () } fileprivate let switchToMailbox = MutableProperty<Mailbox?>(nil) public func switchTo(mailbox: Mailbox) { self.switchToMailbox.value = mailbox } fileprivate let viewDidLoadProperty = MutableProperty(()) public func viewDidLoad() { self.viewDidLoadProperty.value = () } fileprivate let willDisplayRowProperty = MutableProperty<(row: Int, total: Int)?>(nil) public func willDisplayRow(_ row: Int, outOf totalRows: Int) { self.willDisplayRowProperty.value = (row, totalRows) } public let emptyStateIsVisible: Signal<Bool, Never> public let loadingFooterIsHidden: Signal<Bool, Never> public let goToSearch: Signal<(), Never> public let mailboxName: Signal<String, Never> public let messageThreads: Signal<[MessageThread], Never> public let refreshControlEndRefreshing: Signal<(), Never> public let showMailboxChooserActionSheet: Signal<(), Never> public var inputs: MessageThreadsViewModelInputs { return self } public var outputs: MessageThreadsViewModelOutputs { return self } } private struct ConfigData { fileprivate let project: Project? fileprivate let refTag: RefTag? }
apache-2.0
359127f7d4c9ff061ef0d57bc3ec4f0f
33.572254
108
0.725966
4.618533
false
false
false
false
zzeleznick/piazza-clone
Pizzazz/Pizzazz/ViewExtension.swift
1
2945
// // ViewExtension.swift // Pizzazz // // Created by Zach Zeleznick on 5/5/16. // Copyright © 2016 zzeleznick. All rights reserved. // // font helper: http://iosfonts.com/ import UIKit extension UIView { func placeUIElement<T: UIView>(_ element: T, frame: CGRect) { element.frame = frame self.addSubview(element) } func addBorder<T: UIView>(_ myInput: T, height: CGFloat? = 1) { let border = CALayer() border.backgroundColor = UIColor(rgb: 0xCDCDCD).cgColor border.frame = CGRect(x:0, y:myInput.frame.size.height-(1.0 + height!), width: myInput.frame.size.width, height: height!) myInput.layer.addSublayer(border) } func addUIElement<T: UIView>(_ element: T, text: String? = nil, frame: CGRect, onSuccess: (AnyObject)->() = {_ in } ){ switch element { case let label as UILabel: label.text = text label.numberOfLines = 0 case let field as UITextField: field.placeholder = text case let field as UITextView: field.text = text case let button as UIButton: button.setTitle(text, for: UIControlState()) case let image as UIImageView: image.contentMode = .scaleAspectFill image.clipsToBounds = true case _ as UICollectionView: break // pass case let container as UIVisualEffectView: container.effect = UIBlurEffect(style: UIBlurEffectStyle.light) default: break // print("I don't know my type") } placeUIElement(element, frame: frame) onSuccess(element) } } // protocol composition typealias TableMaster = UITableViewDelegate & UITableViewDataSource extension UITableView { convenience init(frame: CGRect, controller: TableMaster, cellWrapper: CellWrapper) { self.init(frame: frame) self.delegate = controller self.dataSource = controller let tp = cellWrapper.cell.self self.register(tp.classForCoder, forCellReuseIdentifier: cellWrapper.identifier) self.backgroundColor = UIColor(white: 0.9, alpha: 1.0) self.rowHeight = 80 } } extension UIColor{ convenience init(rgb: UInt, alphaVal: CGFloat? = 1.0) { self.init( red: CGFloat((rgb & 0xFF0000) >> 16) / 255.0, green: CGFloat((rgb & 0x00FF00) >> 8) / 255.0, blue: CGFloat(rgb & 0x0000FF) / 255.0, alpha: CGFloat(alphaVal!) ) } } extension UISwipeGestureRecognizerDirection: CustomStringConvertible { public var description: String { // print(self.rawValue) switch self.rawValue { case 1 << 0: return "Right" case 1 << 1: return "Left" case 1 << 2: return "Up" case 1 << 3: return "Down" default: return "Unknown" } } }
mit
33477763c95f23c184c2f719e6d89147
30.655914
122
0.597826
4.266667
false
false
false
false
adib/Cheesy-Movies
BadFlix/Models/MovieEntity.swift
1
6238
// Cheesy Movies // Copyright (C) 2016 Sasmito Adibowo – http://cutecoder.org // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. import Foundation import CoreGraphics class MovieEntity { var movieID : Int64? var title: String? var overview: String? var releaseDate: Date? var popularity : Float32? var voteAverage : Float32? var productionCompany : String? var runtime : Float32? var posterPath : String? var backdropPath : String? var genres : Array<GenreEntity>? var casts : Array<CastEntity>? var homepageURLString : String? var trailerURLString : String? init(json:[String:AnyObject]) { self.update(json) } func update(_ json:[String:AnyObject]) { if let number = json["id"] as? NSNumber { movieID = number.int64Value } title = json["original_title"] as? String overview = json["overview"] as? String if let dateStr = json["release_date"] as? String { releaseDate = MovieSearchRequest.dateFormatter.date(from: dateStr) } if let number = json["popularity"] as? NSNumber { popularity = number.floatValue } if let number = json["vote_average"] as? NSNumber { voteAverage = number.floatValue } if let companies = json["production_companies"] as? [[String:AnyObject]], let firstCompany = companies.first { productionCompany = firstCompany["name"] as? String } if let number = json["runtime"] as? NSNumber { runtime = number.floatValue } posterPath = json["poster_path"] as? String backdropPath = json["backdrop_path"] as? String if let genresArray = json["genres"] as? [[String:AnyObject]] { genres = GenreEntity.parse(genresArray) } if let creditsDict = json["credits"] as? [String:AnyObject], let castArray = creditsDict["cast"] as? [[String:AnyObject]] { casts = CastEntity.parse(castArray) } var homepage = json["homepage"] as? String if homepage == nil || homepage?.isEmpty ?? true { if let imdb = json["imdb_id"] as? String { homepage = "https://www.imdb.com/title/\(imdb)/" } } homepageURLString = homepage if let videosDict = json["videos"] as? [String:AnyObject], let videoResults = videosDict["results"] as? [[String:AnyObject]], let firstVideo = videoResults.first { if firstVideo["site"] as? String == "YouTube" { if let youtubeID = firstVideo["key"] { trailerURLString = "https://www.youtube.com/embed/\(youtubeID)" } } } } func posterURL(_ size: CGSize) -> URL? { guard let path = posterPath else { return nil } return MovieBackend.defaultInstance.getImageURL(path, type: .poster, size: size) } func backdropURL(_ size:CGSize) -> URL? { guard let path = backdropPath else { return nil } return MovieBackend.defaultInstance.getImageURL(path, type: .backdrop, size: size) } func refresh(_ completionHandler: ((Error?) -> Void)? ) { guard let movieID = self.movieID else { // TODO: report error of missing ID completionHandler?(nil) return } let params = [ "append_to_response" : "videos,credits" ] MovieBackend.defaultInstance.requestJSON(path:"movie/\(movieID)",parameters: params, completionHandler: { (jsonObject,error) in guard error == nil, let resultDict = jsonObject as? [String:AnyObject] else { completionHandler?(error) return } self.update(resultDict) completionHandler?(nil) }) } static func parse(_ json:[[String:AnyObject]]) -> [MovieEntity] { var resultArray = Array<MovieEntity>() resultArray.reserveCapacity(json.count) for dict in json { let obj = MovieEntity(json: dict) if obj.movieID != nil { resultArray.append(obj) } } return resultArray } static func search(_ request:MovieSearchRequest,completionHandler: @escaping ([MovieEntity]?,Error?) -> Void) { let backend = MovieBackend.defaultInstance backend.requestJSON(path:request.requestPath, parameters: request.requestParameters) { (resultObject, resultError) in guard resultError == nil else { completionHandler(nil,resultError) return } if let resultDict = resultObject as? [String:AnyObject], let resultEntries = resultDict["results"] as? [[String:AnyObject]] { DispatchQueue.global(qos: DispatchQoS.QoSClass.userInteractive).async(execute: { var moviesArray = MovieEntity.parse(resultEntries) if let sortFunction = request.sortFunction { moviesArray.sort(by: sortFunction) } DispatchQueue.main.async(execute: { completionHandler(moviesArray,nil) }) }) } else { completionHandler(nil,nil) } } } }
gpl-3.0
5cbde9e879c8ac48bbce44e9b6693a66
34.634286
115
0.572162
4.856698
false
false
false
false
yunzixun/V2ex-Swift
Controller/TopicDetailViewController.swift
1
21328
// // TopicDetailViewController.swift // V2ex-Swift // // Created by huangfeng on 1/16/16. // Copyright © 2016 Fin. All rights reserved. // import UIKit class TopicDetailViewController: BaseViewController{ var topicId = "0" var currentPage = 1 fileprivate var model:TopicDetailModel? fileprivate var commentsArray:[TopicCommentModel] = [] fileprivate var webViewContentCell:TopicDetailWebViewContentCell? fileprivate var _tableView :UITableView! fileprivate var tableView: UITableView { get{ if(_tableView != nil){ return _tableView!; } _tableView = UITableView(); _tableView.cancelEstimatedHeight() _tableView.separatorStyle = UITableViewCellSeparatorStyle.none; _tableView.backgroundColor = V2EXColor.colors.v2_backgroundColor regClass(_tableView, cell: TopicDetailHeaderCell.self) regClass(_tableView, cell: TopicDetailWebViewContentCell.self) regClass(_tableView, cell: TopicDetailCommentCell.self) regClass(_tableView, cell: BaseDetailTableViewCell.self) _tableView.delegate = self _tableView.dataSource = self return _tableView!; } } /// 忽略帖子成功后 ,调用的闭包 var ignoreTopicHandler : ((String) -> Void)? //点击右上角more按钮后,弹出的 activityView //只在activityView 显示在屏幕上持有它,如果activityView释放了,这里也一起释放。 fileprivate weak var activityView:V2ActivityViewController? //MARK: - 页面事件 override func viewDidLoad() { super.viewDidLoad() self.title = NSLocalizedString("postDetails") self.view.backgroundColor = V2EXColor.colors.v2_backgroundColor self.view.addSubview(self.tableView); self.tableView.snp.makeConstraints{ (make) -> Void in make.top.right.bottom.left.equalTo(self.view); } let rightButton = UIButton(frame: CGRect(x: 0, y: 0, width: 40, height: 40)) rightButton.contentMode = .center rightButton.imageEdgeInsets = UIEdgeInsetsMake(0, 0, 0, -15) rightButton.setImage(UIImage(named: "ic_more_horiz_36pt")!.withRenderingMode(.alwaysTemplate), for: UIControlState()) self.navigationItem.rightBarButtonItem = UIBarButtonItem(customView: rightButton) rightButton.addTarget(self, action: #selector(TopicDetailViewController.rightClick), for: .touchUpInside) self.showLoadingView() self.getData() self.tableView.mj_header = V2RefreshHeader(refreshingBlock: {[weak self] in self?.getData() }) self.tableView.mj_footer = V2RefreshFooter(refreshingBlock: {[weak self] in self?.getNextPage() }) } func getData(){ //根据 topicId 获取 帖子信息 、回复。 TopicDetailModel.getTopicDetailById(self.topicId){ (response:V2ValueResponse<(TopicDetailModel?,[TopicCommentModel])>) -> Void in if response.success { if let aModel = response.value!.0{ self.model = aModel } self.commentsArray = response.value!.1 self.currentPage = 1 //清除将帖子内容cell,因为这是个缓存,如果赋值后,就会cache到这个变量,之后直接读这个变量不重新赋值。 //这里刷新了,则可能需要更新帖子内容cell ,实际上只是重新调用了 cell.load(_:)方法 self.webViewContentCell = nil self.tableView.reloadData() } else{ V2Error(response.message); } if self.tableView.mj_header.isRefreshing{ self.tableView.mj_header.endRefreshing() } self.tableView.mj_footer.resetNoMoreData() self.hideLoadingView() } } /** 点击右上角 more 按钮 */ @objc func rightClick(){ if self.model != nil { let activityView = V2ActivityViewController() activityView.dataSource = self self.navigationController!.present(activityView, animated: true, completion: nil) self.activityView = activityView } } /** 点击节点 */ func nodeClick() { let node = NodeModel() node.nodeId = self.model?.node node.nodeName = self.model?.nodeName let controller = NodeTopicListViewController() controller.node = node self.navigationController?.pushViewController(controller, animated: true) } /** 获取下一页评论,如果有的话 */ func getNextPage(){ if self.model == nil || self.commentsArray.count <= 0 { self.endRefreshingWithNoDataAtAll() return; } self.currentPage += 1 if self.model == nil || self.currentPage > self.model!.commentTotalPages { self.endRefreshingWithNoMoreData() return; } TopicDetailModel.getTopicCommentsById(self.topicId, page: self.currentPage) { (response) -> Void in if response.success { self.commentsArray += response.value! self.tableView.reloadData() self.tableView.mj_footer.endRefreshing() if self.currentPage == self.model?.commentTotalPages { self.endRefreshingWithNoMoreData() } } else{ self.currentPage -= 1 } } } /** 禁用上拉加载更多,并显示一个字符串提醒 */ func endRefreshingWithStateString(_ string:String){ (self.tableView.mj_footer as! V2RefreshFooter).noMoreDataStateString = string self.tableView.mj_footer.endRefreshingWithNoMoreData() } func endRefreshingWithNoDataAtAll() { self.endRefreshingWithStateString("暂无评论") } func endRefreshingWithNoMoreData() { self.endRefreshingWithStateString("没有更多评论了") } } //MARK: - UITableView DataSource enum TopicDetailTableViewSection: Int { case header = 0, comment, other } enum TopicDetailHeaderComponent: Int { case title = 0, webViewContent, other } extension TopicDetailViewController: UITableViewDelegate,UITableViewDataSource { func numberOfSections(in tableView: UITableView) -> Int { return 2 } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { let _section = TopicDetailTableViewSection(rawValue: section)! switch _section { case .header: if self.model != nil{ return 3 } else{ return 0 } case .comment: return self.commentsArray.count; case .other: return 0; } } func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { let _section = TopicDetailTableViewSection(rawValue: indexPath.section)! var _headerComponent = TopicDetailHeaderComponent.other if let headerComponent = TopicDetailHeaderComponent(rawValue: indexPath.row) { _headerComponent = headerComponent } switch _section { case .header: switch _headerComponent { case .title: return tableView.fin_heightForCellWithIdentifier(TopicDetailHeaderCell.self, indexPath: indexPath) { (cell) -> Void in cell.bind(self.model!); } case .webViewContent: if let height = self.webViewContentCell?.contentHeight , height > 0 { return self.webViewContentCell!.contentHeight } else { return 1 } case .other: return 45 } case .comment: let layout = self.commentsArray[indexPath.row].textLayout! return layout.textBoundingRect.size.height + 1 + 12 + 35 + 12 + 12 + 1 case .other: return 200 } } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let _section = TopicDetailTableViewSection(rawValue: indexPath.section)! var _headerComponent = TopicDetailHeaderComponent.other if let headerComponent = TopicDetailHeaderComponent(rawValue: indexPath.row) { _headerComponent = headerComponent } switch _section { case .header: switch _headerComponent { case .title: //帖子标题 let cell = getCell(tableView, cell: TopicDetailHeaderCell.self, indexPath: indexPath); if(cell.nodeClickHandler == nil){ cell.nodeClickHandler = {[weak self] () -> Void in self?.nodeClick() } } cell.bind(self.model!); return cell; case .webViewContent: //帖子内容 if self.webViewContentCell == nil { self.webViewContentCell = getCell(tableView, cell: TopicDetailWebViewContentCell.self, indexPath: indexPath); self.webViewContentCell?.parentScrollView = self.tableView } else { return self.webViewContentCell! } self.webViewContentCell!.load(self.model!); if self.webViewContentCell!.contentHeightChanged == nil { self.webViewContentCell!.contentHeightChanged = { [weak self] (height:CGFloat) -> Void in if let weakSelf = self { //在cell显示在屏幕时更新,否则会崩溃会崩溃会崩溃 //另外刷新清空旧cell,重新创建这个cell ,所以 contentHeightChanged 需要判断cell是否为nil if let cell = weakSelf.webViewContentCell, weakSelf.tableView.visibleCells.contains(cell) { if let height = weakSelf.webViewContentCell?.contentHeight, height > 1.5 * SCREEN_HEIGHT{ //太长了就别动画了。。 UIView.animate(withDuration: 0, animations: { () -> Void in self?.tableView.beginUpdates() self?.tableView.endUpdates() }) } else { self?.tableView.beginUpdates() self?.tableView.endUpdates() } } } } } return self.webViewContentCell! case .other: let cell = getCell(tableView, cell: BaseDetailTableViewCell.self, indexPath: indexPath) cell.detailMarkHidden = true cell.titleLabel.text = self.model?.topicCommentTotalCount cell.titleLabel.font = v2Font(12) cell.backgroundColor = V2EXColor.colors.v2_CellWhiteBackgroundColor cell.separator.image = createImageWithColor(self.view.backgroundColor!) return cell } case .comment: let cell = getCell(tableView, cell: TopicDetailCommentCell.self, indexPath: indexPath) cell.bind(self.commentsArray[indexPath.row]) return cell case .other: return UITableViewCell(); } } func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { if indexPath.section == 1 { self.selectedRowWithActionSheet(indexPath) } } } //MARK: - actionSheet extension TopicDetailViewController: UIActionSheetDelegate { func selectedRowWithActionSheet(_ indexPath:IndexPath){ self.tableView.deselectRow(at: indexPath, animated: true); //这段代码也可以执行,但是当点击时,会有个0.3秒的dismiss动画。 //然后再弹出回复页面或者查看对话页面。感觉太长了,暂时不用 // let actionSheet = UIAlertController(title: nil, message: nil, preferredStyle: .ActionSheet) // let replyAction = UIAlertAction(title: "回复", style: .Default) { _ in // self.replyComment(indexPath.row) // } // let thankAction = UIAlertAction(title: "感谢", style: .Default) { _ in // self.thankComment(indexPath.row) // } // let relevantCommentsAction = UIAlertAction(title: "查看对话", style: .Default) { _ in // self.relevantComment(indexPath.row) // } // let cancelAction = UIAlertAction(title: "取消", style: .Cancel, handler: nil) // //将action全加进actionSheet // [replyAction,thankAction,relevantCommentsAction,cancelAction].forEach { (action) -> () in // actionSheet.addAction(action) // } // self.navigationController?.presentViewController(actionSheet, animated: true, completion: nil) //这段代码在iOS8.3中弃用,但是现在还可以使用,先用着吧 let actionSheet = UIActionSheet(title: nil, delegate: self, cancelButtonTitle: "取消", destructiveButtonTitle: nil, otherButtonTitles: "回复", "感谢" ,"查看对话") actionSheet.tag = indexPath.row actionSheet.show(in: self.view) } func actionSheet(_ actionSheet: UIActionSheet, clickedButtonAt buttonIndex: Int) { guard buttonIndex > 0 && buttonIndex <= 3 else{ return } self.perform([#selector(TopicDetailViewController.replyComment(_:)), #selector(TopicDetailViewController.thankComment(_:)), #selector(TopicDetailViewController.relevantComment(_:))][buttonIndex - 1], with: actionSheet.tag) } @objc func replyComment(_ row:NSNumber){ V2User.sharedInstance.ensureLoginWithHandler { let item = self.commentsArray[row as! Int] let replyViewController = ReplyingViewController() replyViewController.atSomeone = "@" + item.userName! + " " replyViewController.topicModel = self.model! let nav = V2EXNavigationController(rootViewController:replyViewController) self.navigationController?.present(nav, animated: true, completion:nil) } } @objc func thankComment(_ row:NSNumber){ guard V2User.sharedInstance.isLogin else { V2Inform("请先登录") return; } let item = self.commentsArray[row as! Int] if item.replyId == nil { V2Error("回复replyId为空") return; } if self.model?.token == nil { V2Error("帖子token为空") return; } item.favorites += 1 self.tableView.reloadRows(at: [IndexPath(row: row as! Int, section: 1)], with: .none) TopicCommentModel.replyThankWithReplyId(item.replyId!, token: self.model!.token!) { [weak item, weak self](response) in if response.success { } else{ V2Error("感谢失败了") //失败后 取消增加的数量 item?.favorites -= 1 self?.tableView.reloadRows(at: [IndexPath(row: row as! Int, section: 1)], with: .none) } } } @objc func relevantComment(_ row:NSNumber){ let item = self.commentsArray[row as! Int] let relevantComments = TopicCommentModel.getRelevantCommentsInArray(self.commentsArray, firstComment: item) if relevantComments.count <= 0 { return; } let controller = RelevantCommentsNav(comments: relevantComments) self.present(controller, animated: true, completion: nil) } } //MARK: - V2ActivityView enum V2ActivityViewTopicDetailAction : Int { case block = 0, favorite, grade, share, explore } extension TopicDetailViewController: V2ActivityViewDataSource { func V2ActivityView(_ activityView: V2ActivityViewController, numberOfCellsInSection section: Int) -> Int { return 5 } func V2ActivityView(_ activityView: V2ActivityViewController, ActivityAtIndexPath indexPath: IndexPath) -> V2Activity { return V2Activity(title: [ NSLocalizedString("ignore"), NSLocalizedString("favorite"), NSLocalizedString("thank"), NSLocalizedString("share"), "Safari"][indexPath.row], image: UIImage(named: ["ic_block_48pt","ic_grade_48pt","ic_favorite_48pt","ic_share_48pt","ic_explore_48pt"][indexPath.row])!) } func V2ActivityView(_ activityView:V2ActivityViewController ,heightForFooterInSection section: Int) -> CGFloat{ return 45 } func V2ActivityView(_ activityView:V2ActivityViewController ,viewForFooterInSection section: Int) ->UIView?{ let view = UIView() view.backgroundColor = V2EXColor.colors.v2_ButtonBackgroundColor let label = UILabel() label.font = v2Font(18) label.text = NSLocalizedString("reply2") label.textAlignment = .center label.textColor = UIColor.white view.addSubview(label) label.snp.makeConstraints{ (make) -> Void in make.top.right.bottom.left.equalTo(view) } view.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(TopicDetailViewController.reply))) return view } func V2ActivityView(_ activityView: V2ActivityViewController, didSelectRowAtIndexPath indexPath: IndexPath) { activityView.dismiss() let action = V2ActivityViewTopicDetailAction(rawValue: indexPath.row)! guard V2User.sharedInstance.isLogin // 用safari打开是不用登录的 || action == V2ActivityViewTopicDetailAction.explore || action == V2ActivityViewTopicDetailAction.share else { V2Inform("请先登录") return; } switch action { case .block: V2BeginLoading() if let topicId = self.model?.topicId { TopicDetailModel.ignoreTopicWithTopicId(topicId, completionHandler: {[weak self] (response) -> Void in if response.success { V2Success("忽略成功") self?.navigationController?.popViewController(animated: true) self?.ignoreTopicHandler?(topicId) } else{ V2Error("忽略失败") } }) } case .favorite: V2BeginLoading() if let topicId = self.model?.topicId ,let token = self.model?.token { TopicDetailModel.favoriteTopicWithTopicId(topicId, token: token, completionHandler: { (response) -> Void in if response.success { V2Success("收藏成功") } else{ V2Error("收藏失败") } }) } case .grade: V2BeginLoading() if let topicId = self.model?.topicId ,let token = self.model?.token { TopicDetailModel.topicThankWithTopicId(topicId, token: token, completionHandler: { (response) -> Void in if response.success { V2Success("成功送了一波铜币") } else{ V2Error("没感谢成功,再试一下吧") } }) } case .share: let shareUrl = NSURL.init(string: V2EXURL + "t/" + self.model!.topicId!) let shareArr:NSArray = [shareUrl!] let activityController = UIActivityViewController.init(activityItems: shareArr as [AnyObject], applicationActivities: nil) self.present(activityController, animated: true, completion: nil) case .explore: UIApplication.shared.openURL(URL(string: V2EXURL + "t/" + self.model!.topicId!)!) } } @objc func reply(){ self.activityView?.dismiss() V2User.sharedInstance.ensureLoginWithHandler { let replyViewController = ReplyingViewController() replyViewController.topicModel = self.model! let nav = V2EXNavigationController(rootViewController:replyViewController) self.navigationController?.present(nav, animated: true, completion:nil) } } }
mit
64f1da46408ad8280fb932f76720bb75
38.359615
164
0.578297
5.015192
false
false
false
false
wang-chuanhui/CHSDK
Source/Utils/CoreGraphics.swift
1
3454
// // CoreGraphics.swift // CHSDK // // Created by 王传辉 on 2017/8/4. // Copyright © 2017年 王传辉. All rights reserved. // import UIKit import CoreGraphics extension CGFloat: Compatible { } public extension NameSpace where Base == CGFloat { func shortestAngle(_ angle: CGFloat) -> CGFloat { var result = (angle - base).truncatingRemainder(dividingBy: CGFloat.pi * 2) if result >= CGFloat.pi { result = result - CGFloat.pi * 2 } if result <= -CGFloat.pi { result = result + CGFloat.pi * 2 } return result } var sign: CGFloat { return base >= 0 ? 1 : -1 } static func random(_ l: CGFloat, _ r: CGFloat = 0) -> CGFloat { let max = Swift.max(l, r) let min = Swift.min(l, r) return CGFloat(arc4random_uniform(UInt32(max - min))) + min } } extension CGPoint: Compatible { } public extension NameSpace where Base == CGPoint { static func point(_ value: Int) -> CGPoint { return CGPoint(x: value, y: value) } static func point(_ value: CGFloat) -> CGPoint { return CGPoint(x: value, y: value) } static func point(_ value: Double) -> CGPoint { return CGPoint(x: value, y: value) } var length: CGFloat { return CGFloat(sqrt(Double(base.x * base.x + base.y * base.y))) } var normalized: CGPoint { return base / length } var angle: CGFloat { return CGFloat(atan2(Double(base.y), Double(base.x))) } } extension CGSize: Compatible { } public extension NameSpace where Base == CGSize { static func size(_ value: Int) -> CGSize { return CGSize(width: value, height: value) } static func size(_ value: CGFloat) -> CGSize { return CGSize(width: value, height: value) } static func size(_ value: Double) -> CGSize { return CGSize(width: value, height: value) } } extension CGVector: Compatible { } public extension NameSpace where Base == CGVector { static func vector(_ value: Int) -> CGVector { return CGVector(dx: value, dy: value) } static func size(_ value: CGFloat) -> CGVector { return CGVector(dx: value, dy: value) } static func size(_ value: Double) -> CGVector { return CGVector(dx: value, dy: value) } } public func +(l: CGPoint, r: CGPoint) -> CGPoint { return CGPoint(x: l.x + r.x, y: l.y + r.y) } public func +=(l: inout CGPoint, r: CGPoint) { l = l + r } public func -(l: CGPoint, r: CGPoint) -> CGPoint { return CGPoint(x: l.x - r.x, y: l.y - r.y) } public func -=(l: inout CGPoint, r: CGPoint) { l = l - r } public func *(l: CGPoint, r: CGPoint) -> CGPoint { return CGPoint(x: l.x * r.x, y: l.y * r.y) } public func *=(l: inout CGPoint, r: CGPoint) { l = l * r } public func /(l: CGPoint, r: CGPoint) -> CGPoint { return CGPoint(x: l.x / r.x, y: l.y / r.y) } public func /=(l: inout CGPoint, r: CGPoint) { l = l / r } public func *(point: CGPoint, scalar: CGFloat) -> CGPoint { return CGPoint(x: point.x * scalar, y: point.y * scalar) } public func *=(point: inout CGPoint, scalar: CGFloat) { point = point * scalar } public func /(point: CGPoint, scalar: CGFloat) -> CGPoint { return CGPoint(x: point.x / scalar, y: point.y / scalar) } public func /=(point: inout CGPoint, scalar: CGFloat) { point = point / scalar }
mit
e9f653467bbdac92e1edb224bafe48e7
22.554795
83
0.588834
3.48783
false
false
false
false
kevinvanderlugt/Exercism-Solutions
swift/exercism-test-runner/exercism-test-runner/Gigasecond.swift
1
685
// // Gigasecond.swift // exercism-test-runner // // Created by Kevin VanderLugt on 3/19/15. // Copyright (c) 2015 Alpine Pipeline, LLC. All rights reserved. // import Foundation struct Gigasecond { static func from(birthday: String) -> NSDate { let gigasecond = pow(10.0, 9.0) var dateFormatter = NSDateFormatter() dateFormatter.timeZone = NSTimeZone(forSecondsFromGMT: 0) dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss" if let birthdate = dateFormatter.dateFromString(birthday) { return birthdate.dateByAddingTimeInterval(gigasecond) } return NSDate.distantFuture() as! NSDate } }
mit
cd17755872cad61867baed4911c372c9
27.583333
67
0.654015
4.005848
false
false
false
false
timelessg/TLStoryCamera
TLStoryCameraFramework/TLStoryCameraFramework/Class/Models/TLAuthorizedManager.swift
1
3867
// // TLAuthorizedManager.swift // TLStoryCamera // // Created by garry on 2017/5/26. // Copyright © 2017年 com.garry. All rights reserved. // import UIKit import Photos typealias AuthorizedCallback = (TLAuthorizedManager.AuthorizedType, Bool) -> Void class TLAuthorizedManager: NSObject { public enum AuthorizedType { case mic case camera case album } public static func requestAuthorization(with type:AuthorizedType, callback:@escaping AuthorizedCallback) { if type == .mic { self.requestMicAuthorizationStatus(callback) } if type == .camera { self.requestCameraAuthorizationStatus(callback) } if type == .album { self.requestAlbumAuthorizationStatus(callback) } } public static func checkAuthorization(with type:AuthorizedType) -> Bool { if type == .mic { return AVAudioSession.sharedInstance().recordPermission() == .granted } if type == .camera { return AVCaptureDevice.authorizationStatus(for: AVMediaType.video) == .authorized } if type == .album { return PHPhotoLibrary.authorizationStatus() == .authorized } return false } public static func openAuthorizationSetting() { if #available(iOS 10.0, *) { UIApplication.shared.open(URL.init(string: UIApplicationOpenSettingsURLString)!, options: [:], completionHandler: nil) } else { UIApplication.shared.openURL(URL.init(string: UIApplicationOpenSettingsURLString)!) } } fileprivate static func requestMicAuthorizationStatus(_ callabck:@escaping AuthorizedCallback) { let status = AVAudioSession.sharedInstance().recordPermission() if status == .granted { DispatchQueue.main.async { callabck(.mic, true) } }else if status == .denied { DispatchQueue.main.async { callabck(.mic, false) } self.openAuthorizationSetting() }else{ AVAudioSession.sharedInstance().requestRecordPermission({ granted in DispatchQueue.main.async { callabck(.mic, granted) } }) } } fileprivate static func requestCameraAuthorizationStatus(_ callabck:@escaping AuthorizedCallback) { let status = AVCaptureDevice.authorizationStatus(for: AVMediaType.video) if status == .authorized { DispatchQueue.main.async { callabck(.camera, true) } }else if status == .notDetermined { AVCaptureDevice.requestAccess(for: AVMediaType.video, completionHandler: { granted in DispatchQueue.main.async { callabck(.camera, granted) } }) }else if (status == .denied) { DispatchQueue.main.async { callabck(.camera, false) self.openAuthorizationSetting() } } } fileprivate static func requestAlbumAuthorizationStatus(_ callabck:@escaping AuthorizedCallback) { let status = PHPhotoLibrary.authorizationStatus() if status == .authorized { DispatchQueue.main.async { callabck(.album, true) } }else if status == .notDetermined { PHPhotoLibrary.requestAuthorization({ (granted) in DispatchQueue.main.async { callabck(.album, granted == .authorized) } }) }else if status == .denied || status == .restricted { DispatchQueue.main.async { callabck(.album, false) } self.openAuthorizationSetting() } } }
mit
bcb73d35389110077d87cdc6a63d76a4
33.19469
130
0.582816
5.322314
false
false
false
false
onevcat/CotEditor
CotEditor/Sources/StatableMenuToolbarItem.swift
2
1664
// // StatableMenuToolbarItem.swift // // CotEditor // https://coteditor.com // // Created by 1024jp on 2018-06-18. // // --------------------------------------------------------------------------- // // © 2018-2020 1024jp // // 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 // // https://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 AppKit final class StatableMenuToolbarItem: NSMenuToolbarItem, StatableItem, Validatable { // MARK: Public Properties var state: NSControl.StateValue = .on { didSet { self.invalidateImage() } } var stateImages: [NSControl.StateValue: NSImage] = [:] { didSet { self.invalidateImage() } } // MARK: - // MARK: Toolbar Item Methods override var image: NSImage? { get { super.image } @available(*, unavailable, message: "Set images through 'stateImages' instead.") set { } } override func validate() { self.isEnabled = self.validate() } // MARK: Private Methods private func invalidateImage() { assert(self.state != .mixed) super.image = self.stateImages[self.state] } }
apache-2.0
27c3dc3b212f551704d32e5d37298d14
25.396825
97
0.603127
4.364829
false
false
false
false
wendyabrantes/WACustomSwitch
WACustomSwitch/WACustomSwitch.swift
1
3703
// // WACustomSwitch.swift // WACustomSwitchExample // // Created by Wendy Abrantes on 05/10/2015. // Copyright © 2015 ABRANTES DIGITAL LTD. All rights reserved. // import UIKit enum AnimationType{ case NativeAnimation case DayNightAnimation func animationView(frame:CGRect) -> WAAnimationView { switch self { case .DayNightAnimation: return DayNightAnimationView(frame: frame); case .NativeAnimation: return NativeAnimationView(frame: frame); } } } class WACustomSwitch: UIControl { var on: Bool = false var isTapGesture: Bool = false var animationView : WAAnimationView! var _previousTouchPoint:CGPoint! init(frame: CGRect, animationType : AnimationType) { super.init(frame: frame) backgroundColor = UIColor.clearColor() animationView = animationType.animationView(CGRect(x: 0, y: 0, width: frame.width, height: frame.height)) animationView.userInteractionEnabled = false addSubview(animationView) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func beginTrackingWithTouch(touch: UITouch, withEvent event: UIEvent?) -> Bool { isTapGesture = true _previousTouchPoint = touch.locationInView(self) let percent : CGFloat = _previousTouchPoint.x / self.frame.width animationView.animateToProgress(percent) return true } override func continueTrackingWithTouch(touch: UITouch, withEvent event: UIEvent?) -> Bool { isTapGesture = false animationView.pop_removeAllAnimations() let currentTouch = touch.locationInView(self) var percent : CGFloat = currentTouch.x / self.frame.width percent = max(percent, 0.0) percent = min(percent, 1.0) animationView.progress = percent animationView.setNeedsDisplay() return true } override func endTrackingWithTouch(touch: UITouch?, withEvent event: UIEvent?) { if(isTapGesture){ if(self.on){ animationView.animateToProgress(0.0) }else{ animationView.animateToProgress(1.0) } self.on = !self.on }else{ endToggleAnimation() } } override func cancelTrackingWithEvent(event: UIEvent?) { if(isTapGesture){ if(self.on){ animationView.animateToProgress(0.0) }else{ animationView.animateToProgress(1.0) } self.on = !self.on }else{ endToggleAnimation() } } func endToggleAnimation(){ var newProgress : CGFloat! if(animationView.progress >= 0.5) { newProgress = 1.0 animationView.animateToProgress(newProgress) }else{ newProgress = 0.0 animationView.animateToProgress(newProgress) } if(on && newProgress == 0) { on = false sendActionsForControlEvents(UIControlEvents.ValueChanged) }else if(!on && newProgress == 1){ on = true sendActionsForControlEvents(UIControlEvents.ValueChanged) } } func setOn(on: Bool, animated: Bool){ var progress : CGFloat = 0.0 if on { progress = 1.0 } if(animated){ animationView.animateToProgress(progress) }else{ animationView.progress = progress } } }
mit
943f131c887bedf65d0d95efd85275ac
26.220588
113
0.584009
5.009472
false
false
false
false
davidhariri/done
DoneTests/TodoListMethodsTests.swift
1
1749
// // TodoListDefaultAtrributeTests.swift // Done // // Created by David Hariri on 2017-03-13. // Copyright © 2017 David Hariri. All rights reserved. // import XCTest @testable import Done class TodoListMethodsTests: XCTestCase { var todo: Todo! var todoList: TodoList! override func setUp() { super.setUp() todo = Todo(withText: "Test Item") todoList = TodoList() todoList.add(todo: todo) } override func tearDown() { super.tearDown() todo = nil todoList = nil } func testThatAddAddsATodo() { todoList.add(todo: todo) XCTAssert(todoList.length == 2, ".length was not 2. Got \(todoList.length)") XCTAssert(todoList.items[0].text == todo.text, ".items[0] was not todo") } func testThatRemoveRemovesATodo() { todoList.add(todo: Todo(withText: "Test Item 2")) todoList.remove(atIndex: 1) XCTAssert(todoList.length == 1, ".length was not 1. Got \(todoList.length)") XCTAssert(todoList.items[0].text == "Test Item 2", ".text was not 'Test Item 2'. Got '\(todoList.items[0].text)'") } func testThatRemoveSelectedRemovesSelectedTodos() { todo.toggleSelected() todoList.add(todo: Todo(withText: "Test Item 2")) XCTAssert(todoList.length == 2, ".length was not 2") todoList.removeSelected() XCTAssert(todoList.length == 1, ".length was not 1") } func testThatUpdateSelectedDoneMarksSelectedTodosDone() { let todo2 = Todo(withText: "Test Item 2") todo2.toggleSelected() todoList.add(todo: todo2) todoList.updateSelectedDone() XCTAssert(todo2.done, ".done was not true") } }
apache-2.0
f7453b00d5d039497ce70c4865b9f383
29.666667
122
0.618421
3.945824
false
true
false
false
wordpress-mobile/AztecEditor-iOS
Aztec/Classes/Extensions/NSRange+Helpers.swift
2
5034
import Foundation // MARK: - NSRange Extensions // extension NSRange { /// Checks if the receiver contains the specified range. /// /// - Parameters: /// - range: the range that the receiver may or may not contain. /// /// - Returns: `true` if the receiver contains the specified range, `false` otherwise. /// func contains(_ range: NSRange) -> Bool { return intersect(withRange: range) == range } /// Checks if the receiver contains the specified location. /// /// - Parameters: /// - range: the location that the receiver may or may not contain. /// /// - Returns: `true` if the receiver contains the specified location, `false` otherwise. /// func contains(offset: Int) -> Bool { return offset >= location && offset <= location + length } /// Calculates the end location for the receiver. /// /// - Returns: the requested end location /// var endLocation: Int { return location + length } /// Returns a range equal to the receiver extended to its right side by the specified addition /// value. /// /// - Parameters: /// - addition: the number that will be added to the length of the range /// /// - Returns: the new range. /// func extendedRight(by addition: Int) -> NSRange { return NSRange(location: location, length: length + addition) } /// Returns the intersection between the receiver and the specified range. /// /// - Important: the main difference with NSIntersectionRange is that this method considers any contact (even a /// zero-length contact) as an intersection. Another difference is that this method returns `nil` /// when there's absolutely no contact. /// /// - Parameters: /// - range: the range to compare the receiver against. /// /// - Returns: the interesection if there's any, or `nil` otherwise. /// func intersect(withRange target: NSRange) -> NSRange? { let endLocation = location + length let targetEndLocation = target.location + target.length if target.location >= location && targetEndLocation <= endLocation { return target } else if target.location < location && targetEndLocation >= location && targetEndLocation <= endLocation { return NSRange(location: location, length: targetEndLocation - location) } else if target.location >= location && target.location <= endLocation && targetEndLocation > endLocation { return NSRange(location: target.location, length: endLocation - target.location) } else if target.location < location && targetEndLocation > endLocation { return self } else { return nil } } /// Offsets the receiver by the specified value. /// /// - Parameters: /// - offset: the value to apply for the offset operation. /// /// - Returns: the requested range. /// func offset(by offset: Int) -> NSRange { return NSRange(location: location + offset, length: length) } /// Returns a range equal to the receiver shortened on its left side by the specified deduction /// value. /// /// - Parameters: /// - deduction: the number that will be deducted from the length of the range /// /// - Returns: the new range. /// func shortenedLeft(by deduction: Int) -> NSRange { return NSRange(location: location + deduction, length: length - deduction) } /// Returns a range equal to the receiver shortened on its right side by the specified deduction /// value. /// /// - Parameters: /// - deduction: the number that will be deducted from the length of the range /// /// - Returns: the new range. /// func shortenedRight(by deduction: Int) -> NSRange { return NSRange(location: location, length: length - deduction) } /// Returns the union with the specified range. /// /// This is `NSUnionRange` wrapped as an instance method. /// func union(withRange target: NSRange) -> NSRange { return NSUnionRange(self, target) } /// Returns a NSRange instance with location = 0 + length = 0 /// static var zero: NSRange { return NSRange(location: 0, length: 0) } } extension Sequence where Iterator.Element == NSRange { /// Returns the union of all the ranges in the sequence /// func union() -> NSRange? { return reduce(nil) { (partialUnion, range) in guard let partialUnion = partialUnion else { return range } return partialUnion.union(withRange: range) } } } #if swift(>=3.2) // No Op #else extension NSRange: Equatable { public static func ==(lhs: NSRange, rhs: NSRange) -> Bool{ return lhs.location == rhs.location && lhs.length == rhs.length } } #endif
mpl-2.0
154bc804f90230b8547c9dc9b6791f0c
32.337748
116
0.609257
4.678439
false
false
false
false
alltheflow/iCopyPasta
iCopyPasta/PasteViewController.swift
1
1408
// // PasteViewController.swift // iCopyPasta // // Created by Agnes Vasarhelyi on 05/01/16. // Copyright © 2016 Agnes Vasarhelyi. All rights reserved. // import UIKit import RxSwift import RxCocoa class PasteViewController: UIViewController { @IBOutlet weak var tableView: UITableView! let pasteViewModel = PasteViewModel() let disposeBag = DisposeBag() override func viewDidLoad() { super.viewDidLoad() pasteViewModel.pasteboardItems() .bindTo(tableView.rx_itemsWithCellIdentifier("pasteCell", cellType: UITableViewCell.self)) { (row, element, cell) in switch element { case .Text(let string): cell.textLabel?.text = String(string) case .Image(let image): cell.imageView?.image = image case .URL(let url): cell.textLabel?.text = String(url) } }.addDisposableTo(disposeBag) pasteViewModel.pasteboardItems() .subscribeNext { [weak self] _ in self?.tableView.reloadData() }.addDisposableTo(disposeBag) tableView .rx_modelSelected(PasteboardItem) .subscribeNext { [weak self] element in self?.pasteViewModel.addItemsToPasteboard(element) }.addDisposableTo(disposeBag) } }
mit
e27bdb72c06307ae46a7f98ead941505
28.93617
128
0.595593
4.971731
false
false
false
false
louchu0604/algorithm-swift
TestAPP/TestAPP/NO.2addTwoNumbers.swift
1
925
// // NO.2addTwoNumbers.swift // TestAPP // // Created by louchu on 2019/6/23. // Copyright © 2019年 Cy Lou. All rights reserved. // import Foundation /** * Definition for singly-linked list. * public class ListNode { * public var val: Int * public var next: ListNode? * public init(_ val: Int) { * self.val = val * self.next = nil * } * } */ func addTwoNumbers(_ l1: ListNode?, _ l2: ListNode?) -> ListNode? { if(l1==nil && l2 == nil) { return nil } if(l1==nil) { } if(l2==nil) { } } func listToNumber(_ l:ListNode) -> Int{ var node = l var exp = 1 var sum = 0 while (node==nil) { sum = node.val * exp exp = exp * 10 node = node.next } return sum } func numberToList(_ n:Int) -> ListNode ( var sum = n var node =ListNode.init(sum % 10) )
mit
903bc0dfbb01f3cc908e6022d6b91afc
15.175439
67
0.507592
3.212544
false
false
false
false
vector-im/riot-ios
Riot/Modules/Camera/CameraPresenter.swift
1
5301
/* Copyright 2019 New Vector Ltd Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ import Foundation import UIKit import AVFoundation @objc protocol CameraPresenterDelegate: class { func cameraPresenter(_ presenter: CameraPresenter, didSelectImageData imageData: Data, withUTI uti: MXKUTI?) func cameraPresenter(_ presenter: CameraPresenter, didSelectVideoAt url: URL) func cameraPresenterDidCancel(_ cameraPresenter: CameraPresenter) } /// CameraPresenter enables to present native camera @objc final class CameraPresenter: NSObject { // MARK: - Constants private enum Constants { static let jpegCompressionQuality: CGFloat = 1.0 } // MARK: - Properties // MARK: Private private let cameraAccessManager: CameraAccessManager private let cameraAccessAlertPresenter: CameraAccessAlertPresenter private weak var presentingViewController: UIViewController? private weak var cameraViewController: UIViewController? private var mediaUTIs: [MXKUTI] = [] // MARK: Public @objc weak var delegate: CameraPresenterDelegate? // MARK: - Setup override init() { self.cameraAccessManager = CameraAccessManager() self.cameraAccessAlertPresenter = CameraAccessAlertPresenter() super.init() } // MARK: - Public @objc func presentCamera(from presentingViewController: UIViewController, with mediaUTIs: [MXKUTI], animated: Bool) { self.presentingViewController = presentingViewController self.mediaUTIs = mediaUTIs self.checkCameraPermissionAndPresentCamera(animated: animated) } @objc func dismiss(animated: Bool, completion: (() -> Void)?) { guard let cameraViewController = self.cameraViewController else { return } cameraViewController.dismiss(animated: animated, completion: completion) } // MARK: - Private private func checkCameraPermissionAndPresentCamera(animated: Bool) { guard let presentingViewController = self.presentingViewController else { return } guard self.cameraAccessManager.isCameraAvailable else { self.cameraAccessAlertPresenter.presentCameraUnavailableAlert(from: presentingViewController, animated: animated) return } self.cameraAccessManager.askAndRequestCameraAccessIfNeeded { (granted) in if granted { self.presentCameraController(animated: animated) } else { self.cameraAccessAlertPresenter.presentPermissionDeniedAlert(from: presentingViewController, animated: animated) } } } private func presentCameraController(animated: Bool) { guard let presentingViewController = self.presentingViewController else { return } guard let cameraViewController = self.buildCameraViewController() else { return } presentingViewController.present(cameraViewController, animated: true, completion: nil) self.cameraViewController = cameraViewController } private func buildCameraViewController() -> UIViewController? { guard UIImagePickerController.isSourceTypeAvailable(UIImagePickerController.SourceType.camera) else { return nil } let mediaTypes = self.mediaUTIs.map { (uti) -> String in return uti.rawValue } let imagePickerController = UIImagePickerController() imagePickerController.delegate = self imagePickerController.sourceType = UIImagePickerController.SourceType.camera imagePickerController.mediaTypes = mediaTypes imagePickerController.allowsEditing = false return imagePickerController } } // MARK: - UIImagePickerControllerDelegate extension CameraPresenter: UIImagePickerControllerDelegate { func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey: Any]) { if let videoURL = info[.mediaURL] as? URL { self.delegate?.cameraPresenter(self, didSelectVideoAt: videoURL) } else if let image = (info[.editedImage] ?? info[.originalImage]) as? UIImage, let imageData = image.jpegData(compressionQuality: Constants.jpegCompressionQuality) { self.delegate?.cameraPresenter(self, didSelectImageData: imageData, withUTI: MXKUTI.jpeg) } } func imagePickerControllerDidCancel(_ picker: UIImagePickerController) { self.delegate?.cameraPresenterDidCancel(self) } } // MARK: - UINavigationControllerDelegate extension CameraPresenter: UINavigationControllerDelegate { }
apache-2.0
32caafeb1b8b9e8f79354218696b50df
35.558621
174
0.701943
5.825275
false
false
false
false
PigDogBay/Food-Hygiene-Ratings
Food Hygiene Ratings/LocalViewController.swift
1
10290
// // LocalViewController.swift // Food Hygiene Ratings // // Created by Mark Bailey on 20/02/2017. // Copyright © 2017 MPD Bailey Technology. All rights reserved. // import UIKit import GoogleMobileAds import MessageUI class LocalViewController: UIViewController, UITableViewDataSource, UITableViewDelegate, UISearchResultsUpdating, UISearchBarDelegate, AppStateChangeObserver, MFMailComposeViewControllerDelegate { @IBOutlet weak var bannerView: GADBannerView! @IBOutlet weak var tableView: UITableView! @IBOutlet weak var loadingIndicator: UIActivityIndicatorView! @IBOutlet weak var loadingLabel: UILabel! var searchController : UISearchController! private let cellId = "establishmentCell" private var model : MainModel { get { return MainModel.sharedInstance} } private var groupedEstablishments : [Int : [Establishment]]! private var sortedBusinessTypes : [Int]! override func viewDidLoad() { super.viewDidLoad() tableView.dataSource = self tableView.delegate = self tableView.keyboardDismissMode = .onDrag loadingIndicator.startAnimating() loadingLabel.isHidden=false searchController = UISearchController(searchResultsController: nil) searchController.searchResultsUpdater = self searchController.dimsBackgroundDuringPresentation = false searchController.searchBar.scopeButtonTitles = ["All","5", "4", "3", "2", "1", "0"] searchController.searchBar.delegate = self searchController.searchBar.sizeToFit() searchController.searchBar.tintColor = UIColor(red: 0.20, green: 0.41, blue: 0.12, alpha: 1.0) definesPresentationContext = true tableView.tableHeaderView = searchController.searchBar bannerView.adSize = kGADAdSizeBanner bannerView.adUnitID = Ads.localBannerAdId bannerView.rootViewController = self bannerView.load(Ads.createRequest()) } deinit { //Will get a warning if searchController is not removed //http://stackoverflow.com/questions/32282401/attempting-to-load-the-view-of-a-view-controller-while-it-is-deallocating-uis if let superView = searchController.view.superview { superView.removeFromSuperview() } } override func viewWillAppear(_ animated: Bool) { let model = MainModel.sharedInstance stateChanged(model.state) model.addObserver("localView", observer: self) } override func viewWillDisappear(_ animated: Bool) { let model = MainModel.sharedInstance model.removeObserver("localView") } override func willMove(toParent parent: UIViewController?) { //Only do something when moving back to parent if parent == nil { MainModel.sharedInstance.stop() MainModel.sharedInstance.ratings.requestRating() } } fileprivate func loadTableData() { if (model.state == .loaded) { if searchController.isActive { let establishments = model.results let searchText = searchController.searchBar.text! let scopeFiltered = DataProcessing.filter(establishments: establishments, filter: getSearchFilter()) let filtered = DataProcessing.filter(establishments: scopeFiltered, containing: searchText ) self.groupedEstablishments = DataProcessing.createDictionary(fromArray: filtered) self.sortedBusinessTypes = DataProcessing.createSortedIndex(fromDictionary: self.groupedEstablishments) } else { self.groupedEstablishments = DataProcessing.createDictionary(fromArray: model.results) self.sortedBusinessTypes = DataProcessing.createSortedIndex(fromDictionary: self.groupedEstablishments) } tableView.reloadData() } } func getSearchFilter() -> SearchFilter { switch searchController.searchBar.selectedScopeButtonIndex { case 1: return .star5 case 2: return .star4 case 3: return .star3 case 4: return .star2 case 5: return .star1 case 6: return .star0 default: return .all } } func searchBar(_ searchBar: UISearchBar, selectedScopeButtonIndexDidChange selectedScope: Int) { loadTableData() } func updateSearchResults(for searchController: UISearchController) { loadTableData() } func numberOfSections(in tableView: UITableView) -> Int { if (model.state == .loaded && groupedEstablishments != nil){ return groupedEstablishments.keys.count } return 1 } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { if (model.state == .loaded && sortedBusinessTypes != nil){ let businessTypeId = sortedBusinessTypes[section] return groupedEstablishments[businessTypeId]!.count } return 0 } func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? { if (model.state == .loaded && sortedBusinessTypes != nil){ let businessTypeId = sortedBusinessTypes[section] let group = groupedEstablishments[businessTypeId]! return "\(group[0].business.type) (\(group.count))" } return "" } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: cellId, for: indexPath) let businessTypeId = sortedBusinessTypes[indexPath.section] let est = groupedEstablishments[businessTypeId]![indexPath.row] cell.textLabel?.text = est.business.name cell.detailTextLabel?.text = getDetailsText(establishment: est) cell.imageView?.image = UIImage(named: est.rating.getIconName()) cell.tag = est.business.fhrsId return cell } func getDetailsText(establishment : Establishment) -> String { switch MainModel.sharedInstance.searchType { case .local: fallthrough case .map: return String(format: "%.1f miles, ", establishment.distance) + establishment.address.flatten() default: return establishment.address.flatten() } } func sectionIndexTitles(for tableView: UITableView) -> [String]? { if (model.state == .loaded && sortedBusinessTypes != nil && sortedBusinessTypes.count>0){ return (1 ... sortedBusinessTypes.count).map(){"\($0)"} } return nil } // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if segue.identifier == "segueDetails" { if let detailsVC = segue.destination as? DetailsViewController { if let indexPath = tableView.indexPathForSelectedRow { let businessTypeId = sortedBusinessTypes[indexPath.section] let est = groupedEstablishments[businessTypeId]![indexPath.row] detailsVC.establishment = est } } } } // MARK: - AppStateChangeObserver internal func stateChanged(_ newState: AppState) { let model = MainModel.sharedInstance switch newState { case .ready: print("state: Ready") case .requestingLocationAuthorization: print("state: requesting location authorization") case .locating: print("state: locating") case .foundLocation: print("state: found location \(model.location.latitude) \(model.location.longitude)") case .notAuthorizedForLocating: print("state: not authorized for locating") OperationQueue.main.addOperation { self.loadingIndicator.stopAnimating() self.loadingLabel.isHidden=true self.showErrorAlert(title: "Authorisation Required", msg: "Please go to Settings, privacy, location and select While Using the App") } case .errorLocating: print("state: error locating") case .loading: print("state: loading") case .loaded: print("state: loaded") OperationQueue.main.addOperation { self.loadingIndicator.stopAnimating() self.loadingLabel.isHidden=true if model.results.count>0 { self.title = "\(model.results.count) Results" self.loadTableData() } else { self.showErrorAlert(title: "No Results", msg: "No matches were found") } } case .error: print("state: error") OperationQueue.main.addOperation { self.loadingIndicator.stopAnimating() self.loadingLabel.isHidden=true let msg = self.model.error?.localizedDescription ?? "An error occurred, check your internet connection" self.showErrorAlert(title: "Error", msg: msg) } } } fileprivate func showErrorAlert(title: String, msg : String) { let action = UIAlertAction(title: "OK", style: UIAlertAction.Style.default, handler: {_ in self.navigationController?.popViewController(animated: true) }) let controller = UIAlertController(title: title, message: msg, preferredStyle: UIAlertController.Style.alert) controller.addAction(action) self.present(controller, animated: true, completion: nil) } // MARK:- MFMailComposeViewControllerDelegate public func mailComposeController(_ controller: MFMailComposeViewController, didFinishWith result: MFMailComposeResult, error: Error?) { //dismiss on send controller.dismiss(animated: true, completion: nil) } }
apache-2.0
04e6c49c8a5c454e41a65f473e28d36e
37.680451
196
0.635533
5.409569
false
false
false
false
nzaghini/mastering-reuse-viper
Weather/Modules/WeatherList/Core/Presenter/WeatherListPresenter.swift
2
2183
import Foundation struct LocationListViewModel { let locations: [LocationViewModel] } struct LocationViewModel { let locationId: String let name: String let detail: String } protocol WeatherListPresenter { func loadContent() func presentWeatherDetail(_ location: String) func presentAddWeatherLocation() } class WeatherListDefaultPresenter: WeatherListPresenter { fileprivate let interactor: WeatherListInteractor fileprivate let router: WeatherListRouter fileprivate weak var view: WeatherListView? fileprivate let viewModelBuilder = LocationListViewModelBuilder() required init(interactor: WeatherListInteractor, router: WeatherListRouter, view: WeatherListView) { self.interactor = interactor self.router = router self.view = view } // MARK: <WeatherListPresenter> func loadContent() { let locations = self.interactor.locations() self.view?.displayLocationList(self.viewModelBuilder.buildViewModel(locations)) } func presentWeatherDetail(_ locationId: String) { let index = self.interactor.locations().index(where: {$0.locationId == locationId}) if let index = index { self.router.navigateToWeatherDetail(withLocation: self.interactor.locations()[index]) } } func presentAddWeatherLocation() { self.router.navigateToAddWeatherLocation() } } //TODO: can this be a struct class LocationListViewModelBuilder { func buildViewModel(_ locations: [Location]) -> LocationListViewModel { let locationViewModels = locations.map { (location) -> LocationViewModel in return LocationViewModel(locationId: location.locationId, name: location.name, detail: self.detailTextFromLocationData(location)) } return LocationListViewModel(locations: locationViewModels) } fileprivate func detailTextFromLocationData(_ location: Location) -> String { if location.region.isEmpty { return location.country } return "\(location.region), \(location.country)" } }
mit
efded96f3cedd6082fdc4c46ecf164f1
28.90411
104
0.684837
5.160757
false
false
false
false
niceandcoolusername/cosmos
code/data_structures/trie/trie.swift
5
4455
// Part of Cosmos by OpenGenus Foundation import Foundation class TrieNode<T: Hashable> { var value: T? weak var parentNode: TrieNode? var children: [T: TrieNode] = [:] var isTerminating = false var isLeaf: Bool { return children.count == 0 } init(value: T? = nil, parentNode: TrieNode? = nil) { self.value = value self.parentNode = parentNode } func add(value: T) { guard children[value] == nil else { return } children[value] = TrieNode(value: value, parentNode: self) } } class Trie: NSObject, NSCoding { typealias Node = TrieNode<Character> public var count: Int { return wordCount } public var isEmpty: Bool { return wordCount == 0 } public var words: [String] { return wordsInSubtrie(rootNode: root, partialWord: "") } fileprivate let root: Node fileprivate var wordCount: Int override init() { root = Node() wordCount = 0 super.init() } required convenience init?(coder decoder: NSCoder) { self.init() let words = decoder.decodeObject(forKey: "words") as? [String] for word in words! { self.insert(word: word) } } func encode(with coder: NSCoder) { coder.encode(self.words, forKey: "words") } } extension Trie { func insert(word: String) { guard !word.isEmpty else { return } var currentNode = root for character in word.lowercased().characters { if let childNode = currentNode.children[character] { currentNode = childNode } else { currentNode.add(value: character) currentNode = currentNode.children[character]! } } guard !currentNode.isTerminating else { return } wordCount += 1 currentNode.isTerminating = true } func contains(word: String) -> Bool { guard !word.isEmpty else { return false } var currentNode = root for character in word.lowercased().characters { guard let childNode = currentNode.children[character] else { return false } currentNode = childNode } return currentNode.isTerminating } private func findLastNodeOf(word: String) -> Node? { var currentNode = root for character in word.lowercased().characters { guard let childNode = currentNode.children[character] else { return nil } currentNode = childNode } return currentNode } private func findTerminalNodeOf(word: String) -> Node? { if let lastNode = findLastNodeOf(word: word) { return lastNode.isTerminating ? lastNode : nil } return nil } private func deleteNodesForWordEndingWith(terminalNode: Node) { var lastNode = terminalNode var character = lastNode.value while lastNode.isLeaf, let parentNode = lastNode.parentNode { lastNode = parentNode lastNode.children[character!] = nil character = lastNode.value if lastNode.isTerminating { break } } } func remove(word: String) { guard !word.isEmpty else { return } guard let terminalNode = findTerminalNodeOf(word: word) else { return } if terminalNode.isLeaf { deleteNodesForWordEndingWith(terminalNode: terminalNode) } else { terminalNode.isTerminating = false } wordCount -= 1 } fileprivate func wordsInSubtrie(rootNode: Node, partialWord: String) -> [String] { var subtrieWords = [String]() var previousLetters = partialWord if let value = rootNode.value { previousLetters.append(value) } if rootNode.isTerminating { subtrieWords.append(previousLetters) } for childNode in rootNode.children.values { let childWords = wordsInSubtrie(rootNode: childNode, partialWord: previousLetters) subtrieWords += childWords } return subtrieWords } func findWordsWithPrefix(prefix: String) -> [String] { var words = [String]() let prefixLowerCased = prefix.lowercased() if let lastNode = findLastNodeOf(word: prefixLowerCased) { if lastNode.isTerminating { words.append(prefixLowerCased) } for childNode in lastNode.children.values { let childWords = wordsInSubtrie(rootNode: childNode, partialWord: prefixLowerCased) words += childWords } } return words } }
gpl-3.0
a780186dc16636049d2678f3f3aace25
24.901163
97
0.631425
4.380531
false
false
false
false
EurekaCommunity/GooglePlacesRow
Sources/GooglePlacesCell.swift
1
2891
// // GooglePlacesCell.swift // GooglePlacesRow // // Created by Mathias Claassen on 4/13/16. // // import Foundation import UIKit import Eureka import GooglePlaces /// This is the general cell for the GooglePlacesCell. Create a subclass or use GooglePlacesCollectionCell or GooglePlacesTableCell instead. open class GooglePlacesCell: _FieldCell<GooglePlace>, CellType { /// Defines if the cell should wait for a moment before requesting places from google when the user edits the textField open var useTimer = true /// The interval to wait before requesting places from Google if useTimer = true open var timerInterval = 0.3 //MARK: Private / internal let cellReuseIdentifier = "Eureka.GooglePlaceCellIdentifier" var predictions: [GMSAutocompletePrediction]? fileprivate var autocompleteTimer: Timer? //MARK: Methods required public init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) { super.init(style: style, reuseIdentifier: reuseIdentifier) } required public init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } override open func setup() { super.setup() textField.autocorrectionType = .no textField.autocapitalizationType = .words } //MARK: UITextFieldDelegate open override func textFieldDidBeginEditing(_ textField: UITextField) { formViewController()?.beginEditing(of: self) formViewController()?.textInputDidBeginEditing(textField, cell: self) textField.selectAll(nil) } open override func textFieldDidChange(_ textField: UITextField) { super.textFieldDidChange(textField) if useTimer { if let timer = autocompleteTimer { timer.invalidate() autocompleteTimer = nil } autocompleteTimer = Timer.scheduledTimer(timeInterval: timerInterval, target: self, selector: #selector(GooglePlacesCell.timerFired(_:)), userInfo: nil, repeats: false) } else { autocomplete() } } open override func textFieldDidEndEditing(_ textField: UITextField) { formViewController()?.endEditing(of: self) formViewController()?.textInputDidEndEditing(textField, cell: self) textField.text = row.displayValueFor?(row.value) } fileprivate func autocomplete() { if let text = textField.text , !text.isEmpty { (row as? GooglePlacesRowProtocol)?.autoComplete(text) } else { predictions?.removeAll() reload() } } func reload() {} /** Function called when the Google Places autocomplete timer is fired */ @objc func timerFired(_ timer: Timer?) { autocompleteTimer?.invalidate() autocompleteTimer = nil autocomplete() } }
mit
e223484e0820f2443198054e87fe9a49
31.122222
171
0.661017
5.333948
false
false
false
false
Zodiac-Innovations/SlamCocoaTouch
SlamCocoaTouch/SlamSwitch.swift
1
2246
// // SlamSwitch.swift // SlamCocoaTouch // Closure based Switch view // // Created by Steve Sheets on 10/13/17. // Copyright © 2017 Zodiac Innovations. All rights reserved. // import UIKit /// Closure based Switch view public class SlamSwitch: UISwitch, SlamViewProtocol { /// Optional action closure invoked when view is pressed public var actionClosure: SlamActionFlagClosure? /// Optional closure invoked by UI to set view on/off public var onClosure: SlamFlagClosure? /// Optional closure invoked by UI to display/hide view public var visibleClosure: SlamFlagClosure? /// Optional closure invoked by UI to enable/disable view public var activeClosure: SlamFlagClosure? public override init(frame: CGRect) { super.init(frame: frame) self.addTarget(self, action: #selector(press(sender:)), for: .touchUpInside) } public required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) self.addTarget(self, action: #selector(press(sender:)), for: .touchUpInside) } /// Action method invoked when view is pressed. It invokes the closure. @objc func press(sender: UIView) { if let actionClosure = actionClosure { actionClosure(self.isOn) } } public func slamUI() { // Hide the view if needed, set on/off if neeed, enable/disable if needed, then show if needed. let currentlyVisible = !self.isHidden var wantVisible = currentlyVisible if let visibleClosure = visibleClosure { wantVisible = visibleClosure() } if !wantVisible, currentlyVisible { self.isHidden = true } if let onClosure = onClosure { let on = onClosure() if self.isOn != on { self.isOn = on } } if let activeClosure = activeClosure { let isActive = activeClosure() if self.isEnabled != isActive { self.isEnabled = isActive } } if wantVisible, !currentlyVisible { self.isHidden = false } } }
mit
4a1b78f6bbd6af0ea1dc9c6eb7040d2a
27.0625
103
0.596437
4.686848
false
false
false
false
MadArkitekt/Swift_Tutorials_And_Demos
SwiftSideMenuDemo/SwiftSideMenuDemo/ViewController.swift
1
2037
// // ViewController.swift // SwiftSideMenuDemo // // Created by Edward Salter on 9/5/14. // Copyright (c) 2014 Edward Salter. All rights reserved. // import Foundation import UIKit class ViewController: UIViewController, SideMenuDelegate, UIGestureRecognizerDelegate { var sideMenu : SideMenu? let imageView = UIImageView(image: UIImage(named: "background")) override func viewDidLoad() { super.viewDidLoad() self.view.addSubview(imageView) sideMenu = SideMenu(sourceView: self.view, menuData: ["Always", "Endeavor", "to be", "EPIC!!!"]) sideMenu!.delegate = self self.navigationController?.navigationBarHidden = true self.navigationController?.navigationBar.backgroundColor = UIColor.clearColor() self.prefersStatusBarHidden() self.setupNavBar() } func setupNavBar() { let visualEffectView = UIVisualEffectView(effect: UIBlurEffect(style: .Light)) as UIVisualEffectView visualEffectView.frame = CGRectMake(0, 0, self.view.frame.size.width, 44) visualEffectView.setNeedsUpdateConstraints() self.view.addSubview(visualEffectView) let button = self.buildButton() self.view.addSubview(button) } func buildButton() -> UIButton { let menuButton = UIButton(frame: CGRectMake(10, 2, 40, 40)) let image = UIImage(named: "lines") menuButton.setImage(image, forState: UIControlState.Normal) menuButton.setImage(image, forState: UIControlState.Highlighted) menuButton.addTarget(self, action: "toggleSideMenu:", forControlEvents: .TouchUpInside) return menuButton } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } func sideMenuDidSelectItemAtIndex(index: Int) { sideMenu?.toggleMenu() } override func prefersStatusBarHidden() -> Bool { return true } func toggleSideMenu(sender: AnyObject) { sideMenu?.toggleMenu() } }
gpl-2.0
bc323b78a2d691761ef86afbcc7808fd
32.393443
108
0.67403
5.017241
false
false
false
false
Antondomashnev/Sourcery
SourceryTests/Parsing/FileParser + VariableSpec.swift
1
13119
import Quick import Nimble import PathKit import SourceKittenFramework @testable import Sourcery @testable import SourceryRuntime private func build(_ source: String) -> [String: SourceKitRepresentable]? { return Structure(file: File(contents: source)).dictionary } class FileParserVariableSpec: QuickSpec { override func spec() { describe("Parser") { describe("parseVariable") { func parse(_ code: String) -> Variable? { guard let parser = try? FileParser(contents: code) else { fail(); return nil } let code = build(code) guard let substructures = code?[SwiftDocKey.substructure.rawValue] as? [SourceKitRepresentable], let src = substructures.first as? [String: SourceKitRepresentable] else { fail() return nil } _ = parser.parse() return parser.parseVariable(src, definedIn: nil) } it("reports variable mutability") { expect(parse("var name: String")?.isMutable).to(beTrue()) expect(parse("let name: String")?.isMutable).to(beFalse()) expect(parse("private(set) var name: String")?.isMutable).to(beTrue()) expect(parse("var name: String { return \"\" }")?.isMutable).to(beFalse()) } it("extracts standard property correctly") { expect(parse("var name: String")).to(equal(Variable(name: "name", typeName: TypeName("String"), accessLevel: (read: .internal, write: .internal), isComputed: false))) } context("given variable with initial value") { it("extracts default value") { expect(parse("var name: String = String()")?.defaultValue).to(equal("String()")) expect(parse("var name = Parent.Children.init()")?.defaultValue).to(equal("Parent.Children.init()")) expect(parse("var name = [[1, 2], [1, 2]]")?.defaultValue).to(equal("[[1, 2], [1, 2]]")) expect(parse("var name = { return 0 }()")?.defaultValue).to(equal("{ return 0 }()")) expect(parse("var name = \t\n { return 0 }() \t\n")?.defaultValue).to(equal("{ return 0 }()")) expect(parse("var name: Int = \t\n { return 0 }() \t\n")?.defaultValue).to(equal("{ return 0 }()")) expect(parse("var name: String = String() { didSet { print(0) } }")?.defaultValue).to(equal("String()")) expect(parse("var name: String = String() {\n\tdidSet { print(0) }\n}")?.defaultValue).to(equal("String()")) expect(parse("var name: String = String()\n{\n\twillSet { print(0) }\n}")?.defaultValue).to(equal("String()")) } it("extracts property with default initializer correctly") { expect(parse("var name = String()")?.typeName).to(equal(TypeName("String"))) expect(parse("var name = Parent.Children.init()")?.typeName).to(equal(TypeName("Parent.Children"))) expect(parse("var name: String? = String()")?.typeName).to(equal(TypeName("String?"))) expect(parse("var name = { return 0 }() ")?.typeName).toNot(equal(TypeName("{ return 0 }"))) } it("extracts property with literal value correctrly") { expect(parse("var name = 1")?.typeName).to(equal(TypeName("Int"))) expect(parse("var name = 1.0")?.typeName).to(equal(TypeName("Double"))) expect(parse("var name = \"1\"")?.typeName).to(equal(TypeName("String"))) expect(parse("var name = true")?.typeName).to(equal(TypeName("Bool"))) expect(parse("var name = false")?.typeName).to(equal(TypeName("Bool"))) expect(parse("var name = nil")?.typeName).to(equal(TypeName("Optional"))) expect(parse("var name = Optional.none")?.typeName).to(equal(TypeName("<<unknown type, please add type attribution to variable 'var name = Optional.none'>>"))) expect(parse("var name = Optional.some(1)")?.typeName).to(equal(TypeName("<<unknown type, please add type attribution to variable 'var name = Optional.some(1)'>>"))) } it("extracts property with array literal value correctly") { expect(parse("var name = [Int]()")?.typeName).to(equal(TypeName("[Int]"))) expect(parse("var name = [1]")?.typeName).to(equal(TypeName("[Int]"))) expect(parse("var name = [1, 2]")?.typeName).to(equal(TypeName("[Int]"))) expect(parse("var name = [1, \"a\"]")?.typeName).to(equal(TypeName("[Any]"))) expect(parse("var name = [1, nil]")?.typeName).to(equal(TypeName("[Int?]"))) expect(parse("var name = [1, [1, 2]]")?.typeName).to(equal(TypeName("[Any]"))) expect(parse("var name = [[1, 2], [1, 2]]")?.typeName).to(equal(TypeName("[[Int]]"))) expect(parse("var name = [Int()]")?.typeName).to(equal(TypeName("[Int]"))) } it("extracts property with dictionary literal value correctly") { expect(parse("var name = [Int: Int]()")?.typeName).to(equal(TypeName("[Int: Int]"))) expect(parse("var name = [1: 2]")?.typeName).to(equal(TypeName("[Int: Int]"))) expect(parse("var name = [1: 2, 2: 3]")?.typeName).to(equal(TypeName("[Int: Int]"))) expect(parse("var name = [1: 1, 2: \"a\"]")?.typeName).to(equal(TypeName("[Int: Any]"))) expect(parse("var name = [1: 1, 2: nil]")?.typeName).to(equal(TypeName("[Int: Int?]"))) expect(parse("var name = [1: 1, 2: [1, 2]]")?.typeName).to(equal(TypeName("[Int: Any]"))) expect(parse("var name = [[1: 1, 2: 2], [1: 1, 2: 2]]")?.typeName).to(equal(TypeName("[[Int: Int]]"))) expect(parse("var name = [1: [1: 1, 2: 2], 2: [1: 1, 2: 2]]")?.typeName).to(equal(TypeName("[Int: [Int: Int]]"))) expect(parse("var name = [Int(): String()]")?.typeName).to(equal(TypeName("[Int: String]"))) } it("extracts property with tuple literal value correctly") { expect(parse("var name = (1, 2)")?.typeName).to(equal(TypeName("(Int, Int)"))) expect(parse("var name = (1, b: \"[2,3]\", c: 1)")?.typeName).to(equal(TypeName("(Int, b: String, c: Int)"))) expect(parse("var name = (_: 1, b: 2)")?.typeName).to(equal(TypeName("(Int, b: Int)"))) expect(parse("var name = ((1, 2), [\"a\": \"b\"])")?.typeName).to(equal(TypeName("((Int, Int), [String: String])"))) expect(parse("var name = ((1, 2), [1, 2])")?.typeName).to(equal(TypeName("((Int, Int), [Int])"))) expect(parse("var name = ((1, 2), [\"a,b\": \"b\"])")?.typeName).to(equal(TypeName("((Int, Int), [String: String])"))) } } it("extracts standard let property correctly") { let r = parse("let name: String") expect(r).to(equal(Variable(name: "name", typeName: TypeName("String"), accessLevel: (read: .internal, write: .none), isComputed: false))) } it("extracts computed property correctly") { expect(parse("var name: Int { return 2 }")).to(equal(Variable(name: "name", typeName: TypeName("Int"), accessLevel: (read: .internal, write: .none), isComputed: true))) expect(parse("let name: Int")).to(equal(Variable(name: "name", typeName: TypeName("Int"), accessLevel: (read: .internal, write: .none), isComputed: false))) expect(parse("var name: Int")).to(equal(Variable(name: "name", typeName: TypeName("Int"), accessLevel: (read: .internal, write: .internal), isComputed: false))) expect(parse("var name: Int { get { return 0 } set {} }")).to(equal(Variable(name: "name", typeName: TypeName("Int"), accessLevel: (read: .internal, write: .internal), isComputed: true))) expect(parse("var name: Int { willSet { } }")).to(equal(Variable(name: "name", typeName: TypeName("Int"), accessLevel: (read: .internal, write: .internal), isComputed: false))) expect(parse("var name: Int { didSet {} }")).to(equal(Variable(name: "name", typeName: TypeName("Int"), accessLevel: (read: .internal, write: .internal), isComputed: false))) } it("extracts generic property correctly") { expect(parse("let name: Observable<Int>")).to(equal(Variable(name: "name", typeName: TypeName("Observable<Int>"), accessLevel: (read: .internal, write: .none), isComputed: false))) } context("given it has sourcery annotations") { it("extracts single annotation") { let expectedVariable = Variable(name: "name", typeName: TypeName("Int"), accessLevel: (read: .internal, write: .none), isComputed: true) expectedVariable.annotations["skipEquability"] = NSNumber(value: true) expect(parse("// sourcery: skipEquability\n" + "var name: Int { return 2 }")).to(equal(expectedVariable)) } it("extracts multiple annotations on the same line") { let expectedVariable = Variable(name: "name", typeName: TypeName("Int"), accessLevel: (read: .internal, write: .none), isComputed: true) expectedVariable.annotations["skipEquability"] = NSNumber(value: true) expectedVariable.annotations["jsonKey"] = "json_key" as NSString expect(parse("// sourcery: skipEquability, jsonKey = \"json_key\"\n" + "var name: Int { return 2 }")).to(equal(expectedVariable)) } it("extracts multi-line annotations, including numbers") { let expectedVariable = Variable(name: "name", typeName: TypeName("Int"), accessLevel: (read: .internal, write: .none), isComputed: true) expectedVariable.annotations["skipEquability"] = NSNumber(value: true) expectedVariable.annotations["jsonKey"] = "json_key" as NSString expectedVariable.annotations["thirdProperty"] = NSNumber(value: -3) let result = parse( "// sourcery: skipEquability, jsonKey = \"json_key\"\n" + "// sourcery: thirdProperty = -3\n" + "var name: Int { return 2 }") expect(result).to(equal(expectedVariable)) } it("extracts annotations interleaved with comments") { let expectedVariable = Variable(name: "name", typeName: TypeName("Int"), accessLevel: (read: .internal, write: .none), isComputed: true) expectedVariable.annotations["isSet"] = NSNumber(value: true) expectedVariable.annotations["numberOfIterations"] = NSNumber(value: 2) let result = parse( "// sourcery: isSet\n" + "/// isSet is used for something useful\n" + "// sourcery: numberOfIterations = 2\n" + "var name: Int { return 2 }") expect(result).to(equal(expectedVariable)) } it("stops extracting annotations if it encounters a non-comment line") { let expectedVariable = Variable(name: "name", typeName: TypeName("Int"), accessLevel: (read: .internal, write: .none), isComputed: true) expectedVariable.annotations["numberOfIterations"] = NSNumber(value: 2) let result = parse( "// sourcery: isSet\n" + "\n" + "// sourcery: numberOfIterations = 2\n" + "var name: Int { return 2 }") expect(result).to(equal(expectedVariable)) } } } } } }
mit
dfacbc175adcfbad85f6f9a2d98c6038
72.702247
207
0.505679
4.643894
false
false
false
false
teaxus/TSAppEninge
Source/Basic/Model/TSBasicObject.swift
1
1490
// // TSBasic.swift // TSAppEngine // // Created by teaxus on 15/12/5. // Copyright © 2015年 teaxus. All rights reserved. // import UIKit import ObjectiveC.runtime @objc public class TSBasicObject: NSObject { public class var nameOfClass: String{ return (NSStringFromClass(self) as NSString).components(separatedBy: ".").last! } public var nameOfClass: String{ return (NSStringFromClass(type(of: self)) as NSString).components(separatedBy: ".").last! } //MARK:获取所有属性的名称 public func getAllPropertyName()->Array<String>{ var arr_return = Array<String>() var propertyCount : UInt32 = 0 let arr_properties = class_copyPropertyList(type(of: self), &propertyCount) for i in 0..<propertyCount { let propertie = arr_properties?[Int(i)] let string_property_name = String(cString: property_getName(propertie)) arr_return.append(string_property_name) } return arr_return } public func printAllPropertyAndValue(){ let arr_perpoty = self.getAllPropertyName() for key in arr_perpoty{ guard let value = self.value(forKey: key) else{ continue } LogVerbose("property:\(key) value:\(value)") } } } public func ClassFromName(class_name:String)->AnyObject?{ return NSClassFromString(class_name); }
mit
f8db1aff84879384b92627fbfc010943
25.709091
97
0.607216
4.320588
false
false
false
false
quire-io/SwiftyChrono
Sources/Parsers/ZH/ZHDateParser.swift
1
2494
// // ZHHantDateParser.swift // SwiftyChrono // // Created by Jerry Chen on 2/18/17. // Copyright © 2017 Potix. All rights reserved. // import Foundation private let PATTERN = "(\\d{2,4}|\(ZH_NUMBER_PATTERN){2,4})?" + "(?:\\s*)" + "(?:年)?" + "(?:[\\s|,|,]*)" + "(\\d{1,2}|\(ZH_NUMBER_PATTERN){1,2})" + "(?:\\s*)" + "(?:月)" + "(?:\\s*)" + "(\\d{1,2}|\(ZH_NUMBER_PATTERN){1,2})?" + "(?:\\s*)" + "(?:日|號|号)?" private let yearGroup = 1 private let monthGroup = 2 private let dayGroup = 3 public class ZHDateParser: Parser { override var pattern: String { return PATTERN } override var language: Language { return .chinese } override public func extract(text: String, ref: Date, match: NSTextCheckingResult, opt: [OptionType: Int]) -> ParsedResult? { let (matchText, index) = matchTextAndIndexForCHHant(from: text, andMatchResult: match) var result = ParsedResult(ref: ref, index: index, text: matchText) let refMoment = ref let startMoment = refMoment //Month let monthString = match.string(from: text, atRangeIndex: monthGroup) guard let month = NSRegularExpression.isMatch(forPattern: "\\d+", in: monthString) ? Int(monthString) : ZHStringToNumber(text: monthString) else { return nil } result.start.assign(.month, value: month) //Day if match.isNotEmpty(atRangeIndex: dayGroup) { let dayString = match.string(from: text, atRangeIndex: dayGroup) guard let day = NSRegularExpression.isMatch(forPattern: "\\d+", in: dayString) ? Int(dayString) : ZHStringToNumber(text: dayString) else { return nil } result.start.assign(.day, value: day) } else { result.start.imply(.day, to: startMoment.day) } //Year if match.isNotEmpty(atRangeIndex: yearGroup) { let yearString = match.string(from: text, atRangeIndex: yearGroup) guard let year = NSRegularExpression.isMatch(forPattern: "\\d+", in: yearString) ? Int(yearString) : ZHStringToYear(text: yearString) else { return nil } result.start.assign(.year, value: year) } else { result.start.imply(.year, to: startMoment.year) } result.tags[.zhHantDateParser] = true return result } }
mit
2e8bc88eda51dd0ea1573f770638e8b7
32.986301
154
0.573156
4.008078
false
false
false
false
lojals/curiosity_reader
curiosity_reader/curiosity_reader/src/components/LeftMenu.swift
1
4631
// // LeftMenu.swift // Yo Intervengo // // Created by Jorge Raul Ovalle Zuleta on 1/14/15. // Copyright (c) 2015 Olinguito. All rights reserved. // import Foundation import UIKit @objc protocol LeftMenuDelegate{ optional func goTo(index:Int) } class LeftMenu: UIView{ var opened = false var btnRep:UIButton! var btnWiki:UIButton! var btnStat:UIButton! var btnProf:UIButton! var btnSett:UIButton! var delegate:LeftMenuDelegate? var btnBack:UIButton! required init(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } override init(frame: CGRect) { super.init(frame: frame) self.backgroundColor = UIColor.themeMain().colorWithAlphaComponent(0.98) let spacer = 10 let size:CGFloat = frame.width - 40 btnRep = UIButton(frame: CGRect(x: 20, y: 76, width: size, height: 26)) btnWiki = UIButton(frame: CGRect(x: 20, y: btnRep.frame.maxY+10, width: size, height: 26)) btnStat = UIButton(frame: CGRect(x: 20, y: btnWiki.frame.maxY+10, width: size, height: 26)) btnProf = UIButton(frame: CGRect(x: 20, y: btnStat.frame.maxY+10, width: size, height: 26)) btnRep.setTitle("Inicio", forState: UIControlState.Normal) btnWiki.setTitle("Perfil", forState: UIControlState.Normal) btnStat.setTitle("Categorías", forState: UIControlState.Normal) btnProf.setTitle("Acerca de", forState: UIControlState.Normal) btnRep.setTitleColor(UIColor.whiteColor(), forState: UIControlState.Normal) btnWiki.setTitleColor(UIColor.whiteColor(), forState: UIControlState.Normal) btnStat.setTitleColor(UIColor.whiteColor(), forState: UIControlState.Normal) btnProf.setTitleColor(UIColor.whiteColor(), forState: UIControlState.Normal) btnRep.titleLabel?.font = UIFont.fontRegular(20) btnWiki.titleLabel?.font = UIFont.fontRegular(20) btnStat.titleLabel?.font = UIFont.fontRegular(20) btnProf.titleLabel?.font = UIFont.fontRegular(20) btnRep.contentHorizontalAlignment = UIControlContentHorizontalAlignment.Right btnWiki.contentHorizontalAlignment = UIControlContentHorizontalAlignment.Right btnStat.contentHorizontalAlignment = UIControlContentHorizontalAlignment.Right btnProf.contentHorizontalAlignment = UIControlContentHorizontalAlignment.Right btnRep.tag = 3330; btnWiki.tag = 3331; btnStat.tag = 3332; btnProf.tag = 3333; btnRep.addTarget(self, action: "goBtn:", forControlEvents: UIControlEvents.TouchUpInside) btnWiki.addTarget(self, action: "goBtn:", forControlEvents: UIControlEvents.TouchUpInside) btnStat.addTarget(self, action: "goBtn:", forControlEvents: UIControlEvents.TouchUpInside) btnProf.addTarget(self, action: "goBtn:", forControlEvents: UIControlEvents.TouchUpInside) btnBack = UIButton.buttonWithType(UIButtonType.System) as! UIButton btnBack.frame = CGRectMake(0, 0, 50, 50) btnBack.tintColor = UIColor.whiteColor() btnBack.setImage(UIImage(named: "btnMenu"), forState: UIControlState.Normal) btnBack.addTarget(self, action: "interact", forControlEvents: UIControlEvents.TouchUpInside) self.addSubview(btnBack) self.addSubview(btnRep) self.addSubview(btnWiki) self.addSubview(btnStat) self.addSubview(btnProf) opened = false } func interact(){ var spAn = POPBasicAnimation(propertyNamed:kPOPViewCenter) spAn.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseInEaseOut) if opened{ spAn.toValue = NSValue(CGPoint: CGPointMake(-100, self.center.y)) } else{ spAn.toValue = NSValue(CGPoint: CGPointMake(100, self.center.y)) } opened = !opened self.pop_addAnimation(spAn, forKey: "center") } func setColor(idBtn:Int){ btnRep.titleLabel?.font = UIFont.fontRegular(20) btnWiki.titleLabel?.font = UIFont.fontRegular(20) btnStat.titleLabel?.font = UIFont.fontRegular(20) btnProf.titleLabel?.font = UIFont.fontRegular(20) //sender.setTitleColor( UIColor.orangeYI() , forState: UIControlState.Normal) (self.viewWithTag(idBtn) as! UIButton).titleLabel?.font = UIFont.fontBold(21) } func goBtn(sender:UIButton){ setColor(sender.tag) self.delegate!.goTo!(sender.tag - 3330) } }
gpl-2.0
982e3c70cbc5a95e8e29bed752f887f0
38.57265
100
0.667603
4.380322
false
false
false
false
uber/RIBs
ios/tutorials/tutorial4/TicTacToe/LoggedIn/LoggedInBuilder.swift
1
2604
// // Copyright (c) 2017. Uber Technologies // // 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 RIBs protocol LoggedInDependency: Dependency { var loggedInViewController: LoggedInViewControllable { get } } final class LoggedInComponent: Component<LoggedInDependency> { fileprivate var loggedInViewController: LoggedInViewControllable { return dependency.loggedInViewController } fileprivate var games: [Game] { return shared { return [RandomWinAdapter(dependency: self), TicTacToeAdapter(dependency: self)] } } var mutableScoreStream: MutableScoreStream { return shared { ScoreStreamImpl() } } var scoreStream: ScoreStream { return mutableScoreStream } let player1Name: String let player2Name: String init(dependency: LoggedInDependency, player1Name: String, player2Name: String) { self.player1Name = player1Name self.player2Name = player2Name super.init(dependency: dependency) } } // MARK: - Builder protocol LoggedInBuildable: Buildable { func build(withListener listener: LoggedInListener, player1Name: String, player2Name: String) -> LoggedInRouting } final class LoggedInBuilder: Builder<LoggedInDependency>, LoggedInBuildable { override init(dependency: LoggedInDependency) { super.init(dependency: dependency) } func build(withListener listener: LoggedInListener, player1Name: String, player2Name: String) -> LoggedInRouting { let component = LoggedInComponent(dependency: dependency, player1Name: player1Name, player2Name: player2Name) let interactor = LoggedInInteractor(games: component.games) interactor.listener = listener let offGameBuilder = OffGameBuilder(dependency: component) return LoggedInRouter(interactor: interactor, viewController: component.loggedInViewController, offGameBuilder: offGameBuilder) } }
apache-2.0
bc89bffc09360c93514530fb0d861e95
32.818182
118
0.691244
4.777982
false
false
false
false
mahjouri/pokedex
pokedex-by-saamahn/PokemonDetailVC.swift
1
2287
// // PokemonDetailVC.swift // pokedex-by-saamahn // // Created by Saamahn Mahjouri on 3/8/16. // Copyright © 2016 Saamahn Mahjouri. All rights reserved. // import UIKit class PokemonDetailVC: UIViewController { @IBOutlet weak var nameLbl: UILabel! @IBOutlet weak var mainImg: UIImageView! @IBOutlet weak var descriptionLbl: UILabel! @IBOutlet weak var typeLbl: UILabel! @IBOutlet weak var defenseLbl: UILabel! @IBOutlet weak var heightLbl: UILabel! @IBOutlet weak var pokedexLbl: UILabel! @IBOutlet weak var weightLbl: UILabel! @IBOutlet weak var baseAttackLbl: UILabel! @IBOutlet weak var currentEvoImg: UIImageView! @IBOutlet weak var nextEvoImg: UIImageView! @IBOutlet weak var evoLbl: UILabel! var pokemon: Pokemon! override func viewDidLoad() { super.viewDidLoad() nameLbl.text = pokemon.name let img = UIImage(named: "\(pokemon.pokedexId)") mainImg.image = img currentEvoImg.image = img pokemon.downloadPokemonDetails { () -> () in //this will be called after downlaod is done self.updateUI() } } func updateUI() { descriptionLbl.text = pokemon.description typeLbl.text = pokemon.type defenseLbl.text = pokemon.defense heightLbl.text = pokemon.height pokedexLbl.text = "\(pokemon.pokedexId)" weightLbl.text = pokemon.weight baseAttackLbl.text = pokemon.attack if pokemon.nextEvolutionId == "" { evoLbl.text = "No Evolutions" nextEvoImg.hidden = true } else { nextEvoImg.hidden = false nextEvoImg.image = UIImage(named: pokemon.nextEvolutionId) evoLbl.text = "Next Evolution: \(pokemon.nextEvolutionTxt)" // if pokemon.nextEvolutionLvl != "" { // str += " -LVL \(pokemon.nextEvolutionLvl)" // } } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } @IBAction func backBtnPressed(sender: AnyObject) { dismissViewControllerAnimated(true, completion: nil) } }
bsd-3-clause
a2833ddd9796c7857f05b1ab409a8663
29.891892
114
0.618548
4.370937
false
false
false
false
Arthurli/SwiftRouter
Example/SwiftRouter/ViewController.swift
1
4575
// // ViewController.swift // SwiftRouter // // Created by lichen on 06/06/2017. // Copyright (c) 2017 lichen. All rights reserved. // import UIKit import SwiftRouter enum PageType { case first(key: String) case second func inditify() -> String { switch self { case .first(key: _): return "first" case .second: return "second" } } func build(type: RouterPageRequest.ActionType = .push(animation: true)) -> RouterPageRequest { var params: [String: Any] = [:] switch self { case let .first(key: key): params["key"] = key case .second: break } let requst = RouterPageRequest(key: self.inditify(), params: params, type: type) return requst } } class ViewController: UIViewController, UIViewControllerPreviewingDelegate { var handler: RouterPageHandler = { var handle: RouterPageHandler = RouterPageHandler() return handle }() var router: Router = Router() var btn: UIButton? override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. // 注册 router 的 handler router.register(request: RouterPageRequest.self, handler: handler) // 注册 页面跳转 handler.register(key: PageType.second.inditify(), page: SecondViewController.self) handler.register(key: PageType.second.inditify()) { (vc, req, callback) in let second = SecondViewController() vc.navigationController?.pushViewController(second, animated: true) callback(nil) } // 注册中间件 let m1: Middleware = (handleBefore: { (req: RouterRequest, error: Error?, callback: (RouterRequest, Error?) -> Void) -> Void in print("before 1") callback(req, nil) }, handleAfter: { (req: RouterRequest, error: Error?, callback: (RouterRequest, Error?) -> Void) -> Void in print("after 1") callback(req, nil) }) let m11: Middleware = (handleBefore: { (req: RouterRequest, error: Error?, callback: (RouterRequest, Error?) -> Void) -> Void in print("before 11") callback(req, nil) }, handleAfter: nil) let m2: Middleware = (handleBefore: { (req: RouterRequest, error: Error?, callback: (RouterRequest, Error?) -> Void) -> Void in print("before 2") callback(req, nil) }, handleAfter: { (req: RouterRequest, error: Error?, callback: (RouterRequest, Error?) -> Void) -> Void in print("after 2") callback(req, nil) }) let m22: Middleware = (handleBefore: nil, handleAfter: { (req: RouterRequest, error: Error?, callback: (RouterRequest, Error?) -> Void) -> Void in print("after 22") callback(req, nil) }) router.use(middleware: m1) router.use(middleware: m11) router.use(middleware: m2) router.use(middleware: m22) let btn = UIButton(type: .custom) btn.backgroundColor = UIColor.red btn.frame = CGRect(x: 100, y: 100, width: 100, height: 100) btn.addTarget(self, action: #selector(go), for: .touchUpInside) self.view.addSubview(btn) self.btn = btn if #available(iOS 9.0, *) { self.registerForPreviewing(with: self, sourceView: btn) } } @objc func go() { self.router.send(req: PageType.second.build()) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } func previewingContext(_ previewingContext: UIViewControllerPreviewing, viewControllerForLocation location: CGPoint) -> UIViewController? { if #available(iOS 9.0, *) { if previewingContext.sourceView == self.btn { var viewController: UIViewController? = nil let r = PageType.second.build(type: .touch(callback: { (vc) in viewController = vc })) self.router.send(req: r) return viewController } } return nil } func previewingContext(_ previewingContext: UIViewControllerPreviewing, commit viewControllerToCommit: UIViewController) { self.navigationController?.pushViewController(viewControllerToCommit, animated: true) } }
mit
f5e151ee0659b195f2c29b62aad57763
31.021127
143
0.591599
4.484221
false
false
false
false
mathcamp/swiftz
swiftz/MVar.swift
2
2181
// // MVar.swift // swiftz // // Created by Maxwell Swadling on 7/06/2014. // Copyright (c) 2014 Maxwell Swadling. All rights reserved. // import Foundation // Reading an MVar that is empty will block until it has something in it. // Putting into an MVar will block if it has something in it, until someone reads from it. // http://www.haskell.org/ghc/docs/latest/html/libraries/base/Control-Concurrent-MVar.html public class MVar<A> { var value: Optional<(() -> A)> var mutex: UnsafeMutablePointer<pthread_mutex_t> var condPut: UnsafeMutablePointer<pthread_cond_t> var condRead: UnsafeMutablePointer<pthread_cond_t> let matt: UnsafeMutablePointer<pthread_mutexattr_t> public init() { var mattr:UnsafeMutablePointer<pthread_mutexattr_t> = UnsafeMutablePointer.alloc(sizeof(pthread_mutexattr_t)) mutex = UnsafeMutablePointer.alloc(sizeof(pthread_mutex_t)) condPut = UnsafeMutablePointer.alloc(sizeof(pthread_cond_t)) condRead = UnsafeMutablePointer.alloc(sizeof(pthread_cond_t)) pthread_mutexattr_init(mattr) pthread_mutexattr_settype(mattr, PTHREAD_MUTEX_RECURSIVE) matt = UnsafeMutablePointer(mattr) pthread_mutex_init(mutex, matt) pthread_cond_init(condPut, nil) pthread_cond_init(condRead, nil) } public convenience init(a: @autoclosure () -> A) { self.init() value = a } deinit { mutex.destroy() condPut.destroy() condRead.destroy() matt.destroy() } public func put(x: A) { pthread_mutex_lock(mutex) while (value != nil) { pthread_cond_wait(condRead, mutex) } self.value = { x } pthread_mutex_unlock(mutex) pthread_cond_signal(condPut) } public func take() -> A { pthread_mutex_lock(mutex) while (value) == nil { pthread_cond_wait(condPut, mutex) } let cp = value!() value = .None pthread_mutex_unlock(mutex) pthread_cond_signal(condRead) return cp } // this isn't very useful! it is just a snapshot at this point in time. // you could check it is empty, then put, and it could block. // it is mostly for debugging and testing. public func isEmpty() -> Bool { return (value == nil) } }
bsd-3-clause
2f904313f8b2520cde1a092a0ea8e2cb
27.324675
113
0.685924
3.581281
false
false
false
false
paulz/PerspectiveTransform
Example/PerspectiveTransform/PanViewController.swift
1
1678
// // ViewController.swift // PerspectiveTransform // // Created by Paul Zabelin on 02/18/2016. // Copyright (c) 2016 Paul Zabelin. All rights reserved. // import UIKit import QuartzCore import PerspectiveTransform extension UIPanGestureRecognizer { func panView() { let controlPoint = view! let pan = translation(in: controlPoint.superview) let transform = CGAffineTransform(translationX: pan.x, y: pan.y) controlPoint.center = controlPoint.center.applying(transform) setTranslation(CGPoint.zero, in: controlPoint.superview) } } class PanViewController: UIViewController { // MARK: - Outlets @IBOutlet var cornerViews: [UIView]! @IBOutlet weak var toBeTransformedView: UIView! // MARK: - UIViewController override func viewDidLayoutSubviews() { super.viewDidLayoutSubviews() updatePosition() } // MARK: - Actions @IBAction func didPan(_ recognizer: UIPanGestureRecognizer) { recognizer.panView() updatePosition() } // MARK: - private private func updatePosition() { toBeTransformedView.layer.transform = transformToCorners() } private func transformToCorners() -> CATransform3D { return start.projectiveTransform(destination: destination) } private lazy var start: Perspective = createStartingPerspective() private func createStartingPerspective() -> Perspective { toBeTransformedView.resetAnchorPoint() return Perspective(toBeTransformedView.frame) } private var destination: Perspective { return .init(cornerViews.sorted {$0.tag < $1.tag}.map {$0.center}) } }
mit
13f2c009211291306e7be8ccff80c8ee
25.21875
74
0.687723
4.59726
false
false
false
false
rsyncOSX/RsyncOSX
RsyncOSX/RsyncProcess.swift
1
5155
// // RsyncProcessCmdClosure.swift // RsyncOSX // // Created by Thomas Evensen on 14/09/2020. // Copyright © 2020 Thomas Evensen. All rights reserved. // import Combine import Foundation protocol ErrorOutput: AnyObject { func erroroutput() } protocol DisableEnablePopupSelectProfile: AnyObject { func disableselectpopupprofile() func enableselectpopupprofile() } final class RsyncProcess: Errors { // Combine subscribers var subscriptons = Set<AnyCancellable>() // Process termination and filehandler closures var processtermination: () -> Void var filehandler: () -> Void var monitor: NetworkMonitor? // Arguments to command var arguments: [String]? // Enable and disable select profile weak var profilepopupDelegate: DisableEnablePopupSelectProfile? func executemonitornetworkconnection(config: Configuration?) { guard config?.offsiteServer.isEmpty == false else { return } guard SharedReference.shared.monitornetworkconnection == true else { return } monitor = NetworkMonitor() monitor?.netStatusChangeHandler = { [unowned self] in do { try statusDidChange() } catch let e { let error = e as NSError let outputprocess = OutputfromProcess() outputprocess.addlinefromoutput(str: error.description) _ = Logfile(TrimTwo(outputprocess.getOutput() ?? []).trimmeddata, error: false) } } } // Throws error func statusDidChange() throws { if monitor?.monitor?.currentPath.status != .satisfied { let output = OutputfromProcess() let string = NSLocalizedString("Network connection is dropped", comment: "network") + ":" + Date().long_localized_string_from_date() output.addlinefromoutput(str: string) _ = InterruptProcess() throw Networkerror.networkdropped } } func executeProcess(outputprocess: OutputfromProcess?) { // Must check valid rsync exists guard SharedReference.shared.norsync == false else { return } // Process let task = Process() // Getting version of rsync task.launchPath = Getrsyncpath().rsyncpath task.arguments = arguments // If there are any Environmentvariables like // SSH_AUTH_SOCK": "/Users/user/.gnupg/S.gpg-agent.ssh" if let environment = Environment() { task.environment = environment.environment } // Pipe for reading output from Process let pipe = Pipe() task.standardOutput = pipe task.standardError = pipe let outHandle = pipe.fileHandleForReading outHandle.waitForDataInBackgroundAndNotify() // Combine, subscribe to NSNotification.Name.NSFileHandleDataAvailable NotificationCenter.default.publisher( for: NSNotification.Name.NSFileHandleDataAvailable) .sink { _ in let data = outHandle.availableData if data.count > 0 { if let str = NSString(data: data, encoding: String.Encoding.utf8.rawValue) { outputprocess?.addlinefromoutput(str: str as String) self.filehandler() } outHandle.waitForDataInBackgroundAndNotify() } }.store(in: &subscriptons) // Combine, subscribe to Process.didTerminateNotification NotificationCenter.default.publisher( for: Process.didTerminateNotification) .debounce(for: .milliseconds(500), scheduler: globalMainQueue) .sink { [self] _ in self.processtermination() // Logg to file _ = Logfile(TrimTwo(outputprocess?.getOutput() ?? []).trimmeddata, error: false) // Release Combine subscribers subscriptons.removeAll() }.store(in: &subscriptons) profilepopupDelegate?.disableselectpopupprofile() SharedReference.shared.process = task do { try task.run() } catch let e { let error = e as NSError self.error(errordescription: error.localizedDescription, errortype: .task) } } // Terminate Process, used when user Aborts task. func abortProcess() { _ = InterruptProcess() } init(arguments: [String]?, config: Configuration?, processtermination: @escaping () -> Void, filehandler: @escaping () -> Void) { self.arguments = arguments self.processtermination = processtermination self.filehandler = filehandler executemonitornetworkconnection(config: config) profilepopupDelegate = SharedReference.shared.getvcref(viewcontroller: .vctabmain) as? ViewControllerMain } deinit { self.monitor?.stopMonitoring() self.monitor = nil SharedReference.shared.process = nil // Enable select profile self.profilepopupDelegate?.enableselectpopupprofile() } }
mit
79b6e7b146a15b4cb33c20a9278f0a69
36.347826
113
0.622817
4.89924
false
true
false
false
Esri/arcgis-runtime-samples-ios
arcgis-ios-sdk-samples/Display information/Custom dictionary style/CustomDictionaryStyleViewController.swift
1
4293
// Copyright 2020 Esri // // 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 ArcGIS class CustomDictionaryStyleViewController: UIViewController { // MARK: Storyboard views /// The map view managed by the view controller. @IBOutlet var mapView: AGSMapView! { didSet { mapView.map = AGSMap(basemapStyle: .arcGISTopographic) mapView.setViewpoint( AGSViewpoint( latitude: 34.0543, longitude: -117.1963, scale: 1e4 ) ) } } /// The segmented control to toggle between style file and web style. @IBOutlet var segmentedControl: UISegmentedControl! // MARK: Instance properties /// A feature layer showing a subset of restaurants in Redlands, CA. let featureLayer: AGSFeatureLayer = { // Create restaurants feature table from the feature service URL. let restaurantFeatureTable = AGSServiceFeatureTable( url: URL(string: "https://services2.arcgis.com/ZQgQTuoyBrtmoGdP/arcgis/rest/services/Redlands_Restaurants/FeatureServer/0")! ) // Create the restaurants layer. return AGSFeatureLayer(featureTable: restaurantFeatureTable) }() /// A dictionary renderer created from a custom symbol style dictionary file /// (.stylx) on local disk. let dictionaryRendererFromStyleFile: AGSDictionaryRenderer = { // The URL to the symbol style dictionary from shared resources. let restaurantStyleURL = Bundle.main.url(forResource: "Restaurant", withExtension: "stylx")! // Create the dictionary renderer from the style file. let restaurantStyle = AGSDictionarySymbolStyle(url: restaurantStyleURL) return AGSDictionaryRenderer(dictionarySymbolStyle: restaurantStyle) }() /// A dictionary renderer created from a custom symbol style hosted on /// ArcGIS Online. let dictionaryRendererFromWebStyle: AGSDictionaryRenderer = { // The restaurant web style. let item = AGSPortalItem( portal: .arcGISOnline(withLoginRequired: false), itemID: "adee951477014ec68d7cf0ea0579c800" ) // Create the dictionary renderer from the web style. let restaurantStyle = AGSDictionarySymbolStyle(portalItem: item) // Map the input fields in the feature layer to the // dictionary symbol style's expected fields for symbols. return AGSDictionaryRenderer(dictionarySymbolStyle: restaurantStyle, symbologyFieldOverrides: ["healthgrade": "Inspection"], textFieldOverrides: [:]) }() // MARK: Methods @IBAction func segmentedControlValueChanged(_ sender: UISegmentedControl) { let isStyleFile = sender.selectedSegmentIndex == 0 // Apply the dictionary renderer to the feature layer. featureLayer.renderer = isStyleFile ? dictionaryRendererFromStyleFile : dictionaryRendererFromWebStyle } func setupUI() { mapView.map?.operationalLayers.add(featureLayer) segmentedControl.isEnabled = true segmentedControlValueChanged(segmentedControl) } // MARK: UIViewController override func viewDidLoad() { super.viewDidLoad() // Add the source code button item to the right of navigation bar. (self.navigationItem.rightBarButtonItem as? SourceCodeBarButtonItem)?.filenames = ["CustomDictionaryStyleViewController"] featureLayer.load { [weak self] error in guard let self = self else { return } if let error = error { self.presentAlert(error: error) } else { self.setupUI() } } } }
apache-2.0
ba9d4c8cf9b805d6dfb22ba863cacb0d
40.278846
157
0.67086
4.986063
false
false
false
false
AlphaJian/LarsonApp
LarsonApp/LarsonApp/Class/JobDetail/JobDetailViews/TextTitleView.swift
1
937
// // TextTitleView.swift // LarsonApp // // Created by appledev018 on 11/7/16. // Copyright © 2016 Jian Zhang. All rights reserved. // import Foundation import UIKit class TextTitleView: UIView { func initUI( title: String, text: String) { layoutIfNeeded() let titleLable = UILabel(frame: CGRect(x: 0, y: frame.height/2, width: self.frame.width, height: self.frame.height/2)) titleLable.text = title titleLable.font = UIFont.systemFont(ofSize: 13) titleLable.textColor = UIColor.gray self.addSubview(titleLable) let textLable = UILabel(frame: CGRect(x: 0, y: 0, width: self.frame.width, height: self.frame.height/2)) textLable.text = text textLable.font = UIFont.systemFont(ofSize: 13) self.addSubview(textLable) } }
apache-2.0
e92d997f58919fd9093f7ab5e0c617cd
21.829268
126
0.575855
4.197309
false
false
false
false
QuarkWorks/RealmModelGenerator
RealmModelGenerator/Attribute.swift
1
1964
// // Attribute.swift // RealmModelGenerator // // Created by Brandon Erbschloe on 3/2/16. // Copyright © 2016 QuarkWorks. All rights reserved. // import Foundation class Attribute { static let TAG = NSStringFromClass(Attribute.self) private(set) var name:String internal(set) weak var entity:Entity! var isIgnored = false private(set) var isIndexed = false var isRequired = false var hasDefault = false var defaultValue = "" var type : AttributeType = .Unknown { willSet { if !newValue.canBeIndexed() { isIndexed = false if entity.primaryKey === self { try! entity.setPrimaryKey(primaryKey: nil) } } } didSet { self.observable.notifyObservers() } } let observable:Observable internal init(name:String, entity:Entity) { self.name = name self.entity = entity self.observable = DeferredObservable(observable: entity.observable) } func setName(name:String) throws { if name.isEmpty { throw NSError(domain: Attribute.TAG, code: 0, userInfo: nil) } if self.entity.attributes.filter({$0.name == name && $0 !== self}).count > 0 { throw NSError(domain: Attribute.TAG, code: 0, userInfo: nil) } self.name = name self.observable.notifyObservers() } func setIndexed(isIndexed:Bool) throws { if isIndexed && !type.canBeIndexed() { throw NSError(domain: Attribute.TAG, code: 0, userInfo: nil); } self.isIndexed = isIndexed } func removeIndexed() { try! self.setIndexed(isIndexed: false) } func removeFromEntity() { self.entity.removeAttribute(attribute: self) } func isDeleted() -> Bool { return self.entity == nil } }
mit
1d5990ac68b92c42621008e9a07f8500
25.173333
86
0.570555
4.461364
false
false
false
false
ja-mes/experiments
iOS/RetroCalculator/RetroCalculator/AppDelegate.swift
1
4590
// // AppDelegate.swift // RetroCalculator // // Created by James Brown on 8/13/16. // Copyright © 2016 James Brown. All rights reserved. // import UIKit import CoreData @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool { // Override point for customization after application launch. return true } func applicationWillResignActive(_ application: UIApplication) { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. 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 active state; here you can undo many of the changes made on entering the background. } func applicationDidBecomeActive(_ application: UIApplication) { // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. } func applicationWillTerminate(_ application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. // Saves changes in the application's managed object context before the application terminates. self.saveContext() } // MARK: - Core Data stack lazy var persistentContainer: NSPersistentContainer = { /* The persistent container for the application. This implementation creates and returns a container, having loaded the store for the application to it. This property is optional since there are legitimate error conditions that could cause the creation of the store to fail. */ let container = NSPersistentContainer(name: "RetroCalculator") container.loadPersistentStores(completionHandler: { (storeDescription, error) in if let error = error as NSError? { // Replace this implementation with code to handle the error appropriately. // fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. /* Typical reasons for an error here include: * The parent directory does not exist, cannot be created, or disallows writing. * The persistent store is not accessible, due to permissions or data protection when the device is locked. * The device is out of space. * The store could not be migrated to the current model version. Check the error message to determine what the actual problem was. */ fatalError("Unresolved error \(error), \(error.userInfo)") } }) return container }() // MARK: - Core Data Saving support func saveContext () { let context = persistentContainer.viewContext if context.hasChanges { do { try context.save() } catch { // Replace this implementation with code to handle the error appropriately. // fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. let nserror = error as NSError fatalError("Unresolved error \(nserror), \(nserror.userInfo)") } } } }
mit
d5adf33c3286867b081fd7a32ae37d76
48.344086
285
0.685552
5.84586
false
false
false
false
drmohundro/Nimble
Nimble/DSL.swift
1
2202
import Foundation // Begins an assertion on a given value. // file: and line: can be omitted to default to the current line this function is called on. public func expect<T>(expression: @autoclosure () -> T, file: String = __FILE__, line: UInt = __LINE__) -> Expectation<T> { return Expectation( expression: Expression( expression: expression, location: SourceLocation(file: file, line: line))) } // Begins an assertion on a given value. // file: and line: can be omitted to default to the current line this function is called on. public func expect<T>(file: String = __FILE__, line: UInt = __LINE__, expression: () -> T) -> Expectation<T> { return Expectation( expression: Expression( expression: expression, location: SourceLocation(file: file, line: line))) } // Begins an assertion on a given value. // file: and line: can be omitted to default to the current line this function is called on. public func waitUntil(#timeout: NSTimeInterval, action: (() -> Void) -> Void, file: String = __FILE__, line: UInt = __LINE__) -> Void { var completed = false dispatch_async(dispatch_get_main_queue()) { action() { completed = true } } let passed = _pollBlock(pollInterval: 0.01, timeoutInterval: timeout) { return completed } if !passed { let pluralize = (timeout == 1 ? "" : "s") fail("Waited more than \(timeout) second\(pluralize)", file: file, line: line) } } // Begins an assertion on a given value. // file: and line: can be omitted to default to the current line this function is called on. public func waitUntil(action: (() -> Void) -> Void, file: String = __FILE__, line: UInt = __LINE__) -> Void { waitUntil(timeout: 1, action, file: file, line: line) } public func fail(message: String, #location: SourceLocation) { CurrentAssertionHandler.assert(false, message: message, location: location) } public func fail(message: String, file: String = __FILE__, line: UInt = __LINE__) { fail(message, location: SourceLocation(file: file, line: line)) } public func fail(file: String = __FILE__, line: UInt = __LINE__) { fail("fail() always fails") }
apache-2.0
300d9d4935cce87bd60db8a1c5445e46
40.566038
135
0.650772
3.981917
false
false
false
false
Nosrac/Dictater
Dictater/NSTextView.swift
1
1428
// // NSTextView.swift // Dictater // // Created by Kyle Carson on 9/14/15. // Copyright © 2015 Kyle Carson. All rights reserved. // import Foundation import Cocoa extension NSTextView { // Tweaked from http://lists.apple.com/archives/cocoa-dev/2005/Jun/msg01909.html var visibleRange : NSRange { guard let scrollView = self.enclosingScrollView else { return NSRange() } guard let layoutManager = self.layoutManager else { return NSRange() } guard let textContainer = self.textContainer else { return NSRange() } var rect = scrollView.documentVisibleRect rect.origin.x -= self.textContainerOrigin.x rect.origin.y -= self.textContainerOrigin.y if let paragraphStyle = self.defaultParagraphStyle, let font = self.font { rect.size.height -= paragraphStyle.lineHeightMultiple * font.pointSize } let glyphRange = layoutManager.glyphRange(forBoundingRect: rect, in: textContainer) let charRange = layoutManager.characterRange(forGlyphRange: glyphRange, actualGlyphRange: nil) return charRange } func scrollRangeToVisible(range: NSRange, smart: Bool = false) { if !smart { super.scrollRangeToVisible(range) return } let visibleRange = self.visibleRange if visibleRange.location <= range.location && range.location < (visibleRange.location + visibleRange.length) { // Do Nothing } else { self.scrollRangeToVisible(range) } } }
mit
36b42049fe7542bdc41cf94a642818df
22.393443
110
0.721794
3.745407
false
false
false
false
TotalDigital/People-iOS
People at Total/APIUtility.swift
1
9625
// // APIUtility.swift // People at Total // // Created by Florian Letellier on 24/02/2017. // Copyright © 2017 Florian Letellier. All rights reserved. // import UIKit import AFNetworking import p2_OAuth2 import SwiftyJSON import SVProgressHUD class APIUtility: NSObject { //let BASE_URL = "https://people-total.herokuapp.com/api/v1/" var BASE_URL = "" let sessionManager : AFHTTPSessionManager = AFHTTPSessionManager(sessionConfiguration: URLSessionConfiguration.default) class var sharedInstance: APIUtility { struct Static { static let instance = APIUtility() } return Static.instance } var isProd = Bool() { didSet { UserDefaults.standard.set(isProd, forKey: "isProd") UserDefaults.standard.synchronize() print("saved object: \(UserDefaults.standard.bool(forKey: "isProd"))") } } func getAPICall(token: String, url: String!, parameters: NSDictionary!, completionHandler:@escaping (NSArray?, Error?)->()) ->() { let accesstoken = token let isProdGet = UserDefaults.standard.bool(forKey: "isProd") if isProdGet { BASE_URL = "https://people.total/api/v1/" } else { BASE_URL = "https://people-total-staging.herokuapp.com/api/v1/" } var url: String! = url var isUser: Bool if url == "users" { isUser = false url = "\(BASE_URL)\(url!)?access_token=\(accesstoken)&page=\(Int(parameters["page"] as! Int))&per_page=\(Int(parameters["per_page"] as! Int))" } else if (url?.contains("users/featured"))! { isUser = false url = "\(BASE_URL)\(url!)?access_token=\(accesstoken)" } else if (url?.contains("users/search/"))! { isUser = false url = "\(BASE_URL)\(url!)?access_token=\(accesstoken)&page=\(Int(parameters["page"] as! Int))&per_page=\(Int(parameters["per_page"] as! Int))" } else if ((url?.contains("skills/search/"))! || (url?.contains("languages/search/"))!) { isUser = false url = "\(BASE_URL)\(url!)?access_token=\(accesstoken)" } else { isUser = true url = "\(BASE_URL)\(url!)?access_token=\(accesstoken)" } print("url : \(url)") sessionManager.requestSerializer = AFHTTPRequestSerializer() sessionManager.get(url!, parameters: [], progress: nil, success: { (task, responseObject) in if isUser == true { let response: NSArray = [responseObject] completionHandler(response, nil) } else { completionHandler(responseObject as? NSArray, nil) } }) { (task, error) in completionHandler(nil,error) } } func putAPICall(token: String, url: String!, parameters: NSDictionary!, completionHandler:@escaping (NSDictionary?, Error?)->()) ->() { let accesstoken = token let url : String = "\(BASE_URL)\(url!)?access_token=\(accesstoken)" print(url) print(parameters) sessionManager.requestSerializer = AFHTTPRequestSerializer() sessionManager.responseSerializer = AFHTTPResponseSerializer() //sessionManager.responseSerializer.acceptableContentTypes = NSSet(object: "text/html") as! Set<String> sessionManager.put(url, parameters: parameters, success: { (task, responseObject) in completionHandler(responseObject as? NSDictionary, nil) }) { (task, error) in completionHandler(nil,error) } } func postAPICall(token: String, url: String!, parameters: NSDictionary!, completionHandler:@escaping (NSDictionary?, Error?)->()) ->() { let accesstoken = token let url : String = "\(BASE_URL)\(url!)?access_token=\(accesstoken)" print(url) print(parameters) sessionManager.requestSerializer = AFHTTPRequestSerializer() sessionManager.post(url, parameters: parameters, success: { (task, responseObject) in completionHandler(responseObject as? NSDictionary, nil) }) { (task, error) in completionHandler(nil,error) } } func deleteAPICall(token: String, url: String!, parameters: NSDictionary!, completionHandler:@escaping (NSDictionary?, Error?)->()) ->() { let accesstoken = token let url : String = "\(BASE_URL)\(url!)?access_token=\(accesstoken)" print(url) print(parameters) sessionManager.requestSerializer = AFHTTPRequestSerializer() sessionManager.delete(url, parameters: parameters, success: { (task, responseObject) in completionHandler(responseObject as? NSDictionary, nil) }) { (task, error) in completionHandler(nil,error) } } func postAPICallWithImage(url: String!, parameters: NSDictionary!, image : NSMutableArray?, completionHandler:@escaping (NSDictionary?, NSError?)->()) ->() { //SVProgressHUD.showProgress(0.0, status: "chargement...") let url : String = "\(BASE_URL)\(url)" print(url) print(parameters) sessionManager.requestSerializer = AFHTTPRequestSerializer() let arrayImageData = NSMutableArray() if ((image?.count)! > 0) { for img in image! { var imageData : NSData? imageData = UIImagePNGRepresentation(img as! UIImage)! as NSData? arrayImageData.add(imageData!) } } sessionManager.post(url, parameters: parameters, constructingBodyWith: { (multipartFormData) in if (arrayImageData.count > 0) { var i : Int = 0 //print("annonce_pic[\(i)]") for imgData in arrayImageData { multipartFormData.appendPart(withFileData: (imgData as! NSData) as Data, name: "annonce_pic[\(i)]", fileName: "png", mimeType: "image/png") i += 1 // var imageData : NSData? // imageData = UIImagePNGRepresentation(img as! UIImage)! // arrayImageData.addObject(imageData!) } } }, progress: { (progress) in //SVProgressHUD.showProgress(Float(progress.fractionCompleted), status: "chargement...") }, success: { (task, responseObject) in //SVProgressHUD.dismiss() completionHandler(responseObject as? NSDictionary, nil) }) { (task, error) in // SVProgressHUD.dismiss() completionHandler(nil,error as NSError?) } } func updateProfileAPI(url: String!, parameters: NSDictionary!, image : UIImage?, completionHandler:@escaping (NSDictionary?, NSError?)->()) ->() { // SVProgressHUD.showProgress(0.0, status: "chargement...") let url : String = "\(BASE_URL)\(url)" print(url) print(parameters) sessionManager.requestSerializer = AFHTTPRequestSerializer() var imageData : NSData? imageData = UIImagePNGRepresentation(image!) as NSData? sessionManager.post(url, parameters: parameters, constructingBodyWith: { (multipartFormData) in if (imageData != nil) { multipartFormData.appendPart(withFileData: imageData! as Data, name: "avatar", fileName: "png", mimeType: "image/png") } }, progress: { (progress) in // SVProgressHUD.showProgress(Float(progress.fractionCompleted), status: "chargement...") }, success: { (task, responseObject) in //SVProgressHUD.dismiss() completionHandler(responseObject as? NSDictionary, nil) }) { (task, error) in //SVProgressHUD.dismiss() completionHandler(nil,error as NSError?) } } func updateProfilePicture(token: String, url: String!, parameters: NSDictionary!, image : UIImage?, completionHandler:@escaping (NSDictionary?, NSError?)->()) ->() { SVProgressHUD.showProgress(0.0, status: "Uploading...") let accesstoken = token let url : String = "\(BASE_URL)\(url!)?access_token=\(accesstoken)" print(url) print(parameters) sessionManager.requestSerializer = AFHTTPRequestSerializer() // sessionManager.responseSerializer = AFHTTPResponseSerializer() var imageData : NSData? imageData = UIImagePNGRepresentation(image!) as NSData? sessionManager.post(url, parameters: parameters, constructingBodyWith: { (multipartFormData) in if (imageData != nil) { multipartFormData.appendPart(withFileData: imageData! as Data, name: "profile_picture", fileName: "profile_picture", mimeType: "image/png") } }, progress: { (progress) in SVProgressHUD.showProgress(Float(progress.fractionCompleted), status: "Uploading...") }, success: { (task, responseObject) in SVProgressHUD.dismiss() completionHandler(responseObject as? NSDictionary, nil) }) { (task, error) in SVProgressHUD.dismiss() completionHandler(nil,error as NSError?) } } }
apache-2.0
337e7f3732e553686ee3c8f274bcd1b9
39.267782
169
0.581255
4.973643
false
false
false
false
nguyenantinhbk77/practice-swift
Views/Alerts/AlertWithTextField/AlertWithTextField/ViewController.swift
2
1294
// // ViewController.swift // AlertWithTextField // // Created by Domenico Solazzo on 04/05/15. // License MIT // import UIKit class ViewController: UIViewController { var controller:UIAlertController? override func viewDidLoad() { super.viewDidLoad() controller = UIAlertController(title: "Title", message: "Hello", preferredStyle: .Alert) // Adding a TextField controller!.addTextFieldWithConfigurationHandler(){(textField:UITextField!) in textField.placeholder = "XXXXXXX" } let action = UIAlertAction(title: "Done", style: UIAlertActionStyle.Default, handler: {[weak self](paramAction:UIAlertAction!) in if let textFields = self!.controller?.textFields{ var theTextFields = textFields as! [UITextField] let username = theTextFields[0].text println("The username is \(username)") } }) controller!.addAction(action) } override func viewDidAppear(animated: Bool) { super.viewDidAppear(animated) self.presentViewController(controller!, animated: true, completion: nil) } }
mit
11f613071d553e84ff7152d8d2fd9d7d
25.958333
86
0.585781
5.483051
false
false
false
false
AlexMoffat/timecalc
TimeCalc/LineNumberRulerView.swift
1
7284
// // LineNumberRulerView.swift // LineNumber // // Copyright (c) 2015 Yichi Zhang. All rights reserved. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the "Software"), // to deal in the Software without restriction, including without limitation // the rights to use, copy, modify, merge, publish, distribute, sublicense, // and/or sell copies of the Software, and to permit persons to whom the // Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL // THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. // import AppKit import Foundation import ObjectiveC var LineNumberViewAssocObjKey: UInt8 = 0 extension NSTextView { var lineNumberView:LineNumberRulerView { get { return objc_getAssociatedObject(self, &LineNumberViewAssocObjKey) as! LineNumberRulerView } set { objc_setAssociatedObject(self, &LineNumberViewAssocObjKey, newValue, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN_NONATOMIC) } } func lnv_setUpLineNumberView() { if font == nil { font = NSFont.systemFont(ofSize: 16) } if let scrollView = enclosingScrollView { lineNumberView = LineNumberRulerView(textView: self) scrollView.verticalRulerView = lineNumberView scrollView.hasVerticalRuler = true scrollView.rulersVisible = true } postsFrameChangedNotifications = true NotificationCenter.default.addObserver(self, selector: #selector(lnv_framDidChange), name: NSView.frameDidChangeNotification, object: self) NotificationCenter.default.addObserver(self, selector: #selector(lnv_textDidChange), name: NSText.didChangeNotification, object: self) } @objc func lnv_framDidChange(notification: NSNotification) { lineNumberView.needsDisplay = true } @objc func lnv_textDidChange(notification: NSNotification) { lineNumberView.needsDisplay = true } } class LineNumberRulerView: NSRulerView { var font: NSFont! { didSet { self.needsDisplay = true } } init(textView: NSTextView) { super.init(scrollView: textView.enclosingScrollView!, orientation: NSRulerView.Orientation.verticalRuler) self.font = textView.font ?? NSFont.systemFont(ofSize: NSFont.smallSystemFontSize) self.clientView = textView self.ruleThickness = 40 } required init(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func drawHashMarksAndLabels(in rect: NSRect) { if let textView = self.clientView as? NSTextView { if let layoutManager = textView.layoutManager { let relativePoint = self.convert(NSZeroPoint, from: textView) let lineNumberAttributes = [ NSAttributedString.Key.font: NSFont.monospacedDigitSystemFont(ofSize: 16, weight: NSFont.Weight.regular), NSAttributedString.Key.foregroundColor: NSColor.systemGray ] let drawLineNumber = { (lineNumberString:String, y:CGFloat) -> Void in let attString = NSAttributedString(string: lineNumberString, attributes: lineNumberAttributes) let x = 35 - attString.size().width attString.draw(at: NSPoint(x: x, y: relativePoint.y + y)) } let visibleGlyphRange = layoutManager.glyphRange(forBoundingRect: textView.visibleRect, in: textView.textContainer!) let firstVisibleGlyphCharacterIndex = layoutManager.characterIndexForGlyph(at: visibleGlyphRange.location) let newLineRegex = try! NSRegularExpression(pattern: "\n", options: []) // The line number for the first visible line var lineNumber = newLineRegex.numberOfMatches(in: textView.string, options: [], range: NSMakeRange(0, firstVisibleGlyphCharacterIndex)) + 1 var glyphIndexForStringLine = visibleGlyphRange.location // Go through each line in the string. while glyphIndexForStringLine < NSMaxRange(visibleGlyphRange) { // Range of current line in the string. let characterRangeForStringLine = (textView.string as NSString).lineRange( for: NSMakeRange( layoutManager.characterIndexForGlyph(at: glyphIndexForStringLine), 0 ) ) let glyphRangeForStringLine = layoutManager.glyphRange(forCharacterRange: characterRangeForStringLine, actualCharacterRange: nil) var glyphIndexForGlyphLine = glyphIndexForStringLine var glyphLineCount = 0 while ( glyphIndexForGlyphLine < NSMaxRange(glyphRangeForStringLine) ) { // See if the current line in the string spread across // several lines of glyphs var effectiveRange = NSMakeRange(0, 0) // Range of current "line of glyphs". If a line is wrapped, // then it will have more than one "line of glyphs" let lineRect = layoutManager.lineFragmentRect(forGlyphAt: glyphIndexForGlyphLine, effectiveRange: &effectiveRange, withoutAdditionalLayout: true) if glyphLineCount > 0 { drawLineNumber("-", lineRect.minY) } else { drawLineNumber("\(lineNumber)", lineRect.minY) } // Move to next glyph line glyphLineCount += 1 glyphIndexForGlyphLine = NSMaxRange(effectiveRange) } glyphIndexForStringLine = NSMaxRange(glyphRangeForStringLine) lineNumber += 1 } // Draw line number for the extra line at the end of the text if layoutManager.extraLineFragmentTextContainer != nil { drawLineNumber("\(lineNumber)", layoutManager.extraLineFragmentRect.minY) } } } } }
bsd-3-clause
152ee776583a2ce710b066fa8e2c7bb7
43.687117
169
0.606123
5.522365
false
false
false
false
DanielAsher/VIPER-SWIFT
VIPER-SWIFT/Classes/Modules/Add/User Interface/Transition/AddPresentationTransition.swift
1
2040
// // AddPresentationTransition.swift // VIPER-SWIFT // // Created by Conrad Stoll on 6/4/14. // Copyright (c) 2014 Mutual Mobile. All rights reserved. // import Foundation import UIKit class AddPresentationTransition: NSObject, UIViewControllerAnimatedTransitioning { func transitionDuration(transitionContext: UIViewControllerContextTransitioning?) -> NSTimeInterval { return 0.72 } func animateTransition(transitionContext: UIViewControllerContextTransitioning) { let fromVC = transitionContext.viewControllerForKey(UITransitionContextFromViewControllerKey) let toVC = transitionContext.viewControllerForKey(UITransitionContextToViewControllerKey) as! AddViewController toVC.transitioningBackgroundView.backgroundColor = UIColor.darkGrayColor() toVC.transitioningBackgroundView.alpha = 0.0 toVC.transitioningBackgroundView.frame = UIScreen.mainScreen().bounds let containerView = transitionContext.containerView() containerView?.addSubview(toVC.transitioningBackgroundView) containerView?.addSubview(toVC.view) let toViewFrame = CGRectMake(0, 0, 260, 300) toVC.view.frame = toViewFrame let finalCenter = CGPointMake(fromVC!.view.bounds.size.width / 2, 20 + toViewFrame.size.height / 2) toVC.view.center = CGPointMake(finalCenter.x, finalCenter.y - 1000) let options = UIViewAnimationOptions.CurveEaseIn UIView.animateWithDuration(self.transitionDuration(transitionContext), delay: 0.0, usingSpringWithDamping: 0.64, initialSpringVelocity: 0.22, options: options, animations: { toVC.view.center = finalCenter toVC.transitioningBackgroundView.alpha = 0.7 }, completion: { finished in toVC.view.center = finalCenter transitionContext.completeTransition(true) } ) } }
mit
d8bd01346880910a3775abe20d2b9b1a
37.509434
119
0.677941
5.746479
false
false
false
false
basheersubei/swift-t
stc/tests/392-multidimensional-13.swift
4
257
// Test for nested array insertion with computed indices () f () { int A[][]; A[0][i()] = 1; A[i()][1] = 2; A[j()][0] = 3; trace(A[0][0], A[0][1], A[1][0]); } (int r) i () { r = 0; } (int r) j () { r = 1; } main { f(); }
apache-2.0
ed8fb060d9d0198377bc78a9e13c7a3e
11.238095
56
0.373541
2.196581
false
false
false
false
xmkevinchen/CKMessagesKit
CKMessagesKit/Sources/Layout/CKMessageSizeCalculating.swift
1
1969
// // CKMessageSizeCalculating.swift // CKMessagesViewController // // Created by Kevin Chen on 8/27/16. // Copyright © 2016 Kevin Chen. All rights reserved. // import Foundation /// Message size holder of all configurable components of built-in cells public protocol CKMessageCalculatingSize { /// The size of message content itself var messageSize: CGSize { get } /// The insets of message var messageInsets: UIEdgeInsets { get } /// The size of top label var topLabel: CGSize { get } /// The size of bubble top label var bubbleTopLabel: CGSize { get } /// The size of bottom label var bottomLabel: CGSize { get } /// The size of avatar image var avatar: CGSize { get } /// The size of accessory view var accessory: CGSize { get } } public struct CKMessageCalculatedSize: CKMessageCalculatingSize { /// The size of message content itself public var messageSize: CGSize = .zero /// The insets of message public var messageInsets: UIEdgeInsets = .zero /// The size of top label public var topLabel: CGSize = .zero /// The size of bubble top label public var bubbleTopLabel: CGSize = .zero /// The size of bottom label public var bottomLabel: CGSize = .zero /// The size of avatar image public var avatar: CGSize = .zero /// The size of accessory view public var accessory: CGSize = .zero public static var zero: CKMessageCalculatedSize { return CKMessageCalculatedSize(messageSize: .zero, messageInsets: .zero, topLabel: .zero, bubbleTopLabel: .zero, bottomLabel: .zero, avatar: .zero, accessory: .zero) } } public protocol CKMessageSizeCalculating { func size(of message: CKMessageData, at indexPath: IndexPath, with layout: CKMessagesViewLayout) -> CKMessageCalculatingSize func prepareForResetting(layout: CKMessagesViewLayout) }
mit
35ea595f7422afe0adb26b4d51061d66
26.71831
173
0.67124
4.708134
false
false
false
false
noremac/UIKitExtensions
Extensions/Source/UIKit/Extensions/UIColorExtensions.swift
1
3723
/* The MIT License (MIT) Copyright (c) 2017 Cameron Pulsford 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 private extension Int { var rgbValues: (red: CGFloat, blue: CGFloat, green: CGFloat) { let r = CGFloat((self & 0xFF0000) >> 16) / 255.0 let g = CGFloat((self & 0xFF00) >> 8) / 255.0 let b = CGFloat(self & 0xFF) / 255.0 return (r, g, b) } } // MARK: - Creating colors public extension UIColor { convenience init(withHex hex: Int, alpha: CGFloat) { let (r, g, b) = hex.rgbValues self.init(red: r, green: g, blue: b, alpha: alpha) } convenience init(withP3Hex hex: Int, alpha: CGFloat) { let (r, g, b) = hex.rgbValues self.init(displayP3Red: r, green: g, blue: b, alpha: alpha) } convenience init(withIntRed red: UInt8, green: UInt8, blue: UInt8, alpha: CGFloat) { self.init(red: CGFloat(red) / 255, green: CGFloat(green) / 255, blue: CGFloat(blue) / 255, alpha: alpha) } convenience init(withP3IntRed red: UInt8, green: UInt8, blue: UInt8, alpha: CGFloat) { self.init(displayP3Red: CGFloat(red) / 255, green: CGFloat(green) / 255, blue: CGFloat(blue) / 255, alpha: alpha) } func withBrightness(increasedBy amount: CGFloat) -> UIColor? { var hue: CGFloat = 0 var saturation: CGFloat = 0 var brightness: CGFloat = 0 var alpha: CGFloat = 0 if getHue(&hue, saturation: &saturation, brightness: &brightness, alpha: &alpha) { brightness += (amount - 1) brightness = max(min(brightness, 1), 0) return UIColor(hue: hue, saturation: saturation, brightness: brightness, alpha: alpha) } var white: CGFloat = 0 alpha = 0 if getWhite(&white, alpha: &alpha) { white += (amount - 1) white = max(min(brightness, 1), 0) return UIColor(white: white, alpha: alpha) } return nil } } // MARK: - Apple palette public extension UIColor { static let appleRed = UIColor(withIntRed: 255, green: 59, blue: 48, alpha: 1) static let appleOrange = UIColor(withIntRed: 255, green: 149, blue: 0, alpha: 1) static let appleYellow = UIColor(withIntRed: 255, green: 204, blue: 0, alpha: 1) static let appleGreen = UIColor(withIntRed: 76, green: 217, blue: 100, alpha: 1) static let appleTealBlue = UIColor(withIntRed: 90, green: 200, blue: 250, alpha: 1) static let appleBlue = UIColor(withIntRed: 0, green: 122, blue: 255, alpha: 1) static let applePurple = UIColor(withIntRed: 88, green: 86, blue: 214, alpha: 1) static let applePink = UIColor(withIntRed: 255, green: 45, blue: 85, alpha: 1) }
mit
4028992dc1edce965167c9b964660f60
35.145631
121
0.664786
3.795107
false
false
false
false
nsagora/validation-toolkit
Sources/Predicates/Predicate.swift
1
2161
import Foundation /** The `Predicate` protocol defines the structure that must be implemented by concrete predicates. ```swift public struct CopyCatPredicate: Predicate { private let value: String public init(value: String) { self.value = value } public func evaluate(with input: String) -> Bool { return input == value } } let predicate = CopyCatPredicate(value: "alphabet") let isIdentical = predicate.evaluate(with: "alphabet") ``` */ public protocol Predicate: AsyncPredicate { /// A type that provides information about what kind of values the predicate can be evaluated with. associatedtype InputType /** Returns a `Boolean` value that indicates whether a given input matches the conditions specified by the receiver. - parameter input: The input against which to evaluate the receiver. - returns: `true` if input matches the conditions specified by the receiver, `false` otherwise. */ func evaluate(with input: InputType) -> Bool } extension Predicate { private var workQueue: DispatchQueue { return DispatchQueue(label: "com.nsagora.peppermint.predicate", attributes: .concurrent) } /** Asynchronous evaluates whether a given input matches the conditions specified by the receiver, then calls a handler upon completion. - parameter input: The input against which to evaluate the receiver. - parameter queue: The queue on which the completion handler is executed. If not specified, it uses `DispatchQueue.main`. - parameter completionHandler: The completion handler to call when the evaluation is complete. It takes a `Bool` parameter: - parameter matches: `true` if input matches the conditions specified by the receiver, `false` otherwise. */ public func evaluate(with input: InputType, queue: DispatchQueue = .main, completionHandler: @escaping (_ matches: Bool) -> Void) { workQueue.async { let result = self.evaluate(with: input) queue.async { completionHandler(result) } } } }
mit
9a14938a3b2ede7b46236864fbea888e
33.854839
137
0.680241
5.002315
false
false
false
false
arnaudbenard/my-npm
Pods/Charts/Charts/Classes/Data/ChartDataEntry.swift
79
2539
// // ChartDataEntry.swift // Charts // // Created by Daniel Cohen Gindi on 23/2/15. // // Copyright 2015 Daniel Cohen Gindi & Philipp Jahoda // A port of MPAndroidChart for iOS // Licensed under Apache License 2.0 // // https://github.com/danielgindi/ios-charts // import Foundation public class ChartDataEntry: NSObject, Equatable { /// the actual value (y axis) public var value = Double(0.0) /// the index on the x-axis public var xIndex = Int(0) /// optional spot for additional data this Entry represents public var data: AnyObject? public override init() { super.init() } public init(value: Double, xIndex: Int) { super.init() self.value = value self.xIndex = xIndex } public init(value: Double, xIndex: Int, data: AnyObject?) { super.init() self.value = value self.xIndex = xIndex self.data = data } // MARK: NSObject public override func isEqual(object: AnyObject?) -> Bool { if (object === nil) { return false } if (!object!.isKindOfClass(self.dynamicType)) { return false } if (object!.data !== data && !object!.data.isEqual(self.data)) { return false } if (object!.xIndex != xIndex) { return false } if (fabs(object!.value - value) > 0.00001) { return false } return true } // MARK: NSObject public override var description: String { return "ChartDataEntry, xIndex: \(xIndex), value \(value)" } // MARK: NSCopying public func copyWithZone(zone: NSZone) -> AnyObject { var copy = self.dynamicType.allocWithZone(zone) as ChartDataEntry copy.value = value copy.xIndex = xIndex copy.data = data return copy } } public func ==(lhs: ChartDataEntry, rhs: ChartDataEntry) -> Bool { if (lhs === rhs) { return true } if (!lhs.isKindOfClass(rhs.dynamicType)) { return false } if (lhs.data !== rhs.data && !lhs.data!.isEqual(rhs.data)) { return false } if (lhs.xIndex != rhs.xIndex) { return false } if (fabs(lhs.value - rhs.value) > 0.00001) { return false } return true }
mit
49615e743d541c9ad17985257883a6de
18.689922
73
0.522647
4.423345
false
false
false
false
AkshayNG/iSwift
iSwift/Helper/AppFileManager.swift
1
14251
// // AppFileManager.swift // iSwift // // Created by Akshay Gajarlawar on 24/03/19. // Copyright © 2019 yantrana. All rights reserved. // import Foundation class AppFileManager: NSObject { @objc static let shared = BRFileManager() // MARK: Core func createFolderInDocumentsDirectory(folder:String) -> URL? { let documentsUrl:URL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first as URL! let directoryUrl = documentsUrl.appendingPathComponent(folder) if !(self.fileExists(atUrl: directoryUrl)) { do { try FileManager.default.createDirectory(atPath: directoryUrl.path, withIntermediateDirectories: true, attributes: nil) } catch let createError { print("Error creating directory: \(createError.localizedDescription)") return nil } } return directoryUrl } func getDocumentDirectoryPathForComponent(pathComponent:String) -> URL { // We are using rather absolute path if pathComponent.hasPrefix("/") { return URL(fileURLWithPath: pathComponent) } let documentsUrl:URL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first as URL! return documentsUrl.appendingPathComponent(pathComponent) } func contentsOfDirectory(directory:String, isRelative:Bool) -> [URL] { var fileURL:URL? = nil if isRelative { fileURL = getDocumentDirectoryPathForComponent(pathComponent: directory) }else{ fileURL = URL.init(string: directory) } if fileURL != nil { do { let files = try FileManager.default.contentsOfDirectory(at: fileURL!, includingPropertiesForKeys: nil, options: []) return files } catch let error { print("\(error.localizedDescription)") } } return [] } func clearAllFilesFrom(directory:String, isRelative:Bool) { let contents = contentsOfDirectory(directory: directory, isRelative: isRelative) if contents.count > 0 { if contents.count > 0 { for contentPath in contents { do { try FileManager.default.removeItem(atPath: contentPath.path) } catch let removeError { print("Error removing directory: \(removeError.localizedDescription)") } } } } } func removeFile(atPath:String, isRelative:Bool) -> Bool { var filePath = atPath if isRelative { filePath = BRFileManager.shared.getDocumentDirectoryPathForComponent(pathComponent: atPath).path } do { try FileManager.default.removeItem(atPath: filePath) return true } catch let removeError { print("Error removing directory: \(removeError.localizedDescription)") return false } } func fileExists(atUrl:URL) -> Bool { return FileManager.default.fileExists(atPath: atUrl.path) } func copyFile(sourceURL:URL, destinaionURL:URL) -> Bool { _ = self.removeFile(atPath: destinaionURL.path, isRelative: false) do { try FileManager.default.copyItem(at: sourceURL, to: destinaionURL) return true } catch { print("\(error.localizedDescription)") return false } } // MARK: Media func saveText(text:String, inDirectory:String, fileName:String) -> String? { guard let folder = createFolderInDocumentsDirectory(folder: inDirectory) else { return nil } var name = fileName if !((fileName as NSString).contains(".")) { name = fileName + ".txt" } let destinationPath = folder.appendingPathComponent(name) do { try text.write(to: destinationPath, atomically: false, encoding: .utf8) return "%HOME/" + inDirectory + "/" + name } catch { print("\(error.localizedDescription)") return nil } } func saveImages(images:[UIImage], inDirectory:String, clearOld:Bool) -> NSArray { //e.g. inDirectory = "Campaign/Images" if clearOld { clearAllFilesFrom(directory: inDirectory, isRelative: true) } let tempArr = NSMutableArray() var counter = 1 for image in images { let imgName = "image" + String(counter) var ext = "" var imgData:Data? = nil if let jpg = UIImageJPEGRepresentation(image, 1.0) { ext = "jpg" imgData = jpg } else if let png = UIImagePNGRepresentation(image) { ext = "png" imgData = png } if(imgData != nil) { guard let folder = createFolderInDocumentsDirectory(folder: inDirectory) else { return tempArr } let fileName = imgName + "." + ext let destinationPath = folder.appendingPathComponent(fileName) do { try imgData?.write(to: destinationPath, options: Data.WritingOptions.atomic) tempArr.add("%HOME/" + inDirectory + "/" + fileName) } catch (let writeError) { print("Error writing file: \(writeError.localizedDescription)") } } counter = counter + 1 } return tempArr } func saveImage(image:UIImage, inDirectory:String, fileName:String) -> String? { var name = fileName let fName = fileName as NSString if fName.contains("."){ let index = fName.range(of: ".").location name = fName.substring(to: index) } var ext = "" var imgData:Data? = nil if let jpg = UIImageJPEGRepresentation(image, 1.0) { ext = "jpg" imgData = jpg } else if let png = UIImagePNGRepresentation(image) { ext = "png" imgData = png } if imgData != nil { guard let folder = BRFileManager.shared.createFolderInDocumentsDirectory(folder: inDirectory) else { return nil } name = name + "." + ext let destinationPath = folder.appendingPathComponent(name) do{ try imgData?.write(to: destinationPath, options: Data.WritingOptions.atomic) return "%HOME/" + inDirectory + "/" + name } catch let error{ print(error.localizedDescription) return nil } } return nil } @objc func getImage(imagePath:String, isRelative:Bool) -> UIImage? { var fileURL:URL? = nil if isRelative { let component = (imagePath as NSString).replacingOccurrences(of: "%HOME/", with: "") fileURL = self.getDocumentDirectoryPathForComponent(pathComponent: component) } else { fileURL = URL.init(string: imagePath) } if fileURL != nil { do { let imageData = try Data.init(contentsOf: fileURL!) return UIImage.init(data: imageData) } catch let readError { print("Error reading file: \(readError.localizedDescription)") return nil } } return nil } func saveVideo(data:Data, inDirectory:String, fileName:String) -> String? { guard let folder = createFolderInDocumentsDirectory(folder: inDirectory) else { return nil } do { let destinationPath = folder.appendingPathComponent(fileName) try data.write(to: destinationPath, options: Data.WritingOptions.atomic) return "%HOME/" + inDirectory + "/" + fileName } catch let error { print(error.localizedDescription) return nil } } func getVideo(videoPath:String, isRelative:Bool, returnData:Bool) -> Any? { var fileURL:URL? = nil if isRelative { let vidPath = (videoPath as NSString).replacingOccurrences(of: "%HOME/", with: "") fileURL = BRFileManager.shared.getDocumentDirectoryPathForComponent(pathComponent: vidPath) } else { fileURL = URL.init(string: videoPath) } if returnData, fileURL != nil { do { let videoData = try Data.init(contentsOf: fileURL!) return videoData } catch let error{ print("\(error.localizedDescription)") return nil } } else { return fileURL } } func saveObject(anObject:Any, inDirectory:String, fileName:String) -> Bool { guard let folder = BRFileManager.shared.createFolderInDocumentsDirectory(folder: inDirectory) else { return false } let destinationPath = folder.appendingPathComponent(fileName) let data = NSKeyedArchiver.archivedData(withRootObject: anObject) do { try data.write(to: destinationPath) return true } catch let error { print(error.localizedDescription) return false } } func getObject(objectPath:String, isRelative:Bool) -> Any? { var fileURL:URL? = nil if isRelative { let vidPath = (objectPath as NSString).replacingOccurrences(of: "%HOME/", with: "") fileURL = BRFileManager.shared.getDocumentDirectoryPathForComponent(pathComponent: vidPath) } else { fileURL = URL.init(string: objectPath) } if fileURL != nil { do { let data = try Data.init(contentsOf: fileURL!) return NSKeyedUnarchiver.unarchiveObject(with: data) } catch let error { print("\(error.localizedDescription)") return nil } } return nil } func createAndSavePDF(printFormatter:UIPrintFormatter, fileName:String) -> URL { let render = UIPrintPageRenderer() render.addPrintFormatter(printFormatter, startingAtPageAt: 0) let paper = CGRect(x: 0, y: 0, width: 595.2, height: 841.8) // A4, 72 dpi let printable = paper.insetBy(dx: 0, dy: 0) render.setValue(paper, forKey: "paperRect") render.setValue(printable, forKey: "printableRect") let pdfData = NSMutableData() UIGraphicsBeginPDFContextToData(pdfData, .zero, nil) for i in 0..<render.numberOfPages { UIGraphicsBeginPDFPage(); render.drawPage(at: i, in: UIGraphicsGetPDFContextBounds()) } UIGraphicsEndPDFContext(); let saveToUrl = getDocumentDirectoryPathForComponent(pathComponent: fileName) pdfData.write(to: saveToUrl, atomically: true) return saveToUrl } func saveHtml(text:String, fileName:String) -> URL? { let saveToUrl = getDocumentDirectoryPathForComponent(pathComponent: fileName) do { try text.write(to: saveToUrl, atomically: true, encoding: String.Encoding.utf8) return saveToUrl } catch { print("HTML write error :: \(error.localizedDescription)") return nil } } // MARK: Remote func download(url:URL, name:String, completion:@escaping (_ fileURL:URL?, _ error:Error?) -> Void) { var fileName = name if (name as NSString).contains(".") { let tempArr = (name as NSString).components(separatedBy: ".") if tempArr.count == 2 { let ext = tempArr.last if url.pathExtension != ext { fileName = tempArr.first! + "." + url.pathExtension } } } else { fileName = name + url.pathExtension } guard let documentsUrl = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first else { completion(nil,nil) return } let destinationFileUrl = documentsUrl.appendingPathComponent(fileName) if self.fileExists(atUrl: destinationFileUrl) { completion(destinationFileUrl,nil) } else { URLSession.shared.downloadTask(with: url, completionHandler: { (tempLocalURL, response, error) in if let tempLocalUrl = tempLocalURL, error == nil { do { try FileManager.default.copyItem(at: tempLocalUrl, to: destinationFileUrl) completion(destinationFileUrl,nil) } catch (let writeError) { completion(nil,writeError) } } else { completion(nil,error) } }).resume() } }
mit
9cf03fbef069f654019f6ad354949bd9
29.777538
134
0.523509
5.516841
false
false
false
false
wirecard/paymentSDK-iOS
Example-Swift/Embedded/CardfieldVC.swift
1
5473
// // ViewController.swift // Embedded // // Created by Vrana, Jozef on 3/6/17. // Copyright © 2017 Vrana, Jozef. All rights reserved. // import WDeComCard import WDeComCardScannerGallery let AMOUNT = NSDecimalNumber.init(mantissa: 199, exponent: -2, isNegative: false) class CardfieldVC: PaymemtVC, UIActionSheetDelegate, WDECCardFieldDelegate { @IBOutlet weak var cardField: WDECCardFieldScannerGallery! @IBOutlet weak var cardFieldStateLabel: UILabel! @IBOutlet weak var payBtn: UIButton! override func viewDidLoad() { super.viewDidLoad() self.cardField.becomeFirstResponder() let cardLayout = WDECCardLayout.appearance() self.cardField.isManualCardBrandSelectionRequired = cardLayout.manualCardBrandSelectionRequired self.cardField.scanImage = UIImage(named: "scan_cf2") self.cardField.scanImageTintColor = UIColor.blue self.cardField.enableScanImageButton = true self.cardField.scanToolbarButtonTitle = "Scan Card" self.cardField.enableScanToolbarButton = true // Appearance posibility //WDECCardFieldScannerGallery.appearance().scanImage = UIImage(named: "scan_cf2") //WDECCardFieldScannerGallery.appearance().scanImageTintColor = UIColor.blue //WDECCardFieldScannerGallery.appearance().enableScanImageButton = true //WDECCardFieldScannerGallery.appearance().scanToolbarButtonTitle = "Scan Card" //WDECCardFieldScannerGallery.appearance().enableScanToolbarButton = true } @IBAction func onClearAction(_ sender: UIButton) { self.cardField.clear() } @IBAction func onPayAction(_ sender: UIButton) { // if you create payment object just before calling makePayment you are sure that timestamp is correct var payment = self.createCardPayment() self.cardField.cardPayment = payment // append card data payment = self.cardField.cardPayment self.client?.make(payment, withCompletion:{(response: WDECPaymentResponse?,error: Error?) in let alertTitle = error != nil ? "Error" : "Success" let alertMessage = error != nil ? error!.localizedDescription : "Item(s) has been purchased." let ac = UIAlertController(title: alertTitle, message: alertMessage, preferredStyle: .actionSheet) ac.addAction(UIAlertAction(title:"OK", style:.default, handler:nil)); self.present(ac, animated:true, completion:nil) // each request shall have unique ID, once it is used create new one self.cardField.cardPayment = self.createCardPayment() }) } func cardField(_ cardField: WDECCardField, didChange state: WDECCardFieldState) { self.payBtn.isEnabled = cardField.isValid var text : String? switch state { case WDECCardFieldState.cardInitial: text = "card initial" case WDECCardFieldState.jailbrokenDevice: text = "jailbroken device" case WDECCardFieldState.cardValid: text = "card valid" case WDECCardFieldState.cardUnsupported: text = "card unsupported" case WDECCardFieldState.numberEditting: text = "number editting" case WDECCardFieldState.numberIncomplete: text = "number incomplete" case WDECCardFieldState.numberInvalid: text = "number invalid" case WDECCardFieldState.numberValid: text = "number valid" case WDECCardFieldState.monthEditting: text = "month editting" case WDECCardFieldState.yearEditting: text = "year editting" case WDECCardFieldState.expirationDateIncomplete: text = "expiration date incomplete" case WDECCardFieldState.expirationDateInvalid: text = "expiration date invalid" case WDECCardFieldState.expirationDateValid: text = "expiration date valid" case WDECCardFieldState.securityCodeEditting: text = "security code editting" case WDECCardFieldState.securityCodeIncomplete: text = "security code incomplete" case WDECCardFieldState.securityCodeInvalid: text = "security code invalid" case WDECCardFieldState.securityCodeValid: text = "security code valid" case WDECCardFieldState.supportedCardsInvalid: text = "unsupported usage of cards CUP & UPI type at the same time" } self.cardFieldStateLabel.text = text } func createCardPayment() -> WDECCardPayment { let payment = WDECCardPayment() payment.amount = AMOUNT payment.currency = "USD" payment.transactionType = .purchase /** @Warning: We ask you to never share your Secret Key with anyone, or store it inside your application or phone. This is crucial to ensure the security of your transactions. You will be generating the signature on your own server’s backend, as it is the only place where you will store your Secret Key. */ let WD_MERCHANT_ACCOUNT_ID = "33f6d473-3036-4ca5-acb5-8c64dac862d1" let WD_MERCHANT_SECRET_KEY = "9e0130f6-2e1e-4185-b0d5-dc69079c75cc" self.merchantSignedPaymentByMerchantSecretKey(merchantAccountID: WD_MERCHANT_ACCOUNT_ID, payment: payment, merchantSecretKey: WD_MERCHANT_SECRET_KEY) let accountHolder = WDECCustomerData() accountHolder.firstName = "John" accountHolder.lastName = "Doe" payment.accountHolder = accountHolder return payment } }
mit
f2a04fe06331e537b2894af3144dc4ab
47.40708
179
0.700914
4.376
false
false
false
false
mmrmmlrr/ExamMaster
Pods/ModelsTreeKit/JetPack/UIView+Signal.swift
2
506
// // UIView+Signal.swift // ModelsTreeKit // // Created by aleksey on 06.06.16. // Copyright © 2016 aleksey chernish. All rights reserved. // import UIKit public extension UIView { func hiddenSignal(owner: DeinitObservable? = nil) -> Observable<Bool> { var assignedOwner: DeinitObservable! = owner if assignedOwner == nil { assignedOwner = superview as! DeinitObservable } return signalForKeyPath("hidden", owner: assignedOwner).map { $0! } as! Observable<Bool> } }
mit
4cde065646c21e99bc7885fe5ce087f3
23.095238
92
0.685149
3.825758
false
false
false
false
kaideyi/KDYSample
KYChat/KYChat/Helper/Extension/NSObject/NSString+Validate.swift
1
811
// // NSString+Validate.swift // KDYWeChat // // Created by kaideyi on 16/10/15. // Copyright © 2016年 kaideyi.com. All rights reserved. // import Foundation extension NSString { /** * 检测邮箱格式 */ class func validateEmail(_ mail: String) -> Bool { return true } /** * 检测手机号格式 */ class func isPhoneNumber(_ phoneNumber: String) -> Bool { if phoneNumber.characters.count == 0 { return false } let mobile = "^(13[0-9]|15[0-9]|18[0-9]|17[0-9]|147)\\d{8}$" let regexMobile = NSPredicate(format: "SELF MATCHES %@",mobile) if regexMobile.evaluate(with: mobile) == true { return true } else { return false } } }
mit
7953bca0f5294ba107df1f80244b2948
19.578947
71
0.521739
3.796117
false
false
false
false
miller-ms/MMSCropView
Pod/Classes/MMSCropView.swift
1
18616
// // MMSCropImageView.swift // Pods // // Created by William Miller on 3/10/16. // // Copyright (c) 2016 William Miller <[email protected]> // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // // import UIKit @objc open class MMSCropView: UIImageView, UIGestureRecognizerDelegate { /// The dragOrigin is the first point the user touched to begin the drag operation to delineate the crop rectangle. var dragOrigin = CGPoint.zero /// The rectangular view that the user sizes over the image to delineate the crop rectangle var cropView = UIView(frame: CGRect(x: -1.0, y: -1.0, width: -1.0, height: -1.0)) /// Gesture recognizer for delineating the crop rectangle attached to the imageView var dragGesture = DragRecognizer() /// Tap gesture attached to the imageView when detected the cropView is hidden var hideGesture = UITapGestureRecognizer() /// Swallow gesture consumes taps inside the cropView without acting upon them. This is required since without it taps in the crop view are handled by the tap gesture of the imageView. var swallowGesture = UITapGestureRecognizer() /// Moves an existing cropView around to any location over the imageView. var moveGesture = UIPanGestureRecognizer() /// The first touchpoint when the user began moving the cropView var touchOrigin = CGPoint.zero /// Layer that obscures the outside region of the crop rectangle var maskLayer = CAShapeLayer() /// Opacity for the shaded area outside the crop rectangle let shadedOpacity = Float(0.65) /// Opacity for the area under the crop rectangle is transparent let transparentOpacity = Float(0.0) /// The color for the shaded area outside the crop rectangle is black. let maskColor = (UIColor).black override public init(frame: CGRect) { super.init(frame: frame) initializeInstance() } required public init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) initializeInstance() } /** Initializes all the member views to present and operate on the cropView. */ /** Initializes all the subviews and connects the gestures to the corresponding views and their action methods. */ func initializeInstance() { // Enable user interaction isUserInteractionEnabled = true cropView.isHidden = true; // the cropView is modestly transparent cropView.backgroundColor = UIColor.clear // background color is white cropView.alpha = 1.0 // the background is modestly transparent cropView.layer.borderWidth = 0.5 // the crop rectangle has a solid border cropView.layer.borderColor = UIColor.white.cgColor // the crop border is white addSubview(cropView) // add the cropView to the imageView dragGesture.addTarget(self, action: #selector(dragRectangle(_:))) dragGesture.delegate = self addGestureRecognizer(dragGesture) hideGesture.addTarget(self, action: #selector(hideCropRectangle(_:))) hideGesture.delegate = self; addGestureRecognizer(hideGesture) moveGesture.addTarget(self, action: #selector(moveRectangle(_:))) moveGesture.delegate = self cropView.addGestureRecognizer(moveGesture) cropView.addGestureRecognizer(swallowGesture) maskLayer.fillRule = kCAFillRuleEvenOdd maskLayer.fillColor = maskColor.cgColor maskLayer.opacity = transparentOpacity layer.addSublayer(maskLayer) } /** Creates two rectangular paths. One is set to the dimensions of the UIImageVie and a smaller one appended to the first that is the size and origin of the cropRect. - parameter mask The shape layer added to the UIImageView - parameter cropRect The rectangular dimensions of area within the first shape to show transparent. - returns: returns the mask */ func calculateMaskLayer (_ mask:CAShapeLayer, cropRect: CGRect) -> CAShapeLayer { // Create a rectangular path to enclose the circular path within the bounds of the passed in layer size. let outsidePath = UIBezierPath(rect: bounds) let insidePath = UIBezierPath(rect: cropRect) outsidePath.append(insidePath) mask.path = outsidePath.cgPath; return mask } /** Always recognize the gesture. - parameter gestureRecognizer: An instance of a subclass of the abstract base class UIGestureRecognizer. - returns: returns true to recognize the gesture. */ override open func gestureRecognizerShouldBegin(_ gestureRecognizer: UIGestureRecognizer) -> Bool { return true } /** The gesture delegate method to check if two gestures should be recognized simultaniously. The tap and pan gestures are recognized simultaneously by the UIImageView. - parameter gestureRecognizer An instance of a subclass of the abstract base class UIGestureRecognizer. This is the object sending the message to the delegate. - parameter otherGestureRecognizer: An instance of a subclass of the abstract base class UIGestureRecognizer. - returns: Returns true to detect the tap gesture and pan gesture simultaneously. */ open func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldRecognizeSimultaneouslyWith otherGestureRecognizer: UIGestureRecognizer) -> Bool { /* Enable to recognize the pan and tap gestures simultaneous for both the imageView and cropView */ if gestureRecognizer.isKind(of: UITapGestureRecognizer.self) && otherGestureRecognizer.isKind(of: UIPanGestureRecognizer.self) { return true } else { return false } } /** Checks if the bottom right corner and upper left corners of the input rectangle fall within boundary of the image frame. If either corner falls outside, it recalculates the respective origin's coordinate that falls outside the boundary to keep the rectangle witin the frame. To restrict the move, the origin is always adjusted to maintain the size. - parameter cropFrame A rectangle representing the crop frame to check. - returns: returns the input rectangle unchanged if all the dimensions fall within the image frame; otherwise, a rectangle where the origin is recalculate to keep the rectangle within the boundary. */ func restrictMoveWithinFrame (_ cropFrame: CGRect) -> CGRect { var restrictedFrame = cropFrame /* If the origin's y coordinate falls outside the image frame, recalculate it to fall on the boundary. */ if restrictedFrame.origin.y < 0 { restrictedFrame.origin.y = 0 } /* If the bottom right corner's y coordinate falls outside the image frame, recalculate the origin's y coordinate to fit the bottom right corner within the height boundary. */ if (restrictedFrame.origin.y + restrictedFrame.height) > frame.height { restrictedFrame.origin.y = restrictedFrame.origin.y - (restrictedFrame.origin.y + restrictedFrame.height - frame.height) } /* If the origin's x coordinate falls outside the image frame, recalculate it to fall on the boundary. */ if restrictedFrame.origin.x < 0 { restrictedFrame.origin.x = 0 } /* If the bottom right corner's x coordinate falls outside the image frame, recalculate the origin's x coordinate to fit the bottom right corner within the width boundary. */ if (restrictedFrame.origin.x + restrictedFrame.width) > frame.width { restrictedFrame.origin.x = restrictedFrame.origin.x - (restrictedFrame.origin.x + restrictedFrame.width - frame.width) } return restrictedFrame } /** A finger was touched within the boundaries of the crop view. It's responsible for repositioning the crop rectangle over the image based on the coordinates of touchpoint. - parameter gesture A reference to the pan gesture. */ @IBAction func moveRectangle(_ gesture:UIPanGestureRecognizer) { if gesture.state == UIGestureRecognizerState.began { /* save the crop view frame's origin to compute the changing position as the finger glides around the screen. Also, save the first touch point compute the amount to change the frames orign. */ touchOrigin = gesture.location(in: self) dragOrigin = cropView.frame.origin } else { /* Compute the change in x and y coordinates with respect to the original touch point. Compute a new x and y point by adding the change in x and y to the crop view's origin before it was moved. Make this point the new origin. */ let currentPt = gesture.location(in: self) let dx = currentPt.x - touchOrigin.x let dy = currentPt.y - touchOrigin.y cropView.frame = CGRect(x: dragOrigin.x+dx, y: dragOrigin.y+dy, width: cropView.frame.size.width, height: cropView.frame.size.height) cropView.frame = restrictMoveWithinFrame(cropView.frame) let _ = calculateMaskLayer(maskLayer, cropRect: cropView.frame) } } /** Checks if the bottom right corner and upper left corners of the input rectangle fall with in boundary of the image frame. If either corner falls outside, it resets the corner to fall on the boundary for the coordinate that lies outside. - parameter cropFrame A rectangle representing the crop frame to check. - returns: returns the input rectangle unchanged if all the dimensions fall within the image frame; otherwise, a rectangle where the coordinate falling outside the image frame is reset to fall on the boundary. */ func restrictDragWithinFrame(_ cropFrame: CGRect) -> CGRect { var restrictedFrame = cropFrame /* if the origin's y coordinate falls outside the image frame, then move it to the boundary and reduce the height by the number of pixels it falls outside the frame. */ if restrictedFrame.origin.y < 0 { restrictedFrame.size.height += restrictedFrame.origin.y restrictedFrame.origin.y = 0 } /* if the bottom right corner's y coordinate falls outside the image frame, then move it to the boundary and reduce the height by the number of pixels it falls outside the frame. */ if (restrictedFrame.origin.y + restrictedFrame.height) > frame.height { restrictedFrame = CGRect(x: restrictedFrame.origin.x, y: restrictedFrame.origin.y, width: restrictedFrame.width, height: frame.height - restrictedFrame.origin.y) } /* if the origin's x coordinate falls outside the image frame, then move it to the boundary and reduce the height by the number of pixels it falls outside the frame. */ if restrictedFrame.origin.x < 0 { restrictedFrame.size.width += restrictedFrame.origin.x restrictedFrame.origin.x = 0 } /* if the bottom right corner's x coordinate falls outside the image frame, then move it to the boundary and reduce the width by the number of pixels it falls outside the frame. */ if (restrictedFrame.origin.x + restrictedFrame.width) > frame.width { restrictedFrame = CGRect(x: restrictedFrame.origin.x, y: restrictedFrame.origin.y, width: frame.width - restrictedFrame.origin.x, height: restrictedFrame.height) } return restrictedFrame } /** This method resizes the cropView frame as the user drags their finger across the UIImageView. The first tap point becomes the frame's origin and is referenced through the pan duration to compute size and to set the frame's origin. - parameter gesture The gesture that is being recognized. */ @IBAction func dragRectangle(_ gesture: DragRecognizer ) { var cropRect = CGRect.zero if gesture.state == UIGestureRecognizerState.began { /* set the origin for the remainder of the pan gesture to the first touchpoint. */ cropView.isHidden = false maskLayer.opacity = shadedOpacity cropRect.origin = gesture.origin dragOrigin = gesture.origin } else { cropRect = cropView.frame let currentPoint = gesture.location(in: self) if currentPoint.x >= dragOrigin.x && currentPoint.y >= dragOrigin.y { /* finger is dragged down and right with respect to the origin start (Quadrant III); cropViews origin is the original touchpoint. */ cropRect.origin = dragOrigin cropRect.size = CGSize(width: currentPoint.x - cropRect.origin.x, height: currentPoint.y - cropRect.origin.y) } else if currentPoint.x <= dragOrigin.x && currentPoint.y <= dragOrigin.y { /* the finger is dragged up and left with respect to the origin start (Quadrant I); Since the frame origin always represents the upper left corner, the frame rectangle's origin is set to the current point, and the start origin is the bottom right corner. */ cropRect.origin = currentPoint cropRect.size = CGSize(width: dragOrigin.x - currentPoint.x, height: dragOrigin.y - currentPoint.y) } else if currentPoint.x < dragOrigin.x { /* logic falls here when the x coordinate dimension is changing in the opposite direction of the y coordinate and moving down and to the left (Quadrant IV). Thhe frame rectangle's origin is a combination of the current x coordinate and the start origin's y. */ cropRect.origin = CGPoint(x: currentPoint.x, y: dragOrigin.y) cropRect.size = CGSize(width: dragOrigin.x - currentPoint.x, height: currentPoint.y - dragOrigin.y) } else if currentPoint.y < dragOrigin.y { /* Logic falls here when the y coordinate dimension is changing in the opposite direction of the y coordinate and moving up and to the right (Quadrant II). The frame rectangle's origin is a combination of the current y coordinate and the start origin's x. */ cropRect.origin = CGPoint(x: dragOrigin.x, y: currentPoint.y) cropRect.size = CGSize(width: currentPoint.x - dragOrigin.x, height: dragOrigin.y - currentPoint.y) } } cropView.frame = restrictDragWithinFrame(cropRect) /* The mask layer must move with the crop rectangle. */ let _ = calculateMaskLayer(maskLayer, cropRect: cropView.frame) } /** The crop view becomes hidden when the user taps outside the crop view frame. - parameter gesture The gesture being recognized. */ @IBAction func hideCropRectangle (_ gesture: UITapGestureRecognizer) { if !cropView.isHidden { cropView.isHidden = true maskLayer.opacity = transparentOpacity cropView.frame = CGRect(x: -1.0, y: -1.0, width: 0.0, height: 0.0) } } /* crop: returns a new UIImage cut from the crop view frame that overlays it. The underlying CGImage of the returned UIImage has the dimensions of the crop view's frame. */ /** Returns a new UIImage cut from the crop view frame that overlays it. The underlying CGImage of the returned UIImage has the dimensions of the crop view's frame. ;returns: A UIImage having the pixels beneath the crop rectangle and its dimensions. */ open func crop() -> UIImage { // Make sure the crop frame is within the bounds of the image. guard cropView.frame.origin.x >= 0 && cropView.frame.origin.y >= 0 && cropView.frame.height > 0 && cropView.frame.width > 0 && cropView.frame.origin.x + cropView.frame.width <= frame.width && cropView.frame.origin.y + cropView.frame.height <= frame.height else { return image! } let croppedImage = image!.cropRectangle(cropView.frame, inFrame:frame.size) return croppedImage } }
mit
6fd4046456bbe421ef9d50a571249ead
41.213152
354
0.638537
5.290139
false
false
false
false
KosyanMedia/Aviasales-iOS-SDK
AviasalesSDKTemplate/Source/CommonSource/BrowserViewController/GateBrowserViewPresenter.swift
1
2554
// // GateBrowserViewPresenter.swift // AviasalesSDKTemplate // // Created by Dim on 27.03.2018. // Copyright © 2018 Go Travel Un Limited. All rights reserved. // import Foundation @objcMembers class GateBrowserViewPresenter: NSObject { fileprivate weak var view: BrowserViewProtocol? fileprivate let proposal: JRSDKProposal fileprivate let purchasePerformer: AviasalesSDKPurchasePerformer fileprivate var request: URLRequest? init(ticketProposal: JRSDKProposal, searchID: String) { proposal = ticketProposal purchasePerformer = AviasalesSDKPurchasePerformer(proposal: ticketProposal, searchId: searchID) super.init() } } extension GateBrowserViewPresenter: BrowserViewPresenter { func handleLoad(view: BrowserViewProtocol) { self.view = view view.set(title: proposal.gate.label) view.updateControls() view.showLoading() purchasePerformer.perform(with: self) trackFlightsBuyEvent() } func handleClose() { view?.stopLoading() view?.hideActivity() view?.dismiss() } func handleStartNavigation() { view?.showActivity() } func handleCommit() { view?.updateControls() } func handleFinish() { view?.hideLoading() view?.hideActivity() } func handleFail(error: Error) { view?.hideLoading() view?.hideActivity() if !error.isCancelled { view?.showError(message: error.localizedDescription) } } func handleFailedURL() { if let request = request { view?.reload(request: request) } } func handleError() { view?.dismiss() } func handleGoBack() { view?.goBack() } func handleGoForward() { view?.goForward() } } private extension GateBrowserViewPresenter { func trackFlightsBuyEvent() { let event = FlightsBuyEvent(proposal: proposal) AnalyticsManager.log(event: event) } } extension GateBrowserViewPresenter: AviasalesSDKPurchasePerformerDelegate { public func purchasePerformer(_ performer: AviasalesSDKPurchasePerformer!, didFinishWith URLRequest: URLRequest!, clickID: String!) { view?.load(request: URLRequest, scripts: [String]()) self.request = URLRequest } func purchasePerformer(_ performer: AviasalesSDKPurchasePerformer!, didFailWithError error: Error!) { view?.hideLoading() view?.showError(message: error.localizedDescription) } }
mit
c6cb9cfc6c8ac2573eaae585dac9a71a
23.786408
137
0.660008
4.518584
false
false
false
false
younata/BreakOutToRefresh
PullToRefreshDemo/BreakOutToRefreshView.swift
1
13731
// // BreakOutToRefreshView.swift // PullToRefreshDemo // // Created by dasdom on 17.01.15. // // Copyright (c) 2015 Dominik Hauser <[email protected]> // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. import UIKit import SpriteKit @objc public protocol BreakOutToRefreshDelegate: class { func refreshViewDidRefresh(refreshView: BreakOutToRefreshView) } public class BreakOutToRefreshView: SKView { private let sceneHeight = CGFloat(100) private let breakOutScene: BreakOutScene private unowned let scrollView: UIScrollView public weak var delegate: BreakOutToRefreshDelegate? public var forceEnd = false public var isRefreshing = false private var isDragging = false private var isVisible = false public var scenebackgroundColor: UIColor { didSet { breakOutScene.scenebackgroundColor = scenebackgroundColor startScene.backgroundColor = scenebackgroundColor } } public var textColor: UIColor { didSet { breakOutScene.textColor = textColor startScene.textColor = textColor } } public var paddleColor: UIColor { didSet { breakOutScene.paddleColor = paddleColor } } public var ballColor: UIColor { didSet { breakOutScene.ballColor = ballColor } } public var blockColors: [UIColor] { didSet { breakOutScene.blockColors = blockColors } } private lazy var startScene: StartScene = { let size = CGSize(width: self.scrollView.frame.size.width, height: self.sceneHeight) let startScene = StartScene(size: size) startScene.backgroundColor = self.scenebackgroundColor startScene.textColor = self.textColor return startScene }() public override init(frame: CGRect) { fatalError("Use init(scrollView:) instead.") } public init(scrollView inScrollView: UIScrollView) { let frame = CGRect(x: 0.0, y: -sceneHeight, width: inScrollView.frame.size.width, height: sceneHeight) breakOutScene = BreakOutScene(size: frame.size) self.scrollView = inScrollView scenebackgroundColor = UIColor.whiteColor() textColor = UIColor.blackColor() paddleColor = UIColor.grayColor() ballColor = UIColor.blackColor() blockColors = [UIColor(white: 0.2, alpha: 1.0), UIColor(white: 0.4, alpha: 1.0), UIColor(white: 0.6, alpha: 1.0)] breakOutScene.scenebackgroundColor = scenebackgroundColor breakOutScene.textColor = textColor breakOutScene.paddleColor = paddleColor breakOutScene.ballColor = ballColor breakOutScene.blockColors = blockColors super.init(frame: frame) layer.borderColor = UIColor.grayColor().CGColor layer.borderWidth = 1.0 presentScene(startScene) } public required init(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } public func beginRefreshing() { isRefreshing = true let doors = SKTransition.doorsOpenVerticalWithDuration(0.5) presentScene(breakOutScene, transition: doors) breakOutScene.updateLabel("Loading...") UIView.animateWithDuration(0.4, delay: 0, options: .CurveEaseInOut, animations: { () -> Void in self.scrollView.contentInset.top += self.sceneHeight }) { (_) -> Void in if self.scrollView.contentOffset.y < -60 { self.breakOutScene.reset() self.breakOutScene.start() } self.isVisible = true } } public func endRefreshing() { if (!isDragging || forceEnd) && isVisible { self.isVisible = false UIView.animateWithDuration(0.4, delay: 0, options: .CurveEaseInOut, animations: { () -> Void in self.scrollView.contentInset.top -= self.sceneHeight }) { (_) -> Void in self.isRefreshing = false self.presentScene(self.startScene) } } else { breakOutScene.updateLabel("Loading Finished") isRefreshing = false } } } extension BreakOutToRefreshView: UIScrollViewDelegate { public func scrollViewWillBeginDragging(scrollView: UIScrollView) { isDragging = true } public func scrollViewWillEndDragging(scrollView: UIScrollView, withVelocity velocity: CGPoint, targetContentOffset: UnsafeMutablePointer<CGPoint>) { isDragging = false if !isRefreshing && scrollView.contentOffset.y + scrollView.contentInset.top < -sceneHeight { beginRefreshing() targetContentOffset.memory.y = -scrollView.contentInset.top delegate?.refreshViewDidRefresh(self) } if !isRefreshing { endRefreshing() } } public func scrollViewDidScroll(scrollView: UIScrollView) { let yPosition = sceneHeight - (-scrollView.contentInset.top-scrollView.contentOffset.y)*2 breakOutScene.moveHandle(yPosition) } } class BreakOutScene: SKScene, SKPhysicsContactDelegate { let ballName = "ball" let paddleName = "paddle" let blockName = "block" let backgroundLabelName = "backgroundLabel" let ballCategory : UInt32 = 0x1 << 0 let backCategory : UInt32 = 0x1 << 1 let blockCategory : UInt32 = 0x1 << 2 let paddleCategory : UInt32 = 0x1 << 3 var contentCreated = false var isStarted = false var scenebackgroundColor: UIColor! var textColor: UIColor! var paddleColor: UIColor! var ballColor: UIColor! var blockColors: [UIColor]! override func didMoveToView(view: SKView) { super.didMoveToView(view) if !contentCreated { createSceneContents() contentCreated = true } } override func update(currentTime: NSTimeInterval) { guard let ball = self.childNodeWithName(ballName) as? SKSpriteNode, let physicsBody = ball.physicsBody else { return; } let maxSpeed: CGFloat = 600.0 let speed = sqrt(physicsBody.velocity.dx * physicsBody.velocity.dx + physicsBody.velocity.dy * physicsBody.velocity.dy) if speed > maxSpeed { physicsBody.linearDamping = 0.4 } else { physicsBody.linearDamping = 0.0 } } func createSceneContents() { physicsWorld.gravity = CGVectorMake(0.0, 0.0) physicsWorld.contactDelegate = self backgroundColor = scenebackgroundColor scaleMode = .AspectFit physicsBody = SKPhysicsBody(edgeLoopFromRect: frame) physicsBody?.restitution = 1.0 physicsBody?.friction = 0.0 name = "scene" let back = SKNode() back.physicsBody = SKPhysicsBody(edgeFromPoint: CGPointMake(frame.size.width - 1, 0), toPoint: CGPointMake(frame.size.width - 1, frame.size.height)) back.physicsBody?.categoryBitMask = backCategory addChild(back) createLoadingLabelNode() let paddle = createPaddle() paddle.position = CGPoint(x: frame.size.width-30.0, y: CGRectGetMidY(frame)) addChild(paddle) createBall() createBlocks() } func createPaddle() -> SKSpriteNode { let paddle = SKSpriteNode(color: paddleColor, size: CGSize(width: 5, height: 30)) paddle.physicsBody = SKPhysicsBody(rectangleOfSize: paddle.size) paddle.physicsBody?.dynamic = false paddle.physicsBody?.restitution = 1.0 paddle.physicsBody?.friction = 0.0 paddle.name = paddleName return paddle } func createBlocks() { for i in 0..<3 { var color = blockColors.count > 0 ? blockColors[0] : UIColor(white: 0.2, alpha: 1.0) if i == 1 { color = blockColors.count > 1 ? blockColors[1] : UIColor(white: 0.4, alpha: 1.0) } else if i == 2 { color = blockColors.count > 2 ? blockColors[2] : UIColor(white: 0.6, alpha: 1.0) } for j in 0..<5 { let block = SKSpriteNode(color: color, size: CGSize(width: 5, height: 19)) block.position = CGPoint(x: 20+CGFloat(i)*6, y: CGFloat(j)*20 + 10) block.name = blockName block.physicsBody = SKPhysicsBody(rectangleOfSize: block.size) block.physicsBody?.categoryBitMask = blockCategory block.physicsBody?.allowsRotation = false block.physicsBody?.restitution = 1.0 block.physicsBody?.friction = 0.0 block.physicsBody?.dynamic = false addChild(block) } } } func removeBlocks() { var node = childNodeWithName(blockName) while (node != nil) { node?.removeFromParent() node = childNodeWithName(blockName) } } func createBall() { let ball = SKSpriteNode(color: ballColor, size: CGSize(width: 8, height: 8)) ball.position = CGPoint(x: frame.size.width - 30.0 - ball.size.width, y: CGRectGetHeight(frame)*CGFloat(arc4random())/CGFloat(UINT32_MAX)) ball.name = ballName ball.physicsBody = SKPhysicsBody(circleOfRadius: ceil(ball.size.width/2.0)) ball.physicsBody?.usesPreciseCollisionDetection = true ball.physicsBody?.categoryBitMask = ballCategory ball.physicsBody?.contactTestBitMask = blockCategory | paddleCategory | backCategory ball.physicsBody?.allowsRotation = false ball.physicsBody?.linearDamping = 0.0 ball.physicsBody?.restitution = 1.0 ball.physicsBody?.friction = 0.0 addChild(ball) } func removeBall() { if let ball = childNodeWithName(ballName) { ball.removeFromParent() } } func createLoadingLabelNode() { let loadingLabelNode = SKLabelNode(text: "Loading...") loadingLabelNode.fontColor = textColor loadingLabelNode.fontSize = 20 loadingLabelNode.position = CGPoint(x: CGRectGetMidX(frame), y: CGRectGetMidY(frame)) loadingLabelNode.name = backgroundLabelName addChild(loadingLabelNode) } func reset() { removeBlocks() createBlocks() removeBall() createBall() } func start() { isStarted = true let ball = childNodeWithName(ballName) ball?.physicsBody?.applyImpulse(CGVector(dx: -0.5, dy: 0.2)) } func updateLabel(text: String) { if let label: SKLabelNode = childNodeWithName(backgroundLabelName) as? SKLabelNode { label.text = text } } func moveHandle(value: CGFloat) { let paddle = childNodeWithName(paddleName) paddle?.position.y = value } func didEndContact(contact: SKPhysicsContact) { var ballBody: SKPhysicsBody? var otherBody: SKPhysicsBody? if contact.bodyA.categoryBitMask < contact.bodyB.categoryBitMask { ballBody = contact.bodyA otherBody = contact.bodyB } else { ballBody = contact.bodyB otherBody = contact.bodyA } if ((otherBody?.categoryBitMask ?? 0) == backCategory) { reset() start() } else if ballBody!.categoryBitMask & ballCategory != 0 { let minimalXVelocity = CGFloat(20.0) let minimalYVelocity = CGFloat(20.0) var velocity = ballBody!.velocity as CGVector if velocity.dx > -minimalXVelocity && velocity.dx <= 0 { velocity.dx = -minimalXVelocity-1 } else if velocity.dx > 0 && velocity.dx < minimalXVelocity { velocity.dx = minimalXVelocity+1 } if velocity.dy > -minimalYVelocity && velocity.dy <= 0 { velocity.dy = -minimalYVelocity-1 } else if velocity.dy > 0 && velocity.dy < minimalYVelocity { velocity.dy = minimalYVelocity+1 } ballBody?.velocity = velocity } if let body = otherBody where (body.categoryBitMask & blockCategory != 0) && body.categoryBitMask == blockCategory { body.node?.removeFromParent() if isGameWon() { reset() start() } } } func isGameWon() -> Bool { var numberOfBricks = 0 self.enumerateChildNodesWithName(blockName) { node, stop in numberOfBricks = numberOfBricks + 1 } return numberOfBricks == 0 } } class StartScene: SKScene { var contentCreated = false var textColor = SKColor.blackColor() { didSet { self.startLabelNode.fontColor = textColor self.descriptionLabelNode.fontColor = textColor } } lazy var startLabelNode: SKLabelNode = { let startNode = SKLabelNode(text: "Pull to Break Out!") startNode.fontColor = self.textColor startNode.fontSize = 20 startNode.position = CGPoint(x: CGRectGetMidX(self.frame), y: CGRectGetMidY(self.frame)) startNode.name = "start" return startNode }() lazy var descriptionLabelNode: SKLabelNode = { let descriptionNode = SKLabelNode(text: "Scroll to move handle") descriptionNode.fontColor = self.textColor descriptionNode.fontSize = 17 descriptionNode.position = CGPoint(x: CGRectGetMidX(self.frame), y: CGRectGetMidY(self.frame)-20) descriptionNode.name = "description" return descriptionNode }() override func didMoveToView(view: SKView) { super.didMoveToView(view) if !contentCreated { createSceneContents() contentCreated = true } } func createSceneContents() { scaleMode = .AspectFit addChild(startLabelNode) addChild(descriptionLabelNode) } }
mit
8509e85d29d524f57429d84e866dcc90
28.720779
151
0.690846
4.266936
false
false
false
false
kesun421/firefox-ios
Providers/Profile.swift
1
52268
/* 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/. */ // IMPORTANT!: Please take into consideration when adding new imports to // this file that it is utilized by external components besides the core // application (i.e. App Extensions). Introducing new dependencies here // may have unintended negative consequences for App Extensions such as // increased startup times which may lead to termination by the OS. import Account import Shared import Storage import Sync import XCGLogger import SwiftKeychainWrapper import Deferred // Import these dependencies ONLY for the main `Client` application target. #if MOZ_TARGET_CLIENT import SwiftyJSON import SyncTelemetry #endif // Import these dependencies for ALL targets *EXCEPT* `NotificationService`. #if !MOZ_TARGET_NOTIFICATIONSERVICE import ReadingList #endif private let log = Logger.syncLogger public let NotificationProfileDidStartSyncing = Notification.Name("NotificationProfileDidStartSyncing") public let NotificationProfileDidFinishSyncing = Notification.Name("NotificationProfileDidFinishSyncing") public let ProfileRemoteTabsSyncDelay: TimeInterval = 0.1 public protocol SyncManager { var isSyncing: Bool { get } var lastSyncFinishTime: Timestamp? { get set } var syncDisplayState: SyncDisplayState? { get } func hasSyncedHistory() -> Deferred<Maybe<Bool>> func hasSyncedLogins() -> Deferred<Maybe<Bool>> func syncClients() -> SyncResult func syncClientsThenTabs() -> SyncResult func syncHistory() -> SyncResult func syncLogins() -> SyncResult func mirrorBookmarks() -> SyncResult @discardableResult func syncEverything(why: SyncReason) -> Success func syncNamedCollections(why: SyncReason, names: [String]) -> Success // The simplest possible approach. func beginTimedSyncs() func endTimedSyncs() func applicationDidEnterBackground() func applicationDidBecomeActive() func onNewProfile() @discardableResult func onRemovedAccount(_ account: FirefoxAccount?) -> Success @discardableResult func onAddedAccount() -> Success } typealias SyncFunction = (SyncDelegate, Prefs, Ready, SyncReason) -> SyncResult class ProfileFileAccessor: FileAccessor { convenience init(profile: Profile) { self.init(localName: profile.localName()) } init(localName: String) { let profileDirName = "profile.\(localName)" // Bug 1147262: First option is for device, second is for simulator. var rootPath: String let sharedContainerIdentifier = AppInfo.sharedContainerIdentifier if let url = FileManager.default.containerURL(forSecurityApplicationGroupIdentifier: sharedContainerIdentifier) { rootPath = url.path } else { log.error("Unable to find the shared container. Defaulting profile location to ~/Documents instead.") rootPath = (NSSearchPathForDirectoriesInDomains(FileManager.SearchPathDirectory.documentDirectory, FileManager.SearchPathDomainMask.userDomainMask, true)[0]) } super.init(rootPath: URL(fileURLWithPath: rootPath).appendingPathComponent(profileDirName).path) } } class CommandStoringSyncDelegate: SyncDelegate { let profile: Profile init(profile: Profile) { self.profile = profile } public func displaySentTab(for url: URL, title: String, from deviceName: String?) { let item = ShareItem(url: url.absoluteString, title: title, favicon: nil) _ = self.profile.queue.addToQueue(item) } } /** * This exists because the Sync code is extension-safe, and thus doesn't get * direct access to UIApplication.sharedApplication, which it would need to * display a notification. * This will also likely be the extension point for wipes, resets, and * getting access to data sources during a sync. */ let TabSendURLKey = "TabSendURL" let TabSendTitleKey = "TabSendTitle" let TabSendCategory = "TabSendCategory" enum SentTabAction: String { case view = "TabSendViewAction" case bookmark = "TabSendBookmarkAction" case readingList = "TabSendReadingListAction" } /** * A Profile manages access to the user's data. */ protocol Profile: class { var bookmarks: BookmarksModelFactorySource & KeywordSearchSource & ShareToDestination & SyncableBookmarks & LocalItemSource & MirrorItemSource { get } // var favicons: Favicons { get } var prefs: Prefs { get } var queue: TabQueue { get } var searchEngines: SearchEngines { get } var files: FileAccessor { get } var history: BrowserHistory & SyncableHistory & ResettableSyncStorage { get } var metadata: Metadata { get } var recommendations: HistoryRecommendations { get } var favicons: Favicons { get } var logins: BrowserLogins & SyncableLogins & ResettableSyncStorage { get } var certStore: CertStore { get } var recentlyClosedTabs: ClosedTabsStore { get } var panelDataObservers: PanelDataObservers { get } #if !MOZ_TARGET_NOTIFICATIONSERVICE var readingList: ReadingListService? { get } #endif var isShutdown: Bool { get } func shutdown() func reopen() // I got really weird EXC_BAD_ACCESS errors on a non-null reference when I made this a getter. // Similar to <http://stackoverflow.com/questions/26029317/exc-bad-access-when-indirectly-accessing-inherited-member-in-swift>. func localName() -> String // URLs and account configuration. var accountConfiguration: FirefoxAccountConfiguration { get } // Do we have an account at all? func hasAccount() -> Bool // Do we have an account that (as far as we know) is in a syncable state? func hasSyncableAccount() -> Bool func getAccount() -> FirefoxAccount? func removeAccount() func setAccount(_ account: FirefoxAccount) func flushAccount() func getClients() -> Deferred<Maybe<[RemoteClient]>> func getClientsAndTabs() -> Deferred<Maybe<[ClientAndTabs]>> func getCachedClientsAndTabs() -> Deferred<Maybe<[ClientAndTabs]>> @discardableResult func storeTabs(_ tabs: [RemoteTab]) -> Deferred<Maybe<Int>> func sendItems(_ items: [ShareItem], toClients clients: [RemoteClient]) -> Deferred<Maybe<SyncStatus>> var syncManager: SyncManager! { get } var isChinaEdition: Bool { get } } fileprivate let PrefKeyClientID = "PrefKeyClientID" extension Profile { var clientID: String { let clientID: String if let id = prefs.stringForKey(PrefKeyClientID) { clientID = id } else { clientID = UUID().uuidString prefs.setString(clientID, forKey: PrefKeyClientID) } return clientID } } open class BrowserProfile: Profile { fileprivate let name: String fileprivate let keychain: KeychainWrapper var isShutdown = false internal let files: FileAccessor let db: BrowserDB let loginsDB: BrowserDB var syncManager: SyncManager! private static var loginsKey: String? { let key = "sqlcipher.key.logins.db" let keychain = KeychainWrapper.sharedAppContainerKeychain keychain.ensureStringItemAccessibility(.afterFirstUnlock, forKey: key) if keychain.hasValue(forKey: key) { return keychain.string(forKey: key) } let Length: UInt = 256 let secret = Bytes.generateRandomBytes(Length).base64EncodedString keychain.set(secret, forKey: key, withAccessibility: .afterFirstUnlock) return secret } var syncDelegate: SyncDelegate? /** * N.B., BrowserProfile is used from our extensions, often via a pattern like * * BrowserProfile(…).foo.saveSomething(…) * * This can break if BrowserProfile's initializer does async work that * subsequently — and asynchronously — expects the profile to stick around: * see Bug 1218833. Be sure to only perform synchronous actions here. * * A SyncDelegate can be provided in this initializer, or once the profile is initialized. * However, if we provide it here, it's assumed that we're initializing it from the application, * and initialize the logins.db. */ init(localName: String, syncDelegate: SyncDelegate? = nil, clear: Bool = false) { log.debug("Initing profile \(localName) on thread \(Thread.current).") self.name = localName self.files = ProfileFileAccessor(localName: localName) self.keychain = KeychainWrapper.sharedAppContainerKeychain self.syncDelegate = syncDelegate if clear { do { // Remove the contents of the directory… try self.files.removeFilesInDirectory() // …then remove the directory itself. try self.files.remove("") } catch { log.info("Cannot clear profile: \(error)") } } // If the profile dir doesn't exist yet, this is first run (for this profile). The check is made here // since the DB handles will create new DBs under the new profile folder. let isNewProfile = !files.exists("") // Set up our database handles. self.loginsDB = BrowserDB(filename: "logins.db", secretKey: BrowserProfile.loginsKey, schema: LoginsSchema(), files: files) self.db = BrowserDB(filename: "browser.db", schema: BrowserSchema(), files: files) // This has to happen prior to the databases being opened, because opening them can trigger // events to which the SyncManager listens. self.syncManager = BrowserSyncManager(profile: self) let notificationCenter = NotificationCenter.default notificationCenter.addObserver(self, selector: #selector(onLocationChange(notification:)), name: NotificationOnLocationChange, object: nil) notificationCenter.addObserver(self, selector: #selector(onPageMetadataFetched(notification:)), name: NotificationOnPageMetadataFetched, object: nil) if isNewProfile { log.info("New profile. Removing old account metadata.") self.removeAccountMetadata() self.syncManager.onNewProfile() self.removeExistingAuthenticationInfo() prefs.clearAll() } // Always start by needing invalidation. // This is the same as self.history.setTopSitesNeedsInvalidation, but without the // side-effect of instantiating SQLiteHistory (and thus BrowserDB) on the main thread. prefs.setBool(false, forKey: PrefsKeys.KeyTopSitesCacheIsValid) if isChinaEdition { // Set the default homepage. prefs.setString(PrefsDefaults.ChineseHomePageURL, forKey: PrefsKeys.KeyDefaultHomePageURL) if prefs.stringForKey(PrefsKeys.KeyNewTab) == nil { prefs.setString(PrefsDefaults.ChineseNewTabDefault, forKey: PrefsKeys.KeyNewTab) } } else { // Remove the default homepage. This does not change the user's preference, // just the behaviour when there is no homepage. prefs.removeObjectForKey(PrefsKeys.KeyDefaultHomePageURL) } } func reopen() { log.debug("Reopening profile.") isShutdown = false db.reopenIfClosed() loginsDB.reopenIfClosed() } func shutdown() { log.debug("Shutting down profile.") isShutdown = true db.forceClose() loginsDB.forceClose() } @objc func onLocationChange(notification: NSNotification) { if let v = notification.userInfo!["visitType"] as? Int, let visitType = VisitType(rawValue: v), let url = notification.userInfo!["url"] as? URL, !isIgnoredURL(url), let title = notification.userInfo!["title"] as? NSString { // Only record local vists if the change notification originated from a non-private tab if !(notification.userInfo!["isPrivate"] as? Bool ?? false) { // We don't record a visit if no type was specified -- that means "ignore me". let site = Site(url: url.absoluteString, title: title as String) let visit = SiteVisit(site: site, date: Date.nowMicroseconds(), type: visitType) history.addLocalVisit(visit) } history.setTopSitesNeedsInvalidation() } else { log.debug("Ignoring navigation.") } } @objc func onPageMetadataFetched(notification: NSNotification) { let isPrivate = notification.userInfo?["isPrivate"] as? Bool ?? true guard !isPrivate else { log.debug("Private mode - Ignoring page metadata.") return } guard let pageURL = notification.userInfo?["tabURL"] as? URL, let pageMetadata = notification.userInfo?["pageMetadata"] as? PageMetadata else { log.debug("Metadata notification doesn't contain any metadata!") return } let defaultMetadataTTL: UInt64 = 3 * 24 * 60 * 60 * 1000 // 3 days for the metadata to live self.metadata.storeMetadata(pageMetadata, forPageURL: pageURL, expireAt: defaultMetadataTTL + Date.now()) } deinit { log.debug("Deiniting profile \(self.localName).") self.syncManager.endTimedSyncs() } func localName() -> String { return name } lazy var queue: TabQueue = { withExtendedLifetime(self.history) { return SQLiteQueue(db: self.db) } }() /** * Favicons, history, and bookmarks are all stored in one intermeshed * collection of tables. * * Any other class that needs to access any one of these should ensure * that this is initialized first. */ fileprivate lazy var places: BrowserHistory & Favicons & SyncableHistory & ResettableSyncStorage & HistoryRecommendations = { return SQLiteHistory(db: self.db, prefs: self.prefs) }() var favicons: Favicons { return self.places } var history: BrowserHistory & SyncableHistory & ResettableSyncStorage { return self.places } lazy var panelDataObservers: PanelDataObservers = { return PanelDataObservers(profile: self) }() lazy var metadata: Metadata = { return SQLiteMetadata(db: self.db) }() var recommendations: HistoryRecommendations { return self.places } lazy var bookmarks: BookmarksModelFactorySource & KeywordSearchSource & ShareToDestination & SyncableBookmarks & LocalItemSource & MirrorItemSource = { // Make sure the rest of our tables are initialized before we try to read them! // This expression is for side-effects only. withExtendedLifetime(self.places) { return MergedSQLiteBookmarks(db: self.db) } }() lazy var mirrorBookmarks: BookmarkBufferStorage & BufferItemSource = { // Yeah, this is lazy. Sorry. return self.bookmarks as! MergedSQLiteBookmarks }() lazy var searchEngines: SearchEngines = { return SearchEngines(prefs: self.prefs, files: self.files) }() func makePrefs() -> Prefs { return NSUserDefaultsPrefs(prefix: self.localName()) } lazy var prefs: Prefs = { return self.makePrefs() }() #if !MOZ_TARGET_NOTIFICATIONSERVICE lazy var readingList: ReadingListService? = { return ReadingListService(profileStoragePath: self.files.rootPath as String) }() #endif lazy var remoteClientsAndTabs: RemoteClientsAndTabs & ResettableSyncStorage & AccountRemovalDelegate & RemoteDevices = { return SQLiteRemoteClientsAndTabs(db: self.db) }() lazy var certStore: CertStore = { return CertStore() }() lazy var recentlyClosedTabs: ClosedTabsStore = { return ClosedTabsStore(prefs: self.prefs) }() open func getSyncDelegate() -> SyncDelegate { return syncDelegate ?? CommandStoringSyncDelegate(profile: self) } public func getClients() -> Deferred<Maybe<[RemoteClient]>> { return self.syncManager.syncClients() >>> { self.remoteClientsAndTabs.getClients() } } public func getClientsAndTabs() -> Deferred<Maybe<[ClientAndTabs]>> { return self.syncManager.syncClientsThenTabs() >>> { self.remoteClientsAndTabs.getClientsAndTabs() } } public func getCachedClientsAndTabs() -> Deferred<Maybe<[ClientAndTabs]>> { return self.remoteClientsAndTabs.getClientsAndTabs() } func storeTabs(_ tabs: [RemoteTab]) -> Deferred<Maybe<Int>> { return self.remoteClientsAndTabs.insertOrUpdateTabs(tabs) } public func sendItems(_ items: [ShareItem], toClients clients: [RemoteClient]) -> Deferred<Maybe<SyncStatus>> { let id = DeviceInfo.clientIdentifier(self.prefs) let commands = items.map { item in SyncCommand.displayURIFromShareItem(item, asClient: id) } func notifyClients() { let deviceIDs = clients.flatMap { $0.fxaDeviceId } guard let account = self.getAccount() else { return } account.notify(deviceIDs: deviceIDs, collectionsChanged: ["clients"], reason: "sendtab") } return self.remoteClientsAndTabs.insertCommands(commands, forClients: clients) >>> { let syncStatus = self.syncManager.syncClients() syncStatus >>> notifyClients return syncStatus } } lazy var logins: BrowserLogins & SyncableLogins & ResettableSyncStorage = { return SQLiteLogins(db: self.loginsDB) }() lazy var isChinaEdition: Bool = { return Locale.current.identifier == "zh_CN" }() var accountConfiguration: FirefoxAccountConfiguration { if prefs.boolForKey("useCustomSyncService") ?? false { return CustomFirefoxAccountConfiguration(prefs: self.prefs) } if prefs.boolForKey("useChinaSyncService") ?? isChinaEdition { return ChinaEditionFirefoxAccountConfiguration() } if prefs.boolForKey("useStageSyncService") ?? false { return StageFirefoxAccountConfiguration() } return ProductionFirefoxAccountConfiguration() } fileprivate lazy var account: FirefoxAccount? = { let key = self.name + ".account" self.keychain.ensureObjectItemAccessibility(.afterFirstUnlock, forKey: key) if let dictionary = self.keychain.object(forKey: key) as? [String: AnyObject] { let account = FirefoxAccount.fromDictionary(dictionary) // Check to see if the account configuration set is a custom service // and update it to use the custom servers. if let configuration = account?.configuration as? CustomFirefoxAccountConfiguration { account?.configuration = CustomFirefoxAccountConfiguration(prefs: self.prefs) } return account } return nil }() func hasAccount() -> Bool { return account != nil } func hasSyncableAccount() -> Bool { return account?.actionNeeded == FxAActionNeeded.none } func getAccount() -> FirefoxAccount? { return account } func removeAccountMetadata() { self.prefs.removeObjectForKey(PrefsKeys.KeyLastRemoteTabSyncTime) self.keychain.removeObject(forKey: self.name + ".account") } func removeExistingAuthenticationInfo() { self.keychain.setAuthenticationInfo(nil) } func removeAccount() { let old = self.account removeAccountMetadata() self.account = nil // Tell any observers that our account has changed. NotificationCenter.default.post(name: NotificationFirefoxAccountChanged, object: nil) // Trigger cleanup. Pass in the account in case we want to try to remove // client-specific data from the server. self.syncManager.onRemovedAccount(old) } func setAccount(_ account: FirefoxAccount) { self.account = account flushAccount() // tell any observers that our account has changed DispatchQueue.main.async { // Many of the observers for this notifications are on the main thread, // so we should post the notification there, just in case we're not already // on the main thread. let userInfo = [NotificationUserInfoKeyHasSyncableAccount: self.hasSyncableAccount()] NotificationCenter.default.post(name: NotificationFirefoxAccountChanged, object: nil, userInfo: userInfo) } self.syncManager.onAddedAccount() } func flushAccount() { if let account = account { self.keychain.set(account.dictionary() as NSCoding, forKey: name + ".account", withAccessibility: .afterFirstUnlock) } } // Extends NSObject so we can use timers. public class BrowserSyncManager: NSObject, SyncManager, CollectionChangedNotifier { // We shouldn't live beyond our containing BrowserProfile, either in the main app or in // an extension. // But it's possible that we'll finish a side-effect sync after we've ditched the profile // as a whole, so we hold on to our Prefs, potentially for a little while longer. This is // safe as a strong reference, because there's no cycle. unowned fileprivate let profile: BrowserProfile fileprivate let prefs: Prefs let FifteenMinutes = TimeInterval(60 * 15) let OneMinute = TimeInterval(60) fileprivate var syncTimer: Timer? fileprivate var backgrounded: Bool = true public func applicationDidEnterBackground() { self.backgrounded = true self.endTimedSyncs() } public func applicationDidBecomeActive() { self.backgrounded = false guard self.profile.hasSyncableAccount() else { return } self.beginTimedSyncs() // Sync now if it's been more than our threshold. let now = Date.now() let then = self.lastSyncFinishTime ?? 0 guard now >= then else { log.debug("Time was modified since last sync.") self.syncEverythingSoon() return } let since = now - then log.debug("\(since)msec since last sync.") if since > SyncConstants.SyncOnForegroundMinimumDelayMillis { self.syncEverythingSoon() } } /** * Locking is managed by syncSeveral. Make sure you take and release these * whenever you do anything Sync-ey. */ fileprivate let syncLock = NSRecursiveLock() public var isSyncing: Bool { syncLock.lock() defer { syncLock.unlock() } return syncDisplayState != nil && syncDisplayState! == .inProgress } public var syncDisplayState: SyncDisplayState? // The dispatch queue for coordinating syncing and resetting the database. fileprivate let syncQueue = DispatchQueue(label: "com.mozilla.firefox.sync") fileprivate typealias EngineResults = [(EngineIdentifier, SyncStatus)] fileprivate typealias EngineTasks = [(EngineIdentifier, SyncFunction)] // Used as a task queue for syncing. fileprivate var syncReducer: AsyncReducer<EngineResults, EngineTasks>? fileprivate func beginSyncing() { notifySyncing(notification: NotificationProfileDidStartSyncing) } fileprivate func endSyncing(_ result: SyncOperationResult) { // loop through statuses and fill sync state syncLock.lock() defer { syncLock.unlock() } log.info("Ending all queued syncs.") syncDisplayState = SyncStatusResolver(engineResults: result.engineResults).resolveResults() #if MOZ_TARGET_CLIENT if let account = profile.account, canSendUsageData() { SyncPing.from(result: result, account: account, remoteClientsAndTabs: profile.remoteClientsAndTabs, prefs: prefs, why: .schedule) >>== { SyncTelemetry.send(ping: $0, docType: .sync) } } else { log.debug("Profile isn't sending usage data. Not sending sync status event.") } #endif // Dont notify if we are performing a sync in the background. This prevents more db access from happening if !self.backgrounded { notifySyncing(notification: NotificationProfileDidFinishSyncing) } syncReducer = nil } func canSendUsageData() -> Bool { return profile.prefs.boolForKey(AppConstants.PrefSendUsageData) ?? true } private func notifySyncing(notification: Notification.Name) { NotificationCenter.default.post(name: notification, object: syncDisplayState?.asObject()) } init(profile: BrowserProfile) { self.profile = profile self.prefs = profile.prefs super.init() let center = NotificationCenter.default center.addObserver(self, selector: #selector(onDatabaseWasRecreated(notification:)), name: NotificationDatabaseWasRecreated, object: nil) center.addObserver(self, selector: #selector(onLoginDidChange(_:)), name: NotificationDataLoginDidChange, object: nil) center.addObserver(self, selector: #selector(onStartSyncing(_:)), name: NotificationProfileDidStartSyncing, object: nil) center.addObserver(self, selector: #selector(onFinishSyncing(_:)), name: NotificationProfileDidFinishSyncing, object: nil) center.addObserver(self, selector: #selector(onBookmarkBufferValidated(notification:)), name: NotificationBookmarkBufferValidated, object: nil) } func onBookmarkBufferValidated(notification: NSNotification) { #if MOZ_TARGET_CLIENT // We don't send this ad hoc telemetry on the release channel. guard AppConstants.BuildChannel != AppBuildChannel.release else { return } guard profile.prefs.boolForKey(AppConstants.PrefSendUsageData) ?? true else { log.debug("Profile isn't sending usage data. Not sending bookmark event.") return } guard let validations = (notification.object as? Box<[String: Bool]>)?.value else { log.warning("Notification didn't have validations.") return } let attempt: Int32 = self.prefs.intForKey("bookmarkvalidationattempt") ?? 1 self.prefs.setInt(attempt + 1, forKey: "bookmarkvalidationattempt") // Capture the buffer count ASAP, not in the delayed op, because the merge could wipe it! let bufferRows = (self.profile.bookmarks as? MergedSQLiteBookmarks)?.synchronousBufferCount() self.doInBackgroundAfter(300) { self.profile.remoteClientsAndTabs.getClientGUIDs() >>== { clients in // We would love to include the version and OS etc. of each remote client, // but we don't store that information. For now, just do a count. let clientCount = clients.count let id = DeviceInfo.clientIdentifier(self.prefs) let ping = makeAdHocBookmarkMergePing(Bundle.main, clientID: id, attempt: attempt, bufferRows: bufferRows, valid: validations, clientCount: clientCount) let payload = ping.stringValue log.debug("Payload is: \(payload)") guard let body = payload.data(using: String.Encoding.utf8) else { log.debug("Invalid JSON!") return } guard let url = URL(string: "https://mozilla-anonymous-sync-metrics.moo.mx/post/bookmarkvalidation") else { return } var request = URLRequest(url: url) request.httpMethod = "POST" request.httpBody = body request.setValue("application/json", forHTTPHeaderField: "Content-Type") URLSession.shared.dataTask(with: request) { data, response, error in let httpResponse = response as? HTTPURLResponse log.debug("Bookmark validation upload response: \(httpResponse?.statusCode ?? -1).") } } } #endif } private func handleRecreationOfDatabaseNamed(name: String?) -> Success { let loginsCollections = ["passwords"] let browserCollections = ["bookmarks", "history", "tabs"] let dbName = name ?? "<all>" switch dbName { case "<all>": return self.locallyResetCollections(loginsCollections + browserCollections) case "logins.db": return self.locallyResetCollections(loginsCollections) case "browser.db": return self.locallyResetCollections(browserCollections) default: log.debug("Unknown database \(dbName).") return succeed() } } func doInBackgroundAfter(_ millis: Int64, _ block: @escaping () -> Void) { let queue = DispatchQueue.global(qos: DispatchQoS.background.qosClass) //Pretty ambiguous here. I'm thinking .now was DispatchTime.now() and not Date.now() queue.asyncAfter(deadline: DispatchTime.now() + DispatchTimeInterval.milliseconds(Int(millis)), execute: block) } @objc func onDatabaseWasRecreated(notification: NSNotification) { log.debug("Database was recreated.") let name = notification.object as? String log.debug("Database was \(name ?? "nil").") // We run this in the background after a few hundred milliseconds; // it doesn't really matter when it runs, so long as it doesn't // happen in the middle of a sync. let resetDatabase = { return self.handleRecreationOfDatabaseNamed(name: name) >>== { log.debug("Reset of \(name ?? "nil") done") } } self.doInBackgroundAfter(300) { self.syncLock.lock() defer { self.syncLock.unlock() } // If we're syncing already, then wait for sync to end, // then reset the database on the same serial queue. if let reducer = self.syncReducer, !reducer.isFilled { reducer.terminal.upon { _ in self.syncQueue.async(execute: resetDatabase) } } else { // Otherwise, reset the database on the sync queue now // Sync can't start while this is still going on. self.syncQueue.async(execute: resetDatabase) } } } // Simple in-memory rate limiting. var lastTriggeredLoginSync: Timestamp = 0 @objc func onLoginDidChange(_ notification: NSNotification) { log.debug("Login did change.") if (Date.now() - lastTriggeredLoginSync) > OneMinuteInMilliseconds { lastTriggeredLoginSync = Date.now() // Give it a few seconds. // Trigger on the main queue. The bulk of the sync work runs in the background. let greenLight = self.greenLight() DispatchQueue.main.asyncAfter(deadline: .now() + .milliseconds(SyncConstants.SyncDelayTriggered)) { if greenLight() { self.syncLogins() } } } } public var lastSyncFinishTime: Timestamp? { get { return self.prefs.timestampForKey(PrefsKeys.KeyLastSyncFinishTime) } set(value) { if let value = value { self.prefs.setTimestamp(value, forKey: PrefsKeys.KeyLastSyncFinishTime) } else { self.prefs.removeObjectForKey(PrefsKeys.KeyLastSyncFinishTime) } } } @objc func onStartSyncing(_ notification: NSNotification) { syncLock.lock() defer { syncLock.unlock() } syncDisplayState = .inProgress } @objc func onFinishSyncing(_ notification: NSNotification) { syncLock.lock() defer { syncLock.unlock() } if let syncState = syncDisplayState, syncState == .good { self.lastSyncFinishTime = Date.now() } } var prefsForSync: Prefs { return self.prefs.branch("sync") } public func onAddedAccount() -> Success { // Only sync if we're green lit. This makes sure that we don't sync unverified accounts. guard self.profile.hasSyncableAccount() else { return succeed() } self.beginTimedSyncs() return self.syncEverything(why: .didLogin) } func locallyResetCollections(_ collections: [String]) -> Success { return walk(collections, f: self.locallyResetCollection) } func locallyResetCollection(_ collection: String) -> Success { switch collection { case "bookmarks": return BufferingBookmarksSynchronizer.resetSynchronizerWithStorage(self.profile.bookmarks, basePrefs: self.prefsForSync, collection: "bookmarks") case "clients": fallthrough case "tabs": // Because clients and tabs share storage, and thus we wipe data for both if we reset either, // we reset the prefs for both at the same time. return TabsSynchronizer.resetClientsAndTabsWithStorage(self.profile.remoteClientsAndTabs, basePrefs: self.prefsForSync) case "history": return HistorySynchronizer.resetSynchronizerWithStorage(self.profile.history, basePrefs: self.prefsForSync, collection: "history") case "passwords": return LoginsSynchronizer.resetSynchronizerWithStorage(self.profile.logins, basePrefs: self.prefsForSync, collection: "passwords") case "forms": log.debug("Requested reset for forms, but this client doesn't sync them yet.") return succeed() case "addons": log.debug("Requested reset for addons, but this client doesn't sync them.") return succeed() case "prefs": log.debug("Requested reset for prefs, but this client doesn't sync them.") return succeed() default: log.warning("Asked to reset collection \(collection), which we don't know about.") return succeed() } } public func onNewProfile() { SyncStateMachine.clearStateFromPrefs(self.prefsForSync) } public func onRemovedAccount(_ account: FirefoxAccount?) -> Success { let profile = self.profile // Run these in order, because they might write to the same DB! let remove = [ profile.history.onRemovedAccount, profile.remoteClientsAndTabs.onRemovedAccount, profile.logins.onRemovedAccount, profile.bookmarks.onRemovedAccount, ] let clearPrefs: () -> Success = { withExtendedLifetime(self) { // Clear prefs after we're done clearing everything else -- just in case // one of them needs the prefs and we race. Clear regardless of success // or failure. // This will remove keys from the Keychain if they exist, as well // as wiping the Sync prefs. SyncStateMachine.clearStateFromPrefs(self.prefsForSync) } return succeed() } return accumulate(remove) >>> clearPrefs } fileprivate func repeatingTimerAtInterval(_ interval: TimeInterval, selector: Selector) -> Timer { return Timer.scheduledTimer(timeInterval: interval, target: self, selector: selector, userInfo: nil, repeats: true) } public func beginTimedSyncs() { if self.syncTimer != nil { log.debug("Already running sync timer.") return } let interval = FifteenMinutes let selector = #selector(BrowserSyncManager.syncOnTimer) log.debug("Starting sync timer.") self.syncTimer = repeatingTimerAtInterval(interval, selector: selector) } /** * The caller is responsible for calling this on the same thread on which it called * beginTimedSyncs. */ public func endTimedSyncs() { if let t = self.syncTimer { log.debug("Stopping sync timer.") self.syncTimer = nil t.invalidate() } } fileprivate func syncClientsWithDelegate(_ delegate: SyncDelegate, prefs: Prefs, ready: Ready, why: SyncReason) -> SyncResult { log.debug("Syncing clients to storage.") let clientSynchronizer = ready.synchronizer(ClientsSynchronizer.self, delegate: delegate, prefs: prefs, why: why) return clientSynchronizer.synchronizeLocalClients(self.profile.remoteClientsAndTabs, withServer: ready.client, info: ready.info, notifier: self) >>== { result in guard case .completed = result else { return deferMaybe(result) } guard let account = self.profile.account else { return deferMaybe(result) } log.debug("Updating FxA devices list.") return account.updateFxADevices(remoteDevices: self.profile.remoteClientsAndTabs).bind { _ in return deferMaybe(result) } } } fileprivate func syncTabsWithDelegate(_ delegate: SyncDelegate, prefs: Prefs, ready: Ready, why: SyncReason) -> SyncResult { let storage = self.profile.remoteClientsAndTabs let tabSynchronizer = ready.synchronizer(TabsSynchronizer.self, delegate: delegate, prefs: prefs, why: why) return tabSynchronizer.synchronizeLocalTabs(storage, withServer: ready.client, info: ready.info) } fileprivate func syncHistoryWithDelegate(_ delegate: SyncDelegate, prefs: Prefs, ready: Ready, why: SyncReason) -> SyncResult { log.debug("Syncing history to storage.") let historySynchronizer = ready.synchronizer(HistorySynchronizer.self, delegate: delegate, prefs: prefs, why: why) return historySynchronizer.synchronizeLocalHistory(self.profile.history, withServer: ready.client, info: ready.info, greenLight: self.greenLight()) } fileprivate func syncLoginsWithDelegate(_ delegate: SyncDelegate, prefs: Prefs, ready: Ready, why: SyncReason) -> SyncResult { log.debug("Syncing logins to storage.") let loginsSynchronizer = ready.synchronizer(LoginsSynchronizer.self, delegate: delegate, prefs: prefs, why: why) return loginsSynchronizer.synchronizeLocalLogins(self.profile.logins, withServer: ready.client, info: ready.info) } fileprivate func mirrorBookmarksWithDelegate(_ delegate: SyncDelegate, prefs: Prefs, ready: Ready, why: SyncReason) -> SyncResult { log.debug("Synchronizing server bookmarks to storage.") let bookmarksMirrorer = ready.synchronizer(BufferingBookmarksSynchronizer.self, delegate: delegate, prefs: prefs, why: why) return bookmarksMirrorer.synchronizeBookmarksToStorage(self.profile.bookmarks, usingBuffer: self.profile.mirrorBookmarks, withServer: ready.client, info: ready.info, greenLight: self.greenLight(), remoteClientsAndTabs: self.profile.remoteClientsAndTabs) } func takeActionsOnEngineStateChanges<T: EngineStateChanges>(_ changes: T) -> Deferred<Maybe<T>> { var needReset = Set<String>(changes.collectionsThatNeedLocalReset()) needReset.formUnion(changes.enginesDisabled()) needReset.formUnion(changes.enginesEnabled()) if needReset.isEmpty { log.debug("No collections need reset. Moving on.") return deferMaybe(changes) } // needReset needs at most one of clients and tabs, because we reset them // both if either needs reset. This is strictly an optimization to avoid // doing duplicate work. if needReset.contains("clients") { if needReset.remove("tabs") != nil { log.debug("Already resetting clients (and tabs); not bothering to also reset tabs again.") } } return walk(Array(needReset), f: self.locallyResetCollection) >>> effect(changes.clearLocalCommands) >>> always(changes) } /** * Runs the single provided synchronization function and returns its status. */ fileprivate func sync(_ label: EngineIdentifier, function: @escaping SyncFunction) -> SyncResult { return syncSeveral(why: .user, synchronizers: [(label, function)]) >>== { statuses in let status = statuses.find { label == $0.0 }?.1 return deferMaybe(status ?? .notStarted(.unknown)) } } /** * Convenience method for syncSeveral([(EngineIdentifier, SyncFunction)]) */ private func syncSeveral(why: SyncReason, synchronizers: (EngineIdentifier, SyncFunction)...) -> Deferred<Maybe<[(EngineIdentifier, SyncStatus)]>> { return syncSeveral(why: why, synchronizers: synchronizers) } /** * Runs each of the provided synchronization functions with the same inputs. * Returns an array of IDs and SyncStatuses at least length as the input. * The statuses returned will be a superset of the ones that are requested here. * While a sync is ongoing, each engine from successive calls to this method will only be called once. */ fileprivate func syncSeveral(why: SyncReason, synchronizers: [(EngineIdentifier, SyncFunction)]) -> Deferred<Maybe<[(EngineIdentifier, SyncStatus)]>> { syncLock.lock() defer { syncLock.unlock() } guard let account = self.profile.account else { log.info("No account to sync with.") let statuses = synchronizers.map { ($0.0, SyncStatus.notStarted(.noAccount)) } return deferMaybe(statuses) } if !isSyncing { // A sync isn't already going on, so start another one. let statsSession = SyncOperationStatsSession(why: why, uid: account.uid, deviceID: account.deviceRegistration?.id) let reducer = AsyncReducer<EngineResults, EngineTasks>(initialValue: [], queue: syncQueue) { (statuses, synchronizers) in let done = Set(statuses.map { $0.0 }) let remaining = synchronizers.filter { !done.contains($0.0) } if remaining.isEmpty { log.info("Nothing left to sync") return deferMaybe(statuses) } return self.syncWith(synchronizers: remaining, account: account, statsSession: statsSession, why: why) >>== { deferMaybe(statuses + $0) } } reducer.terminal.upon { results in let result = SyncOperationResult( engineResults: results, stats: statsSession.hasStarted() ? statsSession.end() : nil ) self.endSyncing(result) } // The actual work of synchronizing doesn't start until we append // the synchronizers to the reducer below. self.syncReducer = reducer self.beginSyncing() } do { return try syncReducer!.append(synchronizers) } catch let error { log.error("Synchronizers appended after sync was finished. This is a bug. \(error)") let statuses = synchronizers.map { ($0.0, SyncStatus.notStarted(.unknown)) } return deferMaybe(statuses) } } // This SHOULD NOT be called directly: use syncSeveral instead. fileprivate func syncWith(synchronizers: [(EngineIdentifier, SyncFunction)], account: FirefoxAccount, statsSession: SyncOperationStatsSession, why: SyncReason) -> Deferred<Maybe<[(EngineIdentifier, SyncStatus)]>> { log.info("Syncing \(synchronizers.map { $0.0 })") let authState = account.syncAuthState let delegate = self.profile.getSyncDelegate() let readyDeferred = SyncStateMachine(prefs: self.prefsForSync).toReady(authState!) let function: (SyncDelegate, Prefs, Ready) -> Deferred<Maybe<[EngineStatus]>> = { delegate, syncPrefs, ready in let thunks = synchronizers.map { (i, f) in return { () -> Deferred<Maybe<EngineStatus>> in log.debug("Syncing \(i)…") return f(delegate, syncPrefs, ready, why) >>== { deferMaybe((i, $0)) } } } return accumulate(thunks) } return readyDeferred >>== self.takeActionsOnEngineStateChanges >>== { ready in statsSession.start() return function(delegate, self.prefsForSync, ready) } } @discardableResult public func syncEverything(why: SyncReason) -> Success { return self.syncSeveral( why: why, synchronizers: ("clients", self.syncClientsWithDelegate), ("tabs", self.syncTabsWithDelegate), ("logins", self.syncLoginsWithDelegate), ("bookmarks", self.mirrorBookmarksWithDelegate), ("history", self.syncHistoryWithDelegate)) >>> succeed } func syncEverythingSoon() { self.doInBackgroundAfter(SyncConstants.SyncOnForegroundAfterMillis) { log.debug("Running delayed startup sync.") self.syncEverything(why: .startup) } } /** * Allows selective sync of different collections, for use by external APIs. * Some help is given to callers who use different namespaces (specifically: `passwords` is mapped to `logins`) * and to preserve some ordering rules. */ public func syncNamedCollections(why: SyncReason, names: [String]) -> Success { // Massage the list of names into engine identifiers. let engineIdentifiers = names.map { name -> [EngineIdentifier] in switch name { case "passwords": return ["logins"] case "tabs": return ["clients", "tabs"] default: return [name] } }.flatMap { $0 } // By this time, `engineIdentifiers` may have duplicates in. We won't try and dedupe here // because `syncSeveral` will do that for us. let synchronizers: [(EngineIdentifier, SyncFunction)] = engineIdentifiers.flatMap { switch $0 { case "clients": return ("clients", self.syncClientsWithDelegate) case "tabs": return ("tabs", self.syncTabsWithDelegate) case "logins": return ("logins", self.syncLoginsWithDelegate) case "bookmarks": return ("bookmarks", self.mirrorBookmarksWithDelegate) case "history": return ("history", self.syncHistoryWithDelegate) default: return nil } } return self.syncSeveral(why: why, synchronizers: synchronizers) >>> succeed } @objc func syncOnTimer() { self.syncEverything(why: .scheduled) } public func hasSyncedHistory() -> Deferred<Maybe<Bool>> { return self.profile.history.hasSyncedHistory() } public func hasSyncedLogins() -> Deferred<Maybe<Bool>> { return self.profile.logins.hasSyncedLogins() } public func syncClients() -> SyncResult { // TODO: recognize .NotStarted. return self.sync("clients", function: syncClientsWithDelegate) } public func syncClientsThenTabs() -> SyncResult { return self.syncSeveral( why: .user, synchronizers: ("clients", self.syncClientsWithDelegate), ("tabs", self.syncTabsWithDelegate)) >>== { statuses in let status = statuses.find { "tabs" == $0.0 } return deferMaybe(status!.1) } } @discardableResult public func syncLogins() -> SyncResult { return self.sync("logins", function: syncLoginsWithDelegate) } public func syncHistory() -> SyncResult { // TODO: recognize .NotStarted. return self.sync("history", function: syncHistoryWithDelegate) } public func mirrorBookmarks() -> SyncResult { return self.sync("bookmarks", function: mirrorBookmarksWithDelegate) } /** * Return a thunk that continues to return true so long as an ongoing sync * should continue. */ func greenLight() -> () -> Bool { let start = Date.now() // Give it two minutes to run before we stop. let stopBy = start + (2 * OneMinuteInMilliseconds) log.debug("Checking green light. Backgrounded: \(self.backgrounded).") return { Date.now() < stopBy && self.profile.hasSyncableAccount() } } class NoAccountError: MaybeErrorType { var description = "No account." } public func notify(deviceIDs: [GUID], collectionsChanged collections: [String], reason: String) -> Success { guard let account = self.profile.account else { return deferMaybe(NoAccountError()) } return account.notify(deviceIDs: deviceIDs, collectionsChanged: collections, reason: reason) } public func notifyAll(collectionsChanged collections: [String], reason: String) -> Success { guard let account = self.profile.account else { return deferMaybe(NoAccountError()) } return account.notifyAll(collectionsChanged: collections, reason: reason) } } }
mpl-2.0
63e4d5dd2c9b9808cbba29a5717eb8a4
40.769784
265
0.616565
5.415483
false
false
false
false
tardieu/swift
test/Prototypes/CollectionTransformers.swift
7
39348
//===----------------------------------------------------------------------===// // // 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: %target-run-stdlib-swift // REQUIRES: executable_test // FIXME: This test runs very slowly on watchOS. // UNSUPPORTED: OS=watchos public enum ApproximateCount { case Unknown case Precise(IntMax) case Underestimate(IntMax) case Overestimate(IntMax) } public protocol ApproximateCountableSequence : Sequence { /// Complexity: amortized O(1). var approximateCount: ApproximateCount { get } } /// A collection that provides an efficient way to split its index ranges. public protocol SplittableCollection : Collection { // We need this protocol so that collections with only forward or bidirectional // traversals could customize their splitting behavior. // // FIXME: all collections with random access should conform to this protocol // automatically. /// Splits a given range of indices into a set of disjoint ranges covering /// the same elements. /// /// Complexity: amortized O(1). /// /// FIXME: should that be O(log n) to cover some strange collections? /// /// FIXME: index invalidation rules? /// /// FIXME: a better name. Users will never want to call this method /// directly. /// /// FIXME: return an optional for the common case when split() cannot /// subdivide the range further. func split(_ range: Range<Index>) -> [Range<Index>] } internal func _splitRandomAccessIndexRange< C : RandomAccessCollection >( _ elements: C, _ range: Range<C.Index> ) -> [Range<C.Index>] { let startIndex = range.lowerBound let endIndex = range.upperBound let length = elements.distance(from: startIndex, to: endIndex).toIntMax() if length < 2 { return [range] } let middle = elements.index(startIndex, offsetBy: C.IndexDistance(length / 2)) return [startIndex ..< middle, middle ..< endIndex] } /// A helper object to build a collection incrementally in an efficient way. /// /// Using a builder can be more efficient than creating an empty collection /// instance and adding elements one by one. public protocol CollectionBuilder { associatedtype Destination : Collection associatedtype Element = Destination.Iterator.Element init() /// Gives a hint about the expected approximate number of elements in the /// collection that is being built. mutating func sizeHint(_ approximateSize: Int) /// Append `element` to `self`. /// /// If a collection being built supports a user-defined order, the element is /// added at the end. /// /// Complexity: amortized O(1). mutating func append(_ element: Destination.Iterator.Element) /// Append `elements` to `self`. /// /// If a collection being built supports a user-defined order, the element is /// added at the end. /// /// Complexity: amortized O(n), where `n` is equal to `count(elements)`. mutating func append< C : Collection >(contentsOf elements: C) where C.Iterator.Element == Element /// Append elements from `otherBuilder` to `self`, emptying `otherBuilder`. /// /// Equivalent to:: /// /// self.append(contentsOf: otherBuilder.takeResult()) /// /// but is more efficient. /// /// Complexity: O(1). mutating func moveContentsOf(_ otherBuilder: inout Self) /// Build the collection from the elements that were added to this builder. /// /// Once this function is called, the builder may not be reused and no other /// methods should be called. /// /// Complexity: O(n) or better (where `n` is the number of elements that were /// added to this builder); typically O(1). mutating func takeResult() -> Destination } public protocol BuildableCollectionProtocol : Collection { associatedtype Builder : CollectionBuilder } extension Array : SplittableCollection { public func split(_ range: Range<Int>) -> [Range<Int>] { return _splitRandomAccessIndexRange(self, range) } } public struct ArrayBuilder<T> : CollectionBuilder { // FIXME: the compiler didn't complain when I remove public on 'Collection'. // File a bug. public typealias Destination = Array<T> public typealias Element = T internal var _resultParts = [[T]]() internal var _resultTail = [T]() public init() {} public mutating func sizeHint(_ approximateSize: Int) { _resultTail.reserveCapacity(approximateSize) } public mutating func append(_ element: T) { _resultTail.append(element) } public mutating func append< C : Collection >(contentsOf elements: C) where C.Iterator.Element == T { _resultTail.append(contentsOf: elements) } public mutating func moveContentsOf(_ otherBuilder: inout ArrayBuilder<T>) { // FIXME: do something smart with the capacity set in this builder and the // other builder. _resultParts.append(_resultTail) _resultTail = [] // FIXME: not O(1)! _resultParts.append(contentsOf: otherBuilder._resultParts) otherBuilder._resultParts = [] swap(&_resultTail, &otherBuilder._resultTail) } public mutating func takeResult() -> Destination { _resultParts.append(_resultTail) _resultTail = [] // FIXME: optimize. parallelize. return Array(_resultParts.joined()) } } extension Array : BuildableCollectionProtocol { public typealias Builder = ArrayBuilder<Element> } //===----------------------------------------------------------------------===// // Fork-join //===----------------------------------------------------------------------===// // As sad as it is, I think for practical performance reasons we should rewrite // the inner parts of the fork-join framework in C++. In way too many cases // than necessary Swift requires an extra allocation to pin objects in memory // for safe multithreaded access. -Dmitri import SwiftShims import SwiftPrivate import Darwin import Dispatch // FIXME: port to Linux. // XFAIL: linux // A wrapper for pthread_t with platform-independent interface. public struct _stdlib_pthread_t : Equatable, Hashable { internal let _value: pthread_t public var hashValue: Int { return _value.hashValue } } public func == (lhs: _stdlib_pthread_t, rhs: _stdlib_pthread_t) -> Bool { return lhs._value == rhs._value } public func _stdlib_pthread_self() -> _stdlib_pthread_t { return _stdlib_pthread_t(_value: pthread_self()) } struct _ForkJoinMutex { var _mutex: UnsafeMutablePointer<pthread_mutex_t> init() { _mutex = UnsafeMutablePointer.allocate(capacity: 1) if pthread_mutex_init(_mutex, nil) != 0 { fatalError("pthread_mutex_init") } } func `deinit`() { if pthread_mutex_destroy(_mutex) != 0 { fatalError("pthread_mutex_init") } _mutex.deinitialize() _mutex.deallocate(capacity: 1) } func withLock<Result>(_ body: () -> Result) -> Result { if pthread_mutex_lock(_mutex) != 0 { fatalError("pthread_mutex_lock") } let result = body() if pthread_mutex_unlock(_mutex) != 0 { fatalError("pthread_mutex_unlock") } return result } } struct _ForkJoinCond { var _cond: UnsafeMutablePointer<pthread_cond_t> init() { _cond = UnsafeMutablePointer.allocate(capacity: 1) if pthread_cond_init(_cond, nil) != 0 { fatalError("pthread_cond_init") } } func `deinit`() { if pthread_cond_destroy(_cond) != 0 { fatalError("pthread_cond_destroy") } _cond.deinitialize() _cond.deallocate(capacity: 1) } func signal() { pthread_cond_signal(_cond) } func wait(_ mutex: _ForkJoinMutex) { pthread_cond_wait(_cond, mutex._mutex) } } final class _ForkJoinOneShotEvent { var _mutex: _ForkJoinMutex = _ForkJoinMutex() var _cond: _ForkJoinCond = _ForkJoinCond() var _isSet: Bool = false init() {} deinit { _cond.`deinit`() _mutex.`deinit`() } func set() { _mutex.withLock { if !_isSet { _isSet = true _cond.signal() } } } /// Establishes a happens-before relation between calls to set() and wait(). func wait() { _mutex.withLock { while !_isSet { _cond.wait(_mutex) } } } /// If the function returns true, it establishes a happens-before relation /// between calls to set() and isSet(). func isSet() -> Bool { return _mutex.withLock { return _isSet } } } final class _ForkJoinWorkDeque<T> { // FIXME: this is just a proof-of-concept; very inefficient. // Implementation note: adding elements to the head of the deque is common in // fork-join, so _deque is stored reversed (appending to an array is cheap). // FIXME: ^ that is false for submission queues though. var _deque: ContiguousArray<T> = [] var _dequeMutex: _ForkJoinMutex = _ForkJoinMutex() init() {} deinit { precondition(_deque.isEmpty) _dequeMutex.`deinit`() } var isEmpty: Bool { return _dequeMutex.withLock { return _deque.isEmpty } } func prepend(_ element: T) { _dequeMutex.withLock { _deque.append(element) } } func tryTakeFirst() -> T? { return _dequeMutex.withLock { let result = _deque.last if _deque.count > 0 { _deque.removeLast() } return result } } func tryTakeFirstTwo() -> (T?, T?) { return _dequeMutex.withLock { let result1 = _deque.last if _deque.count > 0 { _deque.removeLast() } let result2 = _deque.last if _deque.count > 0 { _deque.removeLast() } return (result1, result2) } } func append(_ element: T) { _dequeMutex.withLock { _deque.insert(element, at: 0) } } func tryTakeLast() -> T? { return _dequeMutex.withLock { let result = _deque.first if _deque.count > 0 { _deque.remove(at: 0) } return result } } func takeAll() -> ContiguousArray<T> { return _dequeMutex.withLock { let result = _deque _deque = [] return result } } func tryReplace( _ value: T, makeReplacement: @escaping () -> T, isEquivalent: @escaping (T, T) -> Bool ) -> Bool { return _dequeMutex.withLock { for i in _deque.indices { if isEquivalent(_deque[i], value) { _deque[i] = makeReplacement() return true } } return false } } } final class _ForkJoinWorkerThread { internal var _tid: _stdlib_pthread_t? internal let _pool: ForkJoinPool internal let _submissionQueue: _ForkJoinWorkDeque<ForkJoinTaskBase> internal let _workDeque: _ForkJoinWorkDeque<ForkJoinTaskBase> internal init( _pool: ForkJoinPool, submissionQueue: _ForkJoinWorkDeque<ForkJoinTaskBase>, workDeque: _ForkJoinWorkDeque<ForkJoinTaskBase> ) { self._tid = nil self._pool = _pool self._submissionQueue = submissionQueue self._workDeque = workDeque } internal func startAsync() { var queue: DispatchQueue? if #available(OSX 10.10, iOS 8.0, *) { queue = DispatchQueue.global(qos: .background) } else { queue = DispatchQueue.global(priority: .background) } queue!.async { self._thread() } } internal func _thread() { print("_ForkJoinWorkerThread begin") _tid = _stdlib_pthread_self() outer: while !_workDeque.isEmpty || !_submissionQueue.isEmpty { _pool._addRunningThread(self) while true { if _pool._tryStopThread() { print("_ForkJoinWorkerThread detected too many threads") _pool._removeRunningThread(self) _pool._submitTasksToRandomWorkers(_workDeque.takeAll()) _pool._submitTasksToRandomWorkers(_submissionQueue.takeAll()) print("_ForkJoinWorkerThread end") return } // Process tasks in FIFO order: first the work queue, then the // submission queue. if let task = _workDeque.tryTakeFirst() { task._run() continue } if let task = _submissionQueue.tryTakeFirst() { task._run() continue } print("_ForkJoinWorkerThread stealing tasks") if let task = _pool._stealTask() { task._run() continue } // FIXME: steal from submission queues? break } _pool._removeRunningThread(self) } assert(_workDeque.isEmpty) assert(_submissionQueue.isEmpty) _ = _pool._totalThreads.fetchAndAdd(-1) print("_ForkJoinWorkerThread end") } internal func _forkTask(_ task: ForkJoinTaskBase) { // Try to inflate the pool. if !_pool._tryCreateThread({ task }) { _workDeque.prepend(task) } } internal func _waitForTask(_ task: ForkJoinTaskBase) { while true { if task._isComplete() { return } // If the task is in work queue of the current thread, run the task. if _workDeque.tryReplace( task, makeReplacement: { ForkJoinTask<()>() {} }, isEquivalent: { $0 === $1 }) { // We found the task. Run it in-place. task._run() return } // FIXME: also check the submission queue, maybe the task is there? // FIXME: try to find the task in other threads' queues. // FIXME: try to find tasks that were forked from this task in other // threads' queues. Help thieves by stealing those tasks back. // At this point, we can't do any work to help with running this task. // We can't start new work either (if we do, we might end up creating // more in-flight work than we can chew, and crash with out-of-memory // errors). _pool._compensateForBlockedWorkerThread() { task._blockingWait() // FIXME: do a timed wait, and retry stealing. } } } } internal protocol _Future { associatedtype Result /// Establishes a happens-before relation between completing the future and /// the call to wait(). func wait() func tryGetResult() -> Result? func tryTakeResult() -> Result? func waitAndGetResult() -> Result func waitAndTakeResult() -> Result } public class ForkJoinTaskBase { final internal var _pool: ForkJoinPool? // FIXME(performance): there is no need to create heavy-weight // synchronization primitives every time. We could start with a lightweight // atomic int for the flag and inflate to a full event when needed. Unless // we really need to block in wait(), we would avoid creating an event. final internal let _completedEvent: _ForkJoinOneShotEvent = _ForkJoinOneShotEvent() final internal func _isComplete() -> Bool { return _completedEvent.isSet() } final internal func _blockingWait() { _completedEvent.wait() } internal func _run() { fatalError("implement") } final public func fork() { precondition(_pool == nil) if let thread = ForkJoinPool._getCurrentThread() { thread._forkTask(self) } else { // FIXME: decide if we want to allow this. precondition(false) ForkJoinPool.commonPool.forkTask(self) } } final public func wait() { if let thread = ForkJoinPool._getCurrentThread() { thread._waitForTask(self) } else { _blockingWait() } } } final public class ForkJoinTask<Result> : ForkJoinTaskBase, _Future { internal let _task: () -> Result internal var _result: Result? public init(_task: @escaping () -> Result) { self._task = _task } override internal func _run() { _complete(_task()) } /// It is not allowed to call _complete() in a racy way. Only one thread /// should ever call _complete(). internal func _complete(_ result: Result) { precondition(!_completedEvent.isSet()) _result = result _completedEvent.set() } public func tryGetResult() -> Result? { if _completedEvent.isSet() { return _result } return nil } public func tryTakeResult() -> Result? { if _completedEvent.isSet() { let result = _result _result = nil return result } return nil } public func waitAndGetResult() -> Result { wait() return tryGetResult()! } public func waitAndTakeResult() -> Result { wait() return tryTakeResult()! } } final public class ForkJoinPool { internal static var _threadRegistry: [_stdlib_pthread_t : _ForkJoinWorkerThread] = [:] internal static var _threadRegistryMutex: _ForkJoinMutex = _ForkJoinMutex() internal static func _getCurrentThread() -> _ForkJoinWorkerThread? { return _threadRegistryMutex.withLock { return _threadRegistry[_stdlib_pthread_self()] } } internal let _maxThreads: Int /// Total number of threads: number of running threads plus the number of /// threads that are preparing to start). internal let _totalThreads: _stdlib_AtomicInt = _stdlib_AtomicInt(0) internal var _runningThreads: [_ForkJoinWorkerThread] = [] internal var _runningThreadsMutex: _ForkJoinMutex = _ForkJoinMutex() internal var _submissionQueues: [_ForkJoinWorkDeque<ForkJoinTaskBase>] = [] internal var _submissionQueuesMutex: _ForkJoinMutex = _ForkJoinMutex() internal var _workDeques: [_ForkJoinWorkDeque<ForkJoinTaskBase>] = [] internal var _workDequesMutex: _ForkJoinMutex = _ForkJoinMutex() internal init(_commonPool: ()) { self._maxThreads = _stdlib_getHardwareConcurrency() } deinit { _runningThreadsMutex.`deinit`() _submissionQueuesMutex.`deinit`() _workDequesMutex.`deinit`() } internal func _addRunningThread(_ thread: _ForkJoinWorkerThread) { ForkJoinPool._threadRegistryMutex.withLock { _runningThreadsMutex.withLock { _submissionQueuesMutex.withLock { _workDequesMutex.withLock { ForkJoinPool._threadRegistry[thread._tid!] = thread _runningThreads.append(thread) _submissionQueues.append(thread._submissionQueue) _workDeques.append(thread._workDeque) } } } } } internal func _removeRunningThread(_ thread: _ForkJoinWorkerThread) { ForkJoinPool._threadRegistryMutex.withLock { _runningThreadsMutex.withLock { _submissionQueuesMutex.withLock { _workDequesMutex.withLock { let i = _runningThreads.index { $0 === thread }! ForkJoinPool._threadRegistry[thread._tid!] = nil _runningThreads.remove(at: i) _submissionQueues.remove(at: i) _workDeques.remove(at: i) } } } } } internal func _compensateForBlockedWorkerThread(_ blockingBody: @escaping () -> ()) { // FIXME: limit the number of compensating threads. let submissionQueue = _ForkJoinWorkDeque<ForkJoinTaskBase>() let workDeque = _ForkJoinWorkDeque<ForkJoinTaskBase>() let thread = _ForkJoinWorkerThread( _pool: self, submissionQueue: submissionQueue, workDeque: workDeque) thread.startAsync() blockingBody() _ = _totalThreads.fetchAndAdd(1) } internal func _tryCreateThread( _ makeTask: () -> ForkJoinTaskBase? ) -> Bool { var success = false var oldNumThreads = _totalThreads.load() repeat { if oldNumThreads >= _maxThreads { return false } success = _totalThreads.compareExchange( expected: &oldNumThreads, desired: oldNumThreads + 1) } while !success if let task = makeTask() { let submissionQueue = _ForkJoinWorkDeque<ForkJoinTaskBase>() let workDeque = _ForkJoinWorkDeque<ForkJoinTaskBase>() workDeque.prepend(task) let thread = _ForkJoinWorkerThread( _pool: self, submissionQueue: submissionQueue, workDeque: workDeque) thread.startAsync() } else { _ = _totalThreads.fetchAndAdd(-1) } return true } internal func _stealTask() -> ForkJoinTaskBase? { return _workDequesMutex.withLock { let randomOffset = pickRandom(_workDeques.indices) let count = _workDeques.count for i in _workDeques.indices { let index = (i + randomOffset) % count if let task = _workDeques[index].tryTakeLast() { return task } } return nil } } /// Check if the pool has grown too large because of compensating /// threads. internal func _tryStopThread() -> Bool { var success = false var oldNumThreads = _totalThreads.load() repeat { // FIXME: magic number 2. if oldNumThreads <= _maxThreads + 2 { return false } success = _totalThreads.compareExchange( expected: &oldNumThreads, desired: oldNumThreads - 1) } while !success return true } internal func _submitTasksToRandomWorkers< C : Collection >(_ tasks: C) where C.Iterator.Element == ForkJoinTaskBase { if tasks.isEmpty { return } _submissionQueuesMutex.withLock { precondition(!_submissionQueues.isEmpty) for task in tasks { pickRandom(_submissionQueues).append(task) } } } public func forkTask(_ task: ForkJoinTaskBase) { while true { // Try to inflate the pool first. if _tryCreateThread({ task }) { return } // Looks like we can't create more threads. Submit the task to // a random thread. let done = _submissionQueuesMutex.withLock { () -> Bool in if !_submissionQueues.isEmpty { pickRandom(_submissionQueues).append(task) return true } return false } if done { return } } } // FIXME: return a Future instead? public func forkTask<Result>(task: @escaping () -> Result) -> ForkJoinTask<Result> { let forkJoinTask = ForkJoinTask(_task: task) forkTask(forkJoinTask) return forkJoinTask } public static var commonPool = ForkJoinPool(_commonPool: ()) public static func invokeAll(_ tasks: ForkJoinTaskBase...) { ForkJoinPool.invokeAll(tasks) } public static func invokeAll(_ tasks: [ForkJoinTaskBase]) { if tasks.isEmpty { return } if ForkJoinPool._getCurrentThread() != nil { // Run the first task in this thread, fork the rest. let first = tasks.first for t in tasks.dropFirst() { // FIXME: optimize forking in bulk. t.fork() } first!._run() } else { // FIXME: decide if we want to allow this. precondition(false) } } } //===----------------------------------------------------------------------===// // Collection transformation DSL: implementation //===----------------------------------------------------------------------===// internal protocol _CollectionTransformerStepProtocol /*: class*/ { associatedtype PipelineInputElement associatedtype OutputElement func transform< InputCollection : Collection, Collector : _ElementCollector >( _ c: InputCollection, _ range: Range<InputCollection.Index>, _ collector: inout Collector ) where InputCollection.Iterator.Element == PipelineInputElement, Collector.Element == OutputElement } internal class _CollectionTransformerStep<PipelineInputElement_, OutputElement_> : _CollectionTransformerStepProtocol { typealias PipelineInputElement = PipelineInputElement_ typealias OutputElement = OutputElement_ func map<U>(_ transform: @escaping (OutputElement) -> U) -> _CollectionTransformerStep<PipelineInputElement, U> { fatalError("abstract method") } func filter(_ isIncluded: @escaping (OutputElement) -> Bool) -> _CollectionTransformerStep<PipelineInputElement, OutputElement> { fatalError("abstract method") } func reduce<U>(_ initial: U, _ combine: @escaping (U, OutputElement) -> U) -> _CollectionTransformerFinalizer<PipelineInputElement, U> { fatalError("abstract method") } func collectTo< C : BuildableCollectionProtocol >(_: C.Type) -> _CollectionTransformerFinalizer<PipelineInputElement, C> where C.Builder.Destination == C, C.Builder.Element == C.Iterator.Element, C.Iterator.Element == OutputElement { fatalError("abstract method") } func transform< InputCollection : Collection, Collector : _ElementCollector >( _ c: InputCollection, _ range: Range<InputCollection.Index>, _ collector: inout Collector ) where InputCollection.Iterator.Element == PipelineInputElement, Collector.Element == OutputElement { fatalError("abstract method") } } final internal class _CollectionTransformerStepCollectionSource< PipelineInputElement > : _CollectionTransformerStep<PipelineInputElement, PipelineInputElement> { typealias InputElement = PipelineInputElement override func map<U>(_ transform: @escaping (InputElement) -> U) -> _CollectionTransformerStep<PipelineInputElement, U> { return _CollectionTransformerStepOneToMaybeOne(self) { transform($0) } } override func filter(_ isIncluded: @escaping (InputElement) -> Bool) -> _CollectionTransformerStep<PipelineInputElement, InputElement> { return _CollectionTransformerStepOneToMaybeOne(self) { isIncluded($0) ? $0 : nil } } override func reduce<U>(_ initial: U, _ combine: @escaping (U, InputElement) -> U) -> _CollectionTransformerFinalizer<PipelineInputElement, U> { return _CollectionTransformerFinalizerReduce(self, initial, combine) } override func collectTo< C : BuildableCollectionProtocol >(_ c: C.Type) -> _CollectionTransformerFinalizer<PipelineInputElement, C> where C.Builder.Destination == C, C.Builder.Element == C.Iterator.Element, C.Iterator.Element == OutputElement { return _CollectionTransformerFinalizerCollectTo(self, c) } override func transform< InputCollection : Collection, Collector : _ElementCollector >( _ c: InputCollection, _ range: Range<InputCollection.Index>, _ collector: inout Collector ) where InputCollection.Iterator.Element == PipelineInputElement, Collector.Element == OutputElement { var i = range.lowerBound while i != range.upperBound { let e = c[i] collector.append(e) c.formIndex(after: &i) } } } final internal class _CollectionTransformerStepOneToMaybeOne< PipelineInputElement, OutputElement, InputStep : _CollectionTransformerStepProtocol > : _CollectionTransformerStep<PipelineInputElement, OutputElement> where InputStep.PipelineInputElement == PipelineInputElement { typealias _Self = _CollectionTransformerStepOneToMaybeOne typealias InputElement = InputStep.OutputElement let _input: InputStep let _transform: (InputElement) -> OutputElement? init(_ input: InputStep, _ transform: @escaping (InputElement) -> OutputElement?) { self._input = input self._transform = transform super.init() } override func map<U>(_ transform: @escaping (OutputElement) -> U) -> _CollectionTransformerStep<PipelineInputElement, U> { // Let the closure below capture only one variable, not the whole `self`. let localTransform = _transform return _CollectionTransformerStepOneToMaybeOne<PipelineInputElement, U, InputStep>(_input) { (input: InputElement) -> U? in if let e = localTransform(input) { return transform(e) } return nil } } override func filter(_ isIncluded: @escaping (OutputElement) -> Bool) -> _CollectionTransformerStep<PipelineInputElement, OutputElement> { // Let the closure below capture only one variable, not the whole `self`. let localTransform = _transform return _CollectionTransformerStepOneToMaybeOne<PipelineInputElement, OutputElement, InputStep>(_input) { (input: InputElement) -> OutputElement? in if let e = localTransform(input) { return isIncluded(e) ? e : nil } return nil } } override func reduce<U>(_ initial: U, _ combine: @escaping (U, OutputElement) -> U) -> _CollectionTransformerFinalizer<PipelineInputElement, U> { return _CollectionTransformerFinalizerReduce(self, initial, combine) } override func collectTo< C : BuildableCollectionProtocol >(_ c: C.Type) -> _CollectionTransformerFinalizer<PipelineInputElement, C> where C.Builder.Destination == C, C.Builder.Element == C.Iterator.Element, C.Iterator.Element == OutputElement { return _CollectionTransformerFinalizerCollectTo(self, c) } override func transform< InputCollection : Collection, Collector : _ElementCollector >( _ c: InputCollection, _ range: Range<InputCollection.Index>, _ collector: inout Collector ) where InputCollection.Iterator.Element == PipelineInputElement, Collector.Element == OutputElement { var collectorWrapper = _ElementCollectorOneToMaybeOne(collector, _transform) _input.transform(c, range, &collectorWrapper) collector = collectorWrapper._baseCollector } } struct _ElementCollectorOneToMaybeOne< BaseCollector : _ElementCollector, Element_ > : _ElementCollector { typealias Element = Element_ var _baseCollector: BaseCollector var _transform: (Element) -> BaseCollector.Element? init( _ baseCollector: BaseCollector, _ transform: @escaping (Element) -> BaseCollector.Element? ) { self._baseCollector = baseCollector self._transform = transform } mutating func sizeHint(_ approximateSize: Int) {} mutating func append(_ element: Element) { if let e = _transform(element) { _baseCollector.append(e) } } mutating func append< C : Collection >(contentsOf elements: C) where C.Iterator.Element == Element { for e in elements { append(e) } } } protocol _ElementCollector { associatedtype Element mutating func sizeHint(_ approximateSize: Int) mutating func append(_ element: Element) mutating func append< C : Collection >(contentsOf elements: C) where C.Iterator.Element == Element } class _CollectionTransformerFinalizer<PipelineInputElement, Result> { func transform< InputCollection : Collection >(_ c: InputCollection) -> Result where InputCollection.Iterator.Element == PipelineInputElement { fatalError("implement") } } final class _CollectionTransformerFinalizerReduce< PipelineInputElement, U, InputElementTy, InputStep : _CollectionTransformerStepProtocol > : _CollectionTransformerFinalizer<PipelineInputElement, U> where InputStep.OutputElement == InputElementTy, InputStep.PipelineInputElement == PipelineInputElement { var _input: InputStep var _initial: U var _combine: (U, InputElementTy) -> U init(_ input: InputStep, _ initial: U, _ combine: @escaping (U, InputElementTy) -> U) { self._input = input self._initial = initial self._combine = combine } override func transform< InputCollection : Collection >(_ c: InputCollection) -> U where InputCollection.Iterator.Element == PipelineInputElement { var collector = _ElementCollectorReduce(_initial, _combine) _input.transform(c, c.startIndex..<c.endIndex, &collector) return collector.takeResult() } } struct _ElementCollectorReduce<Element_, Result> : _ElementCollector { typealias Element = Element_ var _current: Result var _combine: (Result, Element) -> Result init(_ initial: Result, _ combine: @escaping (Result, Element) -> Result) { self._current = initial self._combine = combine } mutating func sizeHint(_ approximateSize: Int) {} mutating func append(_ element: Element) { _current = _combine(_current, element) } mutating func append< C : Collection >(contentsOf elements: C) where C.Iterator.Element == Element { for e in elements { append(e) } } mutating func takeResult() -> Result { return _current } } final class _CollectionTransformerFinalizerCollectTo< PipelineInputElement, U : BuildableCollectionProtocol, InputElementTy, InputStep : _CollectionTransformerStepProtocol > : _CollectionTransformerFinalizer<PipelineInputElement, U> where InputStep.OutputElement == InputElementTy, InputStep.PipelineInputElement == PipelineInputElement, U.Builder.Destination == U, U.Builder.Element == U.Iterator.Element, U.Iterator.Element == InputStep.OutputElement { var _input: InputStep init(_ input: InputStep, _: U.Type) { self._input = input } override func transform< InputCollection : Collection >(_ c: InputCollection) -> U where InputCollection.Iterator.Element == PipelineInputElement { var collector = _ElementCollectorCollectTo<U>() _input.transform(c, c.startIndex..<c.endIndex, &collector) return collector.takeResult() } } struct _ElementCollectorCollectTo< BuildableCollection : BuildableCollectionProtocol > : _ElementCollector where BuildableCollection.Builder.Destination == BuildableCollection, BuildableCollection.Builder.Element == BuildableCollection.Iterator.Element { typealias Element = BuildableCollection.Iterator.Element var _builder: BuildableCollection.Builder init() { self._builder = BuildableCollection.Builder() } mutating func sizeHint(_ approximateSize: Int) { _builder.sizeHint(approximateSize) } mutating func append(_ element: Element) { _builder.append(element) } mutating func append< C : Collection >(contentsOf elements: C) where C.Iterator.Element == Element { _builder.append(contentsOf: elements) } mutating func takeResult() -> BuildableCollection { return _builder.takeResult() } } internal func _optimizeCollectionTransformer<PipelineInputElement, Result>( _ transformer: _CollectionTransformerFinalizer<PipelineInputElement, Result> ) -> _CollectionTransformerFinalizer<PipelineInputElement, Result> { return transformer } internal func _runCollectionTransformer< InputCollection : Collection, Result >( _ c: InputCollection, _ transformer: _CollectionTransformerFinalizer<InputCollection.Iterator.Element, Result> ) -> Result { dump(transformer) let optimized = _optimizeCollectionTransformer(transformer) dump(optimized) return transformer.transform(c) } //===----------------------------------------------------------------------===// // Collection transformation DSL: public interface //===----------------------------------------------------------------------===// public struct CollectionTransformerPipeline< InputCollection : Collection, T > { internal var _input: InputCollection internal var _step: _CollectionTransformerStep<InputCollection.Iterator.Element, T> public func map<U>(_ transform: @escaping (T) -> U) -> CollectionTransformerPipeline<InputCollection, U> { return CollectionTransformerPipeline<InputCollection, U>( _input: _input, _step: _step.map(transform) ) } public func filter(_ isIncluded: @escaping (T) -> Bool) -> CollectionTransformerPipeline<InputCollection, T> { return CollectionTransformerPipeline<InputCollection, T>( _input: _input, _step: _step.filter(isIncluded) ) } public func reduce<U>( _ initial: U, _ combine: @escaping (U, T) -> U ) -> U { return _runCollectionTransformer(_input, _step.reduce(initial, combine)) } public func collectTo< C : BuildableCollectionProtocol >(_ c: C.Type) -> C where C.Builder.Destination == C, C.Iterator.Element == T, C.Builder.Element == T { return _runCollectionTransformer(_input, _step.collectTo(c)) } public func toArray() -> [T] { return collectTo(Array<T>.self) } } public func transform<C : Collection>(_ c: C) -> CollectionTransformerPipeline<C, C.Iterator.Element> { return CollectionTransformerPipeline<C, C.Iterator.Element>( _input: c, _step: _CollectionTransformerStepCollectionSource<C.Iterator.Element>()) } //===----------------------------------------------------------------------===// // Collection transformation DSL: tests //===----------------------------------------------------------------------===// import StdlibUnittest var t = TestSuite("t") t.test("fusion/map+reduce") { let xs = [ 1, 2, 3 ] let result = transform(xs) .map { $0 * 2 } .reduce(0, { $0 + $1 }) expectEqual(12, result) } t.test("fusion/map+filter+reduce") { let xs = [ 1, 2, 3 ] let result = transform(xs) .map { $0 * 2 } .filter { $0 != 0 } .reduce(0, { $0 + $1 }) expectEqual(12, result) } t.test("fusion/map+collectTo") { let xs = [ 1, 2, 3 ] let result = transform(xs) .map { $0 * 2 } .collectTo(Array<Int>.self) expectEqual([ 2, 4, 6 ], result) } t.test("fusion/map+toArray") { let xs = [ 1, 2, 3 ] let result = transform(xs) .map { $0 * 2 } .toArray() expectEqual([ 2, 4, 6 ], result) } t.test("ForkJoinPool.forkTask") { var tasks: [ForkJoinTask<()>] = [] for i in 0..<100 { tasks.append(ForkJoinPool.commonPool.forkTask { () -> () in var result = 1 for i in 0..<10000 { result = result &* i _blackHole(result) } return () }) } for t in tasks { t.wait() } } func fib(_ n: Int) -> Int { if n == 1 || n == 2 { return 1 } if n == 38 { print("\(pthread_self()) fib(\(n))") } if n < 39 { let r = fib(n - 1) + fib(n - 2) _blackHole(r) return r } print("fib(\(n))") let t1 = ForkJoinTask() { fib(n - 1) } let t2 = ForkJoinTask() { fib(n - 2) } ForkJoinPool.invokeAll(t1, t2) return t2.waitAndGetResult() + t1.waitAndGetResult() } t.test("ForkJoinPool.forkTask/Fibonacci") { let t = ForkJoinPool.commonPool.forkTask { fib(40) } expectEqual(102334155, t.waitAndGetResult()) } func _parallelMap(_ input: [Int], transform: @escaping (Int) -> Int, range: Range<Int>) -> Array<Int>.Builder { var builder = Array<Int>.Builder() if range.count < 1_000 { builder.append(contentsOf: input[range].map(transform)) } else { let tasks = input.split(range).map { (subRange) in ForkJoinTask<Array<Int>.Builder> { _parallelMap(input, transform: transform, range: subRange) } } ForkJoinPool.invokeAll(tasks) for t in tasks { var otherBuilder = t.waitAndGetResult() builder.moveContentsOf(&otherBuilder) } } return builder } func parallelMap(_ input: [Int], transform: @escaping (Int) -> Int) -> [Int] { let t = ForkJoinPool.commonPool.forkTask { _parallelMap( input, transform: transform, range: input.startIndex..<input.endIndex) } var builder = t.waitAndGetResult() return builder.takeResult() } t.test("ForkJoinPool.forkTask/MapArray") { expectEqual( Array(2..<1_001), parallelMap(Array(1..<1_000)) { $0 + 1 } ) } /* * FIXME: reduce compiler crasher t.test("ForkJoinPool.forkTask") { func fib(_ n: Int) -> Int { if n == 0 || n == 1 { return 1 } let t1 = ForkJoinPool.commonPool.forkTask { fib(n - 1) } let t2 = ForkJoinPool.commonPool.forkTask { fib(n - 2) } return t2.waitAndGetResult() + t1.waitAndGetResult() } expectEqual(0, fib(10)) } */ /* Useful links: http://habrahabr.ru/post/255659/ */ runAllTests()
apache-2.0
1ce724a299507e96bf597954df9fd3a6
26.11785
108
0.65368
4.52068
false
false
false
false
RoRoche/iOSSwiftStarter
iOSSwiftStarter/Pods/Nimble/Sources/Nimble/Matchers/AllPass.swift
111
3870
import Foundation public func allPass<T,U where U: SequenceType, U.Generator.Element == T> (passFunc: (T?) -> Bool) -> NonNilMatcherFunc<U> { return allPass("pass a condition", passFunc) } public func allPass<T,U where U: SequenceType, U.Generator.Element == T> (passName: String, _ passFunc: (T?) -> Bool) -> NonNilMatcherFunc<U> { return createAllPassMatcher() { expression, failureMessage in failureMessage.postfixMessage = passName return passFunc(try expression.evaluate()) } } public func allPass<U,V where U: SequenceType, V: Matcher, U.Generator.Element == V.ValueType> (matcher: V) -> NonNilMatcherFunc<U> { return createAllPassMatcher() { try matcher.matches($0, failureMessage: $1) } } private func createAllPassMatcher<T,U where U: SequenceType, U.Generator.Element == T> (elementEvaluator:(Expression<T>, FailureMessage) throws -> Bool) -> NonNilMatcherFunc<U> { return NonNilMatcherFunc { actualExpression, failureMessage in failureMessage.actualValue = nil if let actualValue = try actualExpression.evaluate() { for currentElement in actualValue { let exp = Expression( expression: {currentElement}, location: actualExpression.location) if try !elementEvaluator(exp, failureMessage) { failureMessage.postfixMessage = "all \(failureMessage.postfixMessage)," + " but failed first at element <\(stringify(currentElement))>" + " in <\(stringify(actualValue))>" return false } } failureMessage.postfixMessage = "all \(failureMessage.postfixMessage)" } else { failureMessage.postfixMessage = "all pass (use beNil() to match nils)" return false } return true } } #if _runtime(_ObjC) extension NMBObjCMatcher { public class func allPassMatcher(matcher: NMBObjCMatcher) -> NMBObjCMatcher { return NMBObjCMatcher(canMatchNil: false) { actualExpression, failureMessage in let location = actualExpression.location let actualValue = try! actualExpression.evaluate() var nsObjects = [NSObject]() var collectionIsUsable = true if let value = actualValue as? NSFastEnumeration { let generator = NSFastGenerator(value) while let obj:AnyObject = generator.next() { if let nsObject = obj as? NSObject { nsObjects.append(nsObject) } else { collectionIsUsable = false break } } } else { collectionIsUsable = false } if !collectionIsUsable { failureMessage.postfixMessage = "allPass only works with NSFastEnumeration (NSArray, NSSet, ...) of NSObjects" failureMessage.expected = "" failureMessage.to = "" return false } let expr = Expression(expression: ({ nsObjects }), location: location) let elementEvaluator: (Expression<NSObject>, FailureMessage) -> Bool = { expression, failureMessage in return matcher.matches( {try! expression.evaluate()}, failureMessage: failureMessage, location: expr.location) } return try! createAllPassMatcher(elementEvaluator).matches( expr, failureMessage: failureMessage) } } } #endif
apache-2.0
69bab347e59d8b1797d4d9b34995d48e
41.065217
106
0.559948
5.682819
false
false
false
false
jopamer/swift
test/SILGen/access_marker_gen.swift
1
6197
// RUN: %target-swift-emit-silgen -module-name access_marker_gen -parse-as-library -Xllvm -sil-full-demangle -enforce-exclusivity=checked -enable-sil-ownership %s | %FileCheck %s func modify<T>(_ x: inout T) {} public struct S { var i: Int var o: AnyObject? } // CHECK-LABEL: sil hidden [noinline] @$S17access_marker_gen5initSyAA1SVyXlSgF : $@convention(thin) (@guaranteed Optional<AnyObject>) -> @owned S { // CHECK: bb0(%0 : @guaranteed $Optional<AnyObject>): // CHECK: [[BOX:%.*]] = alloc_box ${ var S }, var, name "s" // CHECK: [[MARKED_BOX:%.*]] = mark_uninitialized [var] [[BOX]] : ${ var S } // CHECK: [[ADDR:%.*]] = project_box [[MARKED_BOX]] : ${ var S }, 0 // CHECK: cond_br %{{.*}}, bb1, bb2 // CHECK: bb1: // CHECK: [[ACCESS1:%.*]] = begin_access [modify] [unknown] [[ADDR]] : $*S // CHECK: assign %{{.*}} to [[ACCESS1]] : $*S // CHECK: end_access [[ACCESS1]] : $*S // CHECK: bb2: // CHECK: [[ACCESS2:%.*]] = begin_access [modify] [unknown] [[ADDR]] : $*S // CHECK: assign %{{.*}} to [[ACCESS2]] : $*S // CHECK: end_access [[ACCESS2]] : $*S // CHECK: bb3: // CHECK: [[ACCESS3:%.*]] = begin_access [read] [unknown] [[ADDR]] : $*S // CHECK: [[RET:%.*]] = load [copy] [[ACCESS3]] : $*S // CHECK: end_access [[ACCESS3]] : $*S // CHECK: return [[RET]] : $S // CHECK-LABEL: } // end sil function '$S17access_marker_gen5initSyAA1SVyXlSgF' @inline(never) func initS(_ o: AnyObject?) -> S { var s: S if o == nil { s = S(i: 0, o: nil) } else { s = S(i: 1, o: o) } return s } @inline(never) func takeS(_ s: S) {} // CHECK-LABEL: sil @$S17access_marker_gen14modifyAndReadSyyF : $@convention(thin) () -> () { // CHECK: bb0: // CHECK: %[[BOX:.*]] = alloc_box ${ var S }, var, name "s" // CHECK: %[[ADDRS:.*]] = project_box %[[BOX]] : ${ var S }, 0 // CHECK: %[[ACCESS1:.*]] = begin_access [modify] [unknown] %[[ADDRS]] : $*S // CHECK: %[[ADDRI:.*]] = struct_element_addr %[[ACCESS1]] : $*S, #S.i // CHECK: assign %{{.*}} to %[[ADDRI]] : $*Int // CHECK: end_access %[[ACCESS1]] : $*S // CHECK: %[[ACCESS2:.*]] = begin_access [read] [unknown] %[[ADDRS]] : $*S // CHECK: %{{.*}} = load [copy] %[[ACCESS2]] : $*S // CHECK: end_access %[[ACCESS2]] : $*S // CHECK-LABEL: } // end sil function '$S17access_marker_gen14modifyAndReadSyyF' public func modifyAndReadS() { var s = initS(nil) s.i = 42 takeS(s) } var global = S(i: 0, o: nil) func readGlobal() -> AnyObject? { return global.o } // CHECK-LABEL: sil hidden @$S17access_marker_gen10readGlobalyXlSgyF // CHECK: [[ADDRESSOR:%.*]] = function_ref @$S17access_marker_gen6globalAA1SVvau : // CHECK-NEXT: [[T0:%.*]] = apply [[ADDRESSOR]]() // CHECK-NEXT: [[T1:%.*]] = pointer_to_address [[T0]] : $Builtin.RawPointer to [strict] $*S // CHECK-NEXT: [[T2:%.*]] = begin_access [read] [dynamic] [[T1]] // CHECK-NEXT: [[T3:%.*]] = struct_element_addr [[T2]] : $*S, #S.o // CHECK-NEXT: [[T4:%.*]] = load [copy] [[T3]] // CHECK-NEXT: end_access [[T2]] // CHECK-NEXT: return [[T4]] public struct HasTwoStoredProperties { var f: Int = 7 var g: Int = 9 // CHECK-LABEL: sil hidden @$S17access_marker_gen22HasTwoStoredPropertiesV027noOverlapOnAssignFromPropToM0yyF : $@convention(method) (@inout HasTwoStoredProperties) -> () // CHECK: [[ACCESS1:%.*]] = begin_access [read] [unknown] [[SELF_ADDR:%.*]] : $*HasTwoStoredProperties // CHECK-NEXT: [[G_ADDR:%.*]] = struct_element_addr [[ACCESS1]] : $*HasTwoStoredProperties, #HasTwoStoredProperties.g // CHECK-NEXT: [[G_VAL:%.*]] = load [trivial] [[G_ADDR]] : $*Int // CHECK-NEXT: end_access [[ACCESS1]] : $*HasTwoStoredProperties // CHECK-NEXT: [[ACCESS2:%.*]] = begin_access [modify] [unknown] [[SELF_ADDR]] : $*HasTwoStoredProperties // CHECK-NEXT: [[F_ADDR:%.*]] = struct_element_addr [[ACCESS2]] : $*HasTwoStoredProperties, #HasTwoStoredProperties.f // CHECK-NEXT: assign [[G_VAL]] to [[F_ADDR]] : $*Int // CHECK-NEXT: end_access [[ACCESS2]] : $*HasTwoStoredProperties mutating func noOverlapOnAssignFromPropToProp() { f = g } } class C { final var x: Int = 0 let z: Int = 0 } func testClassInstanceProperties(c: C) { let y = c.x c.x = y } // CHECK-LABEL: sil hidden @$S17access_marker_gen27testClassInstanceProperties1cyAA1CC_tF : // CHECK: bb0([[C:%.*]] : @guaranteed $C // CHECK-NEXT: debug_value // CHECK-NEXT: [[CX:%.*]] = ref_element_addr [[C]] : $C, #C.x // CHECK-NEXT: [[ACCESS:%.*]] = begin_access [read] [dynamic] [[CX]] : $*Int // CHECK-NEXT: [[Y:%.*]] = load [trivial] [[ACCESS]] // CHECK-NEXT: end_access [[ACCESS]] // CHECK-NEXT: debug_value // CHECK-NEXT: [[CX:%.*]] = ref_element_addr [[C]] : $C, #C.x // CHECK-NEXT: [[ACCESS:%.*]] = begin_access [modify] [dynamic] [[CX]] : $*Int // CHECK-NEXT: assign [[Y]] to [[ACCESS]] // CHECK-NEXT: end_access [[ACCESS]] func testClassLetProperty(c: C) -> Int { return c.z } // CHECK-LABEL: sil hidden @$S17access_marker_gen20testClassLetProperty1cSiAA1CC_tF : $@convention(thin) (@guaranteed C) -> Int { // CHECK: bb0(%0 : @guaranteed $C): // CHECK: [[ADR:%.*]] = ref_element_addr %{{.*}} : $C, #C.z // CHECK-NOT: begin_access // CHECK: %{{.*}} = load [trivial] [[ADR]] : $*Int // CHECK-NOT: end_access // CHECK-NOT: destroy_value %0 : $C // CHECK: return %{{.*}} : $Int // CHECK-LABEL: } // end sil function '$S17access_marker_gen20testClassLetProperty1cSiAA1CC_tF' class D { var x: Int = 0 } // materializeForSet callback // CHECK-LABEL: sil private [transparent] @$S17access_marker_gen1DC1xSivmytfU_ // CHECK: end_unpaired_access [dynamic] %1 : $*Builtin.UnsafeValueBuffer // materializeForSet // CHECK-LABEL: sil hidden [transparent] @$S17access_marker_gen1DC1xSivm // CHECK: [[T0:%.*]] = ref_element_addr %2 : $D, #D.x // CHECK-NEXT: begin_unpaired_access [modify] [dynamic] [[T0]] : $*Int func testDispatchedClassInstanceProperty(d: D) { modify(&d.x) } // CHECK-LABEL: sil hidden @$S17access_marker_gen35testDispatchedClassInstanceProperty1dyAA1DC_tF // CHECK: bb0([[D:%.*]] : @guaranteed $D // CHECK: [[METHOD:%.*]] = class_method [[D]] : $D, #D.x!materializeForSet.1 // CHECK: apply [[METHOD]]({{.*}}, [[D]]) // CHECK: begin_access [modify] [unsafe] // CHECK-NOT: begin_access
apache-2.0
abd5e532000a83ee95e197dbfbe3fab7
38.980645
178
0.605454
3.054214
false
false
false
false
blockchain/My-Wallet-V3-iOS
Modules/FeatureCryptoDomain/Sources/FeatureCryptoDomainData/Clients/ClaimEligibilityClient.swift
1
1362
// Copyright © Blockchain Luxembourg S.A. All rights reserved. import Combine import Errors import Foundation import NetworkKit public protocol ClaimEligibilityClientAPI { func getEligibility() -> AnyPublisher<ClaimEligibilityResponse, NabuNetworkError> } public final class ClaimEligibilityClient: ClaimEligibilityClientAPI { // MARK: - Type private enum Path { static let eligibility = [ "users", "domain-campaigns", "eligibility" ] } // MARK: - Properties private let networkAdapter: NetworkAdapterAPI private let requestBuilder: RequestBuilder // MARK: - Setup public init( networkAdapter: NetworkAdapterAPI, requestBuilder: RequestBuilder ) { self.networkAdapter = networkAdapter self.requestBuilder = requestBuilder } // MARK: - API public func getEligibility() -> AnyPublisher<ClaimEligibilityResponse, NabuNetworkError> { let parameters = [ URLQueryItem( name: "domainCampaign", value: "UNSTOPPABLE_DOMAINS" ) ] let request = requestBuilder.get( path: Path.eligibility, parameters: parameters, authenticated: true )! return networkAdapter.perform(request: request) } }
lgpl-3.0
a12dbfc291405f5a913a920558e93830
23.303571
94
0.631154
5.444
false
false
false
false
ashfurrow/eidolon
Kiosk/App/AppDelegate+GlobalActions.swift
2
10408
import UIKit import QuartzCore import ARAnalytics import RxSwift import Action func appDelegate() -> AppDelegate { return UIApplication.shared.delegate as! AppDelegate } extension AppDelegate { // Registration var sale: Sale! { return appViewController!.sale.value } internal var appViewController: AppViewController! { let nav = self.window?.rootViewController?.findChildViewControllerOfType(UINavigationController.self) as? UINavigationController return nav?.delegate as? AppViewController } // Help button and menu func setupHelpButton() { helpButton = MenuButton() helpButton.setTitle("Help", for: .normal) helpButton.rx.action = helpButtonCommand() window?.addSubview(helpButton) helpButton.alignTop(nil, leading: nil, bottom: "-24", trailing: "-24", to: window) window?.layoutIfNeeded() helpIsVisisble.subscribe(onNext: { visisble in let image: UIImage? = visisble ? UIImage(named: "xbtn_white")?.withRenderingMode(.alwaysOriginal) : nil let text: String? = visisble ? nil : "HELP" self.helpButton.setTitle(text, for: .normal) self.helpButton.setImage(image, for: .normal) let transition = CATransition() transition.duration = AnimationDuration.Normal transition.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseInEaseOut) transition.type = kCATransitionFade self.helpButton.layer.add(transition, forKey: "fade") }).disposed(by: rx.disposeBag) } func setHelpButtonHidden(_ hidden: Bool) { helpButton.isHidden = hidden } } // MARK: - ReactiveCocoa extensions fileprivate var retainedAction: CocoaAction? extension AppDelegate { // In this extension, I'm omitting [weak self] because the app delegate will outlive everyone. func showBuyersPremiumCommand(enabled: Observable<Bool> = .just(true)) -> CocoaAction { return CocoaAction(enabledIf: enabled) { _ in self.hideAllTheThings() .then(self.showWebController(address: "https://m.artsy.net/auction/\(self.sale.id)/buyers-premium")) .map(void) } } func registerToBidCommand(enabled: Observable<Bool> = .just(true)) -> CocoaAction { return CocoaAction(enabledIf: enabled) { _ in self.hideAllTheThings() .then(self.showRegistration()) } } func requestBidderDetailsCommand(enabled: Observable<Bool> = .just(true)) -> CocoaAction { return CocoaAction(enabledIf: enabled) { _ in self.hideHelp() .then(self.showBidderDetailsRetrieval()) } } func helpButtonCommand() -> CocoaAction { return CocoaAction { _ in let showHelp = self.hideAllTheThings().then(self.showHelp()) return self.helpIsVisisble.take(1).flatMap { (visible: Bool) -> Observable<Void> in if visible { return self.hideHelp() } else { return showHelp } } } } /// This is a hack around the fact that the command might dismiss the view controller whose UI owns the command itself. /// So we store the CocoaAction in a variable private to this file to retain it. Once the action is complete, then we /// release our reference to the CocoaAction. This ensures that the action isn't cancelled while it's executing. func ensureAction(action: CocoaAction) -> CocoaAction { retainedAction = action let action = CocoaAction { input -> Observable<Void> in return retainedAction? .execute(input) .do(onCompleted: { retainedAction = nil }) ?? Observable.just(Void()) } return action } func showPrivacyPolicyCommand() -> CocoaAction { return ensureAction(action: CocoaAction { _ in self.hideAllTheThings().then(self.showWebController(address: "https://artsy.net/privacy")) }) } func showConditionsOfSaleCommand() -> CocoaAction { return ensureAction(action: CocoaAction { _ in self.hideAllTheThings().then(self.showWebController(address: "https://artsy.net/conditions-of-sale")) }) } } // MARK: - Private ReactiveCocoa Extension private extension AppDelegate { // MARK: - s that do things func ツ() -> Observable<Void>{ return hideAllTheThings() } func hideAllTheThings() -> Observable<Void> { return self.closeFulfillmentViewController().then(self.hideHelp()) } func showBidderDetailsRetrieval() -> Observable<Void> { let appVC = self.appViewController let presentingViewController: UIViewController = (appVC!.presentedViewController ?? appVC!) return presentingViewController.promptForBidderDetailsRetrieval(provider: self.provider) } func showRegistration() -> Observable<Void> { return Observable.create { observer in ARAnalytics.event("Register To Bid Tapped") let storyboard = UIStoryboard.fulfillment() let containerController = storyboard.instantiateInitialViewController() as! FulfillmentContainerViewController containerController.allowAnimations = self.appViewController.allowAnimations if let internalNav: FulfillmentNavigationController = containerController.internalNavigationController() { internalNav.auctionID = self.appViewController.auctionID let registerVC = storyboard.viewController(withID: .RegisterAnAccount) as! RegisterViewController registerVC.placingBid = false registerVC.provider = self.provider internalNav.auctionID = self.appViewController.auctionID internalNav.viewControllers = [registerVC] } self.appViewController.present(containerController, animated: false) { containerController.viewDidAppearAnimation(containerController.allowAnimations) sendDispatchCompleted(to: observer) } return Disposables.create() } } func showHelp() -> Observable<Void> { return Observable.create { observer in let helpViewController = HelpViewController() helpViewController.modalPresentationStyle = .custom helpViewController.transitioningDelegate = self self.window?.rootViewController?.present(helpViewController, animated: true, completion: { self.helpViewController.value = helpViewController sendDispatchCompleted(to: observer) }) return Disposables.create() } } func closeFulfillmentViewController() -> Observable<Void> { let close: Observable<Void> = Observable.create { observer in (self.appViewController.presentedViewController as? FulfillmentContainerViewController)?.closeFulfillmentModal() { sendDispatchCompleted(to: observer) } return Disposables.create() } return fullfilmentVisible.flatMap { visible -> Observable<Void> in if visible { return close } else { return .empty() } } } func showWebController(address: String) -> Observable<Void> { return hideWebViewController().then ( Observable.create { observer in let webController = ModalWebViewController(url: NSURL(string: address)! as URL) let nav = UINavigationController(rootViewController: webController) nav.modalPresentationStyle = .formSheet ARAnalytics.event("Show Web View", withProperties: ["url" : address]) self.window?.rootViewController?.present(nav, animated: true) { sendDispatchCompleted(to: observer) } self.webViewController = nav return Disposables.create() } ) } func hideHelp() -> Observable<Void> { return Observable.create { observer in if let presentingViewController = self.helpViewController.value?.presentingViewController { presentingViewController.dismiss(animated: true) { DispatchQueue.main.async { observer.onCompleted() self.helpViewController.value = nil } sendDispatchCompleted(to: observer) } } else { observer.onCompleted() } return Disposables.create() } } func hideWebViewController() -> Observable<Void> { return Observable.create { observer in if let webViewController = self.webViewController { webViewController.presentingViewController?.dismiss(animated: true) { sendDispatchCompleted(to: observer) } } else { observer.onCompleted() } return Disposables.create() } } // MARK: - Computed property observables var fullfilmentVisible: Observable<Bool> { return Observable.deferred { return Observable.create { observer in observer.onNext((self.appViewController.presentedViewController as? FulfillmentContainerViewController) != nil) observer.onCompleted() return Disposables.create() } } } var helpIsVisisble: Observable<Bool> { return helpViewController.asObservable().map { controller in return controller.hasValue } } } // MARK: - Help transtion animation extension AppDelegate: UIViewControllerTransitioningDelegate { func animationController(forPresented presented: UIViewController, presenting: UIViewController, source: UIViewController) -> UIViewControllerAnimatedTransitioning? { return HelpAnimator(presenting: true) } func animationController(forDismissed dismissed: UIViewController) -> UIViewControllerAnimatedTransitioning? { return HelpAnimator() } }
mit
1c622d84db37a654b995e50349f8be2d
34.882759
170
0.630694
5.471083
false
false
false
false