repo_name
stringlengths
6
91
path
stringlengths
6
999
copies
stringclasses
283 values
size
stringlengths
1
7
content
stringlengths
3
1.05M
license
stringclasses
15 values
ben-ng/swift
validation-test/compiler_crashers_fixed/26275-llvm-optional-swift-diagnostic-operator.swift
1
415
// This source file is part of the Swift.org open source project // Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // RUN: not %target-swift-frontend %s -typecheck func x{{}{}{{}{{
apache-2.0
instacrate/tapcrate-api
Sources/api/Stripe/Models/Charge.swift
2
7761
// // Charge.swift // Stripe // // Created by Hakon Hanesand on 1/1/17. // // import Node import Foundation public enum Action: String, NodeConvertible { case allow case block case manual_review } public final class Rule: NodeConvertible { public let action: Action public let predicate: String public required init(node: Node) throws { action = try node.extract("action") predicate = try node.extract("predicate") } public func makeNode(in context: Context?) throws -> Node { return try Node(node : [ "action" : try action.makeNode(in: context), "predicate" : .string(predicate) ] as [String : Node]) } } public enum NetworkStatus: String, NodeConvertible { case approved_by_network case declined_by_network case not_sent_to_network case reversed_after_approval } public enum Type: String, NodeConvertible { case authorized case issuer_declined case blocked case invalid } public enum Risk: String, NodeConvertible { case normal case elevated case highest } public final class Outcome: NodeConvertible { public let network_status: NetworkStatus public let reason: String? public let risk_level: String? public let seller_message: String public let type: Type public required init(node: Node) throws { network_status = try node.extract("network_status") reason = try? node.extract("reason") risk_level = try? node.extract("risk_level") seller_message = try node.extract("seller_message") type = try node.extract("type") } public func makeNode(in context: Context?) throws -> Node { return try Node(node : [ "network_status" : try network_status.makeNode(in: context), "seller_message" : .string(seller_message), "type" : try type.makeNode(in: context) ] as [String : Node]).add(objects: [ "reason" : reason, "risk_level" : risk_level ]) } } public enum ErrorType: String, NodeConvertible { case api_connection_error case api_error case authentication_error case card_error case invalid_request_error case rate_limit_error } public final class StripeShipping: NodeConvertible { public let address: Address public let name: String public let tracking_number: String public let phone: String public required init(node: Node) throws { address = try node.extract("address") name = try node.extract("name") tracking_number = try node.extract("tracking_number") phone = try node.extract("phone") } public func makeNode(in context: Context?) throws -> Node { return try Node(node : [ "address" : try address.makeNode(in: context), "name" : .string(name), "tracking_number" : .string(tracking_number), "phone" : .string(phone) ] as [String : Node]) } } public enum ChargeStatus: String, NodeConvertible { case succeeded case pending case failed } public final class Charge: NodeConvertible { static let type = "charge" public let id: String public let amount: Int public let amount_refunded: Int public let application: String? public let application_fee: String? public let balance_transaction: String public let captured: Bool public let created: Date public let currency: Currency public let customer: String? public let description: String? public let destination: String? public let dispute: Dispute? public let failure_code: ErrorType? public let failure_message: String? public let fraud_details: Node public let invoice: String? public let livemode: Bool public let order: String? public let outcome: Outcome public let paid: Bool public let receipt_email: String? public let receipt_number: String? public let refunded: Bool public let refunds: Node public let review: String? public let shipping: StripeShipping? public let source: Card public let source_transfer: String? public let statement_descriptor: String? public let status: ChargeStatus? public let transfer: String? public required init(node: Node) throws { guard try node.extract("object") == Charge.type else { throw NodeError.unableToConvert(input: node, expectation: Token.type, path: ["object"]) } id = try node.extract("id") amount = try node.extract("amount") amount_refunded = try node.extract("amount_refunded") application = try? node.extract("application") application_fee = try? node.extract("application_fee") balance_transaction = try node.extract("balance_transaction") captured = try node.extract("captured") created = try node.extract("created") currency = try node.extract("currency") customer = try? node.extract("customer") description = try? node.extract("description") destination = try? node.extract("destination") dispute = try? node.extract("dispute") failure_code = try? node.extract("failure_code") failure_message = try? node.extract("failure_message") fraud_details = try node.extract("fraud_details") invoice = try? node.extract("invoice") livemode = try node.extract("livemode") order = try? node.extract("order") outcome = try node.extract("outcome") paid = try node.extract("paid") receipt_email = try? node.extract("receipt_email") receipt_number = try? node.extract("receipt_number") refunded = try node.extract("refunded") refunds = try node.extract("refunds") review = try? node.extract("review") shipping = try? node.extract("shipping") source = try node.extract("source") source_transfer = try? node.extract("source_transfer") statement_descriptor = try? node.extract("statement_descriptor") status = try? node.extract("status") transfer = try? node.extract("transfer") } public func makeNode(in context: Context?) throws -> Node { return try Node(node : [ "id" : .string(id), "amount" : .number(.int(amount)), "amount_refunded" : .number(.int(amount_refunded)), "balance_transaction" : .string(balance_transaction), "captured" : .bool(captured), "created" : try created.makeNode(in: context), "currency" : try currency.makeNode(in: context), "fraud_details" : fraud_details, "livemode" : .bool(livemode), "outcome" : try outcome.makeNode(in: context), "paid" : .bool(paid), "refunded" : .bool(refunded), "refunds" : refunds, "source" : try source.makeNode(in: context), ] as [String : Node]).add(objects: [ "application" : application, "application_fee" : application_fee, "description" : description, "destination" : destination, "dispute" : dispute, "customer" : customer, "failure_code" : failure_code, "failure_message" : failure_message, "order" : order, "invoice" : invoice, "receipt_email" : receipt_email, "receipt_number" : receipt_number, "source_transfer" : source_transfer, "statement_descriptor" : statement_descriptor, "status" : status, "review" : review, "shipping" : shipping, "transfer" : transfer ]) } }
mit
digdoritos/RestfulAPI-Example
RestfulAPI-Example/ContactsTableViewController.swift
1
3180
// // ContactsTableViewController.swift // RestfulAPI-Example // // Created by Chun-Tang Wang on 27/03/2017. // Copyright © 2017 Chun-Tang Wang. All rights reserved. // import UIKit class ContactsTableViewController: UITableViewController { override func viewDidLoad() { super.viewDidLoad() // Uncomment the following line to preserve selection between presentations // self.clearsSelectionOnViewWillAppear = false // Uncomment the following line to display an Edit button in the navigation bar for this view controller. // self.navigationItem.rightBarButtonItem = self.editButtonItem() addSlideMenu() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } // MARK: - Table view data source override func numberOfSections(in tableView: UITableView) -> Int { // #warning Incomplete implementation, return the number of sections return 0 } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { // #warning Incomplete implementation, return the number of rows return 0 } /* override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "reuseIdentifier", for: indexPath) // Configure the cell... return cell } */ /* // Override to support conditional editing of the table view. override func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool { // Return false if you do not want the specified item to be editable. return true } */ /* // Override to support editing the table view. override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) { if editingStyle == .delete { // Delete the row from the data source tableView.deleteRows(at: [indexPath], with: .fade) } else if editingStyle == .insert { // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view } } */ /* // Override to support rearranging the table view. override func tableView(_ tableView: UITableView, moveRowAt fromIndexPath: IndexPath, to: IndexPath) { } */ /* // Override to support conditional rearranging of the table view. override func tableView(_ tableView: UITableView, canMoveRowAt indexPath: IndexPath) -> Bool { // Return false if you do not want the item to be re-orderable. return true } */ /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepare(for segue: UIStoryboardSegue, sender: Any?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ }
mit
andresbrun/UIKonf_2015
FriendsGlue/FriendsGlue/EventListViewController.swift
1
5670
// // EventListViewController.swift // FriendsGlue // // Created by Andres Brun Moreno on 20/05/15. // Copyright (c) 2015 Andres Brun Moreno. All rights reserved. // import UIKit class EventListViewController: UIViewController, UITableViewDataSource, UITableViewDelegate, UIActionSheetDelegate { @IBOutlet weak var segmentedControl: UISegmentedControl! @IBOutlet weak var tableView: UITableView! var publicEventList: [Event] = [ Event.createEvent("Play football", locationName: "MauerPark", latitude: nil, longitude: nil, date: NSDate().dateByAddingTimeInterval(3600*24*3), friends: []), Event.createEvent("Drink a beer", locationName: "Mitte", latitude: nil, longitude: nil, date: NSDate().dateByAddingTimeInterval(3600*24*1), friends: []), Event.createEvent("Go to the cinema", locationName: "Sony Center", latitude: nil, longitude: nil, date: NSDate().dateByAddingTimeInterval(3600*24*5), friends: []), Event.createEvent("Watch a match", locationName: "Colisseum", latitude: nil, longitude: nil, date: NSDate().dateByAddingTimeInterval(3600*24*10), friends: []), Event.createEvent("Go to the cinema", locationName: "Sony Center", latitude: nil, longitude: nil, date: NSDate().dateByAddingTimeInterval(3600*24*5), friends: []), Event.createEvent("Watch a match", locationName: "At the bar", latitude: nil, longitude: nil, date: NSDate().dateByAddingTimeInterval(3600*24*10), friends: []), Event.createEvent("Drink a beer", locationName: "Mitte", latitude: nil, longitude: nil, date: NSDate().dateByAddingTimeInterval(3600*24*1), friends: []) ] var privateEventList: [Event] = [ Event.createEvent("Play football", locationName: "MauerPark", latitude: nil, longitude: nil, date: NSDate().dateByAddingTimeInterval(3600*24*3), friends: []), Event.createEvent("Go to the cinema", locationName: "Sony Center", latitude: nil, longitude: nil, date: NSDate().dateByAddingTimeInterval(3600*24*5), friends: []), Event.createEvent("Watch a match", locationName: "At the bar", latitude: nil, longitude: nil, date: NSDate().dateByAddingTimeInterval(3600*24*10), friends: []), Event.createEvent("Drink a beer", locationName: "Mitte", latitude: nil, longitude: nil, date: NSDate().dateByAddingTimeInterval(3600*24*1), friends: []) ] var refreshControl:UIRefreshControl! override func viewDidLoad() { super.viewDidLoad() self.refreshControl = UIRefreshControl() self.refreshControl.attributedTitle = NSAttributedString(string: "Pull to refresh") self.refreshControl.addTarget(self, action: "refresh:", forControlEvents: UIControlEvents.ValueChanged) self.refreshControl.tintColor = UIColor.cDarkBlue() self.tableView.addSubview(refreshControl) } func refresh(sender:AnyObject) { APIClient.sharedInstance.requestSessionToken({ () -> Void in println("login success") APIClient.sharedInstance.listEvents({ (events) -> Void in self.privateEventList = events self.publicEventList = events dispatch_async(dispatch_get_main_queue(), { () -> Void in self.tableView.reloadData() self.refreshControl.endRefreshing() }) }, failure: { (_) -> Void in println("events: failure") self.refreshControl.endRefreshing() }) }, failure: { (error) -> Void in println("login failure \(error)") self.refreshControl.endRefreshing() }) } override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) refresh(self) } func numberOfSectionsInTableView(tableView: UITableView) -> Int { return 1 } func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return currentList().count } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("EventTableViewCell") as! EventTableViewCell let currentEvent = currentList()[indexPath.row] cell.locationLabel.text = currentEvent.locationName cell.activityLabel.text = currentEvent.verb // cell.peopleCountLabel.text = "\(currentEvent.friends.count) friends" cell.peopleCountLabel.text = "\(Int(arc4random_uniform(7)+1)) friends" let formatter = NSDateFormatter() formatter.dateStyle = .ShortStyle formatter.timeStyle = .NoStyle cell.timeLabel.text = formatter.stringFromDate(currentEvent.date ?? NSDate()) return cell } func tableView(tableView: UITableView, shouldHighlightRowAtIndexPath indexPath: NSIndexPath) -> Bool { let actionSheet = UIActionSheet(title: "I want to...", delegate: self, cancelButtonTitle: "Dismiss", destructiveButtonTitle: "Meh, nope", otherButtonTitles: "Yeah, I am in!") actionSheet.showInView(view) return false } @IBAction func segmentControlChanged(sender: AnyObject) { tableView.reloadData() } func actionSheet(actionSheet: UIActionSheet, clickedButtonAtIndex buttonIndex: Int) { // API call to update status } func currentList() -> [Event] { return segmentedControl.selectedSegmentIndex == 0 ? privateEventList : publicEventList } }
mit
gobetti/Swift
CollectionView/CollectionView/AppDelegate.swift
1
2155
// // AppDelegate.swift // CollectionView // // Created by Carlos Butron on 02/12/14. // Copyright (c) 2015 Carlos Butron. All rights reserved. // import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool { // Override point for customization after application launch. return true } func applicationWillResignActive(application: UIApplication) { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game. } func applicationDidEnterBackground(application: UIApplication) { // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. } func applicationWillEnterForeground(application: UIApplication) { // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background. } func applicationDidBecomeActive(application: UIApplication) { // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. } func applicationWillTerminate(application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. } }
mit
ioan-chera/DoomMakerSwift
DoomMakerSwift/MapItem.swift
1
2786
/* DoomMaker Copyright (C) 2017 Ioan Chera 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 /// /// Item that has to be saved and loaded from map /// protocol Serializable { init(data: [UInt8]) var serialized: [UInt8] { get } } /// /// Individual map item. It mainly is storable in sets /// class IndividualItem: Hashable { func hash(into hasher: inout Hasher) { hasher.combine(ObjectIdentifier(self)) } static func == (lhs: IndividualItem, rhs: IndividualItem) -> Bool { return lhs === rhs } } /// /// This is a map editor item (thing, linedef, vertex, sector). Sidedefs are /// excluded. /// class InteractiveItem: IndividualItem { var draggables: Set<DraggedItem> { return Set() } var linedefs: Set<Linedef> { return Set() } var sectors: Set<Sector> { return Set() } } /// /// Dragged item. Used by things and vertices for proper display in the editor /// when dragging objects, without changing state until user releases the mouse /// button. /// class DraggedItem: InteractiveItem { var x, y: Int16 // coordinates to map area private(set) var dragging = false private var dragX: Int16 = 0, dragY: Int16 = 0 var apparentX: Int16 { get { return dragging ? dragX : x } } var apparentY: Int16 { get { return dragging ? dragY : y } } init(x: Int16, y: Int16) { self.x = x self.y = y } func setDragging(x: Int16, y: Int16) -> Bool { dragging = dragging || x != self.x || y != self.y dragX = x dragY = y return dragging } func setDragging(point: NSPoint) -> Bool { return setDragging(x: Int16(round(point.x)), y: Int16(round(point.y))) } func endDragging() { dragging = false } var position: NSPoint { get { return NSPoint(x: x, y: y) } set(value) { x = Int16(round(value.x)) y = Int16(round(value.y)) } } // // MARK: InteractiveItem // override var draggables: Set<DraggedItem> { return Set([self]) } }
gpl-3.0
yoshiki/LINEBotAPI
Package.swift
1
496
import PackageDescription let package = Package( name: "LINEBotAPI", dependencies: [ .Package(url: "https://github.com/yoshiki/Curl.git", majorVersion: 0), .Package(url: "https://github.com/Zewo/JSON.git", majorVersion: 0, minor: 12), .Package(url: "https://github.com/Zewo/HTTPServer.git", majorVersion: 0, minor: 13), .Package(url: "https://github.com/ZewoGraveyard/Base64.git", majorVersion: 0, minor: 12), ], exclude: [ "EnvironmentTests" ] )
mit
prolificinteractive/Yoshi
Yoshi/Yoshi/Utility/AppBundleUtility.swift
1
2159
// // AppBundleUtility.swift // Yoshi // // Created by Michael Campbell on 1/4/16. // Copyright © 2016 Prolific Interactive. All rights reserved. // /// Utility for retrieving items from the App Bundle class AppBundleUtility: NSObject { /** The application version + build number text. - returns: The application version. */ class func appVersionText() -> String { return "Version \(AppBundleUtility.appVersionNumber())" + " (\(AppBundleUtility.appBuildNumber()))" } /** The bundle icon. - returns: The bundle icon, if any. */ class func icon() -> UIImage? { let appBundleIconsKey = "CFBundleIcons" let appBundlePrimaryIconKey = "CFBundlePrimaryIcon" let iconFilesKey = "CFBundleIconFiles" guard let icons = Bundle.main.infoDictionary?[appBundleIconsKey] as? [String: AnyObject], let primaryIcons = icons[appBundlePrimaryIconKey] as? [String: AnyObject], let iconFiles = primaryIcons[iconFilesKey] as? [String], let iconImageName = iconFiles.last else { return nil } return UIImage(named: iconImageName) } /** The application display name. - returns: The appplication display name. */ class func appDisplayName() -> String { let appDisplayNameDictionaryKey = "CFBundleName" return Bundle.main.object(forInfoDictionaryKey: appDisplayNameDictionaryKey) as? String ?? "" } /** The application version number. - returns: The application version number. */ private class func appVersionNumber() -> String { let appVersionNumberDictionaryKey = "CFBundleShortVersionString" return Bundle.main.object(forInfoDictionaryKey: appVersionNumberDictionaryKey) as? String ?? "" } /** The application build number. - returns: The application build number. */ private class func appBuildNumber() -> String { let appBuildNumberDictionaryKey = "CFBundleVersion" return Bundle.main.object(forInfoDictionaryKey: appBuildNumberDictionaryKey) as? String ?? "" } }
mit
KrishMunot/swift
test/Interpreter/properties.swift
6
6188
// RUN: %target-run-simple-swift | FileCheck %s // REQUIRES: executable_test var foo: Int { get { print("foo gotten") return 219 } set { print("foo set") } } struct Bar { var bar: Int { get { print("bar gotten") return 20721 } set { print("bar set") } } static var staticBar: Int { get { print("staticBar gotten") return 97210 } set { print("staticBar set") } } static var staticStoredBar: Int = 123456 } struct WillSetDidSetStruct { var x : Int { didSet { print("got \(x)") } willSet { print("from \(x) to \(newValue)") } } init() { x = 0 } } class WillSetDidSetClass { var x : Int { didSet { print("got \(x)") } willSet { print("from \(x) to \(newValue)") } } init() { x = 0 } } class DynamicPropertiesBase { var x: String { return "base" } var y : String { get { return "base" } set { print("set y to \(newValue)") } } } class DynamicPropertiesDerived : DynamicPropertiesBase { override var x: String { return "derived" } } class DynamicPropertiesObserved : DynamicPropertiesBase { override var y : String { willSet { print("willSet Y from \(y) to \(newValue)!") } didSet { print("didSet Y from \(oldValue) to \(y)!") } } } func test() { var b = Bar() // CHECK: foo gotten // CHECK: 219 print(foo) // CHECK: foo set foo = 1 // CHECK: bar gotten // CHECK: 20721 print(b.bar) // CHECK: bar set b.bar = 2 // CHECK: staticBar gotten // CHECK: 97210 print(Bar.staticBar) // CHECK: staticBar set Bar.staticBar = 3 // CHECK: 123456 print(Bar.staticStoredBar) Bar.staticStoredBar = 654321 // CHECK: 654321 print(Bar.staticStoredBar) func increment(_ x: inout Int) { x += 1 } var ds = WillSetDidSetStruct() print("start is \(ds.x)") ds.x = 42 print("now is \(ds.x)") increment(&ds.x) print("now is \(ds.x)") // CHECK: start is 0 // CHECK: from 0 to 42 // CHECK: got 42 // CHECK: now is 42 // CHECK: from 42 to 43 // CHECK: got 43 // CHECK: now is 43 let dsc = WillSetDidSetClass() print("start is \(dsc.x)") dsc.x = 42 print("now is \(dsc.x)") increment(&dsc.x) print("now is \(dsc.x)") // CHECK: start is 0 // CHECK: from 0 to 42 // CHECK: got 42 // CHECK: now is 42 // CHECK: from 42 to 43 // CHECK: got 43 // CHECK: now is 43 // Properties should be dynamically dispatched. var dpd = DynamicPropertiesDerived() print("dpd.x is \(dpd.x)") // CHECK: dpd.x is derived var dpb : DynamicPropertiesBase = dpd print("dpb.x is \(dpb.x)") // CHECK: dpb.x is derived dpb = DynamicPropertiesBase() print("dpb.x is \(dpb.x)") // CHECK: dpb.x is base dpb = DynamicPropertiesObserved() dpb.y = "newString" // CHECK: willSet Y from base to newString! // CHECK: set y to newString // CHECK: didSet Y from base to base! } test() func lazyInitFunction() -> Int { print("lazy property initialized") return 0 } class LazyPropertyClass { var id : Int lazy var lazyProperty = lazyInitFunction() lazy var lazyProperty2 : Int = { print("other lazy property initialized") return 0 }() init(_ ident : Int) { id = ident print("LazyPropertyClass.init #\(id)") } deinit { print("LazyPropertyClass.deinit #\(id)") } } func testLazyProperties() { print("testLazyPropertiesStart") // CHECK: testLazyPropertiesStart if true { var a = LazyPropertyClass(1) // CHECK-NEXT: LazyPropertyClass.init #1 _ = a.lazyProperty // CHECK-NEXT: lazy property initialized _ = a.lazyProperty // executed only once, lazy init not called again. a.lazyProperty = 42 // nothing interesting happens _ = a.lazyProperty2 // CHECK-NEXT: other lazy property initialized // CHECK-NEXT: LazyPropertyClass.init #2 // CHECK-NEXT: LazyPropertyClass.deinit #1 a = LazyPropertyClass(2) a = LazyPropertyClass(3) a.lazyProperty = 42 // Store don't trigger lazy init. // CHECK-NEXT: LazyPropertyClass.init #3 // CHECK-NEXT: LazyPropertyClass.deinit #2 // CHECK-NEXT: LazyPropertyClass.deinit #3 } print("testLazyPropertiesDone") // CHECK: testLazyPropertiesDone } testLazyProperties() /// rdar://16805609 - <rdar://problem/16805609> Providing a 'didSet' in a generic override doesn't work class rdar16805609Base<T> { var value : String = "" } class rdar16805609Derived<T> : rdar16805609Base<String>{ override var value : String { didSet(val) { print("reached me") } } } let person = rdar16805609Derived<Int>() print("testing rdar://16805609") // CHECK: testing rdar://16805609 person.value = "foo" // CHECK-NEXT: reached me print("done rdar://16805609") // CHECK-NEXT: done rdar://16805609 // rdar://17192398 - Lazy optional types always nil class r17192398Failure { lazy var i : Int? = 42 func testLazy() { assert(i == 42) } } let x = r17192398Failure() x.testLazy() // <rdar://problem/17226384> Setting a lazy optional property to nil has a strange behavior (Swift) class r17226384Class { lazy var x : Int? = { print("propertyRun"); return 42 }() } func test_r17226384() { var c = r17226384Class() print("created") // CHECK-NEXT: created // CHECK-NEXT: propertyRun print(c.x) // CHECK-NEXT: Optional(42) print("setting") // CHECK-NEXT: setting c.x = nil print(c.x) // CHECK-NEXT: nil print("done") // CHECK-NEXT: done } test_r17226384() class A {} class HasStaticVar { static var a = A() static var i = 1010 static let j = 2020 } class DerivesHasStaticVar : HasStaticVar {} assert(HasStaticVar.a === DerivesHasStaticVar.a) assert(HasStaticVar.i == DerivesHasStaticVar.i) HasStaticVar.i = 2020 assert(HasStaticVar.i == DerivesHasStaticVar.i) var _x: Int = 0 class HasClassVar { class var x: Int { get { return _x } set { _x = newValue } } } assert(HasClassVar.x == 0) HasClassVar.x += 10 assert(HasClassVar.x == 10)
apache-2.0
GuiBayma/PasswordVault
PasswordVaultTests/AppDelegateTests.swift
1
349
// // AppDelegateTests.swift // PasswordVault // // Created by Guilherme Bayma on 7/28/17. // Copyright © 2017 Bayma. All rights reserved. // import Foundation import Quick import Nimble @testable import PasswordVault class AppDelegateTests: QuickSpec { override func spec() { describe("AppDelegate tests") { } } }
mit
KrishMunot/swift
test/decl/inherit/initializer.swift
3
4166
// RUN: %target-parse-verify-swift class A { init(int i: Int) { } init(double d: Double) { } convenience init(float f: Float) { self.init(double: Double(f)) } } // Implicit overriding of subobject initializers class B : A { var x = "Hello" var (y, z) = (1, 2) } func testB() { _ = B(int: 5) _ = B(double: 2.71828) _ = B(float: 3.14159) } // Okay to have nothing class C : B { } func testC() { _ = C(int: 5) _ = C(double: 2.71828) _ = C(float: 3.14159) } // Okay to add convenience initializers. class D : C { convenience init(string s: String) { self.init(int: Int(s)!) } } func testD() { _ = D(int: 5) _ = D(double: 2.71828) _ = D(float: 3.14159) _ = D(string: "3.14159") } // Adding a subobject initializer prevents inheritance of subobject // initializers. class NotInherited1 : D { override init(int i: Int) { super.init(int: i) } convenience init(float f: Float) { self.init(int: Int(f)) } } func testNotInherited1() { var n1 = NotInherited1(int: 5) var n2 = NotInherited1(double: 2.71828) // expected-error{{argument labels '(double:)' do not match any available overloads}} // expected-note @-1 {{overloads for 'NotInherited1' exist with these partially matching parameter lists: (int: Int), (float: Float)}} } class NotInherited1Sub : NotInherited1 { override init(int i: Int) { super.init(int: i) } } func testNotInherited1Sub() { var n1 = NotInherited1Sub(int: 5) var n2 = NotInherited1Sub(float: 3.14159) var n3 = NotInherited1Sub(double: 2.71828) // expected-error{{argument labels '(double:)' do not match any available overloads}} // expected-note @-1 {{overloads for 'NotInherited1Sub' exist with these partially matching parameter lists: (int: Int), (float: Float)}} } // Having a stored property without an initial value prevents // inheritance of initializers. class NotInherited2 : D { // expected-error{{class 'NotInherited2' has no initializers}} var a: Int // expected-note{{stored property 'a' without initial value prevents synthesized initializers}}{{13-13= = 0}} var b: Int // expected-note{{stored property 'b' without initial value prevents synthesized initializers}}{{13-13= = 0}} , c: Int // expected-note{{stored property 'c' without initial value prevents synthesized initializers}}{{13-13= = 0}} var (d, e): (Int, String) // expected-note{{stored properties 'd' and 'e' without initial values prevent synthesized initializers}}{{28-28= = (0, "")}} var (f, (g, h)): (Int?, (Float, String)) // expected-note{{stored properties 'f', 'g', and 'h' without initial values prevent synthesized initializers}}{{43-43= = (nil, (0.0, ""))}} var (w, i, (j, k)): (Int?, Float, (String, D)) // expected-note{{stored properties 'w', 'i', 'j', and others without initial values prevent synthesized initializers}} } func testNotInherited2() { var n1 = NotInherited2(int: 5) // expected-error{{'NotInherited2' cannot be constructed because it has no accessible initializers}} var n2 = NotInherited2(double: 2.72828) // expected-error{{'NotInherited2' cannot be constructed because it has no accessible initializers}} } // Inheritance of unnamed parameters. class SuperUnnamed { init(int _: Int) { } init(_ : Double) { } init(string _: String) { } init(_ : Float) { } } class SubUnnamed : SuperUnnamed { } func testSubUnnamed(_ i: Int, d: Double, s: String, f: Float) { _ = SubUnnamed(int: i) _ = SubUnnamed(d) _ = SubUnnamed(string: s) _ = SubUnnamed(f) } // FIXME: <rdar://problem/16331406> Implement inheritance of variadic designated initializers class SuperVariadic { init(ints: Int...) { } // expected-note{{variadic superclass initializer defined here}} init(_ : Double...) { } // expected-note{{variadic superclass initializer defined here}} init(s: String, ints: Int...) { } // expected-note{{variadic superclass initializer defined here}} init(s: String, _ : Double...) { } // expected-note{{variadic superclass initializer defined here}} } class SubVariadic : SuperVariadic { } // expected-warning 4{{synthesizing a variadic inherited initializer for subclass 'SubVariadic' is unsupported}}
apache-2.0
iPantry/iPantry-iOS
Pantry/Models/PantryItem.swift
1
3624
// // PantryItem.swift // Pantry // // Created by Justin Oroz on 6/15/17. // Copyright © 2017 Justin Oroz. All rights reserved. // import Foundation struct PantryItem: Hashable { var hashValue: Int { return self.identifier!.hash } static func == (left: PantryItem, right: PantryItem) -> Bool { if left.identifier != nil || right.identifier != nil { return left.identifier == right.identifier } else { return right.upcData?.ean == left.upcData?.ean } } static func != (left: PantryItem, right: PantryItem) -> Bool { return !(left == right) } subscript(index: String) -> FireValue? { get { return modified[index] ?? itemDict[index] ?? upcData?[index] as? FireValue } set(newValue) { //can only modify string: values // if neither places have data, add it guard (upcData?[index] == nil) && (modified[index] == nil) else { modified[index] = newValue return } guard let new = newValue as? String else { return } if let upc = upcData?[index] as? String { if upc == new { // Clear item detail newValue is same modified[index] = nil } else if let item = itemDict[index] as? String { if item != new { // Only add modify if newValue is unique modified[index] = newValue } } } } } // create new item to load to firebase init?(_ creator: String, _ upcData: UPCDatabaseItem?) { guard let ean = upcData?["ean"] as? String else { fb_log(.error, message: "Failed to create new PantryItem, no EAN") return nil } self.creator = creator self.ean = ean self.upcData = upcData self.itemDict = [:] // a modified dictionary for storing changes. // move this init to small temporary class for creating new Items, Idenitifier should be a requirement } // init from firebase and possible upcdb data init?(_ itemId: String, _ itemDict: FireDictionary, _ upcData: UPCDatabaseItem?) { guard let ean = itemDict["ean"] as? String, let creator = itemDict["creator"] as? String else { fb_log(.error, message: "New Pantry Item failed with ID", args: ["id": itemId]) return nil } self.ean = ean self.creator = creator self.identifier = itemId self.itemDict = itemDict self.upcData = upcData } /// private(set) var identifier: String? private var itemDict: FireDictionary private let upcData: UPCDatabaseItem? private var modified = FireDictionary() mutating func update(_ itemDict: FireDictionary) { //self.itemDict += itemDict itemDict.forEach({ self.itemDict[$0.0] = $0.1}) } private(set) var expirationEstimate: Int? var title: String? { if let userItem = self.itemDict["title"] as? String { return userItem } else if let upcItem = self.upcData?.title { return upcItem } else { return nil } } let ean: String var creator: String var quantity: UInt? { return self.itemDict["quantity"] as? UInt } var lasted: UInt? { return self.itemDict["lasted"] as? UInt } var purchasedDate: String? { return self.itemDict["purchasedDate"] as? String } var weight: String? { get { if let userItem = self.itemDict["weight"] as? String { return userItem } else if let upcItem = self.upcData?.weight { return upcItem } else { return nil } } set { self["size"] = newValue } } var size: String? { get { if let userItem = self.itemDict["size"] as? String { return userItem } else if let upcItem = self.upcData?.size { return upcItem } else { return nil } } set { self["size"] = newValue } } var pantry: String? { return self.itemDict["pantry"] as? String } }
agpl-3.0
Bartlebys/Bartleby
Bartleby.xOS/core/Handlers.swift
1
7106
// // Handlers.swift // // Created by Benoit Pereira da silva on 22/01/2016. // Copyright © 2016 Benoit Pereira da silva. All rights reserved. // import Foundation /* # Notes on Handlers ## We expose 6 Handlers - CompletionHandler : a closure with a completion state - ProgressionHandler : a closure with a progression state - Handlers : a class that allows to compose completion an progression Handlers. - ComposedHandler : a composed closure - VoidCompletionHandler : a void handler that can be used as place holder - VoidProgressionHandler : a void handler that can be used as place holder ## We should not use ComposedHandler in XPC context (!) Only one closure can be called per XPC call. So to monitor progression from an XPC : **we use Bidirectionnal XPC + Monitoring protocol for the progress** ## You can create a code Snippets for : ``` let onCompletion:CompletionHandler = { completion in } ``` ``` let onProgression:ProgressHandler = { progression in } ``` ## Chaining Handlers: You can chain an handler but keep in mind it can produce retain cycle ``` let onCompletion:CompletionHandler = { completion in previousHandler(completion) //<--- you can chain a previous handler } ``` ## You can instanciate a ComposedHandler : ``` let handler: ComposedHandler = {(progressionState, completionState) -> Void in if let progression=progressionState { } if let completion=completionState { } } ``` */ // MARK: - /* ProgressionHandler ``` let onProgression:ProgressionHandler = { progression in previousHandler(progression)// Invoke ... } ``` */ public typealias ProgressionHandler = (_ progressionState: Progression) -> () /* CompletionHandler You can chain handlers: ``` let onCompletion:CompletionHandler = { completion in previousHandler(completion)// Invoke ... } ``` */ public typealias CompletionHandler = (_ conpletionState: Completion) -> () public var VoidCompletionHandler:CompletionHandler = { completion in } public var VoidProgressionHandler:ProgressionHandler = { progression in } /** A composed Closure with a progress and acompletion section Generally Used in XPC facades because we can pass only one handler per XPC call To consume and manipulate we generally split the ComposedHandler by calling Handlers.handlersFrom(composed) You can instanciate a ComposedHandler : ``` let handler: ComposedHandler = {(progressionState, completionState) -> Void in if let progression=progressionState { } if let completion=completionState { } } ``` Or you can create one from a Handlers instance by calling `composedHandler()` */ public typealias ComposedHandler = (_ progressionState: Progression?, _ completionState: Completion?)->() // MARK: - Handlers /** * Composable handlers * You can compose multiple completion and progression */ open class Handlers: NSObject { // MARK: Progression handlers open var progressionHandlersCount: Int { get { return self._progressionHandlers.count } } fileprivate var _progressionHandlers: [ProgressionHandler] = [] open func appendProgressHandler(_ ProgressionHandler: @escaping ProgressionHandler) { self._progressionHandlers.append(ProgressionHandler) } // Call all the progression handlers open func notify(_ progressionState: Progression) { for handler in self._progressionHandlers { handler(progressionState) } } // MARK: Completion handlers open var completionHandlersCount: Int { get { return self._completionHandlers.count } } fileprivate var _completionHandlers: [CompletionHandler] = [] open func appendCompletionHandler(_ handler: @escaping CompletionHandler) { self._completionHandlers.append(handler) } // Call all the completion handlers open func on(_ completionState: Completion) { for handler in self._completionHandlers { handler(completionState) } } /** A factory to declare an explicit Handlers with no completion. - returns: an Handlers instance */ public static func withoutCompletion() -> Handlers { return Handlers.init(completionHandler: nil) } /** Appends the chained handlers to the current Handlers All The chained closure will be called sequentially. - parameter chainedHandlers: the handlers to be chained. */ open func appendChainedHandlers(_ chainedHandlers: Handlers) { self.appendCompletionHandler(chainedHandlers.on) self.appendProgressHandler(chainedHandlers.notify) } /** Designated initializer You Should pass a completion Handler (that's the best practice) It is optionnal for rare situations like (TaskGroup placeholder Handlers) - parameter completionHandler: the completion Handler - returns: the instance. */ public required init(completionHandler: CompletionHandler?) { if let completionHandler=completionHandler { self._completionHandlers.append(completionHandler) } } /** A convenience initializer - parameter completionHandler: the completion Handler - parameter progressionHandler: the progression Handler - returns: the instance */ public convenience init(completionHandler: CompletionHandler?, progressionHandler: ProgressionHandler?) { self.init(completionHandler:completionHandler) if let progressionHandler=progressionHandler { self._progressionHandlers.append(progressionHandler) } } /** XPC adapter used to split closure in two parts - parameter composedHandler: the composed handler - returns: an instance of Handlers */ public static func handlersFrom(_ composedHandler: @escaping ComposedHandler) -> Handlers { // Those handlers produce an adaptation // From the unique handler form // progress and completion handlers. let handlers=Handlers {(onCompletion) -> () in composedHandler(nil, onCompletion) } handlers.appendProgressHandler { (onProgression) -> () in composedHandler(onProgression, nil) } return handlers } /** We need to provide a unique handler to be compatible with the XPC context So we use an handler adapter that relays to the progress and completion handlers to mask the constraint. - returns: the composed Handler */ open func composedHandler() -> ComposedHandler { let handler: ComposedHandler = {(progressionState, completionState) -> Void in if let progressionState=progressionState { self.notify(progressionState) } if let completion=completionState { self.on(completion) } } return handler } }
apache-2.0
kean/Nuke-Alamofire-Plugin
Package.swift
1
702
// swift-tools-version:5.6 import PackageDescription let package = Package( name: "Nuke Alamofire Plugin", platforms: [ .macOS(.v10_15), .iOS(.v13), .tvOS(.v13), .watchOS(.v6) ], products: [ .library(name: "NukeAlamofirePlugin", targets: ["NukeAlamofirePlugin"]), ], dependencies: [ .package( url: "https://github.com/kean/Nuke.git", from: "11.0.0" ), .package( url: "https://github.com/Alamofire/Alamofire.git", from: "5.0.0" ) ], targets: [ .target(name: "NukeAlamofirePlugin", dependencies: ["Nuke", "Alamofire"], path: "Source") ] )
mit
danielgindi/ios-charts
Source/Charts/Utils/Platform+Accessibility.swift
2
5735
// // Platform+Accessibility.swift // Charts // // Copyright 2015 Daniel Cohen Gindi & Philipp Jahoda // A port of MPAndroidChart for iOS // Licensed under Apache License 2.0 // // https://github.com/danielgindi/Charts // import Foundation #if os(iOS) || os(tvOS) import UIKit internal func accessibilityPostLayoutChangedNotification(withElement element: Any? = nil) { UIAccessibility.post(notification: .layoutChanged, argument: element) } internal func accessibilityPostScreenChangedNotification(withElement element: Any? = nil) { UIAccessibility.post(notification: .screenChanged, argument: element) } /// A simple abstraction over UIAccessibilityElement and NSAccessibilityElement. open class NSUIAccessibilityElement: UIAccessibilityElement { private weak var containerView: UIView? final var isHeader: Bool = false { didSet { accessibilityTraits = isHeader ? .header : .none } } final var isSelected: Bool = false { didSet { accessibilityTraits = isSelected ? .selected : .none } } override public init(accessibilityContainer container: Any) { // We can force unwrap since all chart views are subclasses of UIView containerView = container as? UIView super.init(accessibilityContainer: container) } override open var accessibilityFrame: CGRect { get { return super.accessibilityFrame } set { guard let containerView = containerView else { return } super.accessibilityFrame = containerView.convert(newValue, to: UIScreen.main.coordinateSpace) } } } extension NSUIView { /// An array of accessibilityElements that is used to implement UIAccessibilityContainer internally. /// Subclasses **MUST** override this with an array of such elements. @objc open func accessibilityChildren() -> [Any]? { return nil } public final override var isAccessibilityElement: Bool { get { return false } // Return false here, so we can make individual elements accessible set { } } open override func accessibilityElementCount() -> Int { return accessibilityChildren()?.count ?? 0 } open override func accessibilityElement(at index: Int) -> Any? { return accessibilityChildren()?[index] } open override func index(ofAccessibilityElement element: Any) -> Int { guard let axElement = element as? NSUIAccessibilityElement else { return NSNotFound } return (accessibilityChildren() as? [NSUIAccessibilityElement])?.firstIndex(of: axElement) ?? NSNotFound } } #endif #if os(OSX) import AppKit internal func accessibilityPostLayoutChangedNotification(withElement element: Any? = nil) { guard let validElement = element else { return } NSAccessibility.post(element: validElement, notification: .layoutChanged) } internal func accessibilityPostScreenChangedNotification(withElement element: Any? = nil) { // Placeholder } /// A simple abstraction over UIAccessibilityElement and NSAccessibilityElement. open class NSUIAccessibilityElement: NSAccessibilityElement { private weak var containerView: NSView? final var isHeader: Bool = false { didSet { setAccessibilityRole(isHeader ? .staticText : .none) } } final var isSelected: Bool = false { didSet { setAccessibilitySelected(isSelected) } } open var accessibilityLabel: String { get { return accessibilityLabel() ?? "" } set { setAccessibilityLabel(newValue) } } open var accessibilityFrame: NSRect { get { return accessibilityFrame() } set { guard let containerView = containerView else { return } let bounds = NSAccessibility.screenRect(fromView: containerView, rect: newValue) // This works, but won't auto update if the window is resized or moved. // setAccessibilityFrame(bounds) // using FrameInParentSpace allows for automatic updating of frame when windows are moved and resized. // However, there seems to be a bug right now where using it causes an offset in the frame. // This is a slightly hacky workaround that calculates the offset and removes it from frame calculation. setAccessibilityFrameInParentSpace(bounds) let axFrame = accessibilityFrame() let widthOffset = abs(axFrame.origin.x - bounds.origin.x) let heightOffset = abs(axFrame.origin.y - bounds.origin.y) let rect = NSRect(x: bounds.origin.x - widthOffset, y: bounds.origin.y - heightOffset, width: bounds.width, height: bounds.height) setAccessibilityFrameInParentSpace(rect) } } public init(accessibilityContainer container: Any) { // We can force unwrap since all chart views are subclasses of NSView containerView = (container as! NSView) super.init() setAccessibilityParent(containerView) setAccessibilityRole(.row) } } /// - Note: setAccessibilityRole(.list) is called at init. See Platform.swift. extension NSUIView: NSAccessibilityGroup { open override func accessibilityLabel() -> String? { return "Chart View" } open override func accessibilityRows() -> [Any]? { return accessibilityChildren() } } #endif
apache-2.0
tadasz/MistikA
MistikA/Classes/BaseViewController.swift
1
2875
// // BaseViewController.swift // MistikA // // Created by Tadas Ziemys on 29/07/14. // Copyright (c) 2014 Tadas Ziemys. All rights reserved. // import UIKit import AVFoundation let conts_GoBack = 84756 class BaseViewController: UIViewController, UIAlertViewDelegate { override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. let gestureRecognizer = UISwipeGestureRecognizer(target: self, action: Selector("swiped:")) gestureRecognizer.direction = UISwipeGestureRecognizerDirection.Right gestureRecognizer.delaysTouchesBegan = true view.addGestureRecognizer(gestureRecognizer) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } override func viewWillDisappear(animated: Bool) { super.viewWillDisappear(animated) player!.stop() } /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepareForSegue(segue: UIStoryboardSegue!, sender: AnyObject!) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ // MARK: - Go back func swiped(object: AnyObject) { let alert = UIAlertView(title: "pasiduodi?", message: "o jeigu tai mistika...", delegate: self, cancelButtonTitle: "gal..", otherButtonTitles: "atgal") alert.tag = conts_GoBack alert.show() } func alertView(alertView: UIAlertView, didDismissWithButtonIndex buttonIndex: Int) { if alertView.tag == 84756 { if buttonIndex == 1 { dismissViewControllerAnimated(true, completion: nil) } } } //MARK: - Sounds var player = try? AVAudioPlayer(contentsOfURL: NSURL(fileURLWithPath: NSBundle.mainBundle().pathForResource("wrong1", ofType: "mp3")!), fileTypeHint: "mp3") func playSoundWrong() { if player!.playing { player!.stop() } let fileName: String = "wrong\(arc4random_uniform(18) + 1)" player = try? AVAudioPlayer(contentsOfURL: NSURL(fileURLWithPath: NSBundle.mainBundle().pathForResource(fileName, ofType: "mp3")!), fileTypeHint: "mp3") player!.play() } func playSoundWin() { if player!.playing { player!.stop() } let fileName: String = "mistika" player = try? AVAudioPlayer(contentsOfURL: NSURL(fileURLWithPath: NSBundle.mainBundle().pathForResource(fileName, ofType: "wav")!), fileTypeHint: "wav") player!.numberOfLoops = -1 player!.play() } }
mit
awesome-labs/LFTimePicker
Sources/LFTimePickerController.swift
1
15867
// // LFTimePickerController.swift // LFTimePicker // // Created by Lucas Farah on 6/1/16. // Copyright © 2016 Lucas Farah. 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 } } //MARK: - LFTimePickerDelegate /** Used to return information after user taps the "Save" button - requires: func didPickTime(start: String, end: String) */ public protocol LFTimePickerDelegate: class { /** Called after pressing save. Used so the user can call their server to check user's information. - returns: start and end times in hh:mm aa */ func didPickTime(_ start: String, end: String) } /** ViewController that handles the Time Picking - customizations: timeType, startTimes, endTimes */ open class LFTimePickerController: UIViewController { // MARK: - Variables open weak var delegate: LFTimePickerDelegate? var startTimes: [String] = [] var endTimes: [String] = [] var leftTimeTable = UITableView() var rightTimeTable = UITableView() var lblLeftTimeSelected = UILabel() var lblRightTimeSelected = UILabel() var detailBackgroundView = UIView() var lblAMPM = UILabel() var lblAMPM2 = UILabel() var firstRowIndex = 0 var lastSelectedLeft = "00:00" var lastSelectedRight = "00:00" var isCustomTime = false /// Used to customize a 12-hour or 24-hour times public enum TimeType { /// Enables AM-PM case hour12 /// 24-hour format case hour24 } /// Used for customization of time possibilities public enum Time { /// Customizing possible start times case startTime /// Customizing possible end times case endTime } /// Hour Format: 12h (default) or 24h format open var timeType = TimeType.hour12 open var backgroundColor = UIColor(red: 255 / 255, green: 128 / 255, blue: 0, alpha: 1) open var titleText: String = "Change Time" open var saveText: String = "Save" open var cancelText: String = "Cancel" // MARK: - Methods /// Used to load all the setup methods override open func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. } var alreadyLayout = false open override func viewWillLayoutSubviews() { if !alreadyLayout { self.title = titleText self.view.backgroundColor = backgroundColor setupTables() setupDetailView() setupBottomDetail() setupNavigationBar() setupTime() alreadyLayout = true } } // MARK: Setup fileprivate func setupNavigationBar() { let saveButton = UIBarButtonItem(title: saveText, style: .plain, target: self, action: #selector(butSave)) saveButton.tintColor = .red let cancelButton = UIBarButtonItem(title: cancelText, style: .plain, target: self, action: #selector(butCancel)) cancelButton.tintColor = .red self.navigationItem.rightBarButtonItem = saveButton self.navigationItem.leftBarButtonItem = cancelButton } fileprivate func setupTables() { let frame1 = CGRect(x: 30, y: 0, width: 100, height: self.view.bounds.height) leftTimeTable = UITableView(frame: frame1, style: .plain) let frame2 = CGRect(x: self.view.frame.width - 100, y: 0, width: 100, height: self.view.bounds.height) rightTimeTable = UITableView(frame: frame2, style: .plain) leftTimeTable.separatorStyle = .none rightTimeTable.separatorStyle = .none leftTimeTable.dataSource = self leftTimeTable.delegate = self rightTimeTable.dataSource = self rightTimeTable.delegate = self leftTimeTable.register(UITableViewCell.self, forCellReuseIdentifier: "cell") rightTimeTable.register(UITableViewCell.self, forCellReuseIdentifier: "cell") leftTimeTable.backgroundColor = .clear rightTimeTable.backgroundColor = .clear leftTimeTable.showsVerticalScrollIndicator = false rightTimeTable.showsVerticalScrollIndicator = false leftTimeTable.allowsSelection = false rightTimeTable.allowsSelection = false view.addSubview(leftTimeTable) view.addSubview(rightTimeTable) self.view.sendSubview(toBack: leftTimeTable) self.view.sendSubview(toBack: rightTimeTable) } fileprivate func setupDetailView() { detailBackgroundView = UIView(frame: CGRect(x: 0, y: (self.view.bounds.height / 5) * 2, width: self.view.bounds.width, height: self.view.bounds.height / 6)) detailBackgroundView.backgroundColor = .white lblLeftTimeSelected = UILabel(frame: CGRect(x: 20, y: detailBackgroundView.frame.height / 2, width: 110, height: detailBackgroundView.frame.height)) lblLeftTimeSelected.center = CGPoint(x: 60, y: detailBackgroundView.frame.height / 2) lblLeftTimeSelected.font = UIFont.systemFont(ofSize: 40) lblLeftTimeSelected.text = "00:00" lblLeftTimeSelected.textAlignment = .center lblRightTimeSelected = UILabel(frame: CGRect(x: detailBackgroundView.frame.width / 7 * 6 + 20, y: detailBackgroundView.frame.height / 2, width: 110, height: detailBackgroundView.frame.height)) lblRightTimeSelected.center = CGPoint(x: detailBackgroundView.bounds.width - 60, y: detailBackgroundView.frame.height / 2) lblRightTimeSelected.font = UIFont.systemFont(ofSize: 40) lblRightTimeSelected.text = "00:00" lblRightTimeSelected.textAlignment = .center detailBackgroundView.addSubview(lblLeftTimeSelected) detailBackgroundView.addSubview(lblRightTimeSelected) let lblTo = UILabel(frame: CGRect(x: detailBackgroundView.frame.width / 2, y: detailBackgroundView.frame.height / 2, width: 30, height: 20)) lblTo.text = "TO" detailBackgroundView.addSubview(lblTo) self.view.addSubview(detailBackgroundView) } fileprivate func setupBottomDetail() { let bottomDetailMainBackground = UIView(frame: CGRect(x: 0, y: self.detailBackgroundView.frame.maxY, width: self.view.frame.width, height: 38)) bottomDetailMainBackground.backgroundColor = UIColor(red: 255 / 255, green: 128 / 255, blue: 0, alpha: 1) let bottomDetailMainShade = UIView(frame: CGRect(x: 0, y: self.detailBackgroundView.frame.maxY, width: self.view.frame.width, height: 38)) bottomDetailMainShade.backgroundColor = UIColor(red: 255 / 255, green: 255 / 255, blue: 255 / 255, alpha: 0.6) lblAMPM = UILabel(frame: CGRect(x: 20, y: bottomDetailMainShade.frame.height / 2, width: 110, height: bottomDetailMainShade.frame.height)) lblAMPM.center = CGPoint(x: 60, y: bottomDetailMainShade.frame.height / 2) lblAMPM.font = UIFont.systemFont(ofSize: 15) lblAMPM.text = "AM" lblAMPM.textAlignment = .center lblAMPM2 = UILabel(frame: CGRect(x: bottomDetailMainShade.frame.width / 7 * 6 + 20, y: bottomDetailMainShade.frame.height / 2, width: 110, height: bottomDetailMainShade.frame.height)) lblAMPM2.center = CGPoint(x: bottomDetailMainShade.bounds.width - 60, y: bottomDetailMainShade.frame.height / 2) lblAMPM2.font = UIFont.systemFont(ofSize: 15) lblAMPM2.text = "AM" lblAMPM2.textAlignment = .center bottomDetailMainShade.addSubview(lblAMPM) bottomDetailMainShade.addSubview(lblAMPM2) self.view.addSubview(bottomDetailMainBackground) self.view.addSubview(bottomDetailMainShade) } fileprivate func setupTime() { if !isCustomTime { switch timeType { case TimeType.hour12: lblAMPM.isHidden = false lblAMPM2.isHidden = false startTimes = defaultTimeArray12() endTimes = defaultTimeArray12() break case TimeType.hour24: lblAMPM.isHidden = true lblAMPM2.isHidden = true startTimes = defaultTimeArray24() endTimes = defaultTimeArray24() break } } else { lblAMPM.isHidden = true lblAMPM2.isHidden = true } } func defaultTimeArray12() -> [String] { var arr: [String] = [] for _ in 0...8 { arr.append("") } for ampm in 0...1 { for hr in 0...11 { for min in 0 ..< 12 { if min == 0 && ampm == 1 && hr == 0 { arr.append("12:00") } else if hr == 0 && ampm == 1 { var minute = "\(min * 5)" minute = minute.characters.count == 1 ? "0"+minute : minute arr.append("12:\(minute)") } else if min == 0 { arr.append("\(hr):00") } else { var minute = "\(min * 5)" minute = minute.characters.count == 1 ? "0"+minute : minute arr.append("\(hr):\(minute)") } } } } for _ in 0...8 { arr.append("") } return arr } func defaultTimeArray24() -> [String] { var arr: [String] = [] lblAMPM.isHidden = true lblAMPM2.isHidden = true for _ in 0...8 { arr.append("") } for hr in 0...23 { for min in 0 ..< 12 { if min == 0 { arr.append("\(hr):00") } else { var minute = "\(min * 5)" minute = minute.characters.count == 1 ? "0"+minute : minute arr.append("\(hr):\(minute)") } } leftTimeTable.reloadData() } for _ in 0...8 { arr.append("") } return arr } // MARK: Button Methods @objc fileprivate func butSave() { let time = self.lblLeftTimeSelected.text! let time2 = self.lblRightTimeSelected.text! if isCustomTime { delegate?.didPickTime(time, end: time2) } else if timeType == .hour12 { delegate?.didPickTime(time + " \(self.lblAMPM.text!)", end: time2 + " \(self.lblAMPM2.text!)") } else { delegate?.didPickTime(time, end: time2) } _ = self.navigationController?.popViewController(animated: true) } @objc fileprivate func butCancel() { _ = self.navigationController?.popViewController(animated: true) } // MARK - Customisations open func customizeTimes(_ timesArray: [String], time: Time) { isCustomTime = true switch time { case .startTime: startTimes = timesArray leftTimeTable.reloadData() for _ in 0...8 { startTimes.insert("", at: 0) } for _ in 0...8 { startTimes.append("") } case .endTime: endTimes = timesArray rightTimeTable.reloadData() for _ in 0...8 { endTimes.insert("", at: 0) } for _ in 0...8 { endTimes.append("") } } } } //MARK: - UITableViewDataSource extension LFTimePickerController: UITableViewDataSource { /// Setup of Time cells public func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { if tableView == leftTimeTable { return startTimes.count } else if tableView == rightTimeTable { return endTimes.count } return 0 } // Setup of Time cells public func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { var cell = tableView.dequeueReusableCell(withIdentifier: "cell") as UITableViewCell! if !(cell != nil) { cell = UITableViewCell(style: .default, reuseIdentifier: "cell") } // setup cell without force unwrapping it var arr: [String] = [] if tableView == leftTimeTable { arr = startTimes } else if tableView == rightTimeTable { arr = endTimes } cell?.textLabel!.text = arr[indexPath.row] cell?.textLabel?.textColor = .white cell?.backgroundColor = .clear return cell! } } //MARK: - UITableViewDelegate extension LFTimePickerController: UITableViewDelegate { /// Used to change AM from PM public func scrollViewDidScroll(_ scrollView: UIScrollView) { if leftTimeTable.visibleCells.count > 8 { let isLeftAM = leftTimeTable.indexPathsForVisibleRows?.first?.row < 48 * 3 self.lblAMPM.text = isLeftAM ? "AM" : "PM" let text = leftTimeTable.visibleCells[8] if text.textLabel?.text != "" { self.lblLeftTimeSelected.text = text.textLabel?.text lastSelectedLeft = (text.textLabel?.text!)! } else { self.lblLeftTimeSelected.text = lastSelectedLeft } } else { self.lblLeftTimeSelected.text = "00:00" } if rightTimeTable.visibleCells.count > 8 { let isRightAM = rightTimeTable.indexPathsForVisibleRows?.first?.row < 48 * 3 self.lblAMPM2.text = isRightAM ? "AM" : "PM" let text2 = rightTimeTable.visibleCells[8] if text2.textLabel?.text != "" { self.lblRightTimeSelected.text = text2.textLabel?.text lastSelectedRight = (text2.textLabel?.text!)! } else { self.lblRightTimeSelected.text = lastSelectedRight } } else { lblRightTimeSelected.text = "00:00" } if let rowIndex = leftTimeTable.indexPathsForVisibleRows?.first?.row { firstRowIndex = rowIndex } if let rowIndex = rightTimeTable.indexPathsForVisibleRows?.first?.row { firstRowIndex = rowIndex } } } //Got from EZSwiftExtensions extension Timer { fileprivate static func runThisAfterDelay(seconds: Double, after: @escaping () -> ()) { runThisAfterDelay(seconds: seconds, queue: DispatchQueue.main, after: after) } fileprivate static func runThisAfterDelay(seconds: Double, queue: DispatchQueue, after: @escaping () -> ()) { let time = DispatchTime.now() + Double(Int64(seconds * Double(NSEC_PER_SEC))) / Double(NSEC_PER_SEC) queue.asyncAfter(deadline: time, execute: after) } }
mit
zane001/ZMTuan
ZMTuan/View/Merchant/MerchantFilterCell.swift
1
7740
// // MerchantFilterCell.swift // ZMTuan // // Created by zm on 4/30/16. // Copyright © 2016 zm. All rights reserved. // import UIKit protocol MerchantFilterDelegate: AnyObject { func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath, withID ID: NSNumber, withName name: String) } class MerchantFilterCell: UIView, UITableViewDelegate, UITableViewDataSource { var tableViewOfGroup: UITableView! var tableViewOfDetail: UITableView! var bigGroupArray = NSMutableArray() //左边分组的数据源 var smallGroupArray = NSMutableArray() //右边分组的数据源 var bigSelectedIndex: NSInteger! var smallSelectedIndex: NSInteger! var delegate: MerchantFilterDelegate! override init(frame: CGRect) { super.init(frame: frame) self.initViews() dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)) { self.getCateListData() } } func initViews() { // 分组 self.tableViewOfGroup = UITableView(frame: CGRectMake(0, 0, self.frame.size.width/2, self.frame.size.height), style: .Plain) self.tableViewOfGroup.delegate = self self.tableViewOfGroup.dataSource = self self.tableViewOfGroup.backgroundColor = UIColor.grayColor() self.tableViewOfGroup.tag = 10 self.tableViewOfGroup.separatorStyle = .None self.addSubview(tableViewOfGroup) // 详情 self.tableViewOfDetail = UITableView(frame: CGRectMake(self.frame.size.width/2, 0, self.frame.size.width/2, self.frame.size.height), style: .Plain) self.tableViewOfDetail.delegate = self self.tableViewOfDetail.dataSource = self self.tableViewOfDetail.tag = 20 self.tableViewOfDetail.separatorStyle = .None self.tableViewOfDetail.backgroundColor = RGB(242, g: 242, b: 242) self.addSubview(tableViewOfDetail) self.userInteractionEnabled = true } // 获取Cate分组信息 func getCateListData() { let url = "http://api.meituan.com/group/v1/poi/cates/showlist?__skck=40aaaf01c2fc4801b9c059efcd7aa146&__skcy=hSjSxtGbfd1QtKRMWnoFV4GB8jU%3D&__skno=0DEF926E-FB94-43B8-819E-DD510241BCC3&__skts=1436504818.875030&__skua=bd6b6e8eadfad15571a15c3b9ef9199a&__vhost=api.mobile.meituan.com&ci=1&cityId=1&client=iphone&movieBundleVersion=100&msid=48E2B810-805D-4821-9CDD-D5C9E01BC98A2015-07-10-12-44726&userid=10086&utm_campaign=AgroupBgroupD100Fa20141120nanning__m1__leftflow___ab_pindaochangsha__a__leftflow___ab_gxtest__gd__leftflow___ab_gxhceshi__nostrategy__leftflow___ab_i550poi_ktv__d__j___ab_chunceshishuju__a__a___ab_gxh_82__nostrategy__leftflow___ab_i_group_5_3_poidetaildeallist__a__b___b1junglehomepagecatesort__b__leftflow___ab_gxhceshi0202__b__a___ab_pindaoquxincelue0630__b__b1___ab_i550poi_xxyl__b__leftflow___ab_i_group_5_6_searchkuang__a__leftflow___i_group_5_2_deallist_poitype__d__d___ab_pindaoshenyang__a__leftflow___ab_b_food_57_purepoilist_extinfo__a__a___ab_waimaiwending__a__a___ab_waimaizhanshi__b__b1___ab_i550poi_lr__d__leftflow___ab_i_group_5_5_onsite__b__b___ab_xinkeceshi__b__leftflowGmerchant&utm_content=4B8C0B46F5B0527D55EA292904FD7E12E48FB7BEA8DF50BFE7828AF7F20BB08D&utm_medium=iphone&utm_source=AppStore&utm_term=5.7&uuid=4B8C0B46F5B0527D55EA292904FD7E12E48FB7BEA8DF50BFE7828AF7F20BB08D&version_name=5.7" NetworkSingleton.sharedManager.sharedSingleton.getCateListResult([:], url: url, successBlock: { (responseBody) in let dataArray = responseBody.objectForKey("data") for i in 0 ..< dataArray!.count { let cateM = MerCateGroupModel.mj_objectWithKeyValues(dataArray![i]) self.bigGroupArray.addObject(cateM) } self.tableViewOfGroup.reloadData() }) { (error) in print("获取cate分组信息失败:\(error)") } } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func awakeFromNib() { super.awakeFromNib() // Initialization code } func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { if tableView.tag == 10 { return bigGroupArray.count } else { if bigGroupArray.count == 0 { return 0 } let cateM = bigGroupArray[bigSelectedIndex] as! MerCateGroupModel if cateM.list == nil { return 0 } else { return cateM.list.count } } } func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat { return 42 } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { if tableView.tag == 10 { let cellIdentifier = "filterCell1" var cell = tableView.dequeueReusableCellWithIdentifier(cellIdentifier) as? KindFilterCell if cell == nil { cell = KindFilterCell() cell?.initWithStyle(.Default, reuseIdentifier: cellIdentifier, withFrame: CGRectMake(0, 0, SCREEN_WIDTH/2, 42)) } let cateM = bigGroupArray[indexPath.row] as? MerCateGroupModel cell?.setGroupM(cateM!) cell?.selectedBackgroundView = UIView(frame: cell!.frame) cell?.selectedBackgroundView?.backgroundColor = RGB(239, g: 239, b: 239) return cell! } else { let cellIdentifier = "filterCell2" var cell = tableView.dequeueReusableCellWithIdentifier(cellIdentifier) if cell == nil { cell = UITableViewCell(style: .Default, reuseIdentifier: cellIdentifier) // 下划线 let lineView = UIView(frame: CGRectMake(0, 41.5, cell!.frame.size.width, 0.5)) lineView.backgroundColor = RGB(0, g: 192, b: 192) cell?.contentView.addSubview(lineView) } let cateM = bigGroupArray[bigSelectedIndex] as? MerCateGroupModel cell?.textLabel?.text = cateM?.list[indexPath.row].objectForKey("name") as? String cell?.detailTextLabel?.text = cateM?.list[indexPath.row].objectForKey("count") as? String cell?.textLabel?.font = UIFont.systemFontOfSize(15) cell?.detailTextLabel?.font = UIFont.systemFontOfSize(13) cell?.backgroundColor = RGB(242, g: 242, b: 242) cell?.selectionStyle = .None return cell! } } func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { if tableView.tag == 10 { bigSelectedIndex = indexPath.row let cateM = bigGroupArray[bigSelectedIndex] as? MerCateGroupModel if cateM?.list == nil { self.tableViewOfDetail.reloadData() self.delegate.tableView(tableView, didSelectRowAtIndexPath: indexPath, withID: (cateM?.id)!, withName: (cateM?.name)!) } else { self.tableViewOfDetail.reloadData() } } else { smallSelectedIndex = indexPath.row let cateM = bigGroupArray[bigSelectedIndex] as? MerCateGroupModel let dic: NSDictionary = (cateM?.list[smallSelectedIndex])! as! NSDictionary let id = dic.objectForKey("id") as? NSNumber let name = dic.objectForKey("name") as? String self.delegate.tableView(tableView, didSelectRowAtIndexPath: indexPath, withID: id!, withName: name!) } } }
mit
jeffreybergier/Hipstapaper
Hipstapaper/Packages/V3Style/Sources/V3Style/PropertyWrappers/ShowsTable.swift
1
1745
// // Created by Jeffrey Bergier on 2022/07/30. // // MIT License // // Copyright (c) 2021 Jeffrey Bergier // // 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 SwiftUI import Umbrella @propertyWrapper public struct ShowsTable: DynamicProperty { public enum Value { case showTable, showList } @JSBSizeClass private var sizeClass @Environment(\.dynamicTypeSize) private var typeSize public init() {} public var wrappedValue: Value { switch (self.sizeClass.horizontal, self.typeSize.isAccessibilitySize) { case (.regular, false): return .showTable default: return .showList } } }
mit
neekeetab/VKAudioPlayer
VKAudioPlayer/CacheController.swift
1
7754
// // CacheController.swift // VKAudioPlayer // // Created by Nikita Belousov on 7/19/16. // Copyright © 2016 Nikita Belousov. All rights reserved. // import Foundation class CacheController: CachingPlayerItemDelegate { static let sharedCacheController = CacheController() private var _numberOfSimultaneousDownloads = 3 var numberOfSimultaneousDownloads: Int { get { return _numberOfSimultaneousDownloads } set { _numberOfSimultaneousDownloads = newValue downloadNextAudioItem() } } private var audioItemsToDownoad = Queue<AudioItem>() private var audioItemsBeingDownloaded = [AudioItem: AudioCachingPlayerItem]() private var audioItemsToCancel = Set<AudioItem>() // audioItemsTotalDownloadStatus holds the invariant: audioItemsTotalDownloadStatus = audioItemsToDownload + audioItemsBeingDownloaded - audioItemsToCancel private var audioItemsTotalDownloadStatus = [AudioItem: Float]() // MARK: private func downloadNextAudioItem() { if audioItemsBeingDownloaded.count < numberOfSimultaneousDownloads { if let audioItem = audioItemsToDownoad.dequeue() { if audioItem.downloadStatus == AudioItemDownloadStatusCached { downloadNextAudioItem() return } if audioItemsToCancel.contains(audioItem) { audioItemsToCancel.remove(audioItem) downloadNextAudioItem() return } let playerItem = AudioCachingPlayerItem(audioItem: audioItem) playerItem.delegate = self audioItemsBeingDownloaded[audioItem] = playerItem playerItem.download() } } } // adds audioItem to download queue func downloadAudioItem(audioItem: AudioItem) { audioItemsToDownoad.enqueue(audioItem) audioItemsToCancel.remove(audioItem) let notification = NSNotification(name: CacheControllerDidUpdateDownloadStatusOfAudioItemNotification, object: nil, userInfo: [ "audioItem": audioItem, "downloadStatus": 0.0 ]) NSNotificationCenter.defaultCenter().postNotification(notification) audioItemsTotalDownloadStatus[audioItem] = 0.0 if audioItemsBeingDownloaded.count < numberOfSimultaneousDownloads { downloadNextAudioItem() } } func cancelDownloadingAudioItem(audioItem: AudioItem) { if let _ = audioItemsBeingDownloaded[audioItem] { audioItemsBeingDownloaded.removeValueForKey(audioItem) } else { audioItemsToCancel.insert(audioItem) } audioItemsTotalDownloadStatus.removeValueForKey(audioItem) let notification = NSNotification(name: CacheControllerDidUpdateDownloadStatusOfAudioItemNotification, object: nil, userInfo: [ "audioItem": audioItem, "downloadStatus": downloadStatusForAudioItem(audioItem) ]) NSNotificationCenter.defaultCenter().postNotification(notification) downloadNextAudioItem() } func playerItemForAudioItem(audioItem: AudioItem, completionHandler: (playerItem: AudioCachingPlayerItem, cached: Bool)->()){ if audioItem.downloadStatus == AudioItemDownloadStatusCached { Storage.sharedStorage.object(String(audioItem.id), completion: { (data: NSData?) in let playerItem = AudioCachingPlayerItem(data: data!, audioItem: audioItem) completionHandler(playerItem: playerItem, cached: true) }) } else { // if audioItem is being downloaded if let playerItem = audioItemsBeingDownloaded[audioItem] { completionHandler(playerItem: playerItem, cached: false) return } let playerItem = AudioCachingPlayerItem(audioItem: audioItem) playerItem.delegate = self completionHandler(playerItem: playerItem, cached: false) } } func downloadStatusForAudioItem(audioItem: AudioItem) -> Float { if let status = audioItemsTotalDownloadStatus[audioItem] { return status } if Storage.sharedStorage.objectIsCached(String(audioItem.id)) { return AudioItemDownloadStatusCached } return AudioItemDownloadStatusNotCached } func uncacheAudioItem(audioItem: AudioItem) { Storage.sharedStorage.remove(String(audioItem.id)) let notification = NSNotification(name: CacheControllerDidUpdateDownloadStatusOfAudioItemNotification, object: nil, userInfo: [ "audioItem": audioItem, "downloadStatus": AudioItemDownloadStatusNotCached ]) NSNotificationCenter.defaultCenter().postNotification(notification) } // MARK: CachingPlayerItem Delegate @objc func playerItem(playerItem: CachingPlayerItem, didDownloadBytesSoFar bytesDownloaded: Int, outOf bytesExpected: Int) { let audioItem = (playerItem as! AudioCachingPlayerItem).audioItem audioItemsTotalDownloadStatus[audioItem] = Float(Double(bytesDownloaded)/Double(bytesExpected)) let notification = NSNotification(name: CacheControllerDidUpdateDownloadStatusOfAudioItemNotification, object: nil, userInfo: [ "audioItem": audioItem, "downloadStatus": downloadStatusForAudioItem(audioItem) ]) NSNotificationCenter.defaultCenter().postNotification(notification) } @objc func playerItem(playerItem: CachingPlayerItem, didFinishDownloadingData data: NSData) { let audioItem = (playerItem as! AudioCachingPlayerItem).audioItem audioItemsBeingDownloaded.removeValueForKey(audioItem) audioItemsTotalDownloadStatus.removeValueForKey(audioItem) downloadNextAudioItem() Storage.sharedStorage.add(String(audioItem.id), object: data) let notification = NSNotification(name: CacheControllerDidUpdateDownloadStatusOfAudioItemNotification, object: nil, userInfo: [ "audioItem": audioItem, "downloadStatus": AudioItemDownloadStatusCached ]) NSNotificationCenter.defaultCenter().postNotification(notification) } @objc func playerItemDidStopPlayback(playerItem: CachingPlayerItem) { let audioItem = (playerItem as! AudioCachingPlayerItem).audioItem downloadNextAudioItem() let notification = NSNotification(name: AudioControllerDidPauseAudioItemNotification, object: nil, userInfo: [ "audioItem": audioItem ]) NSNotificationCenter.defaultCenter().postNotification(notification) } @objc func playerItemWillDeinit(playerItem: CachingPlayerItem) { let audioItem = (playerItem as! AudioCachingPlayerItem).audioItem if let _ = audioItemsTotalDownloadStatus[audioItem] { audioItemsTotalDownloadStatus.removeValueForKey(audioItem) let notification = NSNotification(name: CacheControllerDidUpdateDownloadStatusOfAudioItemNotification, object: nil, userInfo: [ "audioItem": audioItem, "downloadStatus": downloadStatusForAudioItem(audioItem) ]) NSNotificationCenter.defaultCenter().postNotification(notification) } } // MARK: private init() {} }
mit
pinterest/tulsi
src/TulsiGeneratorIntegrationTests/BazelFakeWorkspace.swift
1
4231
// Copyright 2018 The Tulsi Authors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. import Foundation import XCTest import TulsiGenerator class BazelFakeWorkspace { let resourcesPathBase = "src/TulsiGeneratorIntegrationTests/Resources" let extraBuildFlags: [String] var runfilesURL: URL var runfilesWorkspaceURL: URL var fakeExecroot: URL var workspaceRootURL: URL var bazelURL: URL var canaryBazelURL: URL? var pathsToCleanOnTeardown = Set<URL>() init(runfilesURL: URL, tempDirURL: URL) { self.runfilesURL = runfilesURL self.runfilesWorkspaceURL = runfilesURL.appendingPathComponent("__main__", isDirectory: true) self.fakeExecroot = tempDirURL.appendingPathComponent("fake_execroot", isDirectory: true) self.workspaceRootURL = fakeExecroot.appendingPathComponent("__main__", isDirectory: true) self.bazelURL = BazelLocator.bazelURL! // Stop gap for https://github.com/bazelbuild/tulsi/issues/94. // See also: https://github.com/bazelbuild/rules_apple/issues/456. self.extraBuildFlags = ["--host_force_python=PY2"] } private func addExportsFiles(buildFilePath: String, exportedFile: String) throws { try createDummyFile(path: "\(buildFilePath)/BUILD", content: "exports_files([\"\(exportedFile)\"])\n") } private func addFilegroup(buildFilePath: String, filegroup: String) throws { try createDummyFile(path: "\(buildFilePath)/BUILD", content: """ filegroup( name = "\(filegroup)", visibility = ["//visibility:public"], ) """ ) } private func createDummyFile(path: String, content: String) throws { let fileURL = workspaceRootURL.appendingPathComponent(path) let fileManager = FileManager.default let containingDirectory = fileURL.deletingLastPathComponent() if !fileManager.fileExists(atPath: containingDirectory.path) { try fileManager.createDirectory(at: containingDirectory, withIntermediateDirectories: true, attributes: nil) } if fileManager.fileExists(atPath: fileURL.path) { try fileManager.removeItem(at: fileURL) } try content.write(to: fileURL, atomically: false, encoding: String.Encoding.utf8) } private func installWorkspaceFile() { do { try FileManager.default.createDirectory(at: workspaceRootURL, withIntermediateDirectories: true, attributes: nil) do { let fileManager = FileManager.default if fileManager.fileExists(atPath: fakeExecroot.path) { try fileManager.removeItem(at: fakeExecroot) } try fileManager.copyItem(at: runfilesURL, to: fakeExecroot) pathsToCleanOnTeardown.insert(workspaceRootURL) } catch let e as NSError { XCTFail("Failed to copy workspace '\(runfilesURL)' to '\(workspaceRootURL)' for test. Error: \(e.localizedDescription)") return } } catch let e as NSError { XCTFail("Failed to create temp directory '\(workspaceRootURL.path)' for test. Error: \(e.localizedDescription)") } } func setup() -> BazelFakeWorkspace? { installWorkspaceFile() do { try createDummyFile(path: "tools/objc/objc_dummy.mm", content: "") try addExportsFiles(buildFilePath: "tools/objc", exportedFile: "objc_dummy.mm") } catch let e as NSError { XCTFail("Failed to set up fake workspace. Error: \(e.localizedDescription)") } return self } }
apache-2.0
EyreFree/EFQRCode
Examples/iOS/AppDelegate.swift
1
1577
// // AppDelegate.swift // EFQRCode // // Created by EyreFree on 2017/1/24. // // Copyright (c) 2017 EyreFree <eyrefree@eyrefree.org> // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? } func UIImage2CGimage(_ image: UIImage?) -> CGImage? { if let tryImage = image, let tryCIImage = CIImage(image: tryImage) { return CIContext().createCGImage(tryCIImage, from: tryCIImage.extent) } return nil }
mit
Gnodnate/ATerminal
ATerminal/HostTableViewController.swift
1
17677
// // HostTableViewController.swift // ATermial // // Created by Daniel Tan on 11/05/2017. // Copyright © 2017 Thnuth. All rights reserved. // import UIKit import CoreData import NMSSH enum SortKeyWord:String { case date = "addtime" case name = "name" } class HostTableViewController: UITableViewController, UIViewControllerTransitioningDelegate, NSFetchedResultsControllerDelegate, UISearchResultsUpdating { lazy var cancelAlertAction = UIAlertAction(title: NSLocalizedString("Cancel", comment: "button title, user used to cancel"), style: .cancel) lazy var okAlertAction = UIAlertAction(title: NSLocalizedString("OK", comment: "button title, user comfirm the status"), style: .default) private var cacheFolder:URL { return FileManager.default.urls(for: .cachesDirectory, in: .userDomainMask)[0] } private var knowHostsFilePath:String { let path = URL(fileURLWithPath: "./know_hosts", relativeTo: cacheFolder).path if !FileManager.default.fileExists(atPath: path) { FileManager.default.createFile(atPath: path, contents: nil) } return path } private var searchController:UISearchController! private var activeSSHVC = [Int64:SSHViewController]() private var userChangeTheTable:Bool = false private var sortKeyWord:SortKeyWord = .date { didSet { fetchedResultsController.fetchRequest.sortDescriptors = [NSSortDescriptor(key: sortKeyWord.rawValue, ascending: true)] do { try fetchedResultsController.performFetch() } catch { fatalError("Failed to initialize FetchedResultsController: \(error)") } tableView.reloadData() } } private var searchWord:String? { didSet { if searchWord != nil && searchWord!.count > 0 { fetchedResultsController.fetchRequest.predicate = NSPredicate(format: "name like[c] %@ OR hostname like[c] %@ OR username like[c] %@", "*".appending(searchWord!.appending("*")), searchWord!.appending("*"), searchWord!.appending("*")) } else { fetchedResultsController.fetchRequest.predicate = nil } do { try fetchedResultsController.performFetch() } catch { fatalError("Failed to initialize FetchedResultsController: \(error)") } tableView.reloadData() } } private lazy var fetchedResultsController = { () -> NSFetchedResultsController<Server> in let request:NSFetchRequest<Server> = Server.fetchRequest() request.sortDescriptors = [NSSortDescriptor(key: SortKeyWord.date.rawValue, ascending: true)] let moc = ServersController.persistentContainer.viewContext let _fetchedResultsController = NSFetchedResultsController(fetchRequest: request, managedObjectContext: moc, sectionNameKeyPath: nil, cacheName: nil) _fetchedResultsController.delegate = self do { try _fetchedResultsController.performFetch() } catch { fatalError("Failed to initialize FetchedResultsController: \(error)") } return _fetchedResultsController }() override func viewDidLoad() { super.viewDidLoad() self.tableView.tableFooterView = UIView() let longPressGesture = UILongPressGestureRecognizer(target: self, action: #selector(HostTableViewController.longPressAction(gesture:))) longPressGesture.minimumPressDuration = 1.0 tableView.addGestureRecognizer(longPressGesture) searchController = UISearchController(searchResultsController: nil) searchController.searchResultsUpdater = self searchController.dimsBackgroundDuringPresentation = false if #available(iOS 11.0, *) { self.navigationItem.searchController = searchController self.navigationItem.searchController?.isActive = true UITextField.appearance(whenContainedInInstancesOf: [UISearchBar.self]).defaultTextAttributes = [NSAttributedStringKey.foregroundColor.rawValue: UIColor.white] } else { tableView.tableHeaderView = searchController.searchBar } definesPresentationContext = true } override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if segue.identifier == "showServerSetting" && sender is UITableViewCell{ var serverSettingVC:ServerSettingTableViewController? if segue.destination is UINavigationController { serverSettingVC = (segue.destination as! UINavigationController).viewControllers[0] as? ServerSettingTableViewController } else { serverSettingVC = segue.destination as? ServerSettingTableViewController } guard let indexPath = tableView.indexPath(for:(sender as? UITableViewCell)!) else { return } serverSettingVC?.server = self.fetchedResultsController.object(at:indexPath) } } // MARK: - @objc func longPressAction(gesture: UILongPressGestureRecognizer) { if gesture.state == .began { let point = gesture.location(in: tableView) guard let indexPath = tableView.indexPathForRow(at: point) else { return } let serverEditSheet = UIAlertController(title: nil, message: nil, preferredStyle: .actionSheet) serverEditSheet.addAction(UIAlertAction(title: NSLocalizedString("Edit", comment: "edit server"), style: .default, handler: { (action:UIAlertAction) in self.performSegue(withIdentifier: "showServerSetting", sender: self.tableView.cellForRow(at: indexPath)) })) serverEditSheet.addAction(UIAlertAction(title: NSLocalizedString("Delete", comment: "delete server"), style: .default, handler: { (UIAlertAction) in self.deleteServer(at: indexPath) })) serverEditSheet.addAction(cancelAlertAction) self.present(serverEditSheet, animated: true) } } // MARK: - IBAction @IBAction func quickConnect(_ sender: UIBarButtonItem) { let loginHostAlert = UIAlertController(title: "Connect to SSH", message: "Please input host address and port", preferredStyle: UIAlertControllerStyle.alert) loginHostAlert.addTextField { (address:UITextField) in address.resignFirstResponder() address.keyboardType = .numbersAndPunctuation address.placeholder = "example: 192.168.0.1:22" address.returnKeyType = .next } loginHostAlert.addTextField { (user:UITextField) in user.returnKeyType = .next user.keyboardType = .asciiCapable user.placeholder = PlaceHolder.username } loginHostAlert.addTextField { (passwd:UITextField) in passwd.returnKeyType = .go passwd.keyboardType = .asciiCapable passwd.placeholder = PlaceHolder.password } let connect = UIAlertAction(title: "Connect", style: UIAlertActionStyle.default) { (UIAlertAction) in guard let textFields = loginHostAlert.textFields else { fatalError("No textFields") } self.showSSHView(host: textFields[0].text!, username: textFields[1].text!, passwd: textFields[2].text!, time: -1) } loginHostAlert.addAction(connect) loginHostAlert.addAction(cancelAlertAction) self.present(loginHostAlert, animated: true, completion: nil) } // MARK: - tableview datasource override func numberOfSections(in tableView: UITableView) -> Int { return fetchedResultsController.sections!.count } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { // return sshServers.count guard let sections = fetchedResultsController.sections else { fatalError("No sections in fetchedResultsController") } let sectionInfo = sections[section] return sectionInfo.numberOfObjects } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { guard let cell = tableView.dequeueReusableCell(withIdentifier: "hostCell") as? HostNameAndStatusTableViewCell else { fatalError("Wrong cell type dequeued") } let object = self.fetchedResultsController.object(at: indexPath) if !(object.name?.isEmpty)!{ cell.name?.text = object.name } else { cell.name?.text = String(format: "%@@%@", object.username!, object.hostname!) } let sshServer = fetchedResultsController.object(at: indexPath) if let SSHVC = activeSSHVC[sshServer.addtime] { if SSHVC.isConnected { cell.statusImage.image = UIImage(named: "onLine") } else { cell.statusImage.image = UIImage(named: "offLine") } } return cell } // swipe action override func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool { return true } override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) { switch editingStyle { case .delete: let sshServer = fetchedResultsController.object(at: indexPath) activeSSHVC[sshServer.addtime]?.removeFromParentViewController() activeSSHVC.removeValue(forKey: sshServer.addtime) let context = ServersController.persistentContainer.viewContext context.delete(sshServer) do { try context.save() } catch { fatalError("Failure to save context:\(error)") } default: break } } // MARK: tableview delegate override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { let sshServer = fetchedResultsController.object(at: indexPath) if let SSHVC = activeSSHVC[sshServer.addtime] { self.navigationController?.pushViewController(SSHVC, animated: true) } else { showSSHView(host: sshServer.hostname!, username: sshServer.username ?? "", passwd: sshServer.password ?? "", time: sshServer.addtime) } } override func tableView(_ tableView: UITableView, titleForDeleteConfirmationButtonForRowAt indexPath: IndexPath) -> String? { return NSLocalizedString("Delete", comment: "titleForDeleteConfirmationButton") } // MARK: - show terminal view func showSSHView(host:String, username:String, passwd:String = "", time:Int64 = -1){ let SSHVC = self.storyboard?.instantiateViewController(withIdentifier: "SSHView") as? SSHViewController if username.isEmpty { let loginAlert = UIAlertController(title: "Login", message: "Connect to \"\(host)\"", preferredStyle: .alert) loginAlert.addTextField { (user:UITextField) in user.returnKeyType = .next user.keyboardType = .asciiCapable user.placeholder = PlaceHolder.username } loginAlert.addTextField { (passwd:UITextField) in passwd.returnKeyType = .go passwd.keyboardType = .asciiCapable passwd.placeholder = PlaceHolder.password } let connect = UIAlertAction(title: "Connect", style: UIAlertActionStyle.default) { (UIAlertAction) in guard let textFields = loginAlert.textFields else { fatalError("No textFields") } self.showSSHView(host: host, username: textFields[0].text!, passwd: textFields[1].text!, time: time) } loginAlert.addAction(connect) loginAlert.addAction(cancelAlertAction) self.present(loginAlert, animated: true, completion: nil) } else if passwd.isEmpty { let loginAlert = UIAlertController(title: "Password", message: "Please input password for \"\(username)\"", preferredStyle: .alert) loginAlert.addTextField { (passwd:UITextField) in passwd.returnKeyType = .go passwd.keyboardType = .asciiCapable passwd.placeholder = "Password" } let connect = UIAlertAction(title: "Connect", style: UIAlertActionStyle.default) { (UIAlertAction) in guard let textFields = loginAlert.textFields else { fatalError("No textFields") } self.showSSHView(host: host, username: username, passwd: textFields[0].text!, time: time) } loginAlert.addAction(connect) loginAlert.addAction(cancelAlertAction) self.present(loginAlert, animated: true, completion: nil) } else if nil != SSHVC { if let session = NMSSHSession(host: host, andUsername: username) { if !session.connect() { let connectFailedAlert = UIAlertController(title: NSLocalizedString("Connect failed", comment: "Connect failed"), message: NSLocalizedString("Can't connect to \(host)", comment: "Can't connect to special IP Addres in %@"), preferredStyle: .alert) connectFailedAlert.addAction(okAlertAction) self.present(connectFailedAlert, animated: true) return } let pushSSHVC = { self.tableView.reloadData() SSHVC?.session = session SSHVC?.passwd = passwd self.navigationController?.pushViewController(SSHVC!, animated: true) if time != -1 { self.activeSSHVC[time] = SSHVC } } switch session.knownHostStatus(inFiles: [knowHostsFilePath]) { case .match: pushSSHVC() case .failure, .mismatch: return case .notFound: let unknowFingerprint = String(format:NSLocalizedString("Fingerprint is %@", comment: "Alert for unknow fingerprint") , session.fingerprint(.SHA1)) let hostKeyAlert = UIAlertController(title: NSLocalizedString("Unknow fingerprint", comment: "Title of host key alert"), message: unknowFingerprint, preferredStyle: .alert) let connectAnyway = UIAlertAction(title: NSLocalizedString("Connect", comment: "Title for sheet alert user if connect"), style: .default, handler: { (UIAlertAction) in session.addKnownHostName(session.host, port: session.port as! Int, toFile: self.knowHostsFilePath, withSalt: nil) pushSSHVC() }) hostKeyAlert.addAction(connectAnyway) hostKeyAlert.addAction(cancelAlertAction) self.present(hostKeyAlert, animated: true) } } } } // MARK: - NSFetchedResultsControllerDelegate func controllerWillChangeContent(_ controller: NSFetchedResultsController<NSFetchRequestResult>) { if userChangeTheTable { return } tableView.beginUpdates() } func controller(_ controller: NSFetchedResultsController<NSFetchRequestResult>, didChange sectionInfo: NSFetchedResultsSectionInfo, atSectionIndex sectionIndex: Int, for type: NSFetchedResultsChangeType) { if userChangeTheTable { return } switch type { case .insert: tableView.insertSections(IndexSet(integer: sectionIndex), with: .right) case .delete: tableView.deleteSections(IndexSet(integer: sectionIndex), with: .left) case .move: break case .update: break } } func controller(_ controller: NSFetchedResultsController<NSFetchRequestResult>, didChange anObject: Any, at indexPath: IndexPath?, for type: NSFetchedResultsChangeType, newIndexPath: IndexPath?) { if userChangeTheTable { return } switch type { case .insert: tableView.insertRows(at: [newIndexPath!], with: .right) case .delete: tableView.deleteRows(at: [indexPath!], with: .left) case .update: tableView.reloadRows(at: [indexPath!], with: .fade) case .move: tableView.moveRow(at: indexPath!, to: newIndexPath!) } } func controllerDidChangeContent(_ controller: NSFetchedResultsController<NSFetchRequestResult>) { if userChangeTheTable { userChangeTheTable = false return } tableView.endUpdates() } // MARK: - func deleteServer(at indexPath: IndexPath) { let sshServer = fetchedResultsController.object(at: indexPath) activeSSHVC[sshServer.addtime]?.removeFromParentViewController() activeSSHVC.removeValue(forKey: sshServer.addtime) let context = ServersController.persistentContainer.viewContext context.delete(sshServer) do { try context.save() } catch { fatalError("Failure to save context:\(error)") } } // MARK: - search updater func updateSearchResults(for searchController: UISearchController) { searchWord = searchController.searchBar.text } }
mit
EZ-NET/SwiftKeychain
SwiftKeychainTests/KeychainTests.swift
1
3436
// // KeychainTests.swift // SwiftKeychain // // Created by Yanko Dimitrov on 11/11/14. // Copyright (c) 2014 Yanko Dimitrov. All rights reserved. // import UIKit import XCTest class KeychainTests: XCTestCase { let serviceName = "swift.keychain.tests" var keychain: Keychain! let keyName = "password" var key: GenericKey! override func setUp() { super.setUp() keychain = Keychain(serviceName: serviceName) key = GenericKey(keyName: keyName, value: "1234") } override func tearDown() { super.tearDown() keychain.remove(key) } func testSingletonInstance() { let instanceA = Keychain.sharedKeychain let instanceB = Keychain.sharedKeychain XCTAssert(instanceA === instanceB, "Two shared instances should point to the same address") } func testThatWeCanAddNewItem() { let error = keychain.add(key) XCTAssertNil(error, "Can't add a new item to the keychain") } func testWillFailToAddDuplicateItem() { keychain.add(key) let error = keychain.add(key) XCTAssertNotNil(error, "Should fail when attempting to add a duplicate item in the keychain") } func testWillFailToAddItemWithIncompleteData() { let incompleteKey = GenericKey(keyName: keyName) let error = keychain.add(incompleteKey) XCTAssertNotNil(error, "Should fail to add item with incomplete data") } func testThatWeCanDeleteItem() { keychain.add(key) let error = keychain.remove(key) XCTAssertNil(error, "Can't remove an item from the keychain") } func testWillFailToDeleteNonExistingItem() { let error = keychain.remove(key) XCTAssertNotNil(error, "Should fail when attempting to delete a non existing item from the keychain") } func testThatWeCanUpdateItem() { keychain.add(key) let newKey = GenericKey(keyName: keyName, value: "5678") let error = keychain.update(newKey) XCTAssertNil(error, "Can't update the item in the keychain") } func testThatTheUpdatedItemHasBeenUpdated() { keychain.add(key) let newSecret = "5678" let newKey = GenericKey(keyName: keyName, value: newSecret) keychain.update(newKey) let storedKey = keychain.get(key).item?.value XCTAssertEqual(String(storedKey!), newSecret, "Failed to update the item value") } func testWillFailToUpdateItemWithIncompleteData() { let incompleteKey = GenericKey(keyName: keyName) let error = keychain.add(incompleteKey) XCTAssertNotNil(error, "Should fail to update item with incomplete data") } func testThatWeCanGetItem() { keychain.add(key) let storedKey = keychain.get(key).item XCTAssertNotNil(storedKey, "Can't get an item from the keychain") } func testWillFailToGetANonExistingItem() { let error = keychain.get(key).error XCTAssertNotNil(error, "Should fail when attempting to get a non exising item from the keychain") } }
mit
basheersubei/swift-t
stc/tests/170-autodeclare.swift
4
487
import assert; // Test auto-declaration of variables main { x = 1; trace(x); y = x + 2; A[0][1] = x; A[1][0] = y; assertEqual(A[0][1], 1, "A[0][1]"); assertEqual(A[1][0], 3, "A[1][0]"); // Check type inference for array lookups q = A[0]; r = q[1]; assertEqual(r, 1, "r"); // Check whole array creation B = [1,2,3]; z = 2.0; trace(z + 1.0); a = "hello"; b = "world"; c = a + " " + b; trace(c); assertEqual(c, "hello world", "hello world"); }
apache-2.0
marceloreis13/MRTableViewManager
Example/MRTableViewManager/ViewController.swift
1
881
// // ViewController.swift // MRTableViewManager // // Created by Marcelo Reis on 6/25/16. // Copyright © 2016 CocoaPods. All rights reserved. // import UIKit final class ViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ }
mit
KiranJasvanee/KJExpandableTableTree
Example_Dynamic_Init/KJExpandableTableTree/TableviewCells/ParentsTableViewCell.swift
1
1538
// // ParentsTableViewCell.swift // Expandable3 // // Created by MAC241 on 11/05/17. // Copyright © 2017 KiranJasvanee. All rights reserved. // import UIKit class ParentsTableViewCell: UITableViewCell { @IBOutlet weak var imageviewBackground: UIImageView! @IBOutlet weak var constraintLeadingLabelParent: NSLayoutConstraint! @IBOutlet weak var labelParentCell: UILabel! @IBOutlet weak var labelIndex: UILabel! @IBOutlet weak var buttonState: UIButton! override func awakeFromNib() { super.awakeFromNib() // Initialization code labelParentCell.font = UIFont(name: "HelveticaNeue-Bold", size: 15) labelIndex.font = UIFont(name: "HelveticaNeue-Bold", size: 14) } func cellFillUp(indexParam: String, tupleCount: NSInteger) { if tupleCount == 1 { labelParentCell.text = "Parent custom cell" imageviewBackground.image = UIImage(named: "1st") constraintLeadingLabelParent.constant = 16 }else{ labelParentCell.text = "Child custom cell" imageviewBackground.image = nil constraintLeadingLabelParent.constant = 78 } labelParentCell.textColor = UIColor.white labelIndex.textColor = UIColor.white labelIndex.text = "Index: \(indexParam)" } override func setSelected(_ selected: Bool, animated: Bool) { super.setSelected(selected, animated: animated) // Configure the view for the selected state } }
mit
criticalmaps/criticalmaps-ios
CriticalMapsKit/Sources/FileClient/Interface.swift
1
1248
import Combine import ComposableArchitecture import Foundation import Helpers import SharedModels // MARK: Interface /// Client handling FileManager interactions public struct FileClient { public var delete: @Sendable (String) async throws -> Void public var load: @Sendable (String) async throws -> Data public var save: @Sendable (String, Data) async throws -> Void public func load<A: Decodable>( _ type: A.Type, from fileName: String, with decoder: JSONDecoder = JSONDecoder() ) async throws -> A { let data = try await load(fileName) return try data.decoded(decoder: decoder) } public func save<A: Encodable>( _ data: A, to fileName: String, with encoder: JSONEncoder = JSONEncoder() ) async throws { let data = try data.encoded(encoder: encoder) try await self.save(fileName, data) } } // Convenience methods for UserSettings handling public extension FileClient { func loadUserSettings() async throws -> UserSettings { try await load(UserSettings.self, from: userSettingsFileName) } func saveUserSettings(userSettings: UserSettings) async throws { try await self.save(userSettings, to: userSettingsFileName) } } let userSettingsFileName = "user-settings"
mit
Rahulclaritaz/rahul
ixprez/ixprez/SearchPopularCollectionViewCell.swift
1
240
// // SearchPopularCollectionViewCell.swift // ixprez // // Created by Quad on 5/29/17. // Copyright © 2017 Claritaz Techlabs. All rights reserved. // import UIKit class SearchPopularCollectionViewCell: UICollectionViewCell { }
mit
hacktx/iOS-HackTX-2015
HackTX/PageItemViewController.swift
1
698
// // PageItemViewController.swift // HackTX // // Created by Gilad Oved on 8/27/15. // Copyright (c) 2015 HackTX. All rights reserved. // import UIKit class PageItemViewController: UIViewController { var itemIndex: Int = 0 var imageName: String = "" { didSet { if let imageView = mapImageView { imageView.image = UIImage(named: imageName) } } } @IBOutlet weak var mapImageView: UIImageView! @IBOutlet weak var levelLabel: UILabel! override func viewDidLoad() { super.viewDidLoad() mapImageView!.image = UIImage(named: imageName) levelLabel.text = "Level \(itemIndex + 1)" } }
mit
Ramesh-P/virtual-tourist
Virtual Tourist/Preset+CoreDataClass.swift
1
913
// // Preset+CoreDataClass.swift // Virtual Tourist // // Created by Ramesh Parthasarathy on 2/25/17. // Copyright © 2017 Ramesh Parthasarathy. All rights reserved. // import Foundation import CoreData // MARK: Preset public class Preset: NSManagedObject { // MARK: Initializers convenience init(latitude: Double, latitudeDelta: Double, longitude: Double, longitudeDelta: Double, context: NSManagedObjectContext) { // Create entity description for Preset if let entity = NSEntityDescription.entity(forEntityName: "Preset", in: context) { self.init(entity: entity, insertInto: context) self.latitude = latitude self.latitudeDelta = latitude self.longitude = longitude self.longitudeDelta = longitudeDelta } else { fatalError("Unable to find Preset entity") } } }
mit
modocache/Gift
Gift/Commit/Commit.swift
1
2115
import Foundation import LlamaKit /** A commit object holds metadata for each change introduced into the repository, including the author, committer, commit date, and log message. Each commit points to a tree object that captures, in one complete snapshot, the state of the repository at the time the commit was performed. The initial commit, or root commit, has no parent. Most commits have one commit parent, although it is possible to have more than one parent. */ public class Commit { internal let cCommit: COpaquePointer internal init(cCommit: COpaquePointer) { self.cCommit = cCommit } deinit { git_commit_free(cCommit) } } public extension Commit { /** Returns the full message of a commit, or a failure indicating what went wrong when retrieving the message. The returned message will be slightly prettified by removing any potential leading newlines. */ public var message: Result<String, NSError> { let cMessage = git_commit_message(cCommit) if let commitMessage = String.fromCString(cMessage) { return success(commitMessage) } else { let description = "An error occurred when attempting to convert commit message " + "'\(cMessage)', provided by git_commit_message, to a String." return failure(NSError.giftError(.StringConversionFailure, description: description)) } } /** Returns the author's signature for this commit, or a failure indicating what went wrong when retrieving the signature. The author of a commit is the person who authored the changes in the commit. */ public var author: Result<Signature, NSError> { return Signature.fromCSignature(git_commit_author(cCommit).memory) } /** Returns the committer's signature for this commit, or a failure indicating what went wrong when retrieving the signature. The committer of a commit is the person who committed the code on behalf of the original author. */ public var committer: Result<Signature, NSError> { return Signature.fromCSignature(git_commit_committer(cCommit).memory) } }
mit
gogozs/Pulley
Pulley/DrawerContentViewController.swift
1
3156
// // DrawerPreviewContentViewController.swift // Pulley // // Created by Brendan Lee on 7/6/16. // Copyright © 2016 52inc. All rights reserved. // import UIKit class DrawerContentViewController: UIViewController, UITableViewDelegate, UITableViewDataSource, PulleyDrawerViewControllerDelegate, UISearchBarDelegate { @IBOutlet var tableView: UITableView! @IBOutlet var searchBar: UISearchBar! @IBOutlet var gripperView: UIView! @IBOutlet var seperatorHeightConstraint: NSLayoutConstraint! override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. gripperView.layer.cornerRadius = 2.5 seperatorHeightConstraint.constant = 1.0 / UIScreen.main.scale } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } // MARK: Tableview data source & delegate func numberOfSections(in tableView: UITableView) -> Int { return 1 } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return 50 } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { return tableView.dequeueReusableCell(withIdentifier: "SampleCell", for: indexPath) } func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { return 81.0 } func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { tableView.deselectRow(at: indexPath, animated: true) if let drawer = self.parent as? PulleyViewController { let primaryContent = UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "PrimaryTransitionTargetViewController") drawer.setDrawerPosition(position: .collapsed, animated: true) drawer.setPrimaryContentViewController(controller: primaryContent, animated: false) } } // MARK: Drawer Content View Controller Delegate func collapsedDrawerHeight() -> CGFloat { return 68.0 } func partialRevealDrawerHeight() -> CGFloat { return 264.0 } func supportedDrawerPositions() -> [PulleyPosition] { return PulleyPosition.all // You can specify the drawer positions you support. This is the same as: [.open, .partiallyRevealed, .collapsed, .closed] } func drawerPositionDidChange(drawer: PulleyViewController) { tableView.isScrollEnabled = drawer.drawerPosition == .open print("\(#function) tableView.isScrollEnable: \(tableView.isScrollEnabled)") if drawer.drawerPosition != .open { searchBar.resignFirstResponder() } } // MARK: Search Bar delegate func searchBarTextDidBeginEditing(_ searchBar: UISearchBar) { if let drawerVC = self.parent as? PulleyViewController { drawerVC.setDrawerPosition(position: .open, animated: true) } } }
mit
artkirillov/DesignPatterns
Facade.playground/Contents.swift
1
1723
final class Machine { enum State { case notRunning case ready case running } private(set) var state: State = .ready func startMachine() { print("Proccessing start...") state = .ready state = .running print("MACHINE IS RUNNING") } func stopMachine() { print("Proccessing finish...") state = .notRunning print("MACHINE STOPPED") } } final class RequestManager { var isConnected: Bool = false func connectToTerminal() { print("Connecting to terminal...") isConnected = true } func disconnectToTerminal() { print("Disconnecting to terminal...") isConnected = false } func getStatusRequest(for machine: Machine) -> Machine.State { print("Sending status request...") return machine.state } func sendStartRequest(for machine: Machine) { print("Sending request to start the machine...") machine.startMachine() } func sendStopRequest(for machine: Machine) { print("Sending request to stop the machine...") machine.stopMachine() } } protocol Facade { func startMachine() } final class ConcreteFacade: Facade { func startMachine() { let machine = Machine() let manager = RequestManager() if !manager.isConnected { manager.connectToTerminal() } if manager.getStatusRequest(for: machine) == .ready { print("MACHINE IS READY") manager.sendStartRequest(for: machine) } } } let simpleInterface = ConcreteFacade() simpleInterface.startMachine()
mit
daviwiki/Gourmet_Swift
Gourmet/Gourmet/Support/Mappers/MapAccountToAccountVM.swift
1
433
// // MapAccountToAccountVM.swift // Gourmet // // Created by David Martinez on 08/12/2016. // Copyright © 2016 Atenea. All rights reserved. // import Foundation import GourmetModel class MapAccountToAccountVM : NSObject { func map(source: Account) -> AccountVM { let account = AccountVM() account.cardId = source.cardId account.password = source.password return account } }
mit
lotz84/__.swift
__.swiftTests/__UtilityTests.swift
1
2066
// // __UtilityTests.swift // __.swift // // Copyright (c) 2014 Tatsuya Hirose // // 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 XCTest class __UtilityTests: XCTestCase { func testIdentity() { XCTAssert(__.identity(1) == 1) } func testConstant() { let const = __.constant("a") XCTAssert(const() == "a") } func testTimes(){ let result = __.times(4) { 2 * $0 } XCTAssert(result == [0,2,4,6]) } func testRandom(){ let result = __.random(min:10, max:30) XCTAssert(result > 9) XCTAssert(result < 31) } func testUniqueId() { let id0 = __.uniqueId("swift") let id1 = __.uniqueId("swift") XCTAssert(id0 != id1) } func testEscape(){ XCTAssert(__.escape("Larry & Moe")=="Larry &amp; Moe") } func testUnescape(){ XCTAssert(__.unescape("Larry &amp; Moe")=="Larry & Moe") } }
mit
danielloureda/congenial-sniffle
Project5/Project5/AppDelegate.swift
1
2176
// // AppDelegate.swift // Project5 // // Created by Daniel Loureda Arteaga on 21/5/17. // Copyright © 2017 Dano. All rights reserved. // import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { // Override point for customization after application launch. 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:. } }
apache-2.0
Pyroh/Fluor
Fluor/Controllers/StatusMenuController.swift
1
8732
// // StatusMenuController.swift // // Fluor // // MIT License // // Copyright (c) 2020 Pierre Tacchi // // 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 Cocoa import DefaultsWrapper class StatusMenuController: NSObject, NSMenuDelegate, NSWindowDelegate, MenuControlObserver { //MARK: - Menu Delegate @IBOutlet weak var statusMenu: NSMenu! @IBOutlet var menuItemsController: MenuItemsController! @IBOutlet var behaviorController: BehaviorController! private var rulesController: RulesEditorWindowController? private var aboutController: AboutWindowController? private var preferencesController: PreferencesWindowController? private var runningAppsController: RunningAppWindowController? var statusItem: NSStatusItem! override func awakeFromNib() { setupStatusMenu() self.menuItemsController.setupController() self.behaviorController.setupController() startObservingUsesLightIcon() startObservingMenuControlNotification() } deinit { stopObservingUsesLightIcon() stopObservingSwitchMenuControlNotification() } func windowWillClose(_ notification: Notification) { guard let object = notification.object as? NSWindow else { return } NotificationCenter.default.removeObserver(self, name: NSWindow.willCloseNotification, object: object) if object.isEqual(rulesController?.window) { rulesController = nil } else if object.isEqual(aboutController?.window) { aboutController = nil } else if object.isEqual(preferencesController?.window) { preferencesController = nil } else if object.isEqual(runningAppsController?.window) { runningAppsController = nil } } override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) { switch keyPath { case UserDefaultsKeyName.useLightIcon.rawValue?: adaptStatusMenuIcon() default: return } } // MARK: - Private functions /// Setup the status bar's item private func setupStatusMenu() { self.statusItem = NSStatusBar.system.statusItem(withLength: NSStatusItem.variableLength) self.statusItem.menu = statusMenu adaptStatusMenuIcon() } /// Adapt status bar icon from user's settings. private func adaptStatusMenuIcon() { let disabledApp = AppManager.default.isDisabled let usesLightIcon = AppManager.default.useLightIcon switch (disabledApp, usesLightIcon) { case (false, false): statusItem.image = #imageLiteral(resourceName: "IconAppleMode") case (false, true): statusItem.image = #imageLiteral(resourceName: "AppleMode") case (true, false): statusItem.image = #imageLiteral(resourceName: "IconDisabled") case (true, true): statusItem.image = #imageLiteral(resourceName: "LighIconDisabled") } } /// Register self as an observer for some notifications. private func startObservingUsesLightIcon() { UserDefaults.standard.addObserver(self, forKeyPath: UserDefaultsKeyName.useLightIcon.rawValue, options: [], context: nil) } /// Unregister self as an observer for some notifications. private func stopObservingUsesLightIcon() { UserDefaults.standard.removeObserver(self, forKeyPath: UserDefaultsKeyName.useLightIcon.rawValue, context: nil) } // MARK: - NSWindowDelegate func menuWillOpen(_ menu: NSMenu) { self.behaviorController.adaptToAccessibilityTrust() } // MARK: - MenuControlObserver func menuNeedsToOpen(notification: Notification) { } func menuNeedsToClose(notification: Notification) { if let userInfo = notification.userInfo, let animated = userInfo["animated"] as? Bool, !animated { self.statusMenu.cancelTrackingWithoutAnimation() } else { self.statusMenu.cancelTracking() } } // MARK: IBActions /// Show the *Edit Rules* window. /// /// - parameter sender: The object that sent the action. @IBAction func editRules(_ sender: AnyObject) { guard rulesController == nil else { rulesController?.window?.orderFrontRegardless() return } rulesController = RulesEditorWindowController.instantiate() rulesController?.window?.delegate = self rulesController?.window?.orderFrontRegardless() } /// Show the *About* window. /// /// - parameter sender: The object that sent the action. @IBAction func showAbout(_ sender: AnyObject) { guard aboutController == nil else { aboutController?.window?.makeKeyAndOrderFront(self) aboutController?.window?.makeMain() NSApp.activate(ignoringOtherApps: true) return } aboutController = AboutWindowController.instantiate() aboutController?.window?.delegate = self aboutController?.window?.makeKeyAndOrderFront(self) aboutController?.window?.makeMain() NSApp.activate(ignoringOtherApps: true) } /// Show the *Preferences* window. /// /// - parameter sender: The object that sent the action. @IBAction func showPreferences(_ sender: AnyObject) { guard preferencesController == nil else { preferencesController?.window?.makeKeyAndOrderFront(self) preferencesController?.window?.makeMain() NSApp.activate(ignoringOtherApps: true) return } self.preferencesController = PreferencesWindowController.instantiate() preferencesController?.window?.delegate = self preferencesController?.window?.makeKeyAndOrderFront(self) preferencesController?.window?.makeMain() NSApp.activate(ignoringOtherApps: true) } /// Show the *Running Applications* window. /// /// - parameter sender: The object that sent the action. @IBAction func showRunningApps(_ sender: AnyObject) { guard runningAppsController == nil else { runningAppsController?.window?.orderFrontRegardless() return } runningAppsController = RunningAppWindowController.instantiate() runningAppsController?.window?.delegate = self runningAppsController?.window?.orderFrontRegardless() } /// Enable or disable Fluor fn keys management. /// If disabled the keyboard behaviour is set as its behaviour before app launch. /// /// - Parameter sender: The object that sent the action. @IBAction func toggleApplicationState(_ sender: NSMenuItem) { let disabled = sender.state == .off if disabled { self.statusItem.image = AppManager.default.useLightIcon ? #imageLiteral(resourceName: "LighIconDisabled") : #imageLiteral(resourceName: "IconDisabled") } else { self.statusItem.image = AppManager.default.useLightIcon ? #imageLiteral(resourceName: "AppleMode") : #imageLiteral(resourceName: "IconAppleMode") } self.behaviorController.setApplicationIsEnabled(disabled) } /// Terminate the application. /// /// - parameter sender: The object that sent the action. @IBAction func quitApplication(_ sender: AnyObject) { self.stopObservingUsesLightIcon() NSWorkspace.shared.notificationCenter.removeObserver(self) self.behaviorController.performTerminationCleaning() NSApp.terminate(self) } }
mit
duliodenis/facetube
FaceTube/FaceTube/DataService.swift
1
1076
// // DataService.swift // FaceTube // // Created by Dulio Denis on 12/14/15. // Copyright © 2015 Dulio Denis. All rights reserved. // import Foundation import Firebase class DataService { static let ds = DataService() private var _REF_BASE = Firebase(url: "\(URL_BASE)") private var _REF_POSTS = Firebase(url: "\(URL_BASE)/posts") private var _REF_USERS = Firebase(url: "\(URL_BASE)/users") // MARK: Accessors var REF_BASE: Firebase { return _REF_BASE } var REF_POSTS: Firebase { return _REF_POSTS } var REF_USERS: Firebase { return _REF_USERS } var REF_CURRENT_USER: Firebase { let uid = NSUserDefaults.standardUserDefaults().valueForKey(KEY_UID) as! String return Firebase(url: "\(URL_BASE)").childByAppendingPath("users").childByAppendingPath(uid) } // MARK: User Creation func createFirebaseUser(uid: String, user: Dictionary<String, String>) { REF_USERS.childByAppendingPath(uid).setValue(user) } }
mit
tapglue/snaasSdk-iOS
Sources/Internal/Encoder.swift
2
466
// // Encoder.swift // Tapglue // // Created by John Nilsen on 7/5/16. // Copyright © 2016 Tapglue. All rights reserved. // import Foundation class Encoder { static func encode(_ appToken: String, sessionToken: String) -> String { let input = appToken + ":" + sessionToken let utf8Input = input.data(using: String.Encoding.utf8) return utf8Input?.base64EncodedString(options: Data.Base64EncodingOptions(rawValue: 0)) ?? "" } }
apache-2.0
ObjectAlchemist/OOUIKit
Sources/View/Basic/ViewSecureTextField.swift
1
3146
// // ViewSecureTextField.swift // OOSwift // // Created by Karsten Litsche on 01.09.17. // // import UIKit import OOBase public final class ViewSecureTextField: OOView { // MARK: init init(value: OOWritableString, placeholder: OOString, isLast: Bool, optDelegate: UITextFieldDelegate?) { self.optDelegate = optDelegate self.initialValue = value self.editTarget = VrTextFieldTarget(editAction: { text in DoWritableStringSet(text, to: value) }) self.placeholder = placeholder self.isLast = isLast } // MARK: protocol OOView private var _ui: UITextField? public var ui: UIView { if _ui == nil { _ui = createView() } return _ui! } public func setNeedsRefresh() { if _ui != nil { update(view: _ui!) } _ui?.setNeedsLayout() } // MARK: private private let optDelegate: UITextFieldDelegate? private let initialValue: OOString private let editTarget: VrTextFieldTarget private let placeholder: OOString private let isLast: Bool private func createView() -> UITextField { let view = UITextField() view.isSecureTextEntry = true view.text = initialValue.value view.placeholder = placeholder.value view.clearButtonMode = .always view.addTarget(editTarget, action: #selector(VrTextFieldTarget.textDidChanged(_:)), for: .editingChanged) view.returnKeyType = isLast ? .done : .next if let delegate = optDelegate { view.delegate = delegate } update(view: view) return view } private func update(view: UITextField) { // empty } } // convenience initializer public extension ViewSecureTextField { convenience init(value: OOWritableString, placeholder: String = "", isLast: Bool = true) { self.init(value: value, placeholder: StringConst(placeholder), isLast: isLast) } convenience init(value: OOWritableString, placeholder: OOString, isLast: Bool = true) { self.init(value: value, placeholder: placeholder, isLast: isLast, optDelegate: nil) } convenience init(value: OOWritableString, placeholder: String = "", isLast: Bool = true, delegate: UITextFieldDelegate) { self.init(value: value, placeholder: StringConst(placeholder), isLast: isLast, delegate: delegate) } convenience init(value: OOWritableString, placeholder: OOString, isLast: Bool = true, delegate: UITextFieldDelegate) { self.init(value: value, placeholder: placeholder, isLast: isLast, optDelegate: delegate) } } /** Helper for encapsulate the target handling and objc compatibility. */ fileprivate final class VrTextFieldTarget: NSObject { // MARK: - initialization init(editAction: @escaping (String) -> OOExecutable) { self.editAction = editAction } // MARK: - configuration / api @objc func textDidChanged(_ sender: UITextField) { editAction(sender.text!).execute() } // MARK: - private private let editAction: (String) -> OOExecutable }
mit
networkextension/SFSocket
SFSocketTest/SocksTest.swift
1
185
// // SocksTest.swift // SFSocket // // Created by 孔祥波 on 02/03/2017. // Copyright © 2017 Kong XiangBo. All rights reserved. // import UIKit class SocksTest: NSObject { }
bsd-3-clause
icecoffin/GlossLite
GlossLite/Utils/ReferenceLibraryHelper.swift
1
316
// // ReferenceLibraryHelper.swift // GlossLite // import UIKit // A hackish way to avoid importing UIKit into view models class ReferenceLibraryHelper { class func dictionaryHasDefinition(forTerm term: String) -> Bool { return UIReferenceLibraryViewController.dictionaryHasDefinition(forTerm: term) } }
mit
michikono/swift-using-typealiases-as-generics
swift-using-typealiases-as-generics-i.playground/Pages/inferred-typealiases 3.xcplaygroundpage/Contents.swift
2
785
//: Inferred Typealiases //: =================== //: [Previous](@previous) protocol Material {} struct Wood: Material {} struct Glass: Material {} struct Metal: Material {} struct Cotton: Material {} //: `mainMaterial()` and `secondaryMaterial()` may return _different_ types now protocol Furniture { typealias M: Material typealias M2: Material func mainMaterial() -> M // <==== func secondaryMaterial() -> M2 // <==== } struct Chair: Furniture { func mainMaterial() -> Wood { return Wood() } func secondaryMaterial() -> Cotton { return Cotton() } } struct Lamp: Furniture { func mainMaterial() -> Glass { return Glass() } func secondaryMaterial() -> Metal { return Metal() } } //: [Next](@next)
mit
icecoffin/GlossLite
GlossLite/ViewModels/AddEditWord/WordValidationResult.swift
1
225
// // WordValidationResult.swift // GlossLite // // Created by Daniel on 09/10/16. // Copyright © 2016 icecoffin. All rights reserved. // import Foundation enum WordValidationResult { case success case emptyWord }
mit
timfuqua/Bourgeoisie
Bourgeoisie/Bourgeoisie/View Controller/TitleViewController.swift
1
3589
// // TitleViewController.swift // Bourgeoisie // // Created by Tim Fuqua on 9/25/15. // Copyright (c) 2015 FuquaProductions. All rights reserved. // import UIKit // MARK: TitleViewController: UIViewController /** */ class TitleViewController: UIViewController { // MARK: class vars // MARK: private lets // MARK: private vars (computed) // MARK: private vars // MARK: private(set) vars // MARK: lets // MARK: vars (computed) // MARK: vars var numberOfOpponents: Int = 1 // MARK: @IBOutlets @IBOutlet weak var paddingView: UIView! @IBOutlet weak var titleView: UIView! @IBOutlet weak var titleLabel: UILabel! @IBOutlet weak var numPlayersLabelView: UIView! @IBOutlet weak var numPlayersLabel: UILabel! @IBOutlet weak var numPlayersControlView: UIView! @IBOutlet weak var numPlayersControl: UISegmentedControl! @IBOutlet weak var newGameView: UIView! @IBOutlet weak var newGameButton: UIButton! @IBOutlet weak var tutorialView: UIView! @IBOutlet weak var tutorialButton: UIButton! @IBOutlet weak var loadGameView: UIView! @IBOutlet weak var loadGameButton: UIButton! @IBOutlet weak var settingsView: UIView! @IBOutlet weak var settingsButton: UIButton! @IBOutlet weak var helpView: UIView! @IBOutlet weak var helpButton: UIButton! // MARK: init // MARK: vc lifecycle override func viewDidLoad() { super.viewDidLoad() numPlayersControl.selectedSegmentIndex = numberOfOpponents-1 } // MARK: @IBActions @IBAction func unwindToTitleSegue(segue: UIStoryboardSegue) { if let sourceVC = segue.sourceViewController as? GameplayViewController { print("Unwinding from GameplayViewController") } else { fatalError("Should only be unwinding to this VC through one of the previous segues") } } @IBAction func numberOfOpponentsSelectionMade(sender: UISegmentedControl) { print("Selection changed to \(sender.titleForSegmentAtIndex(sender.selectedSegmentIndex)!)") numberOfOpponents = sender.selectedSegmentIndex+1 print("numberOfOpponents: \(numberOfOpponents)") } @IBAction func newGameButtonPressed(sender: UIButton) { performSegueWithIdentifier("Title_New_to_Gameplay", sender: self) } @IBAction func tutorialButtonPressed(sender: UIButton) { performSegueWithIdentifier("Title_Tutorial_to_Gameplay", sender: self) } @IBAction func loadGameButtonPressed(sender: UIButton) { performSegueWithIdentifier("Title_Load_to_Gameplay", sender: self) } // MARK: public funcs override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { if segue.identifier == "Title_New_to_Gameplay" { if let gameplayVC = segue.destinationViewController as? GameplayViewController { gameplayVC.gameMode = GameplayMode.New gameplayVC.numOpponentsSelected = numberOfOpponents } } else if segue.identifier == "Title_Tutorial_to_Gameplay" { if let gameplayVC = segue.destinationViewController as? GameplayViewController { gameplayVC.gameMode = GameplayMode.Tutorial gameplayVC.numOpponentsSelected = numberOfOpponents } } else if segue.identifier == "Title_Load_to_Gameplay" { if let gameplayVC = segue.destinationViewController as? GameplayViewController { gameplayVC.gameMode = GameplayMode.Load gameplayVC.numOpponentsSelected = numberOfOpponents } } else { fatalError("Shouldn't be segueing unless it's one of the previous segues") } } // MARK: private funcs }
mit
YuanZhu-apple/ResearchKit
Testing/ORKTest/ORKTest/Charts/ChartListViewController.swift
5
12924
/* Copyright (c) 2015, James Cox. All rights reserved. Copyright (c) 2015, Ricardo Sánchez-Sáez. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 3. Neither the name of the copyright holder(s) nor the names of any contributors may be used to endorse or promote products derived from this software without specific prior written permission. No license is granted to the trademarks of the copyright holders even if such marks are included in this software. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ import UIKit import ResearchKit func executeAfterDelay(delay:Double, closure:()->()) { dispatch_after( dispatch_time( DISPATCH_TIME_NOW, Int64(delay * Double(NSEC_PER_SEC)) ), dispatch_get_main_queue(), closure) } class ChartListViewController: UIViewController, UITableViewDataSource { @IBOutlet var tableView: UITableView! let colorlessPieChartDataSource = ColorlessPieChartDataSource() let randomColorPieChartDataSource = RandomColorPieChartDataSource() let lineGraphChartDataSource = LineGraphChartDataSource() let coloredLineGraphChartDataSource = ColoredLineGraphChartDataSource() let discreteGraphChartDataSource = DiscreteGraphChartDataSource() let coloredDiscreteGraphChartDataSource = ColoredDiscreteGraphChartDataSource() let barGraphChartDataSource = BarGraphChartDataSource() let coloredBarGraphChartDataSource = ColoredBarGraphChartDataSource() let pieChartIdentifier = "PieChartCell" let lineGraphChartIdentifier = "LineGraphChartCell" let discreteGraphChartIdentifier = "DiscreteGraphChartCell" let barGraphChartIdentifier = "BarGraphChartCell" var pieChartTableViewCell: PieChartTableViewCell! var lineGraphChartTableViewCell: LineGraphChartTableViewCell! var discreteGraphChartTableViewCell: DiscreteGraphChartTableViewCell! var barGraphChartTableViewCell: BarGraphChartTableViewCell! var chartTableViewCells: [UITableViewCell]! @IBAction func dimiss(sender: AnyObject) { self.dismissViewControllerAnimated(true, completion: nil) } override func viewDidLoad() { self.tableView.dataSource = self; // ORKPieChartView pieChartTableViewCell = tableView.dequeueReusableCellWithIdentifier(pieChartIdentifier) as! PieChartTableViewCell let pieChartView = pieChartTableViewCell.pieChartView pieChartView.dataSource = randomColorPieChartDataSource // Optional custom configuration pieChartView.title = "TITLE" pieChartView.text = "TEXT" pieChartView.lineWidth = 1000 pieChartView.showsTitleAboveChart = true pieChartView.showsPercentageLabels = false pieChartView.drawsClockwise = false executeAfterDelay(2.5) { pieChartView.showsTitleAboveChart = false pieChartView.lineWidth = 12 pieChartView.title = "UPDATED" pieChartView.text = "UPDATED TEXT" pieChartView.titleColor = UIColor.redColor() pieChartView.textColor = UIColor.orangeColor() } executeAfterDelay(3.5) { pieChartView.drawsClockwise = true pieChartView.dataSource = self.colorlessPieChartDataSource } executeAfterDelay(4.5) { pieChartView.showsPercentageLabels = true pieChartView.tintColor = UIColor.purpleColor() } executeAfterDelay(5.5) { pieChartView.titleColor = nil pieChartView.textColor = nil } // ORKBarGraphChartView barGraphChartTableViewCell = tableView.dequeueReusableCellWithIdentifier(barGraphChartIdentifier) as! BarGraphChartTableViewCell let barGraphChartView = barGraphChartTableViewCell.graphChartView as! ORKBarGraphChartView barGraphChartView.dataSource = barGraphChartDataSource executeAfterDelay(1.5) { barGraphChartView.tintColor = UIColor.purpleColor() barGraphChartView.showsHorizontalReferenceLines = true barGraphChartView.showsVerticalReferenceLines = true } executeAfterDelay(2.5) { barGraphChartView.axisColor = UIColor.redColor() barGraphChartView.verticalAxisTitleColor = UIColor.redColor() barGraphChartView.referenceLineColor = UIColor.orangeColor() barGraphChartView.scrubberLineColor = UIColor.blueColor() barGraphChartView.scrubberThumbColor = UIColor.greenColor() } executeAfterDelay(3.5) { barGraphChartView.axisColor = nil barGraphChartView.verticalAxisTitleColor = nil barGraphChartView.referenceLineColor = nil barGraphChartView.scrubberLineColor = nil barGraphChartView.scrubberThumbColor = nil } executeAfterDelay(4.5) { barGraphChartView.dataSource = self.coloredBarGraphChartDataSource } executeAfterDelay(5.5) { let maximumValueImage = UIImage(named: "GraphMaximumValueTest")! let minimumValueImage = UIImage(named: "GraphMinimumValueTest")! barGraphChartView.maximumValueImage = maximumValueImage barGraphChartView.minimumValueImage = minimumValueImage } // ORKLineGraphChartView lineGraphChartTableViewCell = tableView.dequeueReusableCellWithIdentifier(lineGraphChartIdentifier) as! LineGraphChartTableViewCell let lineGraphChartView = lineGraphChartTableViewCell.graphChartView as! ORKLineGraphChartView lineGraphChartView.dataSource = lineGraphChartDataSource // Optional custom configuration executeAfterDelay(1.5) { lineGraphChartView.tintColor = UIColor.purpleColor() lineGraphChartView.showsHorizontalReferenceLines = true lineGraphChartView.showsVerticalReferenceLines = true } executeAfterDelay(2.5) { lineGraphChartView.axisColor = UIColor.redColor() lineGraphChartView.verticalAxisTitleColor = UIColor.redColor() lineGraphChartView.referenceLineColor = UIColor.orangeColor() lineGraphChartView.scrubberLineColor = UIColor.blueColor() lineGraphChartView.scrubberThumbColor = UIColor.greenColor() } executeAfterDelay(3.5) { lineGraphChartView.axisColor = nil lineGraphChartView.verticalAxisTitleColor = nil lineGraphChartView.referenceLineColor = nil lineGraphChartView.scrubberLineColor = nil lineGraphChartView.scrubberThumbColor = nil } executeAfterDelay(4.5) { lineGraphChartView.dataSource = self.coloredLineGraphChartDataSource } executeAfterDelay(5.5) { let maximumValueImage = UIImage(named: "GraphMaximumValueTest")! let minimumValueImage = UIImage(named: "GraphMinimumValueTest")! lineGraphChartView.maximumValueImage = maximumValueImage lineGraphChartView.minimumValueImage = minimumValueImage } // ORKDiscreteGraphChartView discreteGraphChartTableViewCell = tableView.dequeueReusableCellWithIdentifier(discreteGraphChartIdentifier) as! DiscreteGraphChartTableViewCell let discreteGraphChartView = discreteGraphChartTableViewCell.graphChartView as! ORKDiscreteGraphChartView discreteGraphChartView.dataSource = discreteGraphChartDataSource // Optional custom configuration discreteGraphChartView.showsHorizontalReferenceLines = true discreteGraphChartView.showsVerticalReferenceLines = true discreteGraphChartView.drawsConnectedRanges = true executeAfterDelay(2.5) { discreteGraphChartView.tintColor = UIColor.purpleColor() } executeAfterDelay(3.5) { discreteGraphChartView.drawsConnectedRanges = false } executeAfterDelay(4.5) { discreteGraphChartView.dataSource = self.coloredDiscreteGraphChartDataSource } executeAfterDelay(5.5) { discreteGraphChartView.drawsConnectedRanges = true } chartTableViewCells = [pieChartTableViewCell, barGraphChartTableViewCell, lineGraphChartTableViewCell, discreteGraphChartTableViewCell] tableView.tableFooterView = UIView(frame: CGRectZero) } func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return chartTableViewCells.count } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = chartTableViewCells[indexPath.row]; return cell } override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) self.view.layoutIfNeeded() pieChartTableViewCell.pieChartView.animateWithDuration(2.5) barGraphChartTableViewCell.graphChartView.animateWithDuration(2.5) lineGraphChartTableViewCell.graphChartView.animateWithDuration(2.5) discreteGraphChartTableViewCell.graphChartView.animateWithDuration(2.5) } } class ChartPerformanceListViewController: UIViewController, UITableViewDataSource { @IBOutlet var tableView: UITableView! let lineGraphChartIdentifier = "LineGraphChartCell" let discreteGraphChartIdentifier = "DiscreteGraphChartCell" let graphChartDataSource = PerformanceLineGraphChartDataSource() var lineGraphChartTableViewCell: LineGraphChartTableViewCell! let discreteGraphChartDataSource = DiscreteGraphChartDataSource() var discreteGraphChartTableViewCell: DiscreteGraphChartTableViewCell! var chartTableViewCells: [UITableViewCell]! @IBAction func dimiss(sender: AnyObject) { self.dismissViewControllerAnimated(true, completion: nil) } override func viewDidLoad() { self.tableView.dataSource = self; // ORKLineGraphChartView lineGraphChartTableViewCell = tableView.dequeueReusableCellWithIdentifier(lineGraphChartIdentifier) as! LineGraphChartTableViewCell let lineGraphChartView = lineGraphChartTableViewCell.graphChartView as! ORKLineGraphChartView lineGraphChartView.dataSource = graphChartDataSource // Optional custom configuration lineGraphChartView.showsHorizontalReferenceLines = true lineGraphChartView.showsVerticalReferenceLines = true // ORKDiscreteGraphChartView discreteGraphChartTableViewCell = tableView.dequeueReusableCellWithIdentifier(discreteGraphChartIdentifier) as! DiscreteGraphChartTableViewCell let discreteGraphChartView = discreteGraphChartTableViewCell.graphChartView as! ORKDiscreteGraphChartView discreteGraphChartView.dataSource = graphChartDataSource // Optional custom configuration discreteGraphChartView.showsHorizontalReferenceLines = true discreteGraphChartView.showsVerticalReferenceLines = true discreteGraphChartView.drawsConnectedRanges = true chartTableViewCells = [lineGraphChartTableViewCell, discreteGraphChartTableViewCell] tableView.tableFooterView = UIView(frame: CGRectZero) } func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return chartTableViewCells.count } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = chartTableViewCells[indexPath.row]; return cell } override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) lineGraphChartTableViewCell.graphChartView.animateWithDuration(0.5) } }
bsd-3-clause
taka0125/AddressBookSync
Pod/Classes/Scan/AddressBookFrameworkAdapter.swift
1
3072
// // AddressBookFrameworkAdapter.swift // AddressBookSync // // Created by Takahiro Ooishi // Copyright (c) 2015 Takahiro Ooishi. All rights reserved. // Released under the MIT license. // import Foundation import AddressBook public struct AddressBookFrameworkAdapter: AdapterProtocol { public func authorizationStatus() -> AuthorizationStatus { let status = ABAddressBookGetAuthorizationStatus() switch status { case .NotDetermined: return .NotDetermined case .Restricted: return .Restricted case .Denied: return .Denied case .Authorized: return .Authorized } } public func requestAccess(completionHandler: (Bool, ErrorType?) -> Void) { switch authorizationStatus() { case .Authorized: completionHandler(true, nil) case .NotDetermined: let addressBookRef = buildAddressBookRef() ABAddressBookRequestAccessWithCompletion(addressBookRef) { (granted, error) in completionHandler(granted, error == nil ? nil : AddressBook.Error.RequestAccessFailed) } default: completionHandler(false, AddressBook.Error.RequestAccessFailed) } } public func fetchAll() -> [AddressBookRecord] { var records = [AddressBookRecord]() let addressBookRef = buildAddressBookRef() let allContacts = ABAddressBookCopyArrayOfAllPeople(addressBookRef).takeRetainedValue() as Array allContacts.forEach { contact in let id = "\(ABRecordGetRecordID(contact))" let firstName = recordCopyStringValue(contact, kABPersonFirstNameProperty) ?? "" let lastName = recordCopyStringValue(contact, kABPersonLastNameProperty) ?? "" let phoneNumbersRef = ABRecordCopyValue(contact, kABPersonPhoneProperty).takeUnretainedValue() as ABMultiValueRef let phoneNumbers = Array(0..<ABMultiValueGetCount(phoneNumbersRef)) .map { (ABMultiValueCopyValueAtIndex(phoneNumbersRef, $0).takeUnretainedValue() as? String) ?? "" } .filter { !$0.isEmpty } .ads_unique let emailsRef = ABRecordCopyValue(contact, kABPersonEmailProperty).takeUnretainedValue() as ABMultiValueRef let emails = Array(0..<ABMultiValueGetCount(emailsRef)) .map { (ABMultiValueCopyValueAtIndex(emailsRef, $0).takeUnretainedValue() as? String) ?? "" } .filter { !$0.isEmpty } .ads_unique records.append(AddressBookRecord(id: id, firstName: firstName, lastName: lastName, phoneNumbers: phoneNumbers, emails: emails)) } return records } } extension AddressBookFrameworkAdapter { private func recordCopyStringValue(record: ABRecord, _ property: ABPropertyID) -> String? { guard let ref = ABRecordCopyValue(record, property) else { return nil } return ref.takeRetainedValue() as? String } } extension AddressBookFrameworkAdapter { private func buildAddressBookRef() -> ABAddressBookRef { return ABAddressBookCreateWithOptions(nil, nil).takeRetainedValue() } } private extension Array where Element: Hashable { var ads_unique: [Element] { return Array(Set(self)) } }
mit
davedufresne/SwiftParsec
Sources/SwiftParsec/CollectionAggregation.swift
1
1299
//============================================================================== // CollectionAggregation.swift // SwiftParsec // // Created by David Dufresne on 2015-10-09. // Copyright © 2015 David Dufresne. All rights reserved. // // Collection extension //============================================================================== //============================================================================== // Extension containing aggregation methods. extension Collection { /// Return the result of repeatedly calling `combine` with an accumulated /// value initialized to `initial` and each element of `self`, in turn from /// the right, i.e. return combine(combine(...combine(combine(initial, /// self[count-1]), self[count-2]), self[count-3]), ... self[0]). /// /// - parameters: /// - initial: The initial value. /// - combine: The combining function. /// - returns: The combined result of each element of `self`. func reduceRight<T>( _ initial: T, combine: (T, Self.Iterator.Element) throws -> T ) rethrows -> T { var acc = initial for elem in reversed() { acc = try combine(acc, elem) } return acc } }
bsd-2-clause
abdullahselek/SwiftyNotifications
SwiftyNotifications/SwiftyNotificationsMessage.swift
1
11755
// // SwiftyNotificationsMessage.swift // SwiftyNotifications // // Copyright © 2017 Abdullah Selek. All rights reserved. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. import UIKit open class SwiftyNotificationsMessage: UIView { @IBOutlet open weak var messageLabel: UILabel! open var delegate: SwiftyNotificationsDelegate? open var direction: SwiftyNotificationsDirection! private var dismissDelay: TimeInterval? private var dismissTimer: Timer? private var touchHandler: SwiftyNotificationsTouchHandler? private var topConstraint: NSLayoutConstraint! private var bottomConstraint: NSLayoutConstraint! private var dynamicHeight = CGFloat(40.0) class func instanceFromNib() -> SwiftyNotificationsMessage { let bundle = Bundle(for: self.classForCoder()) return bundle.loadNibNamed("SwiftyNotificationsMessage", owner: nil, options: nil)?.first as! SwiftyNotificationsMessage } internal override init(frame: CGRect) { super.init(frame: frame) } required public init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } public static func withBackgroundColor(color: UIColor, message: String, direction: SwiftyNotificationsDirection) -> SwiftyNotificationsMessage { let notification = SwiftyNotificationsMessage.withBackgroundColor(color: color, message: message, dismissDelay: 0, direction: direction) return notification } public static func withBackgroundColor(color: UIColor, message: String, dismissDelay: TimeInterval, direction: SwiftyNotificationsDirection) -> SwiftyNotificationsMessage { let notification = SwiftyNotificationsMessage.withBackgroundColor(color: color, message: message, dismissDelay: dismissDelay, direction: direction, touchHandler: nil) return notification } public static func withBackgroundColor(color: UIColor, message: String, dismissDelay: TimeInterval, direction: SwiftyNotificationsDirection, touchHandler: SwiftyNotificationsTouchHandler?) -> SwiftyNotificationsMessage { let notification = SwiftyNotificationsMessage.instanceFromNib() notification.direction = direction notification.backgroundColor = color notification.translatesAutoresizingMaskIntoConstraints = false if dismissDelay > 0 { notification.dismissDelay = dismissDelay } if touchHandler != nil { notification.touchHandler = touchHandler let tapHandler = UITapGestureRecognizer(target: notification, action: #selector(handleTap)) notification.addGestureRecognizer(tapHandler) } notification.setMessage(message: message) return notification } open func setMessage(message: String) { let height = message.height(withConstrainedWidth: messageLabel.frame.size.width, font: messageLabel.font) messageLabel.text = message messageLabel.frame.size.height = height messageLabel.frame.size.width = self.frame.size.width dynamicHeight = height + 20 } open func addTouchHandler(touchHandler: @escaping SwiftyNotificationsTouchHandler) { self.touchHandler = touchHandler let tapHandler = UITapGestureRecognizer(target: self, action: #selector(SwiftyNotifications.handleTap)) addGestureRecognizer(tapHandler) } open override func didMoveToSuperview() { super.didMoveToSuperview() if superview == nil { return } addWidthConstraint() self.direction == .top ? updateTopConstraint(hide: true) : updateBottomConstraint(hide: true) } internal func updateTopConstraint(hide: Bool) { var topSafeAreaHeight: CGFloat = 0 if #available(iOS 11.0, *), UIApplication.shared.windows.count > 0 { let window = UIApplication.shared.windows[0] let safeFrame = window.safeAreaLayoutGuide.layoutFrame topSafeAreaHeight = safeFrame.minY } let constant = hide == true ? -(dynamicHeight + topSafeAreaHeight) : 0 if topConstraint != nil && (superview?.constraints.contains(topConstraint))! { topConstraint.constant = constant } else { topConstraint = NSLayoutConstraint(item: self, attribute: .top, relatedBy: .equal, toItem: superview, attribute: .top, multiplier: 1.0, constant: constant) let widthConstraint = NSLayoutConstraint(item: self, attribute: .width, relatedBy: .equal, toItem: superview, attribute: .width, multiplier: 1.0, constant: 0.0) superview?.addConstraint(topConstraint) superview?.addConstraint(widthConstraint) } } internal func updateBottomConstraint(hide: Bool) { var bottomSafeAreaHeight: CGFloat = 0 if #available(iOS 11.0, *), UIApplication.shared.windows.count > 0 { let window = UIApplication.shared.windows[0] let safeFrame = window.safeAreaLayoutGuide.layoutFrame bottomSafeAreaHeight = window.frame.maxY - safeFrame.maxY } let constant = hide == true ? dynamicHeight + bottomSafeAreaHeight : 0 if bottomConstraint != nil && (superview?.constraints.contains(bottomConstraint))! { bottomConstraint.constant = constant } else { bottomConstraint = NSLayoutConstraint(item: self, attribute: .bottom, relatedBy: .equal, toItem: superview, attribute: .bottom, multiplier: 1.0, constant: constant) let widthConstraint = NSLayoutConstraint(item: self, attribute: .width, relatedBy: .equal, toItem: superview, attribute: .width, multiplier: 1.0, constant: 0.0) superview?.addConstraint(bottomConstraint) superview?.addConstraint(widthConstraint) } } internal func canDisplay() -> Bool { return self.superview != nil ? true : false } @objc internal func handleTap() { touchHandler?() } open func show() { if canDisplay() { self.delegate?.willShowNotification(notification: self) self.direction == .top ? updateTopConstraint(hide: false) : updateBottomConstraint(hide: false) UIView.animate(withDuration: 0.6, delay: 0.0, usingSpringWithDamping: 0.7, initialSpringVelocity: 0.3, options: .allowAnimatedContent, animations: { self.superview?.layoutIfNeeded() }, completion: { (finished) in if self.dismissDelay != nil && self.dismissDelay! > 0 { self.dismissTimer = Timer.scheduledTimer(timeInterval: self.dismissDelay!, target: self, selector: #selector(SwiftyNotificationsMessage.dismiss), userInfo: nil, repeats: false) } self.delegate?.didShowNotification(notification: self) }) } else { NSException(name: NSExceptionName.internalInconsistencyException, reason: "Must have a superview before calling show", userInfo: nil).raise() } } @objc open func dismiss() { self.delegate?.willDismissNotification(notification: self) if self.dismissTimer != nil { self.dismissTimer!.invalidate() self.dismissTimer = nil } self.direction == .top ? updateTopConstraint(hide: true) : updateBottomConstraint(hide: true) UIView.animate(withDuration: 0.6, delay: 0.0, usingSpringWithDamping: 0.7, initialSpringVelocity: 0.3, options: .allowAnimatedContent, animations: { self.superview?.layoutIfNeeded() }, completion: { (finished) in self.delegate?.didDismissNotification(notification: self) }) } internal func addWidthConstraint() { let widthConstraint = NSLayoutConstraint(item: self, attribute: .width, relatedBy: .equal, toItem: superview, attribute: .width, multiplier: 1.0, constant: 0.0) superview?.addConstraint(widthConstraint) } }
mit
Antondomashnev/Sourcery
SourceryTests/Stub/Performance-Code/Kiosk/UILabel+Fonts.swift
2
1785
import UIKit extension UILabel { func makeSubstringsBold(_ text: [String]) { text.forEach { self.makeSubstringBold($0) } } func makeSubstringBold(_ boldText: String) { let attributedText = self.attributedText!.mutableCopy() as! NSMutableAttributedString let range = ((self.text ?? "") as NSString).range(of: boldText) if range.location != NSNotFound { attributedText.setAttributes([NSFontAttributeName: UIFont.serifSemiBoldFont(withSize: self.font.pointSize)], range: range) } self.attributedText = attributedText } func makeSubstringsItalic(_ text: [String]) { text.forEach { self.makeSubstringItalic($0) } } func makeSubstringItalic(_ italicText: String) { let attributedText = self.attributedText!.mutableCopy() as! NSMutableAttributedString let range = ((self.text ?? "") as NSString).range(of: italicText) if range.location != NSNotFound { attributedText.setAttributes([NSFontAttributeName: UIFont.serifItalicFont(withSize: self.font.pointSize)], range: range) } self.attributedText = attributedText } func setLineHeight(_ lineHeight: Int) { let displayText = text ?? "" let attributedString = self.attributedText!.mutableCopy() as! NSMutableAttributedString let paragraphStyle = NSMutableParagraphStyle() paragraphStyle.lineSpacing = CGFloat(lineHeight) paragraphStyle.alignment = textAlignment attributedString.addAttribute(NSParagraphStyleAttributeName, value: paragraphStyle, range: NSMakeRange(0, displayText.count)) attributedText = attributedString } func makeTransparent() { isOpaque = false backgroundColor = .clear } }
mit
silence0201/Swift-Study
Swifter/25UseSelf.playground/Contents.swift
1
467
//: Playground - noun: a place where people can play import UIKit protocol Copyable { func copy() -> Self } class MyClass: Copyable { var num = 1 func copy() -> Self { let result = type(of: self).init() result.num = num return result } required init() {} } let object = MyClass() object.num = 100 let newObject = object.copy() object.num = 1 print(object.num) // 1 print(newObject.num) // 100
mit
karimsallam/Reactive
Reactive/Reactive/ReactiveUserInterface.swift
1
733
// // ReactiveUserInterface.swift // DatePlay // // Created by Karim Sallam on 21/12/2016. // Copyright © 2016 Karim Sallam. All rights reserved. // import Foundation import ReactiveSwift public enum ViewState { case Invisible case WillBecomeVisible case Visible case WillBecomeInvisible } public protocol ReactiveUserInterface: class { var reactiveState: MutableProperty<ReactiveState> { get } var viewState: MutableProperty<ViewState> { get } var reactiveIdentifier: String { get } func prepareForReuse() } public func ==(lhs: ReactiveUserInterface, rhs: ReactiveUserInterface) -> Bool { return lhs.reactiveIdentifier == rhs.reactiveIdentifier }
apache-2.0
zimcherDev/ios
Zimcher/Utils/MixedStream.swift
2
5300
// // DataStream.swift // SwiftPort // // Created by Weiyu Huang on 11/3/15. // Copyright © 2015 Kappa. All rights reserved. // import Foundation func += (inout currentStream: MixedInputStream, stream: MixedInputStream) { currentStream.streams += stream.streams } func += (inout currentStream: MixedInputStream, stream: NSInputStream) { currentStream.streams.append(stream) } class MixedInputStream: NSInputStream, NSStreamDelegate { var streams = [NSInputStream]() var streamsIdx = 0 weak var _delegate: NSStreamDelegate? var _error: NSError? var _streamStatus = NSStreamStatus.NotOpen var currentStream: NSInputStream? { return streams.isEmpty ? nil : streams[streamsIdx] } override var delegate: NSStreamDelegate? { get { return _delegate } set { _delegate = newValue ?? self } } override var streamStatus: NSStreamStatus { return _streamStatus } override var streamError: NSError? { get { return _error } set { _error = newValue } } init() { super.init(data: NSData()) //FailFish } func doRead(buffer: UnsafeMutablePointer<UInt8>, maxLength len: Int) -> Int { guard streamStatus == .Open else { return -1 } guard len > 0 else { //maxLength exhausted return 0 } let bytesRead = currentStream!.read(buffer, maxLength: len) guard bytesRead >= 0 else { streamError = currentStream!.streamError _streamStatus = .Error currentStream!.close() return bytesRead } //sub-stream read succeeded let remainingBytes = len - bytesRead if currentStream!.hasBytesAvailable { //the only possibility here: maxLength exhausted //no remainingBytes return bytesRead } currentStream!.close() //current stream ended but client wants more. Needs to switch //continued guard streamsIdx < streams.count-1 else { //end of all streams reached return bytesRead } ++streamsIdx //next stream currentStream!.open() //print("Stream idx \(streamsIdx) of \(streams.count-1) Open For Read") let nextBytesRead = doRead(buffer + bytesRead, maxLength: remainingBytes) guard nextBytesRead >= 0 else { return nextBytesRead } //error propagates return bytesRead + nextBytesRead } var hasReachedEnd: Bool { guard let stream = currentStream else { return true } if streamsIdx == streams.count - 1 && !stream.hasBytesAvailable { return true } return false } override var hasBytesAvailable: Bool { return !hasReachedEnd } //MARK: function overrides override func open() { guard _streamStatus == .NotOpen else { return } if let cs = currentStream { _streamStatus = .Open cs.open() } } override func close() { _streamStatus = .Closed currentStream?.close() //print("> Stream Closed") } //Not thread-safe override func read(buffer: UnsafeMutablePointer<UInt8>, maxLength len: Int) -> Int { //_streamStatus = .Reading let rb = doRead(buffer, maxLength: len) if hasReachedEnd { _streamStatus = .AtEnd } return rb } // MARK: We don't ship junk JobsFace 4Head EleGiggle // // ░░░░░░░░░ // ░░░░▄▀▀▀▀▀█▀▄▄▄▄░░░░ // ░░▄▀▒▓▒▓▓▒▓▒▒▓▒▓▀▄░░ // ▄▀▒▒▓▒▓▒▒▓▒▓▒▓▓▒▒▓█░ // █▓▒▓▒▓▒▓▓▓░░░░░░▓▓█░ // █▓▓▓▓▓▒▓▒░░░░░░░░▓█░ // ▓▓▓▓▓▒░░░░░░░░░░░░█░ // ▓▓▓▓░░░░▄▄▄▄░░░▄█▄▀░ // ░▀▄▓░░▒▀▓▓▒▒░░█▓▒▒░░ // ▀▄░░░░░░░░░░░░▀▄▒▒█░ // ░▀░▀░░░░░▒▒▀▄▄▒▀▒▒█░ // ░░▀░░░░░░▒▄▄▒▄▄▄▒▒█░ // ░░░▀▄▄▒▒░░░░▀▀▒▒▄▀░░ // ░░░░░▀█▄▒▒░░░░▒▄▀░░░ // ░░░░░░░░▀▀█▄▄▄▄▀░░░ func _setCFClientFlags(inFlags: CFOptionFlags, callback: CFReadStreamClientCallBack!, context: UnsafeMutablePointer<CFStreamClientContext>) -> Bool { return false } func _scheduleInCFRunLoop(runLoop: CFRunLoopRef, forMode aMode:CFStringRef) { } func _unscheduleFromCFRunLoop(runLoop: CFRunLoopRef, forMode aMode:CFStringRef) { } // MARK: Input func append(stream: NSInputStream) { streams.append(stream) } deinit { if streamStatus != .Closed { close() } } }
apache-2.0
austinzheng/swift-compiler-crashes
crashes-duplicates/20050-no-stacktrace.swift
11
226
// Distributed under the terms of the MIT license // Test case submitted to project by https://github.com/practicalswift (practicalswift) // Test case found by fuzzing struct A { let a { { { struct B } { } class case c, case
mit
austinzheng/swift-compiler-crashes
crashes-duplicates/12823-swift-sourcemanager-getmessage.swift
11
243
// Distributed under the terms of the MIT license // Test case submitted to project by https://github.com/practicalswift (practicalswift) // Test case found by fuzzing extension NSSet { var d = ( ) { init { { struct Q { func a { class case ,
mit
austinzheng/swift-compiler-crashes
crashes-duplicates/16733-no-stacktrace.swift
11
214
// Distributed under the terms of the MIT license // Test case submitted to project by https://github.com/practicalswift (practicalswift) // Test case found by fuzzing for { case { class c : { let d{ class case ,
mit
liujinlongxa/AnimationTransition
testTransitioning/AppDelegate.swift
1
2172
// // AppDelegate.swift // testTransitioning // // Created by Liujinlong on 8/9/15. // Copyright © 2015 Jaylon. All rights reserved. // import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { // Override point for customization after application launch. return true } func applicationWillResignActive(_ application: UIApplication) { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game. } func applicationDidEnterBackground(_ application: UIApplication) { // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. } func applicationWillEnterForeground(_ application: UIApplication) { // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background. } func applicationDidBecomeActive(_ application: UIApplication) { // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. } func applicationWillTerminate(_ application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. } }
mit
mpclarkson/StravaSwift
Sources/StravaSwift/StravaConfig.swift
1
2762
// // Client.swift // StravaSwift // // Created by Matthew on 11/11/2015. // Copyright © 2015 Matthew Clarkson. All rights reserved. // /** OAuth scope */ public enum Scope: String { /** Default: Read public segments, public routes, public profile data, public posts, public events, club feeds, and leaderboards **/ case read = "read" /** Read private routes, private segments, and private events for the user **/ case readAll = "read_all" /** Read all profile information even if the user has set their profile visibility to Followers or Only You **/ case profileReadAll = "profile:read_all" /** Update the user's weight and Functional Threshold Power (FTP), and access to star or unstar segments on their behalf **/ case profileWrite = "profile:write" /** Read the user's activity data for activities that are visible to Everyone and Followers, excluding privacy zone data **/ case activityRead = "activity:read" /** The same access as activity:read, plus privacy zone data and access to read the user's activities with visibility set to Only You **/ case activityReadAll = "activity:read_all" /** Access to create manual activities and uploads, and access to edit any activities that are visible to the app, based on activity read access level **/ case activityWrite = "activity:write" } /** Strava configuration struct which should be passed to the StravaClient.sharedInstance.initWithConfig(_:) method **/ public struct StravaConfig { /** The application's Id **/ public let clientId: Int /** The application's Secrent **/ public let clientSecret: String /** The application's RedirectURL - this should be registered in the info.plist **/ public let redirectUri: String /** The requested permission scope **/ public let scopes: [Scope] /** The delegate responsible for storing and retrieving the OAuth token in your app **/ public let delegate: TokenDelegate public let forcePrompt: Bool /** Initializer - Parameters: - clientId: Int - clientSecret: Int - redirectUri: String - scope: Scope enum - default is .read) - delegate: TokenDelegateProtocol - default is the DefaultTokenDelegate **/ public init(clientId: Int, clientSecret: String, redirectUri: String, scopes: [Scope] = [.read], delegate: TokenDelegate? = nil, forcePrompt: Bool = true) { self.clientId = clientId self.clientSecret = clientSecret self.redirectUri = redirectUri self.scopes = scopes self.delegate = delegate ?? DefaultTokenDelegate() self.forcePrompt = forcePrompt } }
mit
austinzheng/swift-compiler-crashes
crashes-duplicates/24566-swift-parser-diagnose.swift
9
245
// Distributed under the terms of the MIT license // Test case submitted to project by https://github.com/practicalswift (practicalswift) // Test case found by fuzzing protocol A{enum A{let a{{}class a{protocol P}}}}class B<d where B:d{let a=B
mit
elkanaoptimove/OptimoveSDK
OptimoveSDK/Common/Security/MD5.swift
1
9328
import Foundation // MARK: - Public public func MD5(_ input: String) -> String { return hex_md5(input) } // MARK: - Functions func hex_md5(_ input: String) -> String { return rstr2hex(rstr_md5(str2rstr_utf8(input))) } func str2rstr_utf8(_ input: String) -> [CUnsignedChar] { return Array(input.utf8) } func rstr2tr(_ input: [CUnsignedChar]) -> String { var output: String = "" input.forEach { output.append(String(UnicodeScalar($0))) } return output } /* * Convert a raw string to a hex string */ func rstr2hex(_ input: [CUnsignedChar]) -> String { let hexTab: [Character] = ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "A", "B", "C", "D", "E", "F"] var output: [Character] = [] for i in 0..<input.count { let x = input[i] let value1 = hexTab[Int((x >> 4) & 0x0F)] let value2 = hexTab[Int(Int32(x) & 0x0F)] output.append(value1) output.append(value2) } return String(output) } /* * Convert a raw string to an array of little-endian words * Characters >255 have their high-byte silently ignored. */ func rstr2binl(_ input: [CUnsignedChar]) -> [Int32] { var output: [Int: Int32] = [:] for i in stride(from: 0, to: input.count * 8, by: 8) { let value: Int32 = (Int32(input[i/8]) & 0xFF) << (Int32(i) % 32) output[i >> 5] = unwrap(output[i >> 5]) | value } return dictionary2array(output) } /* * Convert an array of little-endian words to a string */ func binl2rstr(_ input: [Int32]) -> [CUnsignedChar] { var output: [CUnsignedChar] = [] for i in stride(from: 0, to: input.count * 32, by: 8) { // [i>>5] >>> let value: Int32 = zeroFillRightShift(input[i>>5], Int32(i % 32)) & 0xFF output.append(CUnsignedChar(value)) } return output } /* * Calculate the MD5 of a raw string */ func rstr_md5(_ input: [CUnsignedChar]) -> [CUnsignedChar] { return binl2rstr(binl_md5(rstr2binl(input), input.count * 8)) } /* * Add integers, wrapping at 2^32. This uses 16-bit operations internally * to work around bugs in some JS interpreters. */ func safe_add(_ x: Int32, _ y: Int32) -> Int32 { let lsw = (x & 0xFFFF) + (y & 0xFFFF) let msw = (x >> 16) + (y >> 16) + (lsw >> 16) return (msw << 16) | (lsw & 0xFFFF) } /* * Bitwise rotate a 32-bit number to the left. */ func bit_rol(_ num: Int32, _ cnt: Int32) -> Int32 { // num >>> return (num << cnt) | zeroFillRightShift(num, (32 - cnt)) } /* * These funcs implement the four basic operations the algorithm uses. */ func md5_cmn(_ q: Int32, _ a: Int32, _ b: Int32, _ x: Int32, _ s: Int32, _ t: Int32) -> Int32 { return safe_add(bit_rol(safe_add(safe_add(a, q), safe_add(x, t)), s), b) } func md5_ff(_ a: Int32, _ b: Int32, _ c: Int32, _ d: Int32, _ x: Int32, _ s: Int32, _ t: Int32) -> Int32 { return md5_cmn((b & c) | ((~b) & d), a, b, x, s, t) } func md5_gg(_ a: Int32, _ b: Int32, _ c: Int32, _ d: Int32, _ x: Int32, _ s: Int32, _ t: Int32) -> Int32 { return md5_cmn((b & d) | (c & (~d)), a, b, x, s, t) } func md5_hh(_ a: Int32, _ b: Int32, _ c: Int32, _ d: Int32, _ x: Int32, _ s: Int32, _ t: Int32) -> Int32 { return md5_cmn(b ^ c ^ d, a, b, x, s, t) } func md5_ii(_ a: Int32, _ b: Int32, _ c: Int32, _ d: Int32, _ x: Int32, _ s: Int32, _ t: Int32) -> Int32 { return md5_cmn(c ^ (b | (~d)), a, b, x, s, t) } /* * Calculate the MD5 of an array of little-endian words, and a bit length. */ func binl_md5(_ input: [Int32], _ len: Int) -> [Int32] { /* append padding */ var x: [Int: Int32] = [:] for (index, value) in input.enumerated() { x[index] = value } let value: Int32 = 0x80 << Int32((len) % 32) x[len >> 5] = unwrap(x[len >> 5]) | value // >>> 9 let index = (((len + 64) >> 9) << 4) + 14 x[index] = unwrap(x[index]) | Int32(len) var a: Int32 = 1732584193 var b: Int32 = -271733879 var c: Int32 = -1732584194 var d: Int32 = 271733878 for i in stride(from: 0, to: length(x), by: 16) { let olda: Int32 = a let oldb: Int32 = b let oldc: Int32 = c let oldd: Int32 = d a = md5_ff(a, b, c, d, unwrap(x[i + 0]), 7 , -680876936) d = md5_ff(d, a, b, c, unwrap(x[i + 1]), 12, -389564586) c = md5_ff(c, d, a, b, unwrap(x[i + 2]), 17, 606105819) b = md5_ff(b, c, d, a, unwrap(x[i + 3]), 22, -1044525330) a = md5_ff(a, b, c, d, unwrap(x[i + 4]), 7 , -176418897) d = md5_ff(d, a, b, c, unwrap(x[i + 5]), 12, 1200080426) c = md5_ff(c, d, a, b, unwrap(x[i + 6]), 17, -1473231341) b = md5_ff(b, c, d, a, unwrap(x[i + 7]), 22, -45705983) a = md5_ff(a, b, c, d, unwrap(x[i + 8]), 7 , 1770035416) d = md5_ff(d, a, b, c, unwrap(x[i + 9]), 12, -1958414417) c = md5_ff(c, d, a, b, unwrap(x[i + 10]), 17, -42063) b = md5_ff(b, c, d, a, unwrap(x[i + 11]), 22, -1990404162) a = md5_ff(a, b, c, d, unwrap(x[i + 12]), 7 , 1804603682) d = md5_ff(d, a, b, c, unwrap(x[i + 13]), 12, -40341101) c = md5_ff(c, d, a, b, unwrap(x[i + 14]), 17, -1502002290) b = md5_ff(b, c, d, a, unwrap(x[i + 15]), 22, 1236535329) a = md5_gg(a, b, c, d, unwrap(x[i + 1]), 5 , -165796510) d = md5_gg(d, a, b, c, unwrap(x[i + 6]), 9 , -1069501632) c = md5_gg(c, d, a, b, unwrap(x[i + 11]), 14, 643717713) b = md5_gg(b, c, d, a, unwrap(x[i + 0]), 20, -373897302) a = md5_gg(a, b, c, d, unwrap(x[i + 5]), 5 , -701558691) d = md5_gg(d, a, b, c, unwrap(x[i + 10]), 9 , 38016083) c = md5_gg(c, d, a, b, unwrap(x[i + 15]), 14, -660478335) b = md5_gg(b, c, d, a, unwrap(x[i + 4]), 20, -405537848) a = md5_gg(a, b, c, d, unwrap(x[i + 9]), 5 , 568446438) d = md5_gg(d, a, b, c, unwrap(x[i + 14]), 9 , -1019803690) c = md5_gg(c, d, a, b, unwrap(x[i + 3]), 14, -187363961) b = md5_gg(b, c, d, a, unwrap(x[i + 8]), 20, 1163531501) a = md5_gg(a, b, c, d, unwrap(x[i + 13]), 5 , -1444681467) d = md5_gg(d, a, b, c, unwrap(x[i + 2]), 9 , -51403784) c = md5_gg(c, d, a, b, unwrap(x[i + 7]), 14, 1735328473) b = md5_gg(b, c, d, a, unwrap(x[i + 12]), 20, -1926607734) a = md5_hh(a, b, c, d, unwrap(x[i + 5]), 4 , -378558) d = md5_hh(d, a, b, c, unwrap(x[i + 8]), 11, -2022574463) c = md5_hh(c, d, a, b, unwrap(x[i + 11]), 16, 1839030562) b = md5_hh(b, c, d, a, unwrap(x[i + 14]), 23, -35309556) a = md5_hh(a, b, c, d, unwrap(x[i + 1]), 4 , -1530992060) d = md5_hh(d, a, b, c, unwrap(x[i + 4]), 11, 1272893353) c = md5_hh(c, d, a, b, unwrap(x[i + 7]), 16, -155497632) b = md5_hh(b, c, d, a, unwrap(x[i + 10]), 23, -1094730640) a = md5_hh(a, b, c, d, unwrap(x[i + 13]), 4 , 681279174) d = md5_hh(d, a, b, c, unwrap(x[i + 0]), 11, -358537222) c = md5_hh(c, d, a, b, unwrap(x[i + 3]), 16, -722521979) b = md5_hh(b, c, d, a, unwrap(x[i + 6]), 23, 76029189) a = md5_hh(a, b, c, d, unwrap(x[i + 9]), 4 , -640364487) d = md5_hh(d, a, b, c, unwrap(x[i + 12]), 11, -421815835) c = md5_hh(c, d, a, b, unwrap(x[i + 15]), 16, 530742520) b = md5_hh(b, c, d, a, unwrap(x[i + 2]), 23, -995338651) a = md5_ii(a, b, c, d, unwrap(x[i + 0]), 6 , -198630844) d = md5_ii(d, a, b, c, unwrap(x[i + 7]), 10, 1126891415) c = md5_ii(c, d, a, b, unwrap(x[i + 14]), 15, -1416354905) b = md5_ii(b, c, d, a, unwrap(x[i + 5]), 21, -57434055) a = md5_ii(a, b, c, d, unwrap(x[i + 12]), 6 , 1700485571) d = md5_ii(d, a, b, c, unwrap(x[i + 3]), 10, -1894986606) c = md5_ii(c, d, a, b, unwrap(x[i + 10]), 15, -1051523) b = md5_ii(b, c, d, a, unwrap(x[i + 1]), 21, -2054922799) a = md5_ii(a, b, c, d, unwrap(x[i + 8]), 6 , 1873313359) d = md5_ii(d, a, b, c, unwrap(x[i + 15]), 10, -30611744) c = md5_ii(c, d, a, b, unwrap(x[i + 6]), 15, -1560198380) b = md5_ii(b, c, d, a, unwrap(x[i + 13]), 21, 1309151649) a = md5_ii(a, b, c, d, unwrap(x[i + 4]), 6 , -145523070) d = md5_ii(d, a, b, c, unwrap(x[i + 11]), 10, -1120210379) c = md5_ii(c, d, a, b, unwrap(x[i + 2]), 15, 718787259) b = md5_ii(b, c, d, a, unwrap(x[i + 9]), 21, -343485551) a = safe_add(a, olda) b = safe_add(b, oldb) c = safe_add(c, oldc) d = safe_add(d, oldd) } return [a, b, c, d] } // MARK: - Helper func length(_ dictionary: [Int: Int32]) -> Int { return (dictionary.keys.max() ?? 0) + 1 } func dictionary2array(_ dictionary: [Int: Int32]) -> [Int32] { var array = Array<Int32>(repeating: 0, count: dictionary.keys.count) for i in Array(dictionary.keys).sorted() { array[i] = unwrap(dictionary[i]) } return array } func unwrap(_ value: Int32?, _ fallback: Int32 = 0) -> Int32 { if let value = value { return value } return fallback } func zeroFillRightShift(_ num: Int32, _ count: Int32) -> Int32 { let value = UInt32(bitPattern: num) >> UInt32(bitPattern: count) return Int32(bitPattern: value) }
mit
danielmartin/swift
test/Driver/bindings.swift
4
4820
// RUN: %empty-directory(%t) // RUN: %swiftc_driver -driver-print-bindings -target x86_64-apple-macosx10.9 %/s 2>&1 | %FileCheck %s -check-prefix=BASIC // BASIC: # "x86_64-apple-macosx10.9" - "swift{{c?(\.EXE)?}}", inputs: ["{{.*}}bindings.swift"], output: {object: "[[OBJECT:.*\.o]]"} // BASIC: # "x86_64-apple-macosx10.9" - "ld", inputs: ["[[OBJECT]]"], output: {image: "bindings"} // RUN: %swiftc_driver -driver-print-bindings -target x86_64-apple-macosx10.9 - 2>&1 | %FileCheck %s -check-prefix=STDIN // STDIN: # "x86_64-apple-macosx10.9" - "swift{{c?(\.EXE)?}}", inputs: ["-"], output: {object: "[[OBJECT:.*\.o]]"} // STDIN: # "x86_64-apple-macosx10.9" - "ld", inputs: ["[[OBJECT]]"], output: {image: "main"} // RUN: %swiftc_driver -driver-print-bindings -target x86_64-apple-macosx10.9 %/S/Inputs/invalid-module-name.swift 2>&1 | %FileCheck %s -check-prefix=INVALID-NAME-SINGLE-FILE // INVALID-NAME-SINGLE-FILE: # "x86_64-apple-macosx10.9" - "swift{{c?(\.EXE)?}}", inputs: ["{{.*}}/Inputs/invalid-module-name.swift"], output: {object: "[[OBJECT:.*\.o]]"} // INVALID-NAME-SINGLE-FILE: # "x86_64-apple-macosx10.9" - "ld", inputs: ["[[OBJECT]]"], output: {image: "invalid-module-name"} // RUN: %swiftc_driver -driver-print-bindings -target x86_64-apple-macosx10.9 -o NamedOutput %/s 2>&1 | %FileCheck %s -check-prefix=NAMEDIMG // RUN: %swiftc_driver -driver-print-bindings -target x86_64-apple-macosx10.9 -module-name NamedOutput %/s 2>&1 | %FileCheck %s -check-prefix=NAMEDIMG // NAMEDIMG: # "x86_64-apple-macosx10.9" - "swift{{c?(\.EXE)?}}", inputs: ["{{.*}}bindings.swift"], output: {object: "[[OBJECT:.*\.o]]"} // NAMEDIMG: # "x86_64-apple-macosx10.9" - "ld", inputs: ["[[OBJECT]]"], output: {image: "NamedOutput"} // RUN: %swiftc_driver -driver-print-bindings -target x86_64-apple-macosx10.9 -c %/s 2>&1 | %FileCheck %s -check-prefix=OBJ // OBJ: # "x86_64-apple-macosx10.9" - "swift{{c?(\.EXE)?}}", inputs: ["{{.*}}bindings.swift"], output: {object: "bindings.o"} // RUN: %swiftc_driver -driver-print-bindings -target x86_64-apple-macosx10.9 -c %/s -o /build/bindings.o 2>&1 | %FileCheck %s -check-prefix=NAMEDOBJ // NAMEDOBJ: # "x86_64-apple-macosx10.9" - "swift{{c?(\.EXE)?}}", inputs: ["{{.*}}bindings.swift"], output: {object: "/build/bindings.o"} // RUN: %swiftc_driver -driver-print-bindings -target x86_64-apple-macosx10.9 -emit-sil %/s 2>&1 | %FileCheck %s -check-prefix=SIL // SIL: # "x86_64-apple-macosx10.9" - "swift{{c?(\.EXE)?}}", inputs: ["{{.*}}bindings.swift"], output: {sil: "-"} // RUN: %swiftc_driver -driver-print-bindings -target x86_64-apple-macosx10.9 -emit-ir %S/Inputs/empty.sil 2>&1 | %FileCheck %s -check-prefix=SIL-INPUT // SIL-INPUT: # "x86_64-apple-macosx10.9" - "swift{{c?(\.EXE)?}}", inputs: ["{{.*}}empty.sil"], output: {llvm-ir: "-"} // RUN: %swiftc_driver -driver-print-bindings -target x86_64-apple-macosx10.9 -c -incremental %/s 2>&1 | %FileCheck %s -check-prefix=OBJ-AND-DEPS // OBJ-AND-DEPS: # "x86_64-apple-macosx10.9" - "swift{{c?(\.EXE)?}}", inputs: ["{{.*}}bindings.swift"], output: { // OBJ-AND-DEPS-DAG: swift-dependencies: "bindings.swiftdeps" // OBJ-AND-DEPS-DAG: object: "bindings.o" // OBJ-AND-DEPS: } // RUN: echo '{"%/s": {"object": "objroot/bindings.o"}}' > %t/map.json // RUN: %swiftc_driver -driver-print-bindings -output-file-map %t/map.json -target x86_64-apple-macosx10.9 %/s 2>&1 | %FileCheck %s -check-prefix=MAP // MAP: # "x86_64-apple-macosx10.9" - "swift{{c?(\.EXE)?}}", inputs: ["{{.*}}bindings.swift"], output: {object: "objroot/bindings.o"} // RUN: echo '{"": {"object": "objroot/bindings.o"}}' > %t/map.json // RUN: %swiftc_driver -driver-print-bindings -output-file-map %t/map.json -whole-module-optimization -target x86_64-apple-macosx10.9 %/s %S/Inputs/lib.swift 2>&1 | %FileCheck %s -check-prefix=MAP-WFO // MAP-WFO: # "x86_64-apple-macosx10.9" - "swift{{c?(\.EXE)?}}", inputs: ["{{.*}}bindings.swift", "{{.*}}lib.swift"], output: {object: "objroot/bindings.o"} // RUN: touch %t/a.o %t/b.o // RUN: %swiftc_driver -driver-print-bindings -target x86_64-apple-macosx10.9 %t/a.o %t/b.o -o main 2>&1 | %FileCheck %s -check-prefix=LINK-ONLY // RUN: %swiftc_driver -driver-print-bindings -target x86_64-apple-macosx10.9 -g %t/a.o %t/b.o -o main 2>&1 | %FileCheck %s -check-prefix=LINK-ONLY // LINK-ONLY: # "x86_64-apple-macosx10.9" - "ld", inputs: ["{{.*}}/a.o", "{{.*}}/b.o"], output: {image: "main"} // RUN: touch %t/a.swiftmodule %t/b.swiftmodule // RUN: %swiftc_driver -driver-print-bindings -target x86_64-apple-macosx10.9 -g %t/a.o %t/b.o %t/a.swiftmodule %t/b.swiftmodule -o main 2>&1 | %FileCheck %s -check-prefix=DEBUG-LINK-ONLY // DEBUG-LINK-ONLY-NOT: "swift" // DEBUG-LINK-ONLY: # "x86_64-apple-macosx10.9" - "ld", inputs: ["{{.*}}/a.o", "{{.*}}/b.o", "{{.*}}/a.swiftmodule", "{{.*}}/b.swiftmodule"], output: {image: "main"}
apache-2.0
CatchChat/Yep
Yep/Views/Cells/MediaView/MediaViewCell.swift
1
620
// // MediaViewCell.swift // Yep // // Created by nixzhu on 15/10/28. // Copyright © 2015年 Catch Inc. All rights reserved. // import UIKit final class MediaViewCell: UICollectionViewCell { @IBOutlet weak var mediaView: MediaView! @IBOutlet weak var activityIndicator: UIActivityIndicatorView! override func awakeFromNib() { super.awakeFromNib() mediaView.backgroundColor = UIColor.clearColor() contentView.backgroundColor = UIColor.clearColor() } override func prepareForReuse() { super.prepareForReuse() mediaView.imageView.image = nil } }
mit
NqiOS/DYTV-swift
DYTV/DYTV/AppDelegate.swift
1
473
// // AppDelegate.swift // DYTV // // Created by djk on 17/2/23. // Copyright © 2017年 NQ. All rights reserved. // import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { UITabBar.appearance().tintColor = UIColor.orange; return true } }
mit
hermantai/samples
ios/SwiftUI-Cookbook-2nd-Edition/Chapter14-Cross-Platform-SwiftUI/03-Create-the-watchOS-version/Complete/Cross-Platform/Cross-Platform/Views/ContentView.swift
1
465
// // ContentView.swift // Cross-Platform // // Created by Edgar Nzokwe on 9/18/21. // import SwiftUI struct ContentView: View { @EnvironmentObject var insectData: InsectData var body: some View { InsectListView{InsectDetailView(insect: $0) } .environmentObject(InsectData()) } } struct ContentView_Previews: PreviewProvider { static var previews: some View { ContentView().environmentObject(InsectData()) } }
apache-2.0
GaoZhenWei/PhotoBrowser
PhotoBrowser/AppDelegate.swift
13
2613
// // AppDelegate.swift // PhotoBrowser // // Created by 冯成林 on 15/8/14. // Copyright (c) 2015年 冯成林. All rights reserved. // import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool { // window = UIWindow(frame: UIScreen.mainScreen().bounds) // window?.backgroundColor = UIColor.whiteColor() // let displayVC = DisplayVC() // // displayVC.tabBarItem.title = "Charlin Feng" // //// let navVC = UINavigationController(rootViewController: displayVC) //// // let tabVC = UITabBarController() //// // tabVC.viewControllers = [displayVC] // // window?.rootViewController = tabVC // // window?.makeKeyAndVisible() return true } func applicationWillResignActive(application: UIApplication) { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game. } func applicationDidEnterBackground(application: UIApplication) { // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. } func applicationWillEnterForeground(application: UIApplication) { // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background. } func applicationDidBecomeActive(application: UIApplication) { // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. } func applicationWillTerminate(application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. } }
mit
maxoll90/FSwift
ios7-example/FSwift-Sample-iOS7/FSwift-Sample-iOS7/AppDelegate.swift
1
2158
// // AppDelegate.swift // FSwift-Sample-iOS7 // // Created by Kelton Person on 4/28/15. // Copyright (c) 2015 Kelton Person. All rights reserved. // import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool { // Override point for customization after application launch. return true } func applicationWillResignActive(application: UIApplication) { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game. } func applicationDidEnterBackground(application: UIApplication) { // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. } func applicationWillEnterForeground(application: UIApplication) { // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background. } func applicationDidBecomeActive(application: UIApplication) { // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. } func applicationWillTerminate(application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. } }
mit
Khan/Swiftx
Swiftx/Optional.swift
1
1193
// // Optional.swift // swiftz_core // // Created by Maxwell Swadling on 3/06/2014. // Copyright (c) 2014 Maxwell Swadling. All rights reserved. // /// Lifts a value into an Optional. public func pure<A>(a: A) -> A? { return .Some(a) } /// Fmap | If the Optional is None, ignores the function and returns None. If the Optional is Some, /// applies the function to the Some value and returns the result in a new Some. public func <^> <A, B>(f: A -> B, a: A?) -> B? { if let x = a { return (f(x)) } else { return .None } } /// Ap | Given an Optional<A -> B> and an Optional<A>, returns an Optional<B>. If the `f` or `a' /// param is None, simply returns None. Otherwise the function taken from Some(f) is applied to the /// value from Some(a) and a Some is returned. public func <*> <A, B>(f: (A -> B)?, a: A?) -> B? { if f != nil && a != nil { return (f!(a!)) } else { return .None } } /// Bind | Given an Optional<A>, and a function from A -> Optional<B>, applies the function `f` if /// `a` is Some, otherwise the function is ignored and None is returned. public func >>- <A, B>(a: A?, f: A -> B?) -> B? { if let x = a { return f(x) } else { return .None } }
bsd-3-clause
think-dev/MadridBUS
MadridBUS/Source/Business/BusLinesBasicInfoDTO.swift
1
608
import Foundation import ObjectMapper final class BusLinesBasicInfoDTO: DTO { private var date: String = "" var lines: String = "" init(using lines: [String]) { super.init() date = Date.string(from: Date(), using: "dd/MM/yyyy") if lines.count > 0 { self.lines = lines.joined(separator: "|") } } required init?(map: Map) { fatalError("init(map:) has not been implemented") } override func mapping(map: Map) { super.mapping(map: map) date <- map["SelectDate"] lines <- map["Lines"] } }
mit
ben-ng/swift
validation-test/compiler_crashers_fixed/01686-swift-astcontext-setconformsto.swift
1
444
// This source file is part of the Swift.org open source project // Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // RUN: not %target-swift-frontend %s -typecheck if true { var b = 1]] protocol a : a { func a
apache-2.0
Henryforce/KRActivityIndicatorView
KRActivityIndicatorView/KRActivityIndicatorAnimationBallRotate.swift
2
3965
// // KRActivityIndicatorAnimationBallRotate.swift // KRActivityIndicatorViewDemo // // The MIT License (MIT) // Originally written to work in iOS by Vinh Nguyen in 2016 // Adapted to OSX by Henry Serrano in 2017 // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. // import Cocoa class KRActivityIndicatorAnimationBallRotate: KRActivityIndicatorAnimationDelegate { func setUpAnimation(in layer: CALayer, size: CGSize, color: NSColor) { let circleSize: CGFloat = size.width / 5 let duration: CFTimeInterval = 1 let timingFunction = CAMediaTimingFunction(controlPoints: 0.7, -0.13, 0.22, 0.86) // Scale animation let scaleAnimation = CAKeyframeAnimation(keyPath: "transform.scale") scaleAnimation.keyTimes = [0, 0.5, 1] scaleAnimation.timingFunctions = [timingFunction, timingFunction] scaleAnimation.values = [1, 0.6, 1] scaleAnimation.duration = duration // Rotate animation let rotateAnimation = CAKeyframeAnimation(keyPath:"transform.rotation.z") rotateAnimation.keyTimes = [0, 0.5, 1] rotateAnimation.timingFunctions = [timingFunction, timingFunction] rotateAnimation.values = [0, Float.pi, 2 * Float.pi] rotateAnimation.duration = duration // Animation let animation = CAAnimationGroup() animation.animations = [scaleAnimation, rotateAnimation] animation.duration = duration animation.repeatCount = HUGE animation.isRemovedOnCompletion = false // Draw circles let leftCircle = KRActivityIndicatorShape.circle.layerWith(size: CGSize(width: circleSize, height: circleSize), color: color) let rightCircle = KRActivityIndicatorShape.circle.layerWith(size: CGSize(width: circleSize, height: circleSize), color: color) let centerCircle = KRActivityIndicatorShape.circle.layerWith(size: CGSize(width: circleSize, height: circleSize), color: color) leftCircle.opacity = 0.8 leftCircle.frame = CGRect(x: 0, y: (size.height - circleSize) / 2, width: circleSize, height: circleSize) rightCircle.opacity = 0.8 rightCircle.frame = CGRect(x: size.width - circleSize, y: (size.height - circleSize) / 2, width: circleSize, height: circleSize) centerCircle.frame = CGRect(x: (size.width - circleSize) / 2, y: (size.height - circleSize) / 2, width: circleSize, height: circleSize) let circle = CALayer() let frame = CGRect(x: (layer.bounds.size.width - size.width) / 2, y: (layer.bounds.size.height - size.height) / 2, width: size.width, height: size.height) circle.frame = frame circle.addSublayer(leftCircle) circle.addSublayer(rightCircle) circle.addSublayer(centerCircle) circle.add(animation, forKey: "animation") layer.addSublayer(circle) } }
mit
cnoon/swift-compiler-crashes
fixed/25876-llvm-errs.swift
7
2485
// Distributed under the terms of the MIT license // Test case submitted to project by https://github.com/practicalswift (practicalswift) // Test case found by fuzzing class d<T where g: <T where : String {let a{ let : T.e struct B<T where h: C { var e(d func f:String{ func a{ private let f: NSObject { let g c{() { extension NSData{ class A {()enum S<B<A}c{ " typealias A<T.e(String protocol c struct d:T>:A struct d=c{ "\(){ { {} private let : NSObject {let a { } struct d<T where g: A<T where g: d a(d func a<T where : C { struct B<T where g:A:A< B { { import Foundation struct S<T { func a }struct B<T where g:A func a{ struct c{let v: A { struct c struct S<T where g: {{ let f=e(d func a var d<T where g:A:a< : NSObject { let : C {"\(d func d=c struct d: NSObject { } class d<T>){struct B<T where f: NSObject struct c{ " } () > { struct c : C { enum e {let f: A { struct c class A {{ class d=c{(String extension NSData{"\() > { } struct c func f: C { class a let c n extension NSData{init{ } } case, let a{class{let a { func f{ extension NSData{} (" let f:String protocol a< : { struct B<T where h: A v: a{ var e, : C {protocol c class A { let : NSObject let a } func b deinit{ struct c protocol c{ " var d=c extension NSData{ func f=e(String } class a protocol a<T where g: C { let a{ func d=e, : <T where : <T where struct B<A<T where g: NSObject deinit{ func b func b protocol a func f: A { extension D{(String func d=c let a { typealias A<T where g: T>){let f{ v: NSObject private let : <T where f: d func a class d:String func a{ } let a { func b }c<T where I:T>:String{struct B{(String{(String{ let v: d a class B< : T>){protocol A< B { extension NSData{ let : <T where g:String{ { func b func a func f=c protocol c private let a{() { func b } let a{ deinit{ let a{ func f: A {(d a(d a<T where I:A:T>){ deinit{ extension D{ }c func d:a extension D{func a let a {init{ struct B{let g c } println - case, } let c { func a(d a{ func a{() > { } } struct A<T where I:String struct B{ class B{(d func f: C {struct c }c () { func f: C { protocol c : d func f{let a<A< : NSObject case, struct c n {struct c let g c{ class a{ protocol c enum e, : T>:String{func a (d a{(" let f: <T where let a {let a { struct c n func a<T where : NSObject struct c case, struct S<T>){ }struct d<B{let a {class func d<A:N{ func d:C{struct c{init{ struct c import Foundation case, func d=e struct S<T { func d<T where : NSObject case, struct B<T where I:a class B<T where func f: <T>:C{class{ class
mit
brentdax/swift
test/SourceKit/CodeComplete/complete_structure.swift
11
4194
// XFAIL: broken_std_regex // RUN: %complete-test %s -group=none -fuzz -structure -tok=S1_DOT | %FileCheck %s -check-prefix=S1_DOT // RUN: %complete-test %s -group=none -add-inner-results -fuzz -structure -tok=S1_POSTFIX | %FileCheck %s -check-prefix=S1_POSTFIX // RUN: %complete-test %s -group=none -add-inner-results -fuzz -structure -tok=S1_POSTFIX_INIT | %FileCheck %s -check-prefix=S1_INIT // RUN: %complete-test %s -group=none -fuzz -structure -tok=S1_PAREN_INIT | %FileCheck %s -check-prefix=S1_INIT // RUN: %complete-test %s -group=none -hide-none -fuzz -structure -tok=STMT_0 | %FileCheck %s -check-prefix=STMT_0 // RUN: %complete-test %s -group=none -fuzz -structure -tok=ENUM_0 | %FileCheck %s -check-prefix=ENUM_0 // RUN: %complete-test %s -group=none -fuzz -structure -tok=OVERRIDE_0 | %FileCheck %s -check-prefix=OVERRIDE_0 // RUN: %complete-test %s -group=none -fuzz -structure -tok=S1_INNER_0 | %FileCheck %s -check-prefix=S1_INNER_0 // RUN: %complete-test %s -group=none -fuzz -structure -tok=INT_INNER_0 | %FileCheck %s -check-prefix=INT_INNER_0 // RUN: %complete-test %s -group=none -fuzz -structure -tok=ASSOCIATED_TYPE_1 | %FileCheck %s -check-prefix=ASSOCIATED_TYPE_1 struct S1 { func method1() {} func method2(_ a: Int, b: Int) -> Int { return 1 } func method3(a a: Int, b: Int) {} func method4(_: Int, _: Int) {} func method5(_: inout Int, b: inout Int) {} func method6(_ c: Int) throws {} func method7(_ callback: () throws -> ()) rethrows {} func method8<T, U>(_ d: (T, U) -> T, e: T -> U) {} let v1: Int = 1 var v2: Int { return 1 } subscript(x: Int, y: Int) -> Int { return 1 } subscript(x x: Int, y y: Int) -> Int { return 1 } init() {} init(a: Int, b: Int) {} init(_: Int, _: Int) {} init(c: Int)? {} } func test1(_ x: S1) { x.#^S1_DOT^# } // S1_DOT: {name:method1}() // S1_DOT: {name:method2}({params:{l:a:}{t: Int}, {n:b:}{t: Int}}) // S1_DOT: {name:method3}({params:{n:a:}{t: Int}, {n:b:}{t: Int}}) // S1_DOT: {name:method4}({params:{t:Int}, {t:Int}}) // S1_DOT: {name:method5}({params:{t:&Int}, {n:b:}{t: &Int}}) // FIXME: put throws in a range! // S1_DOT: {name:method6}({params:{l:c:}{t: Int}}){throws: throws} // S1_DOT: {name:method7}({params:{l:callback:}{t: () throws -> ()}}){throws: rethrows} // S1_DOT: {name:method8}({params:{l:d:}{t: (T, U) -> T}, {n:e:}{t: (T) -> U}}) // S1_DOT: {name:v1} // S1_DOT: {name:v2} func test2(_ x: S1) { x#^S1_POSTFIX^# } // Subscripts! // S1_POSTFIX: {name:.} // S1_POSTFIX: [{params:{t:Int}, {t:Int}}] // S1_POSTFIX: [{params:{n:x:}{t: Int}, {n:y:}{t: Int}}] // The dot becomes part of the name // S1_POSTFIX: {name:.method1}() // S1_POSTFIX: {name:.method2}({params:{l:a:}{t: Int}, {n:b:}{t: Int}}) func test4() { S1#^S1_POSTFIX_INIT^# } func test5() { S1(#^S1_PAREN_INIT^# } // S1_INIT: ({params:{t:Int}, {t:Int}}) // S1_INIT: ({params:{n:a:}{t: Int}, {n:b:}{t: Int}}) // S1_INIT: ({params:{n:c:}{t: Int}}) func test6(_ xyz: S1, fgh: (S1) -> S1) { #^STMT_0^# } // STMT_0: {name:func} // STMT_0: {name:fgh} // STMT_0: {name:xyz} // STMT_0: {name:S1} // STMT_0: {name:test6}({params:{l:xyz:}{t: S1}, {n:fgh:}{t: (S1) -> S1}}) // STMT_0: {name:try!} enum E1 { case C1 case C2(S1) case C3(l1: S1, l2: S1) } func test7(_ x: E1) { test7(.#^ENUM_0^#) } // ENUM_0: {name:C1} // ENUM_0: {name:C2}({params:{t:S1}}) // ENUM_0: {name:C3}({params:{n:l1:}{t: S1}, {n:l2:}{t: S1}}) class C1 { func foo(x: S1, y: S1, z: (S1) -> S1) -> S1 {} func zap<T, U>(x: T, y: U, z: (T) -> U) -> T {} } class C2 : C1 { override func #^OVERRIDE_0^# } // FIXME: overrides don't break out their code completion string structure. // OVERRIDE_0: {name:foo(x: S1, y: S1, z: (S1) -> S1) -> S1} // OVERRIDE_0: {name:zap<T, U>(x: T, y: U, z: (T) -> U) -> T} func test8() { #^S1_INNER_0,S1^# } // S1_INNER_0: {name:S1.} // FIXME: should the ( go inside the name here? // S1_INNER_0: {name:S1}( func test9(_ x: inout Int) { #^INT_INNER_0,x^# } // INT_INNER_0: {name:x==} // INT_INNER_0: {name:x<} // INT_INNER_0: {name:x+} // INT_INNER_0: {name:x..<} protocol P1 { associatedtype T } struct S2: P1 { #^ASSOCIATED_TYPE_1^# } // ASSOCIATED_TYPE_1: {name:T = }{params:{l:Type}}
apache-2.0
brentdax/swift
test/stdlib/ArrayDiagnostics.swift
15
621
// RUN: %target-typecheck-verify-swift class NotEquatable {} func test_ArrayOfNotEquatableIsNotEquatable() { var a = [ NotEquatable(), NotEquatable() ] // FIXME: This is an awful error. if a == a {} // expected-error {{'<Self where Self : Equatable> (Self.Type) -> (Self, Self) -> Bool' requires that 'NotEquatable' conform to 'Equatable'}} // expected-error@-1{{type 'NotEquatable' does not conform to protocol 'Equatable'}} // expected-note @-2 {{requirement specified as 'NotEquatable' : 'Equatable'}} // expected-note@-3{{requirement from conditional conformance of '[NotEquatable]' to 'Equatable'}} }
apache-2.0
mitochrome/complex-gestures-demo
apps/GestureRecognizer/Carthage/Checkouts/RxSwift/Rx.playground/Pages/Enable_RxSwift.Resources.total.xcplaygroundpage/Contents.swift
28
796
//: [Back](@previous) /*: Follow these instructions to enable `RxSwift.Resources.total` in your project: # **CocoaPods** 1. Add a `post_install` hook to your Podfile, e.g.: ``` target 'AppTarget' do pod 'RxSwift' end post_install do |installer| installer.pods_project.targets.each do |target| if target.name == 'RxSwift' target.build_configurations.each do |config| if config.name == 'Debug' config.build_settings['OTHER_SWIFT_FLAGS'] ||= ['-D', 'TRACE_RESOURCES'] end end end end end ``` 2. Run `pod update`. 3. Build project (**Product** → **Build**). # **Carthage** 1. Run `carthage build --configuration Debug`. 2. Build project (**Product** → **Build**). */
mit
srn214/Floral
Floral/Floral/Classes/Base/Controller/ViewController.swift
1
5674
// // ViewController.swift // Floral // // Created by LDD on 2019/7/18. // Copyright © 2019 文刂Rn. All rights reserved. // import UIKit import RxCocoa import EmptyDataSet_Swift import RxReachability import Reachability class ViewController<VM: ViewModel>: UIViewController { /// 标题 let navigationTitle = BehaviorRelay<String?>(value: nil) lazy var viewModel: VM = { guard let classType = "\(VM.self)".classType(VM.self) else { return VM() } let viewModel = classType.init() viewModel .loading .drive(isLoading) .disposed(by: rx.disposeBag) viewModel .error .drive(rx.showError) .disposed(by: rx.disposeBag) return viewModel }() /// 监听网络状态改变 lazy var reachability: Reachability? = Reachability() /// 是否正在加载 let isLoading = BehaviorRelay(value: false) /// 当前连接的网络类型 let reachabilityConnection = BehaviorRelay(value: Reachability.Connection.none) /// 数据源 nil 时点击了 view let emptyDataSetViewTap = PublishSubject<Void>() /// 数据源 nil 时显示的标题,默认 " " var emptyDataSetTitle: String = "" /// 数据源 nil 时显示的描述,默认 " " var emptyDataSetDescription: String = "" /// 数据源 nil 时显示的图片 var emptyDataSetImage = UIImage(named: "") /// 没有网络时显示的图片 var noConnectionImage = UIImage(named: "") /// 没有网络时显示的标题 var noConnectionTitle: String = "" /// 没有网络时显示的描述 var noConnectionDescription: String = "" /// 没有网络时点击了 view var noConnectionViewTap = PublishSubject<Void>() /// 数据源 nil 时是否可以滚动,默认 true var emptyDataSetShouldAllowScroll: Bool = true /// 没有网络时是否可以滚动, 默认 false var noConnectionShouldAllowScroll: Bool = false /// 状态栏 + 导航栏高度 lazy var topH: CGFloat = UIApplication.shared.statusBarFrame.size.height + (navigationController?.navigationBar.height ?? 0) // MARK: - LifeCycle override func viewDidLoad() { super.viewDidLoad() registerNotification() setupUI() bindVM() navigationTitle.bind(to: navigationItem.rx.title).disposed(by: rx.disposeBag) } // MARK: - deinit deinit { print("\(type(of: self)): Deinited") } // MARK: - didReceiveMemoryWarning override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() print("\(type(of: self)): Received Memory Warning") } func setupUI() { view.backgroundColor = .white } func bindVM() {} /// 重复点击 TabBar func repeatClickTabBar() {} } // MARK: - EmptyDataSetSource extension ViewController: EmptyDataSetSource { func title(forEmptyDataSet scrollView: UIScrollView) -> NSAttributedString? { var title = "" switch reachabilityConnection.value { case .none: title = noConnectionTitle case .cellular: title = emptyDataSetTitle case .wifi: title = emptyDataSetTitle } return NSAttributedString(string: title) } func description(forEmptyDataSet scrollView: UIScrollView) -> NSAttributedString? { var description = "" switch reachabilityConnection.value { case .none: description = noConnectionDescription case .cellular: description = emptyDataSetDescription case .wifi: description = emptyDataSetDescription } return NSAttributedString(string: description) } func image(forEmptyDataSet scrollView: UIScrollView) -> UIImage? { switch reachabilityConnection.value { case .none: return noConnectionImage case .cellular: return emptyDataSetImage case .wifi: return emptyDataSetImage } } func backgroundColor(forEmptyDataSet scrollView: UIScrollView) -> UIColor? { return .clear } func verticalOffset(forEmptyDataSet scrollView: UIScrollView) -> CGFloat { return -topH } } // MARK: - EmptyDataSetDelegate extension ViewController: EmptyDataSetDelegate { func emptyDataSetShouldDisplay(_ scrollView: UIScrollView) -> Bool { return !isLoading.value } func emptyDataSet(_ scrollView: UIScrollView, didTapView view: UIView) { switch reachabilityConnection.value { case .none: noConnectionViewTap.onNext(()) case .cellular: emptyDataSetViewTap.onNext(()) case .wifi: emptyDataSetViewTap.onNext(()) } } func emptyDataSetShouldAllowScroll(_ scrollView: UIScrollView) -> Bool { switch reachabilityConnection.value { case .none: return noConnectionShouldAllowScroll case .cellular: return emptyDataSetShouldAllowScroll case .wifi: return emptyDataSetShouldAllowScroll } } } // MARK: - 通知 extension ViewController { // MARK: - 注册通知 private func registerNotification() { } // MARK: - tabBar重复点击 func tabBarRepeatClick() { guard view.isShowingOnKeyWindow() else {return} repeatClickTabBar() } }
mit
karivalkama/Agricola-Scripture-Editor
TranslationEditor/TranslationCell.swift
1
2439
// // ParagraphCell.swift // TranslationEditor // // Created by Mikko Hilpinen on 13.1.2017. // Copyright © 2017 SIL. All rights reserved. // import Foundation // This is the superclass for different translation cells (source and target) @available(*, deprecated) class TranslationCell: UITableViewCell, ParagraphAssociated { // ATTRIBUTES ----------------- weak var textView: UITextView? var pathId: String? private static let chapterMarkerFont = UIFont(name: "Arial", size: 32.0)! static let defaultFont = UIFont(name: "Arial", size: 16.0)! // OTHER METHODS ------------- func setContent(_ text: NSAttributedString, withId pathId: String) { self.pathId = pathId guard let textView = textView else { print("ERROR: Text view hasn't been defined for new content") return } textView.scrollsToTop = false let newText = NSMutableAttributedString() newText.append(text) // Adds visual attributes based on the existing attribute data text.enumerateAttributes(in: NSMakeRange(0, text.length), options: []) { attributes, range, _ in for (attrName, value) in attributes { switch attrName { case ChapterMarkerAttributeName: newText.addAttribute(NSAttributedStringKey.font, value: TranslationCell.chapterMarkerFont, range: range) case VerseIndexMarkerAttributeName, ParaMarkerAttributeName: newText.addAttribute(NSAttributedStringKey.foregroundColor, value: UIColor.gray, range: range) case CharStyleAttributeName: if let style = value as? CharStyle { switch style { // TODO: This font is just for testing purposes case .quotation: newText.addAttribute(NSAttributedStringKey.font, value: UIFont(name: "Chalkduster", size: 18.0)!, range: range) // TODO: Add exhaustive cases default: break } } // TODO: Add handling of paraStyle default: newText.addAttribute(NSAttributedStringKey.font, value: TranslationCell.defaultFont, range: range) } } } /* // Adds visual attributes to each verse and paragraph marker newText.enumerateAttribute(VerseIndexMarkerAttributeName, in: NSMakeRange(0, newText.length), options: []) { value, range, _ in // Makes each verse marker gray if value != nil { newText.addAttribute(NSForegroundColorAttributeName, value: UIColor.gray, range: range) } }*/ // Sets text content textView.attributedText = newText } }
mit
sportlabsMike/XLForm
Examples/Swift/SwiftExample/CustomRows/Weekdays/XLFormWeekDaysCell.swift
1
6387
// XLFormWeekDaysCell.swift // XLForm ( https://github.com/xmartlabs/XLForm ) // // Copyright (c) 2014-2015 Xmartlabs ( http://xmartlabs.com ) // // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. let XLFormRowDescriptorTypeWeekDays = "XLFormRowDescriptorTypeWeekDays" class XLFormWeekDaysCell : XLFormBaseCell { enum kWeekDay: Int { case sunday = 1, monday, tuesday, wednesday, thursday, friday, saturday func description() -> String { switch self { case .sunday: return "Sunday" case .monday: return "Monday" case .tuesday: return "Tuesday" case .wednesday: return "Wednesday" case .thursday: return "Thursday" case .friday: return "Friday" case .saturday: return "Saturday" } } //Add Custom Functions //Allows for iteration as needed (for in ...) static let allValues = [sunday, monday, tuesday, wednesday, thursday, friday, saturday] } @IBOutlet weak var sundayButton: UIButton! @IBOutlet weak var mondayButton: UIButton! @IBOutlet weak var tuesdayButton: UIButton! @IBOutlet weak var wednesdayButton: UIButton! @IBOutlet weak var thursdayButton: UIButton! @IBOutlet weak var fridayButton: UIButton! @IBOutlet weak var saturdayButton: UIButton! //MARK: - XLFormDescriptorCell override func configure() { super.configure() selectionStyle = .none configureButtons() } override func update() { super.update() updateButtons() } override static func formDescriptorCellHeight(for rowDescriptor: XLFormRowDescriptor!) -> CGFloat { return 60 } //MARK: - Action @IBAction func dayTapped(_ sender: UIButton) { let day = getDayFormButton(sender) sender.isSelected = !sender.isSelected var newValue = rowDescriptor!.value as! Dictionary<String, Bool> newValue[day] = sender.isSelected rowDescriptor!.value = newValue } //MARK: - Helpers func configureButtons() { for subview in contentView.subviews { if let button = subview as? UIButton { button.setImage(UIImage(named: "uncheckedDay"), for: UIControlState()) button.setImage(UIImage(named: "checkedDay"), for: .selected) button.adjustsImageWhenHighlighted = false imageTopTitleBottom(button) } } } func updateButtons() { var value = rowDescriptor!.value as! Dictionary<String, Bool> sundayButton.isSelected = value[kWeekDay.sunday.description()]! mondayButton.isSelected = value[kWeekDay.monday.description()]! tuesdayButton.isSelected = value[kWeekDay.tuesday.description()]! wednesdayButton.isSelected = value[kWeekDay.wednesday.description()]! thursdayButton.isSelected = value[kWeekDay.thursday.description()]! fridayButton.isSelected = value[kWeekDay.friday.description()]! saturdayButton.isSelected = value[kWeekDay.saturday.description()]! sundayButton.alpha = rowDescriptor!.isDisabled() ? 0.6 : 1 mondayButton.alpha = mondayButton.alpha tuesdayButton.alpha = mondayButton.alpha wednesdayButton.alpha = mondayButton.alpha thursdayButton.alpha = mondayButton.alpha fridayButton.alpha = mondayButton.alpha saturdayButton.alpha = mondayButton.alpha } func imageTopTitleBottom(_ button: UIButton) { // the space between the image and text let spacing : CGFloat = 3.0 // lower the text and push it left so it appears centered // below the image let imageSize : CGSize = button.imageView!.image!.size button.titleEdgeInsets = UIEdgeInsets(top: 0.0, left: -imageSize.width, bottom: -(imageSize.height + spacing), right: 0.0) // raise the image and push it right so it appears centered // above the text let titleSize : CGSize = (button.titleLabel!.text! as NSString).size(withAttributes: [NSAttributedStringKey.font: button.titleLabel!.font]) button.imageEdgeInsets = UIEdgeInsetsMake(-(titleSize.height + spacing), 0.0, 0.0, -titleSize.width) } func getDayFormButton(_ button: UIButton) -> String { switch button { case sundayButton: return kWeekDay.sunday.description() case mondayButton: return kWeekDay.monday.description() case tuesdayButton: return kWeekDay.tuesday.description() case wednesdayButton: return kWeekDay.wednesday.description() case thursdayButton: return kWeekDay.thursday.description() case fridayButton: return kWeekDay.friday.description() default: return kWeekDay.saturday.description() } } }
mit
box/box-ios-sdk
Tests/Responses/SignRequestSignerRoleSpecs.swift
1
1055
// // SignRequestSignerRoleSpecs.swift // BoxSDKTests-iOS // // Created by Artur Jankowski on 14/10/2021. // Copyright © 2021 box. All rights reserved. // @testable import BoxSDK import Nimble import Quick class SignRequestSignerRoleSpecs: QuickSpec { override func spec() { describe("SignRequestSignerRole") { describe("init()") { it("should correctly create an enum value from it's string representation") { expect(SignRequestSignerRole.signer).to(equal(SignRequestSignerRole(SignRequestSignerRole.signer.description))) expect(SignRequestSignerRole.approver).to(equal(SignRequestSignerRole(SignRequestSignerRole.approver.description))) expect(SignRequestSignerRole.finalCopyReader).to(equal(SignRequestSignerRole(SignRequestSignerRole.finalCopyReader.description))) expect(SignRequestSignerRole.customValue("custom value")).to(equal(SignRequestSignerRole("custom value"))) } } } } }
apache-2.0
xusader/firefox-ios
StorageTests/TestTableTable.swift
2
6443
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ import UIKit import XCTest class TestSchemaTable: XCTestCase { // This is a very basic test. Adds an entry. Retrieves it, and then clears the database func testTable() { let files = MockFiles() var db = BrowserDB(files: files) // Test creating a table var testTable = getCreateTable() db.createOrUpdate(testTable) // Now make sure the item is in the table-table var err: NSError? = nil let table = SchemaTable<TableInfo>() var cursor = db.query(&err, callback: { (connection, err) -> Cursor in return table.query(connection, options: QueryOptions(filter: testTable.name)) }) verifyTable(cursor, table: testTable) // We have to close this cursor to ensure we don't get results from a sqlite memory cache below when // we requery the table. cursor.close() // Now test updating the table testTable = getUpgradeTable() db.createOrUpdate(testTable) cursor = db.query(&err, callback: { (connection, err) -> Cursor in return table.query(connection, options: QueryOptions(filter: testTable.name)) }) verifyTable(cursor, table: testTable) // We have to close this cursor to ensure we don't get results from a sqlite memory cache below when // we requery the table. cursor.close() // Now try updating it again to the same version. This shouldn't call create or upgrade testTable = getNoOpTable() db.createOrUpdate(testTable) // Cleanup files.remove("browser.db") } // Helper for verifying that the data in a cursor matches whats in a table private func verifyTable(cursor: Cursor, table: TestTable) { XCTAssertEqual(cursor.count, 1, "Cursor is the right size") var data = cursor[0] as? TableInfoWrapper XCTAssertNotNil(data, "Found an object of the right type") XCTAssertEqual(data!.name, table.name, "Table info has the right name") XCTAssertEqual(data!.version, table.version, "Table info has the right version") } // A test class for fake table creation/upgrades class TestTable : Table { var name: String { return "testName" } var _version: Int = -1 var version: Int { return _version } typealias Type = Int // Called if the table is created let createCallback: () -> Bool // Called if the table is upgraded let updateCallback: (from: Int, to: Int) -> Bool let dropCallback: (() -> Void)? init(version: Int, createCallback: () -> Bool, updateCallback: (from: Int, to: Int) -> Bool, dropCallback: (() -> Void)? = nil) { self._version = version self.createCallback = createCallback self.updateCallback = updateCallback self.dropCallback = dropCallback } func exists(db: SQLiteDBConnection) -> Bool { let res = db.executeQuery("SELECT name FROM sqlite_master WHERE type = 'table' AND name=?", factory: StringFactory, withArgs: [name]) return res.count > 0 } func drop(db: SQLiteDBConnection) -> Bool { if let dropCallback = dropCallback { dropCallback() } let sqlStr = "DROP TABLE IF EXISTS \(name)" let err = db.executeChange(sqlStr, withArgs: []) return err == nil } func create(db: SQLiteDBConnection, version: Int) -> Bool { // BrowserDB uses a different query to determine if a table exists, so we need to ensure it actually happens db.executeChange("CREATE TABLE IF NOT EXISTS \(name) (ID INTEGER PRIMARY KEY AUTOINCREMENT)") return createCallback() } func updateTable(db: SQLiteDBConnection, from: Int, to: Int) -> Bool { return updateCallback(from: from, to: to) } // These are all no-ops for testing func insert(db: SQLiteDBConnection, item: Type?, inout err: NSError?) -> Int { return -1 } func update(db: SQLiteDBConnection, item: Type?, inout err: NSError?) -> Int { return -1 } func delete(db: SQLiteDBConnection, item: Type?, inout err: NSError?) -> Int { return -1 } func query(db: SQLiteDBConnection, options: QueryOptions?) -> Cursor { return Cursor(status: .Failure, msg: "Shouldn't hit this") } } // This function will create a table with appropriate callbacks set. Pass "create" if you expect the table to // be created. Pass "update" if it should be updated. Pass anythign else if neither callback should be called. func getCreateTable() -> TestTable { let t = TestTable(version: 1, createCallback: { _ -> Bool in XCTAssert(true, "Should have created table") return true }, updateCallback: { (from, to) -> Bool in XCTFail("Should not try to update table") return false }) return t } func getUpgradeTable() -> TestTable { var upgraded = false var dropped = false let t = TestTable(version: 2, createCallback: { _ -> Bool in XCTAssertTrue(dropped, "Create should be called after upgrade attempt") return true }, updateCallback: { (from, to) -> Bool in XCTAssert(true, "Should try to update table") XCTAssertEqual(from, 1, "From is correct") XCTAssertEqual(to, 2, "To is correct") // We'll return false here. The db will take that as a sign to drop and recreate our table. upgraded = true return false }, dropCallback: { () -> Void in XCTAssertTrue(upgraded, "Should try to drop table") dropped = true }) return t } func getNoOpTable() -> TestTable { let t = TestTable(version: 2, createCallback: { _ -> Bool in XCTFail("Should not try to create table") return false }, updateCallback: { (from, to) -> Bool in XCTFail("Should not try to update table") return false }) return t } }
mpl-2.0
cdmx/MiniMancera
miniMancera/Model/Option/WhistlesVsZombies/SonicBoom/MOptionWhistlesVsZombiesSonicBoomItemStrategyRelease.swift
1
1113
import Foundation class MOptionWhistlesVsZombiesSonicBoomItemStrategyRelease:MGameStrategy<MOptionWhistlesVsZombiesSonicBoomItem, MOptionWhistlesVsZombies> { private var startingTime:TimeInterval? private let kDuration:TimeInterval = 0.2 override func update( elapsedTime:TimeInterval, scene:ViewGameScene<MOptionWhistlesVsZombies>) { if let startingTime:TimeInterval = self.startingTime { let deltaTime:TimeInterval = elapsedTime - startingTime if deltaTime > kDuration { model.moving(scene:scene) } } else { startingTime = elapsedTime createView(scene:scene) } } //MARK: private private func createView(scene:ViewGameScene<MOptionWhistlesVsZombies>) { guard let scene:VOptionWhistlesVsZombiesScene = scene as? VOptionWhistlesVsZombiesScene else { return } scene.addSonicBoomRelease(model:model) } }
mit
prpr-man/DivePlanner
Dive PlannerTests/Dive_PlannerTests.swift
1
993
// // Dive_PlannerTests.swift // Dive PlannerTests // // Created by PeroPeroMan on 2015/07/27. // Copyright © 2015年 TMDC. All rights reserved. // import XCTest @testable import Dive_Planner class Dive_PlannerTests: XCTestCase { override func setUp() { super.setUp() // Put setup code here. This method is called before the invocation of each test method in the class. } override func tearDown() { // Put teardown code here. This method is called after the invocation of each test method in the class. super.tearDown() } func testExample() { // This is an example of a functional test case. // Use XCTAssert and related functions to verify your tests produce the correct results. } func testPerformanceExample() { // This is an example of a performance test case. self.measureBlock { // Put the code you want to measure the time of here. } } }
mit
fernandomarins/food-drivr-pt
Pods/SlideMenuControllerSwift/Source/SlideMenuController.swift
2
41667
// // SlideMenuController.swift // // Created by Yuji Hato on 12/3/14. // import Foundation import UIKit @objc public protocol SlideMenuControllerDelegate { optional func leftWillOpen() optional func leftDidOpen() optional func leftWillClose() optional func leftDidClose() optional func rightWillOpen() optional func rightDidOpen() optional func rightWillClose() optional func rightDidClose() } public struct SlideMenuOptions { public static var leftViewWidth: CGFloat = 270.0 public static var leftBezelWidth: CGFloat? = 16.0 public static var contentViewScale: CGFloat = 0.96 public static var contentViewOpacity: CGFloat = 0.5 public static var contentViewDrag: Bool = false public static var shadowOpacity: CGFloat = 0.0 public static var shadowRadius: CGFloat = 0.0 public static var shadowOffset: CGSize = CGSizeMake(0,0) public static var panFromBezel: Bool = true public static var animationDuration: CGFloat = 0.4 public static var rightViewWidth: CGFloat = 270.0 public static var rightBezelWidth: CGFloat? = 16.0 public static var rightPanFromBezel: Bool = true public static var hideStatusBar: Bool = true public static var pointOfNoReturnWidth: CGFloat = 44.0 public static var simultaneousGestureRecognizers: Bool = true public static var opacityViewBackgroundColor: UIColor = UIColor.blackColor() } public class SlideMenuController: UIViewController, UIGestureRecognizerDelegate { public enum SlideAction { case Open case Close } public enum TrackAction { case LeftTapOpen case LeftTapClose case LeftFlickOpen case LeftFlickClose case RightTapOpen case RightTapClose case RightFlickOpen case RightFlickClose } struct PanInfo { var action: SlideAction var shouldBounce: Bool var velocity: CGFloat } public weak var delegate: SlideMenuControllerDelegate? public var opacityView = UIView() public var mainContainerView = UIView() public var leftContainerView = UIView() public var rightContainerView = UIView() public var mainViewController: UIViewController? public var leftViewController: UIViewController? public var leftPanGesture: UIPanGestureRecognizer? public var leftTapGesture: UITapGestureRecognizer? public var rightViewController: UIViewController? public var rightPanGesture: UIPanGestureRecognizer? public var rightTapGesture: UITapGestureRecognizer? public required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } public override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: NSBundle?) { super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil) } public convenience init(mainViewController: UIViewController, leftMenuViewController: UIViewController) { self.init() self.mainViewController = mainViewController leftViewController = leftMenuViewController initView() } public convenience init(mainViewController: UIViewController, rightMenuViewController: UIViewController) { self.init() self.mainViewController = mainViewController rightViewController = rightMenuViewController initView() } public convenience init(mainViewController: UIViewController, leftMenuViewController: UIViewController, rightMenuViewController: UIViewController) { self.init() self.mainViewController = mainViewController leftViewController = leftMenuViewController rightViewController = rightMenuViewController initView() } public override func awakeFromNib() { initView() } deinit { } public func initView() { mainContainerView = UIView(frame: view.bounds) mainContainerView.backgroundColor = UIColor.clearColor() mainContainerView.autoresizingMask = [.FlexibleHeight, .FlexibleWidth] view.insertSubview(mainContainerView, atIndex: 0) var opacityframe: CGRect = view.bounds let opacityOffset: CGFloat = 0 opacityframe.origin.y = opacityframe.origin.y + opacityOffset opacityframe.size.height = opacityframe.size.height - opacityOffset opacityView = UIView(frame: opacityframe) opacityView.backgroundColor = SlideMenuOptions.opacityViewBackgroundColor opacityView.autoresizingMask = [UIViewAutoresizing.FlexibleHeight, UIViewAutoresizing.FlexibleWidth] opacityView.layer.opacity = 0.0 view.insertSubview(opacityView, atIndex: 1) if leftViewController != nil { var leftFrame: CGRect = view.bounds leftFrame.size.width = SlideMenuOptions.leftViewWidth leftFrame.origin.x = leftMinOrigin(); let leftOffset: CGFloat = 0 leftFrame.origin.y = leftFrame.origin.y + leftOffset leftFrame.size.height = leftFrame.size.height - leftOffset leftContainerView = UIView(frame: leftFrame) leftContainerView.backgroundColor = UIColor.clearColor() leftContainerView.autoresizingMask = UIViewAutoresizing.FlexibleHeight view.insertSubview(leftContainerView, atIndex: 2) addLeftGestures() } if rightViewController != nil { var rightFrame: CGRect = view.bounds rightFrame.size.width = SlideMenuOptions.rightViewWidth rightFrame.origin.x = rightMinOrigin() let rightOffset: CGFloat = 0 rightFrame.origin.y = rightFrame.origin.y + rightOffset; rightFrame.size.height = rightFrame.size.height - rightOffset rightContainerView = UIView(frame: rightFrame) rightContainerView.backgroundColor = UIColor.clearColor() rightContainerView.autoresizingMask = UIViewAutoresizing.FlexibleHeight view.insertSubview(rightContainerView, atIndex: 3) addRightGestures() } } public override func viewWillTransitionToSize(size: CGSize, withTransitionCoordinator coordinator: UIViewControllerTransitionCoordinator) { super.viewWillTransitionToSize(size, withTransitionCoordinator: coordinator) mainContainerView.transform = CGAffineTransformMakeScale(1.0, 1.0) leftContainerView.hidden = true rightContainerView.hidden = true coordinator.animateAlongsideTransition(nil, completion: { (context: UIViewControllerTransitionCoordinatorContext!) -> Void in self.closeLeftNonAnimation() self.closeRightNonAnimation() self.leftContainerView.hidden = false self.rightContainerView.hidden = false if self.leftPanGesture != nil && self.leftPanGesture != nil { self.removeLeftGestures() self.addLeftGestures() } if self.rightPanGesture != nil && self.rightPanGesture != nil { self.removeRightGestures() self.addRightGestures() } }) } public override func viewDidLoad() { super.viewDidLoad() edgesForExtendedLayout = UIRectEdge.None } public override func supportedInterfaceOrientations() -> UIInterfaceOrientationMask { if let mainController = self.mainViewController{ return mainController.supportedInterfaceOrientations() } return UIInterfaceOrientationMask.All } public override func shouldAutorotate() -> Bool { return mainViewController?.shouldAutorotate() ?? false } public override func viewWillLayoutSubviews() { // topLayoutGuideの値が確定するこのタイミングで各種ViewControllerをセットする setUpViewController(mainContainerView, targetViewController: mainViewController) setUpViewController(leftContainerView, targetViewController: leftViewController) setUpViewController(rightContainerView, targetViewController: rightViewController) } public override func openLeft() { guard let _ = leftViewController else { // If leftViewController is nil, then return return } self.delegate?.leftWillOpen?() setOpenWindowLevel() // for call viewWillAppear of leftViewController leftViewController?.beginAppearanceTransition(isLeftHidden(), animated: true) openLeftWithVelocity(0.0) track(.LeftTapOpen) } public override func openRight() { guard let _ = rightViewController else { // If rightViewController is nil, then return return } self.delegate?.rightWillOpen?() setOpenWindowLevel() rightViewController?.beginAppearanceTransition(isRightHidden(), animated: true) openRightWithVelocity(0.0) track(.RightTapOpen) } public override func closeLeft() { guard let _ = leftViewController else { // If leftViewController is nil, then return return } self.delegate?.leftWillClose?() leftViewController?.beginAppearanceTransition(isLeftHidden(), animated: true) closeLeftWithVelocity(0.0) setCloseWindowLevel() } public override func closeRight() { guard let _ = rightViewController else { // If rightViewController is nil, then return return } self.delegate?.rightWillClose?() rightViewController?.beginAppearanceTransition(isRightHidden(), animated: true) closeRightWithVelocity(0.0) setCloseWindowLevel() } public func addLeftGestures() { if (leftViewController != nil) { if leftPanGesture == nil { leftPanGesture = UIPanGestureRecognizer(target: self, action: #selector(self.handleLeftPanGesture(_:))) leftPanGesture!.delegate = self view.addGestureRecognizer(leftPanGesture!) } if leftTapGesture == nil { leftTapGesture = UITapGestureRecognizer(target: self, action: #selector(self.toggleLeft)) leftTapGesture!.delegate = self view.addGestureRecognizer(leftTapGesture!) } } } public func addRightGestures() { if (rightViewController != nil) { if rightPanGesture == nil { rightPanGesture = UIPanGestureRecognizer(target: self, action: #selector(self.handleRightPanGesture(_:))) rightPanGesture!.delegate = self view.addGestureRecognizer(rightPanGesture!) } if rightTapGesture == nil { rightTapGesture = UITapGestureRecognizer(target: self, action: #selector(self.toggleRight)) rightTapGesture!.delegate = self view.addGestureRecognizer(rightTapGesture!) } } } public func removeLeftGestures() { if leftPanGesture != nil { view.removeGestureRecognizer(leftPanGesture!) leftPanGesture = nil } if leftTapGesture != nil { view.removeGestureRecognizer(leftTapGesture!) leftTapGesture = nil } } public func removeRightGestures() { if rightPanGesture != nil { view.removeGestureRecognizer(rightPanGesture!) rightPanGesture = nil } if rightTapGesture != nil { view.removeGestureRecognizer(rightTapGesture!) rightTapGesture = nil } } public func isTagetViewController() -> Bool { // Function to determine the target ViewController // Please to override it if necessary return true } public func track(trackAction: TrackAction) { // function is for tracking // Please to override it if necessary } struct LeftPanState { static var frameAtStartOfPan: CGRect = CGRectZero static var startPointOfPan: CGPoint = CGPointZero static var wasOpenAtStartOfPan: Bool = false static var wasHiddenAtStartOfPan: Bool = false static var lastState : UIGestureRecognizerState = .Ended } func handleLeftPanGesture(panGesture: UIPanGestureRecognizer) { if !isTagetViewController() { return } if isRightOpen() { return } switch panGesture.state { case UIGestureRecognizerState.Began: if LeftPanState.lastState != .Ended && LeftPanState.lastState != .Cancelled && LeftPanState.lastState != .Failed { return } if isLeftHidden() { self.delegate?.leftWillOpen?() } else { self.delegate?.leftWillClose?() } LeftPanState.frameAtStartOfPan = leftContainerView.frame LeftPanState.startPointOfPan = panGesture.locationInView(view) LeftPanState.wasOpenAtStartOfPan = isLeftOpen() LeftPanState.wasHiddenAtStartOfPan = isLeftHidden() leftViewController?.beginAppearanceTransition(LeftPanState.wasHiddenAtStartOfPan, animated: true) addShadowToView(leftContainerView) setOpenWindowLevel() case UIGestureRecognizerState.Changed: if LeftPanState.lastState != .Began && LeftPanState.lastState != .Changed { return } let translation: CGPoint = panGesture.translationInView(panGesture.view!) leftContainerView.frame = applyLeftTranslation(translation, toFrame: LeftPanState.frameAtStartOfPan) applyLeftOpacity() applyLeftContentViewScale() case UIGestureRecognizerState.Ended, UIGestureRecognizerState.Cancelled: if LeftPanState.lastState != .Changed { return } let velocity:CGPoint = panGesture.velocityInView(panGesture.view) let panInfo: PanInfo = panLeftResultInfoForVelocity(velocity) if panInfo.action == .Open { if !LeftPanState.wasHiddenAtStartOfPan { leftViewController?.beginAppearanceTransition(true, animated: true) } openLeftWithVelocity(panInfo.velocity) track(.LeftFlickOpen) } else { if LeftPanState.wasHiddenAtStartOfPan { leftViewController?.beginAppearanceTransition(false, animated: true) } closeLeftWithVelocity(panInfo.velocity) setCloseWindowLevel() track(.LeftFlickClose) } case UIGestureRecognizerState.Failed, UIGestureRecognizerState.Possible: break } LeftPanState.lastState = panGesture.state } struct RightPanState { static var frameAtStartOfPan: CGRect = CGRectZero static var startPointOfPan: CGPoint = CGPointZero static var wasOpenAtStartOfPan: Bool = false static var wasHiddenAtStartOfPan: Bool = false static var lastState : UIGestureRecognizerState = .Ended } func handleRightPanGesture(panGesture: UIPanGestureRecognizer) { if !isTagetViewController() { return } if isLeftOpen() { return } switch panGesture.state { case UIGestureRecognizerState.Began: if RightPanState.lastState != .Ended && RightPanState.lastState != .Cancelled && RightPanState.lastState != .Failed { return } if isRightHidden() { self.delegate?.rightWillOpen?() } else { self.delegate?.rightWillClose?() } RightPanState.frameAtStartOfPan = rightContainerView.frame RightPanState.startPointOfPan = panGesture.locationInView(view) RightPanState.wasOpenAtStartOfPan = isRightOpen() RightPanState.wasHiddenAtStartOfPan = isRightHidden() rightViewController?.beginAppearanceTransition(RightPanState.wasHiddenAtStartOfPan, animated: true) addShadowToView(rightContainerView) setOpenWindowLevel() case UIGestureRecognizerState.Changed: if RightPanState.lastState != .Began && RightPanState.lastState != .Changed { return } let translation: CGPoint = panGesture.translationInView(panGesture.view!) rightContainerView.frame = applyRightTranslation(translation, toFrame: RightPanState.frameAtStartOfPan) applyRightOpacity() applyRightContentViewScale() case UIGestureRecognizerState.Ended, UIGestureRecognizerState.Cancelled: if RightPanState.lastState != .Changed { return } let velocity: CGPoint = panGesture.velocityInView(panGesture.view) let panInfo: PanInfo = panRightResultInfoForVelocity(velocity) if panInfo.action == .Open { if !RightPanState.wasHiddenAtStartOfPan { rightViewController?.beginAppearanceTransition(true, animated: true) } openRightWithVelocity(panInfo.velocity) track(.RightFlickOpen) } else { if RightPanState.wasHiddenAtStartOfPan { rightViewController?.beginAppearanceTransition(false, animated: true) } closeRightWithVelocity(panInfo.velocity) setCloseWindowLevel() track(.RightFlickClose) } case UIGestureRecognizerState.Failed, UIGestureRecognizerState.Possible: break } RightPanState.lastState = panGesture.state } public func openLeftWithVelocity(velocity: CGFloat) { let xOrigin: CGFloat = leftContainerView.frame.origin.x let finalXOrigin: CGFloat = 0.0 var frame = leftContainerView.frame; frame.origin.x = finalXOrigin; var duration: NSTimeInterval = Double(SlideMenuOptions.animationDuration) if velocity != 0.0 { duration = Double(fabs(xOrigin - finalXOrigin) / velocity) duration = Double(fmax(0.1, fmin(1.0, duration))) } addShadowToView(leftContainerView) UIView.animateWithDuration(duration, delay: 0.0, options: UIViewAnimationOptions.CurveEaseInOut, animations: { [weak self]() -> Void in if let strongSelf = self { strongSelf.leftContainerView.frame = frame strongSelf.opacityView.layer.opacity = Float(SlideMenuOptions.contentViewOpacity) SlideMenuOptions.contentViewDrag == true ? (strongSelf.mainContainerView.transform = CGAffineTransformMakeTranslation(SlideMenuOptions.leftViewWidth, 0)) : (strongSelf.mainContainerView.transform = CGAffineTransformMakeScale(SlideMenuOptions.contentViewScale, SlideMenuOptions.contentViewScale)) } }) { [weak self](Bool) -> Void in if let strongSelf = self { strongSelf.disableContentInteraction() strongSelf.leftViewController?.endAppearanceTransition() strongSelf.delegate?.leftDidOpen?() } } } public func openRightWithVelocity(velocity: CGFloat) { let xOrigin: CGFloat = rightContainerView.frame.origin.x // CGFloat finalXOrigin = SlideMenuOptions.rightViewOverlapWidth; let finalXOrigin: CGFloat = CGRectGetWidth(view.bounds) - rightContainerView.frame.size.width var frame = rightContainerView.frame frame.origin.x = finalXOrigin var duration: NSTimeInterval = Double(SlideMenuOptions.animationDuration) if velocity != 0.0 { duration = Double(fabs(xOrigin - CGRectGetWidth(view.bounds)) / velocity) duration = Double(fmax(0.1, fmin(1.0, duration))) } addShadowToView(rightContainerView) UIView.animateWithDuration(duration, delay: 0.0, options: UIViewAnimationOptions.CurveEaseInOut, animations: { [weak self]() -> Void in if let strongSelf = self { strongSelf.rightContainerView.frame = frame strongSelf.opacityView.layer.opacity = Float(SlideMenuOptions.contentViewOpacity) SlideMenuOptions.contentViewDrag == true ? (strongSelf.mainContainerView.transform = CGAffineTransformMakeTranslation(-SlideMenuOptions.rightViewWidth, 0)) : (strongSelf.mainContainerView.transform = CGAffineTransformMakeScale(SlideMenuOptions.contentViewScale, SlideMenuOptions.contentViewScale)) } }) { [weak self](Bool) -> Void in if let strongSelf = self { strongSelf.disableContentInteraction() strongSelf.rightViewController?.endAppearanceTransition() strongSelf.delegate?.rightDidOpen?() } } } public func closeLeftWithVelocity(velocity: CGFloat) { let xOrigin: CGFloat = leftContainerView.frame.origin.x let finalXOrigin: CGFloat = leftMinOrigin() var frame: CGRect = leftContainerView.frame; frame.origin.x = finalXOrigin var duration: NSTimeInterval = Double(SlideMenuOptions.animationDuration) if velocity != 0.0 { duration = Double(fabs(xOrigin - finalXOrigin) / velocity) duration = Double(fmax(0.1, fmin(1.0, duration))) } UIView.animateWithDuration(duration, delay: 0.0, options: UIViewAnimationOptions.CurveEaseInOut, animations: { [weak self]() -> Void in if let strongSelf = self { strongSelf.leftContainerView.frame = frame strongSelf.opacityView.layer.opacity = 0.0 strongSelf.mainContainerView.transform = CGAffineTransformMakeScale(1.0, 1.0) } }) { [weak self](Bool) -> Void in if let strongSelf = self { strongSelf.removeShadow(strongSelf.leftContainerView) strongSelf.enableContentInteraction() strongSelf.leftViewController?.endAppearanceTransition() strongSelf.delegate?.leftDidClose?() } } } public func closeRightWithVelocity(velocity: CGFloat) { let xOrigin: CGFloat = rightContainerView.frame.origin.x let finalXOrigin: CGFloat = CGRectGetWidth(view.bounds) var frame: CGRect = rightContainerView.frame frame.origin.x = finalXOrigin var duration: NSTimeInterval = Double(SlideMenuOptions.animationDuration) if velocity != 0.0 { duration = Double(fabs(xOrigin - CGRectGetWidth(view.bounds)) / velocity) duration = Double(fmax(0.1, fmin(1.0, duration))) } UIView.animateWithDuration(duration, delay: 0.0, options: UIViewAnimationOptions.CurveEaseInOut, animations: { [weak self]() -> Void in if let strongSelf = self { strongSelf.rightContainerView.frame = frame strongSelf.opacityView.layer.opacity = 0.0 strongSelf.mainContainerView.transform = CGAffineTransformMakeScale(1.0, 1.0) } }) { [weak self](Bool) -> Void in if let strongSelf = self { strongSelf.removeShadow(strongSelf.rightContainerView) strongSelf.enableContentInteraction() strongSelf.rightViewController?.endAppearanceTransition() strongSelf.delegate?.rightDidClose?() } } } public override func toggleLeft() { if isLeftOpen() { closeLeft() setCloseWindowLevel() // Tracking of close tap is put in here. Because closeMenu is due to be call even when the menu tap. track(.LeftTapClose) } else { openLeft() } } public func isLeftOpen() -> Bool { return leftViewController != nil && leftContainerView.frame.origin.x == 0.0 } public func isLeftHidden() -> Bool { return leftContainerView.frame.origin.x <= leftMinOrigin() } public override func toggleRight() { if isRightOpen() { closeRight() setCloseWindowLevel() // Tracking of close tap is put in here. Because closeMenu is due to be call even when the menu tap. track(.RightTapClose) } else { openRight() } } public func isRightOpen() -> Bool { return rightViewController != nil && rightContainerView.frame.origin.x == CGRectGetWidth(view.bounds) - rightContainerView.frame.size.width } public func isRightHidden() -> Bool { return rightContainerView.frame.origin.x >= CGRectGetWidth(view.bounds) } public func changeMainViewController(mainViewController: UIViewController, close: Bool) { removeViewController(self.mainViewController) self.mainViewController = mainViewController setUpViewController(mainContainerView, targetViewController: mainViewController) if (close) { closeLeft() closeRight() } } public func changeLeftViewWidth(width: CGFloat) { SlideMenuOptions.leftViewWidth = width; var leftFrame: CGRect = view.bounds leftFrame.size.width = width leftFrame.origin.x = leftMinOrigin(); let leftOffset: CGFloat = 0 leftFrame.origin.y = leftFrame.origin.y + leftOffset leftFrame.size.height = leftFrame.size.height - leftOffset leftContainerView.frame = leftFrame; } public func changeRightViewWidth(width: CGFloat) { SlideMenuOptions.rightBezelWidth = width; var rightFrame: CGRect = view.bounds rightFrame.size.width = width rightFrame.origin.x = rightMinOrigin() let rightOffset: CGFloat = 0 rightFrame.origin.y = rightFrame.origin.y + rightOffset; rightFrame.size.height = rightFrame.size.height - rightOffset rightContainerView.frame = rightFrame; } public func changeLeftViewController(leftViewController: UIViewController, closeLeft:Bool) { removeViewController(self.leftViewController) self.leftViewController = leftViewController setUpViewController(leftContainerView, targetViewController: leftViewController) if closeLeft { self.closeLeft() } } public func changeRightViewController(rightViewController: UIViewController, closeRight:Bool) { removeViewController(self.rightViewController) self.rightViewController = rightViewController; setUpViewController(rightContainerView, targetViewController: rightViewController) if closeRight { self.closeRight() } } private func leftMinOrigin() -> CGFloat { return -SlideMenuOptions.leftViewWidth } private func rightMinOrigin() -> CGFloat { return CGRectGetWidth(view.bounds) } private func panLeftResultInfoForVelocity(velocity: CGPoint) -> PanInfo { let thresholdVelocity: CGFloat = 1000.0 let pointOfNoReturn: CGFloat = CGFloat(floor(leftMinOrigin())) + SlideMenuOptions.pointOfNoReturnWidth let leftOrigin: CGFloat = leftContainerView.frame.origin.x var panInfo: PanInfo = PanInfo(action: .Close, shouldBounce: false, velocity: 0.0) panInfo.action = leftOrigin <= pointOfNoReturn ? .Close : .Open; if velocity.x >= thresholdVelocity { panInfo.action = .Open panInfo.velocity = velocity.x } else if velocity.x <= (-1.0 * thresholdVelocity) { panInfo.action = .Close panInfo.velocity = velocity.x } return panInfo } private func panRightResultInfoForVelocity(velocity: CGPoint) -> PanInfo { let thresholdVelocity: CGFloat = -1000.0 let pointOfNoReturn: CGFloat = CGFloat(floor(CGRectGetWidth(view.bounds)) - SlideMenuOptions.pointOfNoReturnWidth) let rightOrigin: CGFloat = rightContainerView.frame.origin.x var panInfo: PanInfo = PanInfo(action: .Close, shouldBounce: false, velocity: 0.0) panInfo.action = rightOrigin >= pointOfNoReturn ? .Close : .Open if velocity.x <= thresholdVelocity { panInfo.action = .Open panInfo.velocity = velocity.x } else if (velocity.x >= (-1.0 * thresholdVelocity)) { panInfo.action = .Close panInfo.velocity = velocity.x } return panInfo } private func applyLeftTranslation(translation: CGPoint, toFrame:CGRect) -> CGRect { var newOrigin: CGFloat = toFrame.origin.x newOrigin += translation.x let minOrigin: CGFloat = leftMinOrigin() let maxOrigin: CGFloat = 0.0 var newFrame: CGRect = toFrame if newOrigin < minOrigin { newOrigin = minOrigin } else if newOrigin > maxOrigin { newOrigin = maxOrigin } newFrame.origin.x = newOrigin return newFrame } private func applyRightTranslation(translation: CGPoint, toFrame: CGRect) -> CGRect { var newOrigin: CGFloat = toFrame.origin.x newOrigin += translation.x let minOrigin: CGFloat = rightMinOrigin() let maxOrigin: CGFloat = rightMinOrigin() - rightContainerView.frame.size.width var newFrame: CGRect = toFrame if newOrigin > minOrigin { newOrigin = minOrigin } else if newOrigin < maxOrigin { newOrigin = maxOrigin } newFrame.origin.x = newOrigin return newFrame } private func getOpenedLeftRatio() -> CGFloat { let width: CGFloat = leftContainerView.frame.size.width let currentPosition: CGFloat = leftContainerView.frame.origin.x - leftMinOrigin() return currentPosition / width } private func getOpenedRightRatio() -> CGFloat { let width: CGFloat = rightContainerView.frame.size.width let currentPosition: CGFloat = rightContainerView.frame.origin.x return -(currentPosition - CGRectGetWidth(view.bounds)) / width } private func applyLeftOpacity() { let openedLeftRatio: CGFloat = getOpenedLeftRatio() let opacity: CGFloat = SlideMenuOptions.contentViewOpacity * openedLeftRatio opacityView.layer.opacity = Float(opacity) } private func applyRightOpacity() { let openedRightRatio: CGFloat = getOpenedRightRatio() let opacity: CGFloat = SlideMenuOptions.contentViewOpacity * openedRightRatio opacityView.layer.opacity = Float(opacity) } private func applyLeftContentViewScale() { let openedLeftRatio: CGFloat = getOpenedLeftRatio() let scale: CGFloat = 1.0 - ((1.0 - SlideMenuOptions.contentViewScale) * openedLeftRatio); let drag: CGFloat = SlideMenuOptions.leftViewWidth + leftContainerView.frame.origin.x SlideMenuOptions.contentViewDrag == true ? (mainContainerView.transform = CGAffineTransformMakeTranslation(drag, 0)) : (mainContainerView.transform = CGAffineTransformMakeScale(scale, scale)) } private func applyRightContentViewScale() { let openedRightRatio: CGFloat = getOpenedRightRatio() let scale: CGFloat = 1.0 - ((1.0 - SlideMenuOptions.contentViewScale) * openedRightRatio) let drag: CGFloat = rightContainerView.frame.origin.x - mainContainerView.frame.size.width SlideMenuOptions.contentViewDrag == true ? (mainContainerView.transform = CGAffineTransformMakeTranslation(drag, 0)) : (mainContainerView.transform = CGAffineTransformMakeScale(scale, scale)) } private func addShadowToView(targetContainerView: UIView) { targetContainerView.layer.masksToBounds = false targetContainerView.layer.shadowOffset = SlideMenuOptions.shadowOffset targetContainerView.layer.shadowOpacity = Float(SlideMenuOptions.shadowOpacity) targetContainerView.layer.shadowRadius = SlideMenuOptions.shadowRadius targetContainerView.layer.shadowPath = UIBezierPath(rect: targetContainerView.bounds).CGPath } private func removeShadow(targetContainerView: UIView) { targetContainerView.layer.masksToBounds = true mainContainerView.layer.opacity = 1.0 } private func removeContentOpacity() { opacityView.layer.opacity = 0.0 } private func addContentOpacity() { opacityView.layer.opacity = Float(SlideMenuOptions.contentViewOpacity) } private func disableContentInteraction() { mainContainerView.userInteractionEnabled = false } private func enableContentInteraction() { mainContainerView.userInteractionEnabled = true } private func setOpenWindowLevel() { if (SlideMenuOptions.hideStatusBar) { dispatch_async(dispatch_get_main_queue(), { if let window = UIApplication.sharedApplication().keyWindow { window.windowLevel = UIWindowLevelStatusBar + 1 } }) } } private func setCloseWindowLevel() { if (SlideMenuOptions.hideStatusBar) { dispatch_async(dispatch_get_main_queue(), { if let window = UIApplication.sharedApplication().keyWindow { window.windowLevel = UIWindowLevelNormal } }) } } private func setUpViewController(targetView: UIView, targetViewController: UIViewController?) { if let viewController = targetViewController { addChildViewController(viewController) viewController.view.frame = targetView.bounds targetView.addSubview(viewController.view) viewController.didMoveToParentViewController(self) } } private func removeViewController(viewController: UIViewController?) { if let _viewController = viewController { _viewController.view.layer.removeAllAnimations() _viewController.willMoveToParentViewController(nil) _viewController.view.removeFromSuperview() _viewController.removeFromParentViewController() } } public func closeLeftNonAnimation(){ setCloseWindowLevel() let finalXOrigin: CGFloat = leftMinOrigin() var frame: CGRect = leftContainerView.frame; frame.origin.x = finalXOrigin leftContainerView.frame = frame opacityView.layer.opacity = 0.0 mainContainerView.transform = CGAffineTransformMakeScale(1.0, 1.0) removeShadow(leftContainerView) enableContentInteraction() } public func closeRightNonAnimation(){ setCloseWindowLevel() let finalXOrigin: CGFloat = CGRectGetWidth(view.bounds) var frame: CGRect = rightContainerView.frame frame.origin.x = finalXOrigin rightContainerView.frame = frame opacityView.layer.opacity = 0.0 mainContainerView.transform = CGAffineTransformMakeScale(1.0, 1.0) removeShadow(rightContainerView) enableContentInteraction() } // MARK: UIGestureRecognizerDelegate public func gestureRecognizer(gestureRecognizer: UIGestureRecognizer, shouldReceiveTouch touch: UITouch) -> Bool { let point: CGPoint = touch.locationInView(view) if gestureRecognizer == leftPanGesture { return slideLeftForGestureRecognizer(gestureRecognizer, point: point) } else if gestureRecognizer == rightPanGesture { return slideRightViewForGestureRecognizer(gestureRecognizer, withTouchPoint: point) } else if gestureRecognizer == leftTapGesture { return isLeftOpen() && !isPointContainedWithinLeftRect(point) } else if gestureRecognizer == rightTapGesture { return isRightOpen() && !isPointContainedWithinRightRect(point) } return true } // returning true here helps if the main view is fullwidth with a scrollview public func gestureRecognizer(gestureRecognizer: UIGestureRecognizer, shouldRecognizeSimultaneouslyWithGestureRecognizer otherGestureRecognizer: UIGestureRecognizer) -> Bool { return SlideMenuOptions.simultaneousGestureRecognizers } private func slideLeftForGestureRecognizer( gesture: UIGestureRecognizer, point:CGPoint) -> Bool{ return isLeftOpen() || SlideMenuOptions.panFromBezel && isLeftPointContainedWithinBezelRect(point) } private func isLeftPointContainedWithinBezelRect(point: CGPoint) -> Bool{ if let bezelWidth = SlideMenuOptions.leftBezelWidth { var leftBezelRect: CGRect = CGRectZero var tempRect: CGRect = CGRectZero CGRectDivide(view.bounds, &leftBezelRect, &tempRect, bezelWidth, CGRectEdge.MinXEdge) return CGRectContainsPoint(leftBezelRect, point) } else { return true } } private func isPointContainedWithinLeftRect(point: CGPoint) -> Bool { return CGRectContainsPoint(leftContainerView.frame, point) } private func slideRightViewForGestureRecognizer(gesture: UIGestureRecognizer, withTouchPoint point: CGPoint) -> Bool { return isRightOpen() || SlideMenuOptions.rightPanFromBezel && isRightPointContainedWithinBezelRect(point) } private func isRightPointContainedWithinBezelRect(point: CGPoint) -> Bool { if let rightBezelWidth = SlideMenuOptions.rightBezelWidth { var rightBezelRect: CGRect = CGRectZero var tempRect: CGRect = CGRectZero let bezelWidth: CGFloat = CGRectGetWidth(view.bounds) - rightBezelWidth CGRectDivide(view.bounds, &tempRect, &rightBezelRect, bezelWidth, CGRectEdge.MinXEdge) return CGRectContainsPoint(rightBezelRect, point) } else { return true } } private func isPointContainedWithinRightRect(point: CGPoint) -> Bool { return CGRectContainsPoint(rightContainerView.frame, point) } } extension UIViewController { public func slideMenuController() -> SlideMenuController? { var viewController: UIViewController? = self while viewController != nil { if viewController is SlideMenuController { return viewController as? SlideMenuController } viewController = viewController?.parentViewController } return nil; } public func addLeftBarButtonWithImage(buttonImage: UIImage) { let leftButton: UIBarButtonItem = UIBarButtonItem(image: buttonImage, style: UIBarButtonItemStyle.Plain, target: self, action: #selector(self.toggleLeft)) navigationItem.leftBarButtonItem = leftButton; } public func addRightBarButtonWithImage(buttonImage: UIImage) { let rightButton: UIBarButtonItem = UIBarButtonItem(image: buttonImage, style: UIBarButtonItemStyle.Plain, target: self, action: #selector(self.toggleRight)) navigationItem.rightBarButtonItem = rightButton; } public func toggleLeft() { slideMenuController()?.toggleLeft() } public func toggleRight() { slideMenuController()?.toggleRight() } public func openLeft() { slideMenuController()?.openLeft() } public func openRight() { slideMenuController()?.openRight() } public func closeLeft() { slideMenuController()?.closeLeft() } public func closeRight() { slideMenuController()?.closeRight() } // Please specify if you want menu gesuture give priority to than targetScrollView public func addPriorityToMenuGesuture(targetScrollView: UIScrollView) { guard let slideController = slideMenuController(), let recognizers = slideController.view.gestureRecognizers else { return } for recognizer in recognizers where recognizer is UIPanGestureRecognizer { targetScrollView.panGestureRecognizer.requireGestureRecognizerToFail(recognizer) } } }
mit
firebase/snippets-ios
database/DatabaseReference/swift/ViewController.swift
1
7030
// // Copyright (c) 2017 Google Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // import UIKit import FirebaseDatabase class ViewController: UIViewController { var ref: DatabaseReference! override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } func persistenceReference() { // [START keep_synchronized] let scoresRef = Database.database().reference(withPath: "scores") scoresRef.keepSynced(true) // [END keep_synchronized] // [START stop_sync] scoresRef.keepSynced(false) // [END stop_sync] } func loadCached() { // [START load_cached] let scoresRef = Database.database().reference(withPath: "scores") scoresRef.queryOrderedByValue().queryLimited(toLast: 4).observe(.childAdded) { snapshot in print("The \(snapshot.key) dinosaur's score is \(snapshot.value ?? "null")") } // [END load_cached] // [START load_more_cached] scoresRef.queryOrderedByValue().queryLimited(toLast: 2).observe(.childAdded) { snapshot in print("The \(snapshot.key) dinosaur's score is \(snapshot.value ?? "null")") } // [END load_more_cached] // [START disconnected] let presenceRef = Database.database().reference(withPath: "disconnectmessage"); // Write a string when this client loses connection presenceRef.onDisconnectSetValue("I disconnected!") // [END disconnected] // [START remove_disconnect] presenceRef.onDisconnectRemoveValue { error, reference in if let error = error { print("Could not establish onDisconnect event: \(error)") } } // [END remove_disconnect] // [START cancel_disconnect] presenceRef.onDisconnectSetValue("I disconnected") // some time later when we change our minds presenceRef.cancelDisconnectOperations() // [END cancel_disconnect] // [START test_connection] let connectedRef = Database.database().reference(withPath: ".info/connected") connectedRef.observe(.value, with: { snapshot in if snapshot.value as? Bool ?? false { print("Connected") } else { print("Not connected") } }) // [END test_connection] // [START last_online] let userLastOnlineRef = Database.database().reference(withPath: "users/morgan/lastOnline") userLastOnlineRef.onDisconnectSetValue(ServerValue.timestamp()) // [END last_online] // [START clock_skew] let offsetRef = Database.database().reference(withPath: ".info/serverTimeOffset") offsetRef.observe(.value, with: { snapshot in if let offset = snapshot.value as? TimeInterval { print("Estimated server time in milliseconds: \(Date().timeIntervalSince1970 * 1000 + offset)") } }) // [END clock_skew] } func writeNewUser(_ user: Firebase.User, withUsername username: String) { // [START rtdb_write_new_user] ref.child("users").child(user.uid).setValue(["username": username]) // [END rtdb_write_new_user] } func writeNewUserWithCompletion(_ user: Firebase.User, withUsername username: String) { // [START rtdb_write_new_user_completion] ref.child("users").child(user.uid).setValue(["username": username]) { (error:Error?, ref:DatabaseReference) in if let error = error { print("Data could not be saved: \(error).") } else { print("Data saved successfully!") } } // [END rtdb_write_new_user_completion] } func singleUseFetchData(uid: String) { let ref = Database.database().reference(); // [START single_value_get_data] ref.child("users/\(uid)/username").getData(completion: { error, snapshot in guard error == nil else { print(error!.localizedDescription) return; } let userName = snapshot.value as? String ?? "Unknown"; }); // [END single_value_get_data] } func emulatorSettings() { // [START rtdb_emulator_connect] // In almost all cases the ns (namespace) is your project ID. let db = Database.database(url:"http://localhost:9000?ns=YOUR_DATABASE_NAMESPACE") // [END rtdb_emulator_connect] } func flushRealtimeDatabase() { // [START rtdb_emulator_flush] // With a DatabaseReference, write nil to clear the database. Database.database().reference().setValue(nil); // [END rtdb_emulator_flush] } func incrementStars(forPost postID: String, byUser userID: String) { // [START rtdb_post_stars_increment] let updates = [ "posts/\(postID)/stars/\(userID)": true, "posts/\(postID)/starCount": ServerValue.increment(1), "user-posts/\(postID)/stars/\(userID)": true, "user-posts/\(postID)/starCount": ServerValue.increment(1) ] as [String : Any] Database.database().reference().updateChildValues(updates); // [END rtdb_post_stars_increment] } } func combinedExample() { // [START combined] // since I can connect from multiple devices, we store each connection instance separately // any time that connectionsRef's value is null (i.e. has no children) I am offline let myConnectionsRef = Database.database().reference(withPath: "users/morgan/connections") // stores the timestamp of my last disconnect (the last time I was seen online) let lastOnlineRef = Database.database().reference(withPath: "users/morgan/lastOnline") let connectedRef = Database.database().reference(withPath: ".info/connected") connectedRef.observe(.value, with: { snapshot in // only handle connection established (or I've reconnected after a loss of connection) guard let connected = snapshot.value as? Bool, connected else { return } // add this device to my connections list let con = myConnectionsRef.childByAutoId() // when this device disconnects, remove it. con.onDisconnectRemoveValue() // The onDisconnect() call is before the call to set() itself. This is to avoid a race condition // where you set the user's presence to true and the client disconnects before the // onDisconnect() operation takes effect, leaving a ghost user. // this value could contain info about the device or a timestamp instead of just true con.setValue(true) // when I disconnect, update the last time I was seen online lastOnlineRef.onDisconnectSetValue(ServerValue.timestamp()) }) // [END combined] }
apache-2.0
hsusmita/SwiftResponsiveLabel
SwiftResponsiveLabel/Source/NSAttributedString+Processing.swift
1
2864
// // NSAttributedString+Processing.swift // SwiftResponsiveLabel // // Created by Susmita Horrow on 01/03/16. // Copyright © 2016 hsusmita.com. All rights reserved. // import Foundation import UIKit extension NSAttributedString.Key { public static let RLTapResponder = NSAttributedString.Key("TapResponder") public static let RLHighlightedForegroundColor = NSAttributedString.Key("HighlightedForegroundColor") public static let RLHighlightedBackgroundColor = NSAttributedString.Key("HighlightedBackgroundColor") public static let RLBackgroundCornerRadius = NSAttributedString.Key("HighlightedBackgroundCornerRadius") public static let RLHighlightedAttributesDictionary = NSAttributedString.Key("HighlightedAttributes") } open class PatternTapResponder { let action: (String) -> Void public init(currentAction: @escaping (_ tappedString: String) -> (Void)) { action = currentAction } open func perform(_ string: String) { action(string) } } extension NSAttributedString { func sizeOfText() -> CGSize { var range = NSMakeRange(NSNotFound, 0) let fontAttributes = self.attributes(at: 0, longestEffectiveRange: &range, in: NSRange(location: 0, length: self.length)) var size = (self.string as NSString).size(withAttributes: fontAttributes) self.enumerateAttribute(NSAttributedString.Key.attachment, in: NSRange(location: 0, length: self.length), options: []) { (value, range, stop) in if let attachment = value as? NSTextAttachment { size.width += attachment.bounds.width } } return size } func isNewLinePresent() -> Bool { let newLineRange = self.string.rangeOfCharacter(from: CharacterSet.newlines) return newLineRange?.lowerBound != newLineRange?.upperBound } /** Setup paragraph alignement properly. Interface builder applies line break style to the attributed string. This makes text container break at first line of text. So we need to set the line break to wrapping. IB only allows a single paragraph so getting the style of the first character is fine. */ func wordWrappedAttributedString() -> NSAttributedString { var processedString = self if (self.string.count > 0) { let rangePointer: NSRangePointer? = nil if let paragraphStyle: NSParagraphStyle = self.attribute(NSAttributedString.Key.paragraphStyle, at: 0, effectiveRange: rangePointer) as? NSParagraphStyle, let mutableParagraphStyle = paragraphStyle.mutableCopy() as? NSMutableParagraphStyle { // Remove the line breaks mutableParagraphStyle.lineBreakMode = .byWordWrapping // Apply new style let restyled = NSMutableAttributedString(attributedString: self) restyled.addAttribute(NSAttributedString.Key.paragraphStyle, value: mutableParagraphStyle, range: NSMakeRange(0, restyled.length)) processedString = restyled } } return processedString } }
mit
imjerrybao/SocketIO-Kit
Tests/Tests.swift
2
189
// // Tests.swift // Tests // // Created by Ricardo Pereira on 22/05/2015. // Copyright (c) 2015 Ricardo Pereira. All rights reserved. // import SocketIOKit class SocketIOKitSpec { }
mit
benlangmuir/swift
test/IDE/complete_from_foundation_overlay.swift
21
1322
import Foundation // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=PLAIN_TOP_LEVEL_1 > %t.toplevel.txt // RUN: %FileCheck %s -check-prefix=PLAIN_TOP_LEVEL < %t.toplevel.txt // RUN: %FileCheck %s -check-prefix=NO_STDLIB_PRIVATE < %t.toplevel.txt // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=PRIVATE_NOMINAL_MEMBERS_1 > %t.members.txt // RUN: %FileCheck %s -check-prefix=PRIVATE_NOMINAL_MEMBERS_1 < %t.members.txt // RUN: %FileCheck %s -check-prefix=NO_STDLIB_PRIVATE < %t.members.txt // REQUIRES: objc_interop // NO_STDLIB_PRIVATE: Begin completions // NO_STDLIB_PRIVATE-NOT: _convertErrorToNSError // NO_STDLIB_PRIVATE: End completions #^PLAIN_TOP_LEVEL_1^# // PLAIN_TOP_LEVEL: Begin completions // PLAIN_TOP_LEVEL-DAG: Decl[Struct]/OtherModule[Foundation.NSURL]/IsSystem: URLResourceKey[#URLResourceKey#]{{; name=.+}} // PLAIN_TOP_LEVEL: End completions func privateNominalMembers(a: String) { a.#^PRIVATE_NOMINAL_MEMBERS_1^# } // PRIVATE_NOMINAL_MEMBERS_1: Begin completions // FIXME: we should show the qualified String.Index type. // rdar://problem/20788802 // PRIVATE_NOMINAL_MEMBERS_1-DAG: Decl[InstanceVar]/CurrNominal/IsSystem: startIndex[#String.Index#]{{; name=.+$}} // PRIVATE_NOMINAL_MEMBERS_1: End completions
apache-2.0
benlangmuir/swift
test/SILGen/vtable_thunks.swift
7
14092
// RUN: %target-swift-emit-silgen -sdk %S/Inputs -I %S/Inputs -enable-source-import %s -disable-objc-attr-requires-foundation-module -enable-objc-interop | %FileCheck %s protocol AddrOnly {} func callMethodsOnD<U>(d: D, b: B, a: AddrOnly, u: U, i: Int) { _ = d.iuo(x: b, y: b, z: b) _ = d.f(x: b, y: b) _ = d.f2(x: b, y: b) _ = d.f3(x: b, y: b) _ = d.f4(x: b, y: b) _ = d.g(x: a, y: a) _ = d.g2(x: a, y: a) _ = d.g3(x: a, y: a) _ = d.g4(x: a, y: a) _ = d.h(x: u, y: u) _ = d.h2(x: u, y: u) _ = d.h3(x: u, y: u) _ = d.h4(x: u, y: u) _ = d.i(x: i, y: i) _ = d.i2(x: i, y: i) _ = d.i3(x: i, y: i) _ = d.i4(x: i, y: i) } func callMethodsOnF<U>(d: F, b: B, a: AddrOnly, u: U, i: Int) { _ = d.iuo(x: b, y: b, z: b) _ = d.f(x: b, y: b) _ = d.f2(x: b, y: b) _ = d.f3(x: b, y: b) _ = d.f4(x: b, y: b) _ = d.g(x: a, y: a) _ = d.g2(x: a, y: a) _ = d.g3(x: a, y: a) _ = d.g4(x: a, y: a) _ = d.h(x: u, y: u) _ = d.h2(x: u, y: u) _ = d.h3(x: u, y: u) _ = d.h4(x: u, y: u) _ = d.i(x: i, y: i) _ = d.i2(x: i, y: i) _ = d.i3(x: i, y: i) _ = d.i4(x: i, y: i) } @objc class B { // We only allow B! -> B overrides for @objc methods. // The IUO force-unwrap requires a thunk. @objc func iuo(x: B, y: B!, z: B) -> B? {} // f* don't require thunks, since the parameters and returns are object // references. func f(x: B, y: B) -> B? {} func f2(x: B, y: B) -> B? {} func f3(x: B, y: B) -> B {} func f4(x: B, y: B) -> B {} // Thunking monomorphic address-only params and returns func g(x: AddrOnly, y: AddrOnly) -> AddrOnly? {} func g2(x: AddrOnly, y: AddrOnly) -> AddrOnly? {} func g3(x: AddrOnly, y: AddrOnly) -> AddrOnly {} func g4(x: AddrOnly, y: AddrOnly) -> AddrOnly {} // Thunking polymorphic address-only params and returns func h<T>(x: T, y: T) -> T? {} func h2<T>(x: T, y: T) -> T? {} func h3<T>(x: T, y: T) -> T {} func h4<T>(x: T, y: T) -> T {} // Thunking value params and returns func i(x: Int, y: Int) -> Int? {} func i2(x: Int, y: Int) -> Int? {} func i3(x: Int, y: Int) -> Int {} func i4(x: Int, y: Int) -> Int {} // Note: i3, i4 are implicitly @objc } class D: B { override func iuo(x: B?, y: B, z: B) -> B {} override func f(x: B?, y: B) -> B {} override func f2(x: B, y: B) -> B {} override func f3(x: B?, y: B) -> B {} override func f4(x: B, y: B) -> B {} override func g(x: AddrOnly?, y: AddrOnly) -> AddrOnly {} override func g2(x: AddrOnly, y: AddrOnly) -> AddrOnly {} override func g3(x: AddrOnly?, y: AddrOnly) -> AddrOnly {} override func g4(x: AddrOnly, y: AddrOnly) -> AddrOnly {} override func h<U>(x: U?, y: U) -> U {} override func h2<U>(x: U, y: U) -> U {} override func h3<U>(x: U?, y: U) -> U {} override func h4<U>(x: U, y: U) -> U {} override func i(x: Int?, y: Int) -> Int {} override func i2(x: Int, y: Int) -> Int {} // Int? cannot be represented in ObjC so the override has to be // explicitly @nonobjc @nonobjc override func i3(x: Int?, y: Int) -> Int {} override func i4(x: Int, y: Int) -> Int {} } // Inherits the thunked impls from D class E: D { } // Overrides w/ its own thunked impls class F: D { override func f(x: B?, y: B) -> B {} override func f2(x: B, y: B) -> B {} override func f3(x: B?, y: B) -> B {} override func f4(x: B, y: B) -> B {} override func g(x: AddrOnly?, y: AddrOnly) -> AddrOnly {} override func g2(x: AddrOnly, y: AddrOnly) -> AddrOnly {} override func g3(x: AddrOnly?, y: AddrOnly) -> AddrOnly {} override func g4(x: AddrOnly, y: AddrOnly) -> AddrOnly {} override func h<U>(x: U?, y: U) -> U {} override func h2<U>(x: U, y: U) -> U {} override func h3<U>(x: U?, y: U) -> U {} override func h4<U>(x: U, y: U) -> U {} override func i(x: Int?, y: Int) -> Int {} override func i2(x: Int, y: Int) -> Int {} // Int? cannot be represented in ObjC so the override has to be // explicitly @nonobjc @nonobjc override func i3(x: Int?, y: Int) -> Int {} override func i4(x: Int, y: Int) -> Int {} } protocol Proto {} class G { func foo<T: Proto>(arg: T) {} } class H: G { override func foo<T>(arg: T) {} } // This test is incorrect in semantic SIL today. But it will be fixed in // forthcoming commits. // // CHECK-LABEL: sil private [thunk] [ossa] @$s13vtable_thunks1DC3iuo{{[_0-9a-zA-Z]*}}FTV // CHECK: bb0([[X:%.*]] : @guaranteed $B, [[Y:%.*]] : @guaranteed $Optional<B>, [[Z:%.*]] : @guaranteed $B, [[W:%.*]] : @guaranteed $D): // CHECK: [[WRAP_X:%.*]] = enum $Optional<B>, #Optional.some!enumelt, [[X]] : $B // CHECK: [[Y_COPY:%.*]] = copy_value [[Y]] // CHECK: switch_enum [[Y_COPY]] : $Optional<B>, case #Optional.some!enumelt: [[SOME_BB:bb[0-9]+]], case #Optional.none!enumelt: [[NONE_BB:bb[0-9]+]] // CHECK: [[NONE_BB]]: // CHECK: [[DIAGNOSE_UNREACHABLE_FUNC:%.*]] = function_ref @$ss30_diagnoseUnexpectedNilOptional{{.*}} // CHECK: apply [[DIAGNOSE_UNREACHABLE_FUNC]] // CHECK: unreachable // CHECK: [[SOME_BB]]([[UNWRAP_Y:%.*]] : @owned $B): // CHECK: [[BORROWED_UNWRAP_Y:%.*]] = begin_borrow [[UNWRAP_Y]] // CHECK: [[THUNK_FUNC:%.*]] = function_ref @$s13vtable_thunks1DC3iuo{{.*}} // CHECK: [[RES:%.*]] = apply [[THUNK_FUNC]]([[WRAP_X]], [[BORROWED_UNWRAP_Y]], [[Z]], [[W]]) // CHECK: [[WRAP_RES:%.*]] = enum $Optional<B>, {{.*}} [[RES]] // CHECK: return [[WRAP_RES]] // CHECK-LABEL: sil private [thunk] [ossa] @$s13vtable_thunks1DC1g{{[_0-9a-zA-Z]*}}FTV // TODO: extra copies here // CHECK: [[WRAPPED_X_ADDR:%.*]] = init_enum_data_addr [[WRAP_X_ADDR:%.*]] : // CHECK: copy_addr [take] {{%.*}} to [initialization] [[WRAPPED_X_ADDR]] // CHECK: inject_enum_addr [[WRAP_X_ADDR]] // CHECK: [[RES_ADDR:%.*]] = alloc_stack // CHECK: apply {{%.*}}([[RES_ADDR]], [[WRAP_X_ADDR]], %2, %3) // CHECK: [[DEST_ADDR:%.*]] = init_enum_data_addr %0 // CHECK: copy_addr [take] [[RES_ADDR]] to [initialization] [[DEST_ADDR]] // CHECK: inject_enum_addr %0 class ThrowVariance { func mightThrow() throws {} } class NoThrowVariance: ThrowVariance { override func mightThrow() {} } // rdar://problem/20657811 class X<T: B> { func foo(x: T) { } } class Y: X<D> { override func foo(x: D) { } } // rdar://problem/21154055 // Ensure reabstraction happens when necessary to get a value in or out of an // optional. class Foo { func foo(x: @escaping (Int) -> Int) -> ((Int) -> Int)? {} } class Bar: Foo { override func foo(x: ((Int) -> Int)?) -> (Int) -> Int {} } // rdar://problem/21364764 // Ensure we can override an optional with an IUO or vice-versa. struct S {} class Aap { func cat(b: B?) -> B? {} func dog(b: B!) -> B! {} func catFast(s: S?) -> S? {} func dogFast(s: S!) -> S! {} func flip() -> (() -> S?) {} func map() -> (S) -> () -> Aap? {} } class Noot : Aap { override func cat(b: B!) -> B! {} override func dog(b: B?) -> B? {} override func catFast(s: S!) -> S! {} override func dogFast(s: S?) -> S? {} override func flip() -> (() -> S) {} override func map() -> (S?) -> () -> Noot {} } // rdar://problem/59669591 class Base { func returnsOptional() -> Int? { return nil } } class Derived<Foo> : Base { // The thunk here needs to be generic. override func returnsOptional() -> Int { return 0 } } // CHECK-LABEL: sil private [thunk] [ossa] @$s13vtable_thunks3BarC3foo{{[_0-9a-zA-Z]*}}FTV : $@convention(method) (@guaranteed @callee_guaranteed (Int) -> Int, @guaranteed Bar) -> @owned Optional<@callee_guaranteed (Int) -> Int> // CHECK: [[IMPL:%.*]] = function_ref @$s13vtable_thunks3BarC3foo{{[_0-9a-zA-Z]*}}F // CHECK: apply [[IMPL]] // CHECK-LABEL: sil private [thunk] [ossa] @$s13vtable_thunks4NootC4flip{{[_0-9a-zA-Z]*}}FTV // CHECK: [[IMPL:%.*]] = function_ref @$s13vtable_thunks4NootC4flip{{[_0-9a-zA-Z]*}}F // CHECK: [[INNER:%.*]] = apply %1(%0) // CHECK: [[THUNK:%.*]] = function_ref @$s13vtable_thunks1SVIegd_ACSgIegd_TR // CHECK: [[OUTER:%.*]] = partial_apply [callee_guaranteed] [[THUNK]]([[INNER]]) // CHECK: return [[OUTER]] // CHECK-LABEL: sil shared [transparent] [serialized] [reabstraction_thunk] [ossa] @$s13vtable_thunks1SVIegd_ACSgIegd_TR // CHECK: [[INNER:%.*]] = apply %0() // CHECK: [[OUTER:%.*]] = enum $Optional<S>, #Optional.some!enumelt, [[INNER]] : $S // CHECK: return [[OUTER]] : $Optional<S> // CHECK-LABEL: sil private [thunk] [ossa] @$s13vtable_thunks4NootC3map{{[_0-9a-zA-Z]*}}FTV // CHECK: [[IMPL:%.*]] = function_ref @$s13vtable_thunks4NootC3map{{[_0-9a-zA-Z]*}}F // CHECK: [[INNER:%.*]] = apply %1(%0) // CHECK: [[THUNK:%.*]] = function_ref @$s13vtable_thunks1SVSgAA4NootCIego_Iegyo_AcA3AapCSgIego_Iegyo_TR // CHECK: [[OUTER:%.*]] = partial_apply [callee_guaranteed] [[THUNK]]([[INNER]]) // CHECK: return [[OUTER]] // CHECK-LABEL: sil shared [transparent] [serialized] [reabstraction_thunk] [ossa] @$s13vtable_thunks1SVSgAA4NootCIego_Iegyo_AcA3AapCSgIego_Iegyo_TR // CHECK: [[ARG:%.*]] = enum $Optional<S>, #Optional.some!enumelt, %0 // CHECK: [[INNER:%.*]] = apply %1([[ARG]]) // CHECK: [[OUTER:%.*]] = convert_function [[INNER]] : $@callee_guaranteed () -> @owned Noot to $@callee_guaranteed () -> @owned Optional<Aap> // CHECK: return [[OUTER]] // CHECK-LABEL: sil private [thunk] [ossa] @$s13vtable_thunks7DerivedC15returnsOptionalSiyFAA4BaseCADSiSgyFTV : $@convention(method) <τ_0_0> (@guaranteed Derived<τ_0_0>) -> Optional<Int> { // CHECK-LABEL: sil_vtable D { // CHECK: #B.iuo: {{.*}} : @$s13vtable_thunks1D{{[A-Z0-9a-z_]*}}FTV // CHECK: #B.f: {{.*}} : @$s13vtable_thunks1D{{[A-Z0-9a-z_]*}}F // CHECK: #B.f2: {{.*}} : @$s13vtable_thunks1D{{[A-Z0-9a-z_]*}}F // CHECK: #B.f3: {{.*}} : @$s13vtable_thunks1D{{[A-Z0-9a-z_]*}}F // CHECK: #B.f4: {{.*}} : @$s13vtable_thunks1D{{[A-Z0-9a-z_]*}}F // CHECK: #B.g: {{.*}} : @$s13vtable_thunks1D{{[A-Z0-9a-z_]*}}FTV // CHECK: #B.g2: {{.*}} : @$s13vtable_thunks1D{{[A-Z0-9a-z_]*}}FTV // CHECK: #B.g3: {{.*}} : @$s13vtable_thunks1D{{[A-Z0-9a-z_]*}}FTV // CHECK: #B.g4: {{.*}} : @$s13vtable_thunks1D{{[A-Z0-9a-z_]*}}F // CHECK: #B.h: {{.*}} : @$s13vtable_thunks1D{{[A-Z0-9a-z_]*}}FTV // CHECK: #B.h2: {{.*}} : @$s13vtable_thunks1D{{[A-Z0-9a-z_]*}}FTV // CHECK: #B.h3: {{.*}} : @$s13vtable_thunks1D{{[A-Z0-9a-z_]*}}FTV // CHECK: #B.h4: {{.*}} : @$s13vtable_thunks1D{{[A-Z0-9a-z_]*}}F // CHECK: #B.i: {{.*}} : @$s13vtable_thunks1D{{[A-Z0-9a-z_]*}}FTV // CHECK: #B.i2: {{.*}} : @$s13vtable_thunks1D{{[A-Z0-9a-z_]*}}FTV // CHECK: #B.i3: {{.*}} : @$s13vtable_thunks1D{{[A-Z0-9a-z_]*}}FTV // CHECK: #B.i4: {{.*}} : @$s13vtable_thunks1D{{[A-Z0-9a-z_]*}}F // CHECK-LABEL: sil_vtable E { // CHECK: #B.iuo: {{.*}} : @$s13vtable_thunks1D{{[A-Z0-9a-z_]*}}FTV // CHECK: #B.f: {{.*}} : @$s13vtable_thunks1D{{[A-Z0-9a-z_]*}}F // CHECK: #B.f2: {{.*}} : @$s13vtable_thunks1D{{[A-Z0-9a-z_]*}}F // CHECK: #B.f3: {{.*}} : @$s13vtable_thunks1D{{[A-Z0-9a-z_]*}}F // CHECK: #B.f4: {{.*}} : @$s13vtable_thunks1D{{[A-Z0-9a-z_]*}}F // CHECK: #B.g: {{.*}} : @$s13vtable_thunks1D{{[A-Z0-9a-z_]*}}FTV // CHECK: #B.g2: {{.*}} : @$s13vtable_thunks1D{{[A-Z0-9a-z_]*}}FTV // CHECK: #B.g3: {{.*}} : @$s13vtable_thunks1D{{[A-Z0-9a-z_]*}}FTV // CHECK: #B.g4: {{.*}} : @$s13vtable_thunks1D{{[A-Z0-9a-z_]*}}F // CHECK: #B.h: {{.*}} : @$s13vtable_thunks1D{{[A-Z0-9a-z_]*}}FTV // CHECK: #B.h2: {{.*}} : @$s13vtable_thunks1D{{[A-Z0-9a-z_]*}}FTV // CHECK: #B.h3: {{.*}} : @$s13vtable_thunks1D{{[A-Z0-9a-z_]*}}FTV // CHECK: #B.h4: {{.*}} : @$s13vtable_thunks1D{{[A-Z0-9a-z_]*}}F // CHECK: #B.i: {{.*}} : @$s13vtable_thunks1D{{[A-Z0-9a-z_]*}}FTV // CHECK: #B.i2: {{.*}} : @$s13vtable_thunks1D{{[A-Z0-9a-z_]*}}FTV // CHECK: #B.i3: {{.*}} : @$s13vtable_thunks1D{{[A-Z0-9a-z_]*}}FTV // CHECK: #B.i4: {{.*}} : @$s13vtable_thunks1D{{[A-Z0-9a-z_]*}}F // CHECK-LABEL: sil_vtable F { // CHECK: #B.iuo: {{.*}} : @$s13vtable_thunks1D{{[A-Z0-9a-z_]*}}FTV // CHECK: #B.f: {{.*}} : @$s13vtable_thunks1F{{[A-Z0-9a-z_]*}}F // CHECK: #B.f2: {{.*}} : @$s13vtable_thunks1F{{[A-Z0-9a-z_]*}}F // CHECK: #B.f3: {{.*}} : @$s13vtable_thunks1F{{[A-Z0-9a-z_]*}}F // CHECK: #B.f4: {{.*}} : @$s13vtable_thunks1F{{[A-Z0-9a-z_]*}}F // CHECK: #B.g: {{.*}} : @$s13vtable_thunks1F{{[A-Z0-9a-z_]*}}FTV // CHECK: #B.g2: {{.*}} : @$s13vtable_thunks1F{{[A-Z0-9a-z_]*}}FTV // CHECK: #B.g3: {{.*}} : @$s13vtable_thunks1F{{[A-Z0-9a-z_]*}}FTV // CHECK: #B.g4: {{.*}} : @$s13vtable_thunks1F{{[A-Z0-9a-z_]*}}F // CHECK: #B.h: {{.*}} : @$s13vtable_thunks1F{{[A-Z0-9a-z_]*}}FTV // CHECK: #B.h2: {{.*}} : @$s13vtable_thunks1F{{[A-Z0-9a-z_]*}}FTV // CHECK: #B.h3: {{.*}} : @$s13vtable_thunks1F{{[A-Z0-9a-z_]*}}FTV // CHECK: #B.h4: {{.*}} : @$s13vtable_thunks1F{{[A-Z0-9a-z_]*}}F // CHECK: #B.i: {{.*}} : @$s13vtable_thunks1F{{[A-Z0-9a-z_]*}}FTV // CHECK: #B.i2: {{.*}} : @$s13vtable_thunks1F{{[A-Z0-9a-z_]*}}FTV // CHECK: #B.i3: {{.*}} : @$s13vtable_thunks1F{{[A-Z0-9a-z_]*}}FTV // CHECK: #B.i4: {{.*}} : @$s13vtable_thunks1F{{[A-Z0-9a-z_]*}}F // CHECK-LABEL: sil_vtable H { // CHECK: #G.foo: <T where T : Proto> (G) -> (T) -> () : @$s13vtable_thunks1H{{[A-Z0-9a-z_]*}}FTV [override] // CHECK: #H.foo: <T> (H) -> (T) -> () : @$s13vtable_thunks1H{{[A-Z0-9a-z_]*}}tlF // CHECK-LABEL: sil_vtable NoThrowVariance { // CHECK: #ThrowVariance.mightThrow: {{.*}} : @$s13vtable_thunks{{[A-Z0-9a-z_]*}}F // CHECK-LABEL: sil_vtable Base { // CHECK: #Base.returnsOptional: (Base) -> () -> Int? : @$s13vtable_thunks4BaseC15returnsOptionalSiSgyF // CHECK-LABEL: sil_vtable Derived { // CHECK: #Base.returnsOptional: (Base) -> () -> Int? : @$s13vtable_thunks7DerivedC15returnsOptionalSiyFAA4BaseCADSiSgyFTV [override]
apache-2.0
sharath-cliqz/browser-ios
Client/Frontend/Browser/BrowserViewController.swift
2
192454
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ import Foundation import Photos import UIKit import WebKit import Shared import Storage import SnapKit import XCGLogger import Alamofire import Account import ReadingList import MobileCoreServices import WebImage import SwiftyJSON private let log = Logger.browserLogger private let KVOLoading = "loading" private let KVOEstimatedProgress = "estimatedProgress" private let KVOURL = "URL" private let KVOCanGoBack = "canGoBack" private let KVOCanGoForward = "canGoForward" private let KVOContentSize = "contentSize" private let ActionSheetTitleMaxLength = 120 private struct BrowserViewControllerUX { fileprivate static let BackgroundColor = UIConstants.AppBackgroundColor fileprivate static let ShowHeaderTapAreaHeight: CGFloat = 32 fileprivate static let BookmarkStarAnimationDuration: Double = 0.5 fileprivate static let BookmarkStarAnimationOffset: CGFloat = 80 } let ShowBrowserViewControllerNotification = NSNotification.Name(rawValue: "ShowBrowserViewControllerNotification") class BrowserViewController: UIViewController { // Cliqz: modifed the type of homePanelController to CliqzSearchViewController to show Cliqz index page instead of FireFox home page // var homePanelController: CliqzSearchViewController? var homePanelController: FreshtabViewController? var controlCenterController: ControlCenterViewController? var controlCenterActiveInLandscape: Bool = false var webViewContainer: UIView! var menuViewController: MenuViewController? // Cliqz: replace URLBarView with our custom URLBarView // var urlBar: URLBarView! var urlBar: CliqzURLBarView! var readerModeBar: ReaderModeBarView? var readerModeCache: ReaderModeCache fileprivate var statusBarOverlay: UIView! fileprivate(set) var toolbar: TabToolbar? //Cliqz: use CliqzSearchViewController instead of FireFox one fileprivate var searchController: CliqzSearchViewController? //SearchViewController? fileprivate var screenshotHelper: ScreenshotHelper! fileprivate var homePanelIsInline = false fileprivate var searchLoader: SearchLoader! fileprivate let snackBars = UIView() fileprivate let webViewContainerToolbar = UIView() var findInPageBar: FindInPageBar? fileprivate let findInPageContainer = UIView() lazy fileprivate var customSearchEngineButton: UIButton = { let searchButton = UIButton() searchButton.setImage(UIImage(named: "AddSearch")?.withRenderingMode(.alwaysTemplate), for: UIControlState()) searchButton.addTarget(self, action: #selector(BrowserViewController.addCustomSearchEngineForFocusedElement), for: .touchUpInside) return searchButton }() fileprivate var customSearchBarButton: UIBarButtonItem? // popover rotation handling fileprivate var displayedPopoverController: UIViewController? fileprivate var updateDisplayedPopoverProperties: (() -> ())? fileprivate var openInHelper: OpenInHelper? // location label actions fileprivate var pasteGoAction: AccessibleAction! fileprivate var pasteAction: AccessibleAction! fileprivate var copyAddressAction: AccessibleAction! fileprivate weak var tabTrayController: TabTrayController! fileprivate let profile: Profile let tabManager: TabManager // These views wrap the urlbar and toolbar to provide background effects on them // Cliqz: Replaced BlurWrapper because according new requirements we don't need to blur background of ULRBar var header: UIView! // var header: BlurWrapper! var headerBackdrop: UIView! var footer: UIView! var footerBackdrop: UIView! fileprivate var footerBackground: BlurWrapper? fileprivate var topTouchArea: UIButton! // Backdrop used for displaying greyed background for private tabs var webViewContainerBackdrop: UIView! fileprivate var scrollController = TabScrollingController() fileprivate var keyboardState: KeyboardState? let WhiteListedUrls = ["\\/\\/itunes\\.apple\\.com\\/"] // Tracking navigation items to record history types. // TODO: weak references? var ignoredNavigation = Set<WKNavigation>() var typedNavigation = [WKNavigation: VisitType]() var navigationToolbar: TabToolbarProtocol { return toolbar ?? urlBar } fileprivate var needsNewTab = true fileprivate var isAppResponsive = false // Cliqz: Added TransitionAnimator which is responsible for layers change animations let transition = TransitionAnimator() // Cliqz: Added for logging the navigation Telemetry signal var isBackNavigation : Bool = false var backListSize : Int = 0 var navigationStep : Int = 0 var backNavigationStep : Int = 0 var navigationEndTime : Double = Date.getCurrentMillis() // Cliqz: Custom dashboard fileprivate lazy var dashboard : DashboardViewController = { let dashboard = DashboardViewController(profile: self.profile, tabManager: self.tabManager) dashboard.delegate = self return dashboard }() // Cliqz: Added to adjust header constraint to work during the animation to/from past layer var headerConstraintUpdated:Bool = false lazy var recommendationsContainer: UINavigationController = { let recommendationsViewController = RecommendationsViewController(profile: self.profile) recommendationsViewController.delegate = self recommendationsViewController.tabManager = self.tabManager let containerViewController = UINavigationController(rootViewController: recommendationsViewController) containerViewController.transitioningDelegate = self return containerViewController }() // Cliqz: added to record keyboard show duration for keyboard telemetry signal var keyboardShowTime : Double? // Cliqz: key for storing the last visited website let lastVisitedWebsiteKey = "lastVisitedWebsite" // Cliqz: the response state code of the current opened link var currentResponseStatusCode = 0 // Cliqz: Added data member for push notification URL string in the case when the app isn't in background to load URL on viewDidAppear. var initialURL: String? // var initialURL: String? { // didSet { // if self.urlBar != nil { // self.loadInitialURL() // } // } // } // Cliqz: swipe back and forward var historySwiper = HistorySwiper() // Cliqz: added to mark if pervious run was crashed or not var hasPendingCrashReport = false init(profile: Profile, tabManager: TabManager) { self.profile = profile self.tabManager = tabManager self.readerModeCache = DiskReaderModeCache.sharedInstance super.init(nibName: nil, bundle: nil) didInit() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override var supportedInterfaceOrientations : UIInterfaceOrientationMask { if UIDevice.current.userInterfaceIdiom == .phone { return UIInterfaceOrientationMask.allButUpsideDown } else { return UIInterfaceOrientationMask.all } } override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) { super.viewWillTransition(to: size, with: coordinator) if let controlCenter = controlCenterController { controlCenter.closeControlCenter() } displayedPopoverController?.dismiss(animated: true) { self.displayedPopoverController = nil } guard let displayedPopoverController = self.displayedPopoverController else { return } coordinator.animate(alongsideTransition: nil) { context in self.updateDisplayedPopoverProperties?() self.present(displayedPopoverController, animated: true, completion: nil) } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() log.debug("BVC received memory warning") self.tabManager.purgeTabs(includeSelectedTab: false) } fileprivate func didInit() { screenshotHelper = ScreenshotHelper(controller: self) tabManager.addDelegate(self) tabManager.addNavigationDelegate(self) } override var preferredStatusBarStyle : UIStatusBarStyle { // Cliqz: Changed StatusBar style to the black return UIStatusBarStyle.default } func shouldShowFooterForTraitCollection(_ previousTraitCollection: UITraitCollection) -> Bool { return previousTraitCollection.verticalSizeClass != .compact && previousTraitCollection.horizontalSizeClass != .regular } func toggleSnackBarVisibility(show: Bool) { if show { UIView.animate(withDuration: 0.1, animations: { self.snackBars.isHidden = false }) } else { snackBars.isHidden = true } } fileprivate func updateToolbarStateForTraitCollection(_ newCollection: UITraitCollection) { let showToolbar = shouldShowFooterForTraitCollection(newCollection) urlBar.setShowToolbar(!showToolbar) toolbar?.removeFromSuperview() toolbar?.tabToolbarDelegate = nil footerBackground?.removeFromSuperview() footerBackground = nil toolbar = nil if showToolbar { toolbar = TabToolbar() toolbar?.tabToolbarDelegate = self // Cliqz: update tabs button to update newly created toolbar self.updateTabCountUsingTabManager(self.tabManager, animated: false) footerBackground = BlurWrapper(view: toolbar!) footerBackground?.translatesAutoresizingMaskIntoConstraints = false // Need to reset the proper blur style if let selectedTab = tabManager.selectedTab, selectedTab.isPrivate { footerBackground!.blurStyle = .dark toolbar?.applyTheme(Theme.PrivateMode) } footer.addSubview(footerBackground!) } view.setNeedsUpdateConstraints() // if let home = homePanelController { // home.view.setNeedsUpdateConstraints() // } if let tab = tabManager.selectedTab, let webView = tab.webView { updateURLBarDisplayURL(tab) navigationToolbar.updateBackStatus(webView.canGoBack) navigationToolbar.updateForwardStatus(webView.canGoForward) navigationToolbar.updateReloadStatus(tab.loading ?? false) } } override func willTransition(to newCollection: UITraitCollection, with coordinator: UIViewControllerTransitionCoordinator) { super.willTransition(to: newCollection, with: coordinator) if let controlCenter = controlCenterController { controlCenter.closeControlCenter() } // During split screen launching on iPad, this callback gets fired before viewDidLoad gets a chance to // set things up. Make sure to only update the toolbar state if the view is ready for it. if isViewLoaded { updateToolbarStateForTraitCollection(newCollection) } displayedPopoverController?.dismiss(animated: true, completion: nil) // WKWebView looks like it has a bug where it doesn't invalidate it's visible area when the user // performs a device rotation. Since scrolling calls // _updateVisibleContentRects (https://github.com/WebKit/webkit/blob/master/Source/WebKit2/UIProcess/API/Cocoa/WKWebView.mm#L1430) // this method nudges the web view's scroll view by a single pixel to force it to invalidate. if let scrollView = self.tabManager.selectedTab?.webView?.scrollView { let contentOffset = scrollView.contentOffset coordinator.animate(alongsideTransition: { context in scrollView.setContentOffset(CGPoint(x: contentOffset.x, y: contentOffset.y + 1), animated: true) self.scrollController.showToolbars(false) }, completion: { context in scrollView.setContentOffset(CGPoint(x: contentOffset.x, y: contentOffset.y), animated: false) }) } } // Cliqz: commented method as is it overriden by us // func SELappDidEnterBackgroundNotification() { // displayedPopoverController?.dismissViewControllerAnimated(false, completion: nil) // } func SELtappedTopArea() { scrollController.showToolbars(true) } func SELappWillResignActiveNotification() { // Dismiss any popovers that might be visible displayedPopoverController?.dismiss(animated: false) { self.displayedPopoverController = nil } // If we are displying a private tab, hide any elements in the tab that we wouldn't want shown // when the app is in the home switcher guard let privateTab = tabManager.selectedTab, privateTab.isPrivate else { return } webViewContainerBackdrop.alpha = 1 webViewContainer.alpha = 0 urlBar.locationView.alpha = 0 presentedViewController?.popoverPresentationController?.containerView?.alpha = 0 presentedViewController?.view.alpha = 0 } func SELappDidBecomeActiveNotification() { // Re-show any components that might have been hidden because they were being displayed // as part of a private mode tab UIView.animate(withDuration: 0.2, delay: 0, options: UIViewAnimationOptions(), animations: { self.webViewContainer.alpha = 1 self.urlBar.locationView.alpha = 1 self.presentedViewController?.popoverPresentationController?.containerView?.alpha = 1 self.presentedViewController?.view.alpha = 1 self.view.backgroundColor = UIColor.clear }, completion: { _ in self.webViewContainerBackdrop.alpha = 0 // Cliqz Added functionality for session timeout and telemtery logging when app becomes active self.appDidBecomeResponsive("warm") if self.initialURL != nil { // Cliqz: Added call for initial URL if one exists self.loadInitialURL() } // Cliqz: ask for news notification permission according to our workflow self.askForNewsNotificationPermissionIfNeeded() }) // Re-show toolbar which might have been hidden during scrolling (prior to app moving into the background) scrollController.showToolbars(false) //Cliqz send rotate telemetry signal for warm start logOrientationSignal() } deinit { NotificationCenter.default.removeObserver(self) } override func viewDidLoad() { log.debug("BVC viewDidLoad…") super.viewDidLoad() log.debug("BVC super viewDidLoad called.") NotificationCenter.default.addObserver(self, selector: #selector(BrowserViewController.SELBookmarkStatusDidChange(_:)), name: NSNotification.Name(rawValue: BookmarkStatusChangedNotification), object: nil) NotificationCenter.default.addObserver(self, selector: #selector(BrowserViewController.SELappWillResignActiveNotification), name: NSNotification.Name.UIApplicationWillResignActive, object: nil) NotificationCenter.default.addObserver(self, selector: #selector(BrowserViewController.SELappDidBecomeActiveNotification), name: NSNotification.Name.UIApplicationDidBecomeActive, object: nil) NotificationCenter.default.addObserver(self, selector: #selector(BrowserViewController.SELappDidEnterBackgroundNotification), name: NSNotification.Name.UIApplicationDidEnterBackground, object: nil) // Cliqz: Add observers for Connection features NotificationCenter.default.addObserver(self, selector: #selector(openTabViaConnect), name: SendTabNotification, object: nil) NotificationCenter.default.addObserver(self, selector: #selector(downloadVideoViaConnect), name: DownloadVideoNotification, object: nil) // Cliqz: Add observer for device orientation NotificationCenter.default.addObserver(self, selector: #selector(BrowserViewController.logOrientationSignal), name: Notification.Name.UIApplicationDidChangeStatusBarOrientation, object: nil) // Cliqz: Add observer for favorites removed to refresh the bookmark status NotificationCenter.default.addObserver(self, selector: #selector(updateBookmarkStatus), name: FavoriteRemovedNotification, object: nil) //Cliqz: Add observer for autocomplete notification from AutoComplete Module NotificationCenter.default.addObserver(self, selector: #selector(autocomplete(_:)), name: AutoCompleteNotification, object: nil) KeyboardHelper.defaultHelper.addDelegate(self) log.debug("BVC adding footer and header…") footerBackdrop = UIView() footerBackdrop.backgroundColor = UIColor.white view.addSubview(footerBackdrop) headerBackdrop = UIView() headerBackdrop.backgroundColor = UIColor.clear view.addSubview(headerBackdrop) log.debug("BVC setting up webViewContainer…") webViewContainerBackdrop = UIView() webViewContainerBackdrop.backgroundColor = UIColor.gray webViewContainerBackdrop.alpha = 0 webViewContainerBackdrop.accessibilityLabel = "Forget Mode Background" view.addSubview(webViewContainerBackdrop) webViewContainer = UIView() webViewContainer.addSubview(webViewContainerToolbar) view.addSubview(webViewContainer) log.debug("BVC setting up status bar…") // Temporary work around for covering the non-clipped web view content statusBarOverlay = UIView() statusBarOverlay.backgroundColor = UIColor.clear view.addSubview(statusBarOverlay) log.debug("BVC setting up top touch area…") topTouchArea = UIButton() topTouchArea.isAccessibilityElement = false topTouchArea.addTarget(self, action: #selector(BrowserViewController.SELtappedTopArea), for: UIControlEvents.touchUpInside) view.addSubview(topTouchArea) log.debug("BVC setting up URL bar…") // Setup the URL bar, wrapped in a view to get transparency effect // Cliqz: Type change urlBar = CliqzURLBarView() urlBar.translatesAutoresizingMaskIntoConstraints = false urlBar.delegate = self urlBar.tabToolbarDelegate = self // Cliqz: Replaced BlurWrapper because of requirements header = urlBar //BlurWrapper(view: urlBar) view.addSubview(header) // UIAccessibilityCustomAction subclass holding an AccessibleAction instance does not work, thus unable to generate AccessibleActions and UIAccessibilityCustomActions "on-demand" and need to make them "persistent" e.g. by being stored in BVC pasteGoAction = AccessibleAction(name: NSLocalizedString("Paste & Go", comment: "Paste the URL into the location bar and visit"), handler: { () -> Bool in if let pasteboardContents = UIPasteboard.general.string { self.urlBar(self.urlBar, didSubmitText: pasteboardContents) return true } return false }) pasteAction = AccessibleAction(name: NSLocalizedString("Paste", comment: "Paste the URL into the location bar"), handler: { () -> Bool in if let pasteboardContents = UIPasteboard.general.string { // Enter overlay mode and fire the text entered callback to make the search controller appear. self.urlBar.enterOverlayMode(pasteboardContents, pasted: true) self.urlBar(self.urlBar, didEnterText: pasteboardContents) return true } return false }) copyAddressAction = AccessibleAction(name: NSLocalizedString("Copy Address", comment: "Copy the URL from the location bar"), handler: { () -> Bool in if let url = self.urlBar.currentURL { UIPasteboard.general.url = url } return true }) log.debug("BVC setting up search loader…") searchLoader = SearchLoader(profile: profile, urlBar: urlBar) footer = UIView() self.view.addSubview(footer) self.view.addSubview(snackBars) snackBars.backgroundColor = UIColor.clear self.view.addSubview(findInPageContainer) scrollController.urlBar = urlBar scrollController.header = header scrollController.footer = footer scrollController.snackBars = snackBars log.debug("BVC updating toolbar state…") self.updateToolbarStateForTraitCollection(self.traitCollection) log.debug("BVC setting up constraints…") setupConstraints() log.debug("BVC done.") // Cliqz: start listening for user location changes LocationManager.sharedInstance.startUpdatingLocation() // Cliqz: added observer for NotificationBadRequestDetected notification for Antitracking NotificationCenter.default.addObserver(self, selector: #selector(BrowserViewController.SELBadRequestDetected), name: NSNotification.Name(rawValue: NotificationBadRequestDetected), object: nil) #if CLIQZ // Cliqz: setup back and forward swipe historySwiper.setup(self.view, webViewContainer: self.webViewContainer) #endif //Cliqz send rotate telemetry signal for cold start logOrientationSignal() } fileprivate func setupConstraints() { urlBar.snp.makeConstraints { make in make.edges.equalTo(self.header) } header.snp.makeConstraints { make in scrollController.headerTopConstraint = make.top.equalTo(topLayoutGuide.snp.bottom).constraint make.height.equalTo(UIConstants.ToolbarHeight) make.left.right.equalTo(self.view) } headerBackdrop.snp.makeConstraints { make in make.edges.equalTo(self.header) } webViewContainerBackdrop.snp.makeConstraints { make in make.edges.equalTo(webViewContainer) } webViewContainerToolbar.snp.makeConstraints { make in make.left.right.top.equalTo(webViewContainer) make.height.equalTo(0) } } override func viewDidLayoutSubviews() { log.debug("BVC viewDidLayoutSubviews…") super.viewDidLayoutSubviews() statusBarOverlay.snp.remakeConstraints { make in make.top.left.right.equalTo(self.view) make.height.equalTo(self.topLayoutGuide.length) } // Cliqz: fix headerTopConstraint for scrollController to work properly during the animation to/from past layer fixHeaderConstraint() self.appDidUpdateState(getCurrentAppState()) log.debug("BVC done.") } func loadQueuedTabs() { log.debug("Loading queued tabs in the background.") // Chain off of a trivial deferred in order to run on the background queue. succeed().upon() { res in self.dequeueQueuedTabs() } } fileprivate func dequeueQueuedTabs() { assert(!Thread.current.isMainThread, "This must be called in the background.") self.profile.queue.getQueuedTabs() >>== { cursor in // This assumes that the DB returns rows in some kind of sane order. // It does in practice, so WFM. log.debug("Queue. Count: \(cursor.count).") if cursor.count <= 0 { return } let urls = cursor.flatMap { $0?.url.asURL } if !urls.isEmpty { DispatchQueue.main.async { self.tabManager.addTabsForURLs(urls, zombie: false) } } // Clear *after* making an attempt to open. We're making a bet that // it's better to run the risk of perhaps opening twice on a crash, // rather than losing data. self.profile.queue.clearQueuedTabs() } } override func viewWillAppear(_ animated: Bool) { log.debug("BVC viewWillAppear.") super.viewWillAppear(animated) log.debug("BVC super.viewWillAppear done.") // Cliqz: Remove onboarding screen /* // On iPhone, if we are about to show the On-Boarding, blank out the tab so that it does // not flash before we present. This change of alpha also participates in the animation when // the intro view is dismissed. if UIDevice.currentDevice().userInterfaceIdiom == .Phone { self.view.alpha = (profile.prefs.intForKey(IntroViewControllerSeenProfileKey) != nil) ? 1.0 : 0.0 } */ // Cliqz: Disable FF crash reporting /* if PLCrashReporter.sharedReporter().hasPendingCrashReport() { PLCrashReporter.sharedReporter().purgePendingCrashReport() */ if hasPendingCrashReport { hasPendingCrashReport = false showRestoreTabsAlert() } else { log.debug("Restoring tabs.") tabManager.restoreTabs() log.debug("Done restoring tabs.") } log.debug("Updating tab count.") updateTabCountUsingTabManager(tabManager, animated: false) NotificationCenter.default.addObserver(self, selector: #selector(BrowserViewController.openSettings), name: Notification.Name(rawValue: NotificationStatusNotificationTapped), object: nil) // Cliqz: add observer for keyboard actions for Telemetry signals NotificationCenter.default.addObserver(self, selector: #selector(BrowserViewController.keyboardWillShow(_:)), name: Notification.Name.UIKeyboardWillShow, object: nil) NotificationCenter.default.addObserver(self, selector: #selector(BrowserViewController.keyboardWillHide(_:)), name: Notification.Name.UIKeyboardWillHide, object: nil) if let tab = self.tabManager.selectedTab { applyTheme(tab.isPrivate ? Theme.PrivateMode : Theme.NormalMode) } log.debug("BVC done.") } fileprivate func showRestoreTabsAlert() { guard shouldRestoreTabs() else { self.tabManager.addTabAndSelect() return } // Cliqz: apply normal theme to the urlbar when showing the restore alert to avoid weird look self.urlBar.applyTheme(Theme.NormalMode) let alert = UIAlertController.restoreTabsAlert( { _ in self.tabManager.restoreTabs() self.updateTabCountUsingTabManager(self.tabManager, animated: false) }, noCallback: { _ in self.tabManager.addTabAndSelect() self.updateTabCountUsingTabManager(self.tabManager, animated: false) // Cliqz: focus on the search bar when selecting not to restore tabs self.urlBar.enterOverlayMode("", pasted: false) } ) self.present(alert, animated: true, completion: nil) } fileprivate func shouldRestoreTabs() -> Bool { guard let tabsToRestore = TabManager.tabsToRestore() else { return false } let onlyNoHistoryTabs = !tabsToRestore.every { ($0.sessionData?.urls.count ?? 0) > 1 || !AboutUtils.isAboutHomeURL($0.sessionData?.urls.first) } return !onlyNoHistoryTabs && !DebugSettingsBundleOptions.skipSessionRestore } override func viewDidAppear(_ animated: Bool) { log.debug("BVC viewDidAppear.") // Cliqz: Remove onboarding screen // presentIntroViewController() // Cliqz: switch to search mode if needed switchToSearchModeIfNeeded() // Cliqz: ask for news notification permission according to our workflow askForNewsNotificationPermissionIfNeeded() log.debug("BVC intro presented.") self.webViewContainerToolbar.isHidden = false screenshotHelper.viewIsVisible = true log.debug("BVC taking pending screenshots….") screenshotHelper.takePendingScreenshots(tabManager.tabs) log.debug("BVC done taking screenshots.") log.debug("BVC calling super.viewDidAppear.") super.viewDidAppear(animated) log.debug("BVC done.") // Cliqz: cold start finished (for telemetry signals) self.appDidBecomeResponsive("cold") // Cliqz: Added call for initial URL if one exists self.loadInitialURL() // Cliqz: Prevent the app from opening a new tab at startup to show whats new in FireFox /* if shouldShowWhatsNewTab() { if let whatsNewURL = SupportUtils.URLForTopic("new-ios-50") { self.openURLInNewTab(whatsNewURL) profile.prefs.setString(AppInfo.appVersion, forKey: LatestAppVersionProfileKey) } } */ showQueuedAlertIfAvailable() } fileprivate func shouldShowWhatsNewTab() -> Bool { guard let latestMajorAppVersion = profile.prefs.stringForKey(LatestAppVersionProfileKey)?.components(separatedBy: ".").first else { return DeviceInfo.hasConnectivity() } return latestMajorAppVersion != AppInfo.majorAppVersion && DeviceInfo.hasConnectivity() } fileprivate func showQueuedAlertIfAvailable() { if let queuedAlertInfo = tabManager.selectedTab?.dequeueJavascriptAlertPrompt() { let alertController = queuedAlertInfo.alertController() alertController.delegate = self present(alertController, animated: true, completion: nil) } } override func viewWillDisappear(_ animated: Bool) { screenshotHelper.viewIsVisible = false super.viewWillDisappear(animated) } override func viewDidDisappear(_ animated: Bool) { super.viewDidDisappear(animated) NotificationCenter.default.removeObserver(self, name: Notification.Name(rawValue: NotificationStatusNotificationTapped), object: nil) // Cliqz: remove keyboard obervers NotificationCenter.default.removeObserver(self, name: Notification.Name.UIKeyboardWillShow, object: nil) NotificationCenter.default.removeObserver(self, name: Notification.Name.UIKeyboardWillHide, object: nil) } func resetBrowserChrome() { // animate and reset transform for tab chrome urlBar.updateAlphaForSubviews(1) [header, footer, readerModeBar, footerBackdrop, headerBackdrop].forEach { view in view?.transform = CGAffineTransform.identity } } override func updateViewConstraints() { super.updateViewConstraints() topTouchArea.snp.remakeConstraints { make in make.top.left.right.equalTo(self.view) make.height.equalTo(BrowserViewControllerUX.ShowHeaderTapAreaHeight) } readerModeBar?.snp.remakeConstraints { make in if controlCenterActiveInLandscape{ make.top.equalTo(self.header.snp.bottom) make.height.equalTo(UIConstants.ToolbarHeight) //make.leading.equalTo(self.view) //make.trailing.equalTo(self.controlCenterController?) make.left.equalTo(self.view) make.width.equalTo(self.view.frame.width/2) } else{ make.top.equalTo(self.header.snp.bottom) make.height.equalTo(UIConstants.ToolbarHeight) make.leading.trailing.equalTo(self.view) } } webViewContainer.snp.remakeConstraints { make in if controlCenterActiveInLandscape{ make.left.equalTo(self.view) make.width.equalTo(self.view.frame.size.width/2) } else{ make.left.right.equalTo(self.view) } if let readerModeBarBottom = readerModeBar?.snp.bottom { make.top.equalTo(readerModeBarBottom) } else { make.top.equalTo(self.header.snp.bottom) } let findInPageHeight = (findInPageBar == nil) ? 0 : UIConstants.ToolbarHeight if let toolbar = self.toolbar { make.bottom.equalTo(toolbar.snp.top).offset(-findInPageHeight) } else { make.bottom.equalTo(self.view).offset(-findInPageHeight) } } // Setup the bottom toolbar toolbar?.snp.remakeConstraints { make in make.edges.equalTo(self.footerBackground!) make.height.equalTo(UIConstants.ToolbarHeight) } footer.snp.remakeConstraints { make in scrollController.footerBottomConstraint = make.bottom.equalTo(self.view.snp.bottom).constraint make.top.equalTo(self.snackBars.snp.top) make.leading.trailing.equalTo(self.view) } footerBackdrop.snp.remakeConstraints { make in make.edges.equalTo(self.footer) } updateSnackBarConstraints() footerBackground?.snp.remakeConstraints { make in make.bottom.left.right.equalTo(self.footer) make.height.equalTo(UIConstants.ToolbarHeight) } urlBar.setNeedsUpdateConstraints() // Remake constraints even if we're already showing the home controller. // The home controller may change sizes if we tap the URL bar while on about:home. homePanelController?.view.snp.remakeConstraints { make in make.top.equalTo(self.urlBar.snp.bottom) make.left.right.equalTo(self.view) if self.homePanelIsInline, let toolbar = self.toolbar { make.bottom.equalTo(self.view) self.view.bringSubview(toFront: self.footer) } else { make.bottom.equalTo(self.view.snp.bottom) } } findInPageContainer.snp.remakeConstraints { make in make.left.right.equalTo(self.view) if let keyboardHeight = keyboardState?.intersectionHeightForView(self.view), keyboardHeight > 0 { make.bottom.equalTo(self.view).offset(-keyboardHeight) } else if let toolbar = self.toolbar { make.bottom.equalTo(toolbar.snp.top) } else { make.bottom.equalTo(self.view) } } } // Cliqz: modifed showHomePanelController to show Cliqz index page (SearchViewController) instead of FireFox home page fileprivate func showHomePanelController(inline: Bool) { log.debug("BVC showHomePanelController.") homePanelIsInline = inline //navigationToolbar.updateForwardStatus(false) navigationToolbar.updateBackStatus(false) if homePanelController == nil { homePanelController = FreshtabViewController(profile: self.profile) homePanelController?.delegate = self // homePanelController!.delegate = self addChildViewController(homePanelController!) view.addSubview(homePanelController!.view) } if let tab = tabManager.selectedTab { homePanelController?.isForgetMode = tab.isPrivate // homePanelController?.updatePrivateMode(tab.isPrivate) } UIView.animate(withDuration: 0.2, animations: { () -> Void in self.homePanelController!.view.alpha = 1 }, completion: { finished in if finished { self.webViewContainer.accessibilityElementsHidden = true UIAccessibilityPostNotification(UIAccessibilityScreenChangedNotification, nil) } }) if !urlBar.inOverlayMode { getApp().changeToBgImage(.lightContent, isNormalMode: !(tabManager.selectedTab?.isPrivate ?? false)) } view.setNeedsUpdateConstraints() log.debug("BVC done with showHomePanelController.") } /* private func showHomePanelController(inline inline: Bool) { log.debug("BVC showHomePanelController.") homePanelIsInline = inline if homePanelController == nil { homePanelController = HomePanelViewController() homePanelController!.profile = profile homePanelController!.delegate = self homePanelController!.appStateDelegate = self homePanelController!.url = tabManager.selectedTab?.displayURL homePanelController!.view.alpha = 0 addChildViewController(homePanelController!) view.addSubview(homePanelController!.view) homePanelController!.didMoveToParentViewController(self) } let panelNumber = tabManager.selectedTab?.url?.fragment // splitting this out to see if we can get better crash reports when this has a problem var newSelectedButtonIndex = 0 if let numberArray = panelNumber?.componentsSeparatedByString("=") { if let last = numberArray.last, lastInt = Int(last) { newSelectedButtonIndex = lastInt } } homePanelController?.selectedPanel = HomePanelType(rawValue: newSelectedButtonIndex) homePanelController?.isPrivateMode = tabTrayController?.privateMode ?? tabManager.selectedTab?.isPrivate ?? false // We have to run this animation, even if the view is already showing because there may be a hide animation running // and we want to be sure to override its results. UIView.animateWithDuration(0.2, animations: { () -> Void in self.homePanelController!.view.alpha = 1 }, completion: { finished in if finished { self.webViewContainer.accessibilityElementsHidden = true UIAccessibilityPostNotification(UIAccessibilityScreenChangedNotification, nil) } }) view.setNeedsUpdateConstraints() log.debug("BVC done with showHomePanelController.") } */ fileprivate func hideHomePanelController() { if let controller = homePanelController { UIView.animate(withDuration: 0.2, delay: 0, options: .beginFromCurrentState, animations: { () -> Void in controller.view.alpha = 0 }, completion: { finished in if finished { controller.willMove(toParentViewController: nil) controller.view.removeFromSuperview() controller.removeFromParentViewController() self.homePanelController = nil self.webViewContainer.accessibilityElementsHidden = false UIAccessibilityPostNotification(UIAccessibilityScreenChangedNotification, nil) // Refresh the reading view toolbar since the article record may have changed if let readerMode = self.tabManager.selectedTab?.getHelper(ReaderMode.name()) as? ReaderMode, readerMode.state == .Active { self.showReaderModeBar(animated: false) } self.navigationToolbar.updateBackStatus(self.tabManager.selectedTab?.webView?.canGoBack ?? false) } }) } } fileprivate func updateInContentHomePanel(_ url: URL?) { if !urlBar.inOverlayMode { // Cliqz: Added check to test if url is nul due to changing the method parameter to urlBar.url instead of selectedTab.url inside urlBarDidLeaveOverlayMode if url == nil || AboutUtils.isAboutHomeURL(url) || isTrampolineURL(url!) { // Cliqz: always set showInline to true to show the bottom toolbar // let showInline = AppConstants.MOZ_MENU || ((tabManager.selectedTab?.canGoForward ?? false || tabManager.selectedTab?.canGoBack ?? false)) let showInline = true showHomePanelController(inline: showInline) self.urlBar.showAntitrackingButton(false) } else { hideHomePanelController() self.urlBar.showAntitrackingButton(true) } } } // Cliqz: separate the creating of searchcontroller into a new method fileprivate func createSearchController() { guard searchController == nil else { return } searchController = CliqzSearchViewController(profile: self.profile) searchController!.delegate = self searchLoader.addListener(HistoryListener.shared) addChildViewController(searchController!) view.addSubview(searchController!.view) searchController!.view.snp_makeConstraints { make in make.top.equalTo(self.urlBar.snp_bottom) make.left.right.bottom.equalTo(self.view) return } } // Cliqz: modified showSearchController to show SearchViewController insead of searchController fileprivate func showSearchController() { if let selectedTab = tabManager.selectedTab { searchController?.updatePrivateMode(selectedTab.isPrivate) } homePanelController?.view?.isHidden = true searchController!.view.isHidden = false searchController!.didMove(toParentViewController: self) self.view.sendSubview(toBack: self.footer) // Cliqz: reset navigation steps navigationStep = 0 backNavigationStep = 0 } /* private func showSearchController() { if searchController != nil { return } let isPrivate = tabManager.selectedTab?.isPrivate ?? false searchController = SearchViewController(isPrivate: isPrivate) searchController!.searchEngines = profile.searchEngines searchController!.searchDelegate = self searchController!.profile = self.profile searchLoader.addListener(searchController!) addChildViewController(searchController!) view.addSubview(searchController!.view) searchController!.view.snp_makeConstraints { make in make.top.equalTo(self.urlBar.snp_bottom) make.left.right.bottom.equalTo(self.view) return } homePanelController?.view?.hidden = true searchController!.didMoveToParentViewController(self) } */ fileprivate func hideSearchController() { self.view.bringSubview(toFront: self.footer) if let searchController = searchController { // Cliqz: Modify hiding the search view controller as our behaviour is different than regular search that was exist searchController.view.isHidden = true homePanelController?.view?.isHidden = false /* searchController.willMoveToParentViewController(nil) searchController.view.removeFromSuperview() searchController.removeFromParentViewController() self.searchController = nil homePanelController?.view?.hidden = false */ } } fileprivate func finishEditingAndSubmit(_ url: URL, visitType: VisitType) { urlBar.currentURL = url urlBar.leaveOverlayMode() self.hideHomePanelController() guard let tab = tabManager.selectedTab else { return } // Cliqz:[UIWebView] Extra logic we might not need it #if !CLIQZ if let webView = tab.webView { resetSpoofedUserAgentIfRequired(webView, newURL: url) } #endif if BloomFilterManager.sharedInstance.shouldOpenInPrivateTab(url: url, currentTab: tab) { self.openURLInNewTab(url, isPrivate: true) return } if let nav = tab.loadRequest(PrivilegedRequest(url: url) as URLRequest) { self.recordNavigationInTab(tab, navigation: nav, visitType: visitType) } } func addBookmark(_ tabState: TabState) { guard let url = tabState.url else { return } // Cliqz: replaced ShareItem with CliqzShareItem to extend bookmarks behaviour let shareItem = CliqzShareItem(url: url.absoluteString, title: tabState.title, favicon: nil, bookmarkedDate: Date.now()) // let shareItem = ShareItem(url: url.absoluteString, title: tabState.title, favicon: tabState.favicon) profile.bookmarks.shareItem(shareItem) // Cliqz: comented Firefox 3D Touch code // if #available(iOS 9, *) { // var userData = [QuickActions.TabURLKey: shareItem.url] // if let title = shareItem.title { // userData[QuickActions.TabTitleKey] = title // } // QuickActions.sharedInstance.addDynamicApplicationShortcutItemOfType(.OpenLastBookmark, // withUserData: userData, // toApplication: UIApplication.sharedApplication()) // } if let tab = tabManager.getTabForURL(url) { tab.isBookmarked = true } if !AppConstants.MOZ_MENU { // Dispatch to the main thread to update the UI DispatchQueue.main.async { _ in self.animateBookmarkStar() self.toolbar?.updateBookmarkStatus(true) self.urlBar.updateBookmarkStatus(true) } } } fileprivate func animateBookmarkStar() { // Cliqz: Removed bookmarkButton /* let offset: CGFloat let button: UIButton! if let toolbar: TabToolbar = self.toolbar { offset = BrowserViewControllerUX.BookmarkStarAnimationOffset * -1 button = toolbar.bookmarkButton } else { offset = BrowserViewControllerUX.BookmarkStarAnimationOffset button = self.urlBar.bookmarkButton } JumpAndSpinAnimator.animateFromView(button.imageView ?? button, offset: offset, completion: nil) */ } fileprivate func removeBookmark(_ tabState: TabState) { guard let url = tabState.url else { return } profile.bookmarks.modelFactory >>== { $0.removeByURL(url.absoluteString) .uponQueue(DispatchQueue.main) { res in if res.isSuccess { if let tab = self.tabManager.getTabForURL(url) { tab.isBookmarked = false } if !AppConstants.MOZ_MENU { self.toolbar?.updateBookmarkStatus(false) self.urlBar.updateBookmarkStatus(false) } } } } } // Cliqz: Changed bookmarkItem to String, because for Cliqz Bookmarks status change notifications only URL is sent func SELBookmarkStatusDidChange(_ notification: Notification) { if let bookmarkUrl = notification.object as? String { if bookmarkUrl == urlBar.currentURL?.absoluteString { if let userInfo = notification.userInfo as? Dictionary<String, Bool>{ if let added = userInfo["added"]{ if let tab = self.tabManager.getTabForURL(urlBar.currentURL!) { tab.isBookmarked = false } if !AppConstants.MOZ_MENU { self.toolbar?.updateBookmarkStatus(added) self.urlBar.updateBookmarkStatus(added) } } } } } } override func accessibilityPerformEscape() -> Bool { if urlBar.inOverlayMode { urlBar.SELdidClickCancel() return true } else if let selectedTab = tabManager.selectedTab, selectedTab.canGoBack { // Cliqz: use one entry to go back/forward in all code self.goBack() return true } return false } override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey: Any]?, context: UnsafeMutableRawPointer?) { // Cliqz: Replaced forced unwrapping of optional (let webView = object as! CliqzWebView) with a guard check to avoid crashes guard let webView = object as? CliqzWebView else { return } if webView !== tabManager.selectedTab?.webView { return } guard let path = keyPath else { assertionFailure("Unhandled KVO key: \(keyPath)"); return } switch path { case KVOEstimatedProgress: guard webView == tabManager.selectedTab?.webView, let progress = change?[NSKeyValueChangeKey.newKey] as? Float else { break } urlBar.updateProgressBar(progress) if progress > 0.99 { hideNetworkActivitySpinner() } case KVOLoading: guard let loading = change?[NSKeyValueChangeKey.newKey] as? Bool else { break } if webView == tabManager.selectedTab?.webView { navigationToolbar.updateReloadStatus(loading) } if (!loading) { runScriptsOnWebView(webView) } case KVOURL: // Cliqz: temporary solution, later we should fix subscript and replace with original code // guard let tab = tabManager[webView] else { break } guard let tab = tabManager.tabForWebView(webView) else { break } // To prevent spoofing, only change the URL immediately if the new URL is on // the same origin as the current URL. Otherwise, do nothing and wait for // didCommitNavigation to confirm the page load. if tab.url?.origin == webView.url?.origin { tab.url = webView.url if tab === tabManager.selectedTab && !tab.restoring { updateUIForReaderHomeStateForTab(tab) } } case KVOCanGoBack: guard webView == tabManager.selectedTab?.webView, let canGoBack = change?[NSKeyValueChangeKey.newKey] as? Bool else { break } navigationToolbar.updateBackStatus(canGoBack) case KVOCanGoForward: guard webView == tabManager.selectedTab?.webView, let canGoForward = change?[NSKeyValueChangeKey.newKey] as? Bool else { break } navigationToolbar.updateForwardStatus(canGoForward) default: assertionFailure("Unhandled KVO key: \(keyPath)") } } // Cliqz:[UIWebView] Type change // private func runScriptsOnWebView(webView: WKWebView) { fileprivate func runScriptsOnWebView(_ webView: CliqzWebView) { webView.evaluateJavaScript("__firefox__.favicons.getFavicons()", completionHandler:nil) } fileprivate func updateUIForReaderHomeStateForTab(_ tab: Tab) { // Cliqz: Added gaurd statement to avoid overridding url when search results are displayed guard self.searchController != nil && self.searchController!.view.isHidden && tab.url != nil && !tab.url!.absoluteString.contains("/cliqz/") else { return } updateURLBarDisplayURL(tab) scrollController.showToolbars(false) if let url = tab.url { if ReaderModeUtils.isReaderModeURL(url) { showReaderModeBar(animated: false) NotificationCenter.default.addObserver(self, selector: #selector(BrowserViewController.SELDynamicFontChanged(_:)), name: NotificationDynamicFontChanged, object: nil) } else { hideReaderModeBar(animated: false) NotificationCenter.default.removeObserver(self, name: NotificationDynamicFontChanged, object: nil) } updateInContentHomePanel(url as URL) } } fileprivate func isWhitelistedUrl(_ url: URL) -> Bool { for entry in WhiteListedUrls { if let _ = url.absoluteString.range(of: entry, options: .regularExpression) { return UIApplication.shared.canOpenURL(url) } } return false } /// Updates the URL bar text and button states. /// Call this whenever the page URL changes. fileprivate func updateURLBarDisplayURL(_ tab: Tab) { guard tab.displayURL?.host != "localhost" else { return } if (urlBar.currentURL != tab.displayURL) { urlBar.currentURL = tab.displayURL } if let w = tab.webView { urlBar.updateTrackersCount(w.unsafeRequests) } // Cliqz: update the toolbar only if the search controller is not visible if searchController?.view.isHidden == true { let isPage = tab.displayURL?.isWebPage() ?? false navigationToolbar.updatePageStatus(isPage) } guard let url = tab.displayURL?.absoluteString else { return } profile.bookmarks.modelFactory >>== { $0.isBookmarked(url).uponQueue(DispatchQueue.main) { [weak tab] result in guard let bookmarked = result.successValue else { log.error("Error getting bookmark status: \(result.failureValue).") return } tab?.isBookmarked = bookmarked if !AppConstants.MOZ_MENU { self.navigationToolbar.updateBookmarkStatus(bookmarked) } } } } // Mark: Opening New Tabs @available(iOS 9, *) func switchToPrivacyMode(isPrivate: Bool ){ applyTheme(isPrivate ? Theme.PrivateMode : Theme.NormalMode) let tabTrayController = self.tabTrayController ?? TabTrayController(tabManager: tabManager, profile: profile, tabTrayDelegate: self) if tabTrayController.privateMode != isPrivate { tabTrayController.changePrivacyMode(isPrivate) } self.tabTrayController = tabTrayController } func switchToTabForURLOrOpen(_ url: URL, isPrivate: Bool = false) { popToBVC() if let tab = tabManager.getTabForURL(url) { tabManager.selectTab(tab) } else { openURLInNewTab(url, isPrivate: isPrivate) } } func openURLInNewTab(_ url: URL?, isPrivate: Bool = false) { // Cliqz: leave overlay mode before opening a new tab self.urlBar.leaveOverlayMode() var _isPrivate = isPrivate if let selectedTab = tabManager.selectedTab { screenshotHelper.takeScreenshot(selectedTab) } let request: URLRequest? if let url = url { request = PrivilegedRequest(url: url) as URLRequest if !_isPrivate && BloomFilterManager.sharedInstance.shouldOpenInPrivateTab(url: url, currentTab: tabManager.selectedTab) { _isPrivate = true } } else { request = nil } if #available(iOS 9, *) { switchToPrivacyMode(isPrivate: _isPrivate) _ = tabManager.addTabAndSelect(request, isPrivate: _isPrivate) } else { _ = tabManager.addTabAndSelect(request) } } func openBlankNewTabAndFocus(isPrivate: Bool = false) { popToBVC() openURLInNewTab(nil, isPrivate: isPrivate) urlBar.tabLocationViewDidTapLocation(urlBar.locationView) } fileprivate func popToBVC() { guard let currentViewController = navigationController?.topViewController else { return } // TODO: [Review] if let presentedViewController = currentViewController.presentedViewController { presentedViewController.dismiss(animated: false, completion: nil) } // currentViewController.dismissViewControllerAnimated(true, completion: nil) if currentViewController != self { self.navigationController?.popViewController(animated: false) } else if urlBar.inOverlayMode { urlBar.SELdidClickCancel() } } // Mark: User Agent Spoofing fileprivate func resetSpoofedUserAgentIfRequired(_ webView: WKWebView, newURL: URL) { guard #available(iOS 9.0, *) else { return } // Reset the UA when a different domain is being loaded if webView.url?.host != newURL.host { webView.customUserAgent = nil } } fileprivate func restoreSpoofedUserAgentIfRequired(_ webView: WKWebView, newRequest: URLRequest) { guard #available(iOS 9.0, *) else { return } // Restore any non-default UA from the request's header let ua = newRequest.value(forHTTPHeaderField: "User-Agent") webView.customUserAgent = ua != UserAgent.defaultUserAgent() ? ua : nil } fileprivate func presentActivityViewController(_ url: URL, tab: Tab? = nil, sourceView: UIView?, sourceRect: CGRect, arrowDirection: UIPopoverArrowDirection) { var activities = [UIActivity]() let findInPageActivity = FindInPageActivity() { [unowned self] in self.updateFindInPageVisibility(visible: true) // Cliqz: log telemetry signal for share menu TelemetryLogger.sharedInstance.logEvent(.ShareMenu("click", "search_page")) } activities.append(findInPageActivity) // Cliqz: disable Desktop/Mobile website option #if !CLIQZ if #available(iOS 9.0, *) { if let tab = tab, (tab.getHelper(ReaderMode.name()) as? ReaderMode)?.state != .Active { let requestDesktopSiteActivity = RequestDesktopSiteActivity(requestMobileSite: tab.desktopSite) { [unowned tab] in tab.toggleDesktopSite() } activities.append(requestDesktopSiteActivity) } } #endif // Cliqz: Added settings activity to sharing menu let settingsActivity = SettingsActivity() { self.openSettings() // Cliqz: log telemetry signal for share menu TelemetryLogger.sharedInstance.logEvent(.ShareMenu("click", "settings")) } //activities.append(settingsActivity) activities.insert(settingsActivity, at: 0) //insert the settings activity at the beginning of the list. (Tim). let helper = ShareExtensionHelper(url: url, tab: tab, activities: activities) let controller = helper.createActivityViewController({ [unowned self] completed in // After dismissing, check to see if there were any prompts we queued up self.showQueuedAlertIfAvailable() // Usually the popover delegate would handle nil'ing out the references we have to it // on the BVC when displaying as a popover but the delegate method doesn't seem to be // invoked on iOS 10. See Bug 1297768 for additional details. self.displayedPopoverController = nil self.updateDisplayedPopoverProperties = nil if completed { // We don't know what share action the user has chosen so we simply always // update the toolbar and reader mode bar to reflect the latest status. if let tab = tab { self.updateURLBarDisplayURL(tab) } self.updateReaderModeBar() } else { // Cliqz: log telemetry signal for share menu TelemetryLogger.sharedInstance.logEvent(.ShareMenu("click", "cancel")) } }) let setupPopover = { [unowned self] in if let popoverPresentationController = controller.popoverPresentationController { popoverPresentationController.sourceView = sourceView popoverPresentationController.sourceRect = sourceRect popoverPresentationController.permittedArrowDirections = arrowDirection popoverPresentationController.delegate = self } } setupPopover() if controller.popoverPresentationController != nil { displayedPopoverController = controller updateDisplayedPopoverProperties = setupPopover } self.present(controller, animated: true, completion: nil) } fileprivate func updateFindInPageVisibility(visible: Bool) { if visible { if findInPageBar == nil { let findInPageBar = FindInPageBar() self.findInPageBar = findInPageBar findInPageBar.delegate = self findInPageContainer.addSubview(findInPageBar) findInPageContainer.superview?.bringSubview(toFront: findInPageContainer) findInPageBar.snp_makeConstraints { make in make.edges.equalTo(findInPageContainer) make.height.equalTo(UIConstants.ToolbarHeight) } updateViewConstraints() // We make the find-in-page bar the first responder below, causing the keyboard delegates // to fire. This, in turn, will animate the Find in Page container since we use the same // delegate to slide the bar up and down with the keyboard. We don't want to animate the // constraints added above, however, so force a layout now to prevent these constraints // from being lumped in with the keyboard animation. findInPageBar.layoutIfNeeded() } self.findInPageBar?.becomeFirstResponder() } else if let findInPageBar = self.findInPageBar { findInPageBar.endEditing(true) guard let webView = tabManager.selectedTab?.webView else { return } webView.evaluateJavaScript("__firefox__.findDone()", completionHandler: nil) findInPageBar.removeFromSuperview() self.findInPageBar = nil updateViewConstraints() } } override var canBecomeFirstResponder : Bool { return true } override func becomeFirstResponder() -> Bool { // Make the web view the first responder so that it can show the selection menu. return tabManager.selectedTab?.webView?.becomeFirstResponder() ?? false } func reloadTab(){ if(homePanelController == nil){ tabManager.selectedTab?.reload() } } func goBack(){ if(tabManager.selectedTab?.canGoBack == true && homePanelController == nil){ tabManager.selectedTab?.goBack() } } func goForward(){ if(tabManager.selectedTab?.canGoForward == true) { tabManager.selectedTab?.goForward() if (homePanelController != nil) { urlBar.leaveOverlayMode() self.hideHomePanelController() } } } func findOnPage(){ if(homePanelController == nil){ tab( (tabManager.selectedTab)!, didSelectFindInPageForSelection: "") } } func selectLocationBar(){ urlBar.tabLocationViewDidTapLocation(urlBar.locationView) } func newTab() { openBlankNewTabAndFocus(isPrivate: false) } func newPrivateTab() { openBlankNewTabAndFocus(isPrivate: true) } func closeTab() { if(tabManager.tabs.count > 1){ tabManager.removeTab(tabManager.selectedTab!); } else{ //need to close the last tab and show the favorites screen thing } } func nextTab() { if(tabManager.selectedIndex < (tabManager.tabs.count - 1) ){ tabManager.selectTab(tabManager.tabs[tabManager.selectedIndex+1]) } else{ if(tabManager.tabs.count > 1){ tabManager.selectTab(tabManager.tabs[0]); } } } func previousTab() { if(tabManager.selectedIndex > 0){ tabManager.selectTab(tabManager.tabs[tabManager.selectedIndex-1]) } else{ if(tabManager.tabs.count > 1){ tabManager.selectTab(tabManager.tabs[tabManager.count-1]) } } } override var keyCommands: [UIKeyCommand]? { if #available(iOS 9.0, *) { return [ UIKeyCommand(input: "r", modifierFlags: .command, action: #selector(BrowserViewController.reloadTab), discoverabilityTitle: Strings.ReloadPageTitle), UIKeyCommand(input: "[", modifierFlags: .command, action: #selector(BrowserViewController.goBack), discoverabilityTitle: Strings.BackTitle), UIKeyCommand(input: "]", modifierFlags: .command, action: #selector(BrowserViewController.goForward), discoverabilityTitle: Strings.ForwardTitle), UIKeyCommand(input: "f", modifierFlags: .command, action: #selector(BrowserViewController.findOnPage), discoverabilityTitle: Strings.FindTitle), UIKeyCommand(input: "l", modifierFlags: .command, action: #selector(BrowserViewController.selectLocationBar), discoverabilityTitle: Strings.SelectLocationBarTitle), UIKeyCommand(input: "t", modifierFlags: .command, action: #selector(BrowserViewController.newTab), discoverabilityTitle: Strings.NewTabTitle), UIKeyCommand(input: "p", modifierFlags: [.command, .shift], action: #selector(BrowserViewController.newPrivateTab), discoverabilityTitle: Strings.NewPrivateTabTitle), UIKeyCommand(input: "w", modifierFlags: .command, action: #selector(BrowserViewController.closeTab), discoverabilityTitle: Strings.CloseTabTitle), UIKeyCommand(input: "\t", modifierFlags: .control, action: #selector(BrowserViewController.nextTab), discoverabilityTitle: Strings.ShowNextTabTitle), UIKeyCommand(input: "\t", modifierFlags: [.control, .shift], action: #selector(BrowserViewController.previousTab), discoverabilityTitle: Strings.ShowPreviousTabTitle), ] } else { // Fallback on earlier versions return [ UIKeyCommand(input: "r", modifierFlags: .command, action: #selector(BrowserViewController.reloadTab)), UIKeyCommand(input: "[", modifierFlags: .command, action: #selector(BrowserViewController.goBack)), UIKeyCommand(input: "f", modifierFlags: .command, action: #selector(BrowserViewController.findOnPage)), UIKeyCommand(input: "l", modifierFlags: .command, action: #selector(BrowserViewController.selectLocationBar)), UIKeyCommand(input: "t", modifierFlags: .command, action: #selector(BrowserViewController.newTab)), UIKeyCommand(input: "p", modifierFlags: [.command, .shift], action: #selector(BrowserViewController.newPrivateTab)), UIKeyCommand(input: "w", modifierFlags: .command, action: #selector(BrowserViewController.closeTab)), UIKeyCommand(input: "\t", modifierFlags: .control, action: #selector(BrowserViewController.nextTab)), UIKeyCommand(input: "\t", modifierFlags: [.control, .shift], action: #selector(BrowserViewController.previousTab)) ] } } fileprivate func getCurrentAppState() -> AppState { return mainStore.updateState(getCurrentUIState()) } fileprivate func getCurrentUIState() -> UIState { if let homePanelController = homePanelController { return .homePanels(homePanelState: HomePanelState(isPrivate: false , selectedIndex: 0)) //homePanelController.homePanelState) } guard let tab = tabManager.selectedTab, !tab.loading else { return .loading } return .tab(tabState: tab.tabState) } @objc internal func openSettings() { assert(Thread.isMainThread, "Opening settings requires being invoked on the main thread") let settingsTableViewController = AppSettingsTableViewController() settingsTableViewController.profile = profile settingsTableViewController.tabManager = tabManager settingsTableViewController.settingsDelegate = self let controller = SettingsNavigationController(rootViewController: settingsTableViewController) controller.popoverDelegate = self controller.modalPresentationStyle = UIModalPresentationStyle.formSheet self.present(controller, animated: true, completion: nil) } } extension BrowserViewController: AppStateDelegate { func appDidUpdateState(_ appState: AppState) { if AppConstants.MOZ_MENU { menuViewController?.appState = appState } toolbar?.appDidUpdateState(appState) urlBar?.appDidUpdateState(appState) } } extension BrowserViewController: MenuActionDelegate { func performMenuAction(_ action: MenuAction, withAppState appState: AppState) { if let menuAction = AppMenuAction(rawValue: action.action) { switch menuAction { case .OpenNewNormalTab: if #available(iOS 9, *) { self.openURLInNewTab(nil, isPrivate: false) } else { self.tabManager.addTabAndSelect(nil) } // this is a case that is only available in iOS9 case .OpenNewPrivateTab: if #available(iOS 9, *) { self.openURLInNewTab(nil, isPrivate: true) } case .FindInPage: self.updateFindInPageVisibility(visible: true) case .ToggleBrowsingMode: if #available(iOS 9, *) { guard let tab = tabManager.selectedTab else { break } tab.toggleDesktopSite() } case .ToggleBookmarkStatus: switch appState.ui { case .tab(let tabState): self.toggleBookmarkForTabState(tabState) default: break } case .ShowImageMode: self.setNoImageMode(false) case .HideImageMode: self.setNoImageMode(true) case .ShowNightMode: NightModeHelper.setNightMode(self.profile.prefs, tabManager: self.tabManager, enabled: false) case .HideNightMode: NightModeHelper.setNightMode(self.profile.prefs, tabManager: self.tabManager, enabled: true) case .OpenSettings: self.openSettings() case .OpenTopSites: openHomePanel(.topSites, forAppState: appState) case .OpenBookmarks: openHomePanel(.bookmarks, forAppState: appState) case .OpenHistory: openHomePanel(.history, forAppState: appState) case .OpenReadingList: openHomePanel(.readingList, forAppState: appState) case .SetHomePage: guard let tab = tabManager.selectedTab else { break } HomePageHelper(prefs: profile.prefs).setHomePage(toTab: tab, withNavigationController: navigationController) case .OpenHomePage: guard let tab = tabManager.selectedTab else { break } HomePageHelper(prefs: profile.prefs).openHomePage(inTab: tab, withNavigationController: navigationController) case .SharePage: guard let url = tabManager.selectedTab?.url else { break } // Cliqz: Removed menu button as we don't need it // let sourceView = self.navigationToolbar.menuButton // presentActivityViewController(url, sourceView: sourceView.superview, sourceRect: sourceView.frame, arrowDirection: .Up) default: break } } } fileprivate func openHomePanel(_ panel: HomePanelType, forAppState appState: AppState) { switch appState.ui { case .tab(_): self.openURLInNewTab(panel.localhostURL as URL, isPrivate: appState.ui.isPrivate()) case .homePanels(_): // Not aplicable print("Not aplicable") // self.homePanelController?.selectedPanel = panel default: break } } } extension BrowserViewController: SettingsDelegate { func settingsOpenURLInNewTab(_ url: URL) { self.openURLInNewTab(url) } } extension BrowserViewController: PresentingModalViewControllerDelegate { func dismissPresentedModalViewController(_ modalViewController: UIViewController, animated: Bool) { self.appDidUpdateState(getCurrentAppState()) self.dismiss(animated: animated, completion: nil) } } /** * History visit management. * TODO: this should be expanded to track various visit types; see Bug 1166084. */ extension BrowserViewController { func ignoreNavigationInTab(_ tab: Tab, navigation: WKNavigation) { self.ignoredNavigation.insert(navigation) } func recordNavigationInTab(_ tab: Tab, navigation: WKNavigation, visitType: VisitType) { self.typedNavigation[navigation] = visitType } /** * Untrack and do the right thing. */ func getVisitTypeForTab(_ tab: Tab, navigation: WKNavigation?) -> VisitType? { guard let navigation = navigation else { // See https://github.com/WebKit/webkit/blob/master/Source/WebKit2/UIProcess/Cocoa/NavigationState.mm#L390 return VisitType.Link } if let _ = self.ignoredNavigation.remove(navigation) { return nil } return self.typedNavigation.removeValue(forKey: navigation) ?? VisitType.Link } } extension BrowserViewController: URLBarDelegate { func isPrivate() -> Bool { return self.tabManager.selectedTab?.isPrivate ?? false } func urlBarDidPressReload(_ urlBar: URLBarView) { tabManager.selectedTab?.reload() } func urlBarDidPressStop(_ urlBar: URLBarView) { tabManager.selectedTab?.stop() } func urlBarDidPressTabs(_ urlBar: URLBarView) { // Cliqz: telemetry logging for toolbar self.logToolbarOverviewSignal() self.webViewContainerToolbar.isHidden = true updateFindInPageVisibility(visible: false) if let tab = tabManager.selectedTab { screenshotHelper.takeScreenshot(tab) } if let controlCenter = controlCenterController { controlCenter.closeControlCenter() } // Cliqz: Replaced FF TabsController with our's which also contains history and favorites /* let tabTrayController = TabTrayController(tabManager: tabManager, profile: profile, tabTrayDelegate: self) self.navigationController?.pushViewController(tabTrayController, animated: true) self.tabTrayController = tabTrayController */ dashboard.currentPanel = .TabsPanel self.navigationController?.pushViewController(dashboard, animated: false) } func urlBarDidPressReaderMode(_ urlBar: URLBarView) { self.controlCenterController?.closeControlCenter() if let tab = tabManager.selectedTab { if let readerMode = tab.getHelper("ReaderMode") as? ReaderMode { switch readerMode.state { case .Available: enableReaderMode() logToolbarReaderModeSignal(false) case .Active: disableReaderMode() logToolbarReaderModeSignal(true) case .Unavailable: break } } } } func urlBarDidLongPressReaderMode(_ urlBar: URLBarView) -> Bool { self.controlCenterController?.closeControlCenter() guard let tab = tabManager.selectedTab, let url = tab.displayURL, let result = profile.readingList?.createRecordWithURL(url.absoluteString, title: tab.title ?? "", addedBy: UIDevice.current.name) else { UIAccessibilityPostNotification(UIAccessibilityAnnouncementNotification, NSLocalizedString("Could not add page to Reading list", comment: "Accessibility message e.g. spoken by VoiceOver after adding current webpage to the Reading List failed.")) return false } switch result { case .success: UIAccessibilityPostNotification(UIAccessibilityAnnouncementNotification, NSLocalizedString("Added page to Reading List", comment: "Accessibility message e.g. spoken by VoiceOver after the current page gets added to the Reading List using the Reader View button, e.g. by long-pressing it or by its accessibility custom action.")) // TODO: https://bugzilla.mozilla.org/show_bug.cgi?id=1158503 provide some form of 'this has been added' visual feedback? case .failure(let error): UIAccessibilityPostNotification(UIAccessibilityAnnouncementNotification, NSLocalizedString("Could not add page to Reading List. Maybe it's already there?", comment: "Accessibility message e.g. spoken by VoiceOver after the user wanted to add current page to the Reading List and this was not done, likely because it already was in the Reading List, but perhaps also because of real failures.")) log.error("readingList.createRecordWithURL(url: \"\(url.absoluteString)\", ...) failed with error: \(error)") } return true } func locationActionsForURLBar(_ urlBar: URLBarView) -> [AccessibleAction] { if UIPasteboard.general.string != nil { return [pasteGoAction, pasteAction, copyAddressAction] } else { return [copyAddressAction] } } func urlBarDisplayTextForURL(_ url: URL?) -> String? { // use the initial value for the URL so we can do proper pattern matching with search URLs // Cliqz: return search query to display in the case when search results are visible (added for back/forward feature if self.searchController != nil && !self.searchController!.view.isHidden { return self.searchController!.searchQuery } var searchURL = self.tabManager.selectedTab?.currentInitialURL if searchURL == nil || ErrorPageHelper.isErrorPageURL(searchURL!) { searchURL = url } return profile.searchEngines.queryForSearchURL(searchURL) ?? url?.absoluteString } func urlBarDidLongPressLocation(_ urlBar: URLBarView) { let longPressAlertController = UIAlertController(title: nil, message: nil, preferredStyle: .actionSheet) for action in locationActionsForURLBar(urlBar) { longPressAlertController.addAction(action.alertAction(style: .default)) } let cancelAction = UIAlertAction(title: NSLocalizedString("Cancel", comment: "Label for Cancel button"), style: .cancel, handler: { (alert: UIAlertAction) -> Void in }) longPressAlertController.addAction(cancelAction) let setupPopover = { [unowned self] in if let popoverPresentationController = longPressAlertController.popoverPresentationController { popoverPresentationController.sourceView = urlBar popoverPresentationController.sourceRect = urlBar.frame popoverPresentationController.permittedArrowDirections = .any popoverPresentationController.delegate = self } } setupPopover() if longPressAlertController.popoverPresentationController != nil { displayedPopoverController = longPressAlertController updateDisplayedPopoverProperties = setupPopover } self.present(longPressAlertController, animated: true, completion: nil) } func urlBarDidPressScrollToTop(_ urlBar: URLBarView) { if let selectedTab = tabManager.selectedTab { // Only scroll to top if we are not showing the home view controller if homePanelController == nil { selectedTab.webView?.scrollView.setContentOffset(CGPoint.zero, animated: true) } } } func urlBarLocationAccessibilityActions(_ urlBar: URLBarView) -> [UIAccessibilityCustomAction]? { return locationActionsForURLBar(urlBar).map { $0.accessibilityCustomAction } } func urlBar(_ urlBar: URLBarView, didEnterText text: String) { searchLoader.query = text // Cliqz: always show search controller even if query was empty createSearchController() if text != "" { hideHomePanelController() showSearchController() searchController!.searchQuery = text } else { hideSearchController() showHomePanelController(inline: true) } /* if text.isEmpty { hideSearchController() } else { showSearchController() searchController!.searchQuery = text } */ // Cliqz: hide AntiTracking button and reader mode button when switching to search mode //self.urlBar.updateReaderModeState(ReaderModeState.Unavailable) //self.urlBar.hideReaderModeButton(hidden: true) self.urlBar.showAntitrackingButton(false) } func urlBar(_ urlBar: URLBarView, didSubmitText text: String) { // If we can't make a valid URL, do a search query. // If we still don't have a valid URL, something is broken. Give up. if InteractiveIntro.sharedInstance.shouldShowCliqzSearchHint() { urlBar.locationTextField?.enforceResignFirstResponder() self.showHint(.cliqzSearch(text.characters.count)) } else { self.tabManager.selectedTab?.query = self.searchController?.searchQuery var url = URIFixup.getURL(text) // If we can't make a valid URL, do a search query. if url == nil { url = profile.searchEngines.defaultEngine.searchURLForQuery(text) if url != nil { // Cliqz: Support showing search view with query set when going back from search result navigateToUrl(url!, searchQuery: text) } else { // If we still don't have a valid URL, something is broken. Give up. log.error("Error handling URL entry: \"\(text)\".") } } else { finishEditingAndSubmit(url!, visitType: VisitType.Typed) } //TODO: [Review] /* let engine = profile.searchEngines.defaultEngine guard let url = URIFixup.getURL(text) ?? engine.searchURLForQuery(text) else { log.error("Error handling URL entry: \"\(text)\".") return } finishEditingAndSubmit(url!, visitType: VisitType.Typed) */ } } func urlBarDidEnterOverlayMode(_ urlBar: URLBarView) { self.controlCenterController?.closeControlCenter() // Cliqz: telemetry logging for toolbar self.logToolbarFocusSignal() // Cliqz: hide AntiTracking button in overlay mode self.urlBar.showAntitrackingButton(false) // Cliqz: send `urlbar-focus` to extension self.searchController?.sendUrlBarFocusEvent() navigationToolbar.updatePageStatus(false) if .BlankPage == NewTabAccessors.getNewTabPage(profile.prefs) { UIAccessibilityPostNotification(UIAccessibilityScreenChangedNotification, nil) } else { // Cliqz: disable showing home panel when entering overlay mode // showHomePanelController(inline: false) } } func urlBarDidLeaveOverlayMode(_ urlBar: URLBarView) { // Cliqz: telemetry logging for toolbar self.logToolbarBlurSignal() hideSearchController() // Cliqz: update URL bar and the tab toolbar when leaving overlay if let tab = tabManager.selectedTab { updateUIForReaderHomeStateForTab(tab) let isPage = tab.displayURL?.isWebPage() ?? false navigationToolbar.updatePageStatus(isPage) } updateInContentHomePanel(tabManager.selectedTab?.url) //self.urlBar.hideReaderModeButton(hidden: false) } // Cliqz: Add delegate methods for new tab button func urlBarDidPressNewTab(_ urlBar: URLBarView, button: UIButton) { if let controlCenter = controlCenterController { controlCenter.closeControlCenter() } if let selectedTab = self.tabManager.selectedTab { tabManager.addTabAndSelect(nil, configuration: nil, isPrivate: selectedTab.isPrivate) } else { tabManager.addTabAndSelect() } switchToSearchModeIfNeeded() // Cliqz: log telemetry singal for web menu logWebMenuSignal("click", target: "new_tab") } // Cliqz: Added video download button to urlBar func urlBarDidTapVideoDownload(_ urlBar: URLBarView) { if let url = self.urlBar.currentURL { self.downloadVideoFromURL(url.absoluteString, sourceRect: urlBar.frame) let isForgetMode = self.tabManager.selectedTab?.isPrivate TelemetryLogger.sharedInstance.logEvent(.Toolbar("click", "video_downloader", "web", isForgetMode, nil)) } } func urlBarDidShowVideoDownload(_ urlBar: URLBarView) { if InteractiveIntro.sharedInstance.shouldShowVideoDownloaderHint() { self.showHint(.videoDownloader) } } // Cliqz: Added delegate methods for QuickAcessBar func urlBarDidPressHistroy(_ urlBar: URLBarView) { dashboard.currentPanel = .HistoryPanel self.navigationController?.pushViewController(dashboard, animated: false) } func urlBarDidPressFavorites(_ urlBar: URLBarView) { dashboard.currentPanel = .FavoritesPanel self.navigationController?.pushViewController(dashboard, animated: false) } func urlBarDidPressOffrz(_ urlBar: URLBarView) { dashboard.currentPanel = .OffrzPanel self.navigationController?.pushViewController(dashboard, animated: false) } func hasUnreadOffrz() -> Bool { if let offrzDataSource = self.profile.offrzDataSource { return offrzDataSource.hasUnseenOffrz() } return false } func shouldShowOffrz() -> Bool { if let offrzDataSource = self.profile.offrzDataSource { return offrzDataSource.shouldShowOffrz() } return false } } extension BrowserViewController: TabToolbarDelegate { func tabToolbarDidPressBack(_ tabToolbar: TabToolbarProtocol, button: UIButton) { // Cliqz: use one entry to go back/forward in all code self.goBack() // Cliqz: log telemetry singal for web menu logWebMenuSignal("click", target: "back") } func tabToolbarDidLongPressBack(_ tabToolbar: TabToolbarProtocol, button: UIButton) { showBackForwardList() } func tabToolbarDidPressReload(_ tabToolbar: TabToolbarProtocol, button: UIButton) { tabManager.selectedTab?.reload() } func tabToolbarDidLongPressReload(_ tabToolbar: TabToolbarProtocol, button: UIButton) { guard #available(iOS 9.0, *) else { return } guard let tab = tabManager.selectedTab, tab.webView?.url != nil && (tab.getHelper(ReaderMode.name()) as? ReaderMode)?.state != .Active else { return } let toggleActionTitle: String if tab.desktopSite { toggleActionTitle = NSLocalizedString("Request Mobile Site", comment: "Action Sheet Button for Requesting the Mobile Site") } else { toggleActionTitle = NSLocalizedString("Request Desktop Site", comment: "Action Sheet Button for Requesting the Desktop Site") } let controller = UIAlertController(title: nil, message: nil, preferredStyle: .actionSheet) controller.addAction(UIAlertAction(title: toggleActionTitle, style: .default, handler: { _ in tab.toggleDesktopSite() })) controller.addAction(UIAlertAction(title: NSLocalizedString("Cancel", comment:"Label for Cancel button"), style: .cancel, handler: nil)) controller.popoverPresentationController?.sourceView = toolbar ?? urlBar controller.popoverPresentationController?.sourceRect = button.frame present(controller, animated: true, completion: nil) } func tabToolbarDidPressStop(_ tabToolbar: TabToolbarProtocol, button: UIButton) { tabManager.selectedTab?.stop() } func tabToolbarDidPressForward(_ tabToolbar: TabToolbarProtocol, button: UIButton) { // Cliqz: use one entry to go back/forward in all code self.goForward() // Cliqz: log telemetry singal for web menu logWebMenuSignal("click", target: "forward") } func tabToolbarDidLongPressForward(_ tabToolbar: TabToolbarProtocol, button: UIButton) { showBackForwardList() } func tabToolbarDidPressMenu(_ tabToolbar: TabToolbarProtocol, button: UIButton) { // ensure that any keyboards or spinners are dismissed before presenting the menu UIApplication.shared.sendAction(#selector(UIResponder.resignFirstResponder), to:nil, from:nil, for:nil) // check the trait collection // open as modal if portrait\ let presentationStyle: MenuViewPresentationStyle = (self.traitCollection.horizontalSizeClass == .compact && traitCollection.verticalSizeClass == .regular) ? .modal : .popover let mvc = MenuViewController(withAppState: getCurrentAppState(), presentationStyle: presentationStyle) mvc.delegate = self mvc.actionDelegate = self mvc.menuTransitionDelegate = MenuPresentationAnimator() mvc.modalPresentationStyle = presentationStyle == .modal ? .overCurrentContext : .popover if let popoverPresentationController = mvc.popoverPresentationController { popoverPresentationController.backgroundColor = UIColor.clear popoverPresentationController.delegate = self popoverPresentationController.sourceView = button popoverPresentationController.sourceRect = CGRect(x: button.frame.width/2, y: button.frame.size.height * 0.75, width: 1, height: 1) popoverPresentationController.permittedArrowDirections = UIPopoverArrowDirection.up } self.present(mvc, animated: true, completion: nil) menuViewController = mvc } fileprivate func setNoImageMode(_ enabled: Bool) { self.profile.prefs.setBool(enabled, forKey: PrefsKeys.KeyNoImageModeStatus) for tab in self.tabManager.tabs { tab.setNoImageMode(enabled, force: true) } self.tabManager.selectedTab?.reload() } func toggleBookmarkForTabState(_ tabState: TabState) { if tabState.isBookmarked { self.removeBookmark(tabState) // Cliqz: log telemetry singal for web menu logWebMenuSignal("click", target: "remove_favorite") } else { self.addBookmark(tabState) // Cliqz: log telemetry singal for web menu logWebMenuSignal("click", target: "add_favorite") } } func tabToolbarDidPressBookmark(_ tabToolbar: TabToolbarProtocol, button: UIButton) { guard let tab = tabManager.selectedTab, let _ = tab.displayURL?.absoluteString else { log.error("Bookmark error: No tab is selected, or no URL in tab.") return } toggleBookmarkForTabState(tab.tabState) } func tabToolbarDidLongPressBookmark(_ tabToolbar: TabToolbarProtocol, button: UIButton) { } func tabToolbarDidPressShare(_ tabToolbar: TabToolbarProtocol, button: UIButton) { if let tab = tabManager.selectedTab, let url = tab.displayURL { let sourceView = self.navigationToolbar.shareButton presentActivityViewController(url as URL, tab: tab, sourceView: sourceView.superview, sourceRect: sourceView.frame, arrowDirection: .up) // Cliqz: log telemetry singal for web menu logWebMenuSignal("click", target: "share") } } func tabToolbarDidPressHomePage(_ tabToolbar: TabToolbarProtocol, button: UIButton) { guard let tab = tabManager.selectedTab else { return } HomePageHelper(prefs: profile.prefs).openHomePage(inTab: tab, withNavigationController: navigationController) } func showBackForwardList() { // Cliqz: Discarded the code as it is not used in our flow instead of doing a ching of modification to fix the compilation errors #if !CLIQZ guard AppConstants.MOZ_BACK_FORWARD_LIST else { return } if let backForwardList = tabManager.selectedTab?.webView?.backForwardList { let backForwardViewController = BackForwardListViewController(profile: profile, backForwardList: backForwardList, isPrivate: tabManager.selectedTab?.isPrivate ?? false) backForwardViewController.tabManager = tabManager backForwardViewController.bvc = self backForwardViewController.modalPresentationStyle = UIModalPresentationStyle.overCurrentContext backForwardViewController.backForwardTransitionDelegate = BackForwardListAnimator() self.present(backForwardViewController, animated: true, completion: nil) } #endif } // Cliqz: Add delegate methods for tabs button func tabToolbarDidPressTabs(_ tabToolbar: TabToolbarProtocol, button: UIButton) { // check if the dashboard is already pushed before guard self.navigationController?.topViewController != dashboard else { return } // Cliqz: telemetry logging for toolbar self.logToolbarOverviewSignal() self.webViewContainerToolbar.isHidden = true updateFindInPageVisibility(visible: false) if let tab = tabManager.selectedTab { screenshotHelper.takeScreenshot(tab) } if let controlCenter = controlCenterController { controlCenter.closeControlCenter() } // Cliqz: Replaced FF TabsController with our's which also contains history and favorites /* let tabTrayController = TabTrayController(tabManager: tabManager, profile: profile, tabTrayDelegate: self) self.navigationController?.pushViewController(tabTrayController, animated: true) self.tabTrayController = tabTrayController */ dashboard.currentPanel = .TabsPanel self.navigationController?.pushViewController(dashboard, animated: false) } // Cliqz: Add delegate methods for tabs button func tabToolbarDidLongPressTabs(_ tabToolbar: TabToolbarProtocol, button: UIButton) { if #available(iOS 9, *) { let newTabHandler = { (action: UIAlertAction) in self.tabManager.addTabAndSelect() self.homePanelController?.restoreToInitialState() self.logWebMenuSignal("click", target: "new_tab") self.switchToSearchModeIfNeeded() } let newForgetModeTabHandler = { (action: UIAlertAction) in self.tabManager.addTabAndSelect(nil, configuration: nil, isPrivate: true) self.logWebMenuSignal("click", target: "new_forget_tab") self.switchToSearchModeIfNeeded() } var closeAllTabsHandler: ((UIAlertAction) -> Void)? = nil let tabsCount = self.tabManager.tabs.count if tabsCount > 1 { closeAllTabsHandler = { (action: UIAlertAction) in self.tabManager.removeAll() self.logWebMenuSignal("click", target: "close_all_tabs") self.switchToSearchModeIfNeeded() } } let cancelHandler = { (action: UIAlertAction) in self.logWebMenuSignal("click", target: "cancel") } let actionSheetController = UIAlertController.createNewTabActionSheetController(button, newTabHandler: newTabHandler, newForgetModeTabHandler: newForgetModeTabHandler, cancelHandler: cancelHandler, closeAllTabsHandler: closeAllTabsHandler) self.present(actionSheetController, animated: true, completion: nil) logWebMenuSignal("longpress", target: "tabs") } } } extension BrowserViewController: MenuViewControllerDelegate { func menuViewControllerDidDismiss(_ menuViewController: MenuViewController) { self.menuViewController = nil displayedPopoverController = nil updateDisplayedPopoverProperties = nil } func shouldCloseMenu(_ menuViewController: MenuViewController, forRotationToNewSize size: CGSize, forTraitCollection traitCollection: UITraitCollection) -> Bool { // if we're presenting in popover but we haven't got a preferred content size yet, don't dismiss, otherwise we might dismiss before we've presented if (traitCollection.horizontalSizeClass == .compact && traitCollection.verticalSizeClass == .compact) && menuViewController.preferredContentSize == CGSize.zero { return false } func orientationForSize(_ size: CGSize) -> UIInterfaceOrientation { return size.height < size.width ? .landscapeLeft : .portrait } let currentOrientation = orientationForSize(self.view.bounds.size) let newOrientation = orientationForSize(size) let isiPhone = UI_USER_INTERFACE_IDIOM() == .phone // we only want to dismiss when rotating on iPhone // if we're rotating from landscape to portrait then we are rotating from popover to modal return isiPhone && currentOrientation != newOrientation } } extension BrowserViewController: WindowCloseHelperDelegate { func windowCloseHelper(_ helper: WindowCloseHelper, didRequestToCloseTab tab: Tab) { tabManager.removeTab(tab) } } extension BrowserViewController: TabDelegate { func urlChangedForTab(_ tab: Tab) { if self.tabManager.selectedTab == tab && tab.url?.baseDomain() != "localhost" { //update the url in the urlbar self.urlBar.currentURL = tab.url } } // Cliqz:[UIWebView] Type change // func tab(tab: Tab, didCreateWebView webView: WKWebView) { func tab(_ tab: Tab, didCreateWebView webView: CliqzWebView) { webView.frame = webViewContainer.frame // Observers that live as long as the tab. Make sure these are all cleared // in willDeleteWebView below! webView.addObserver(self, forKeyPath: KVOEstimatedProgress, options: .new, context: nil) webView.addObserver(self, forKeyPath: KVOLoading, options: .new, context: nil) webView.addObserver(self, forKeyPath: KVOCanGoBack, options: .new, context: nil) webView.addObserver(self, forKeyPath: KVOCanGoForward, options: .new, context: nil) tab.webView?.addObserver(self, forKeyPath: KVOURL, options: .new, context: nil) webView.scrollView.addObserver(self.scrollController, forKeyPath: KVOContentSize, options: .new, context: nil) webView.UIDelegate = self let readerMode = ReaderMode(tab: tab) readerMode.delegate = self tab.addHelper(readerMode, name: ReaderMode.name()) let favicons = FaviconManager(tab: tab, profile: profile) tab.addHelper(favicons, name: FaviconManager.name()) #if !CLIQZ // Cliqz: disable adding login and context menu helpers as ther are not used // only add the logins helper if the tab is not a private browsing tab if !tab.isPrivate { let logins = LoginsHelper(tab: tab, profile: profile) tab.addHelper(logins, name: LoginsHelper.name()) } let contextMenuHelper = ContextMenuHelper(tab: tab) contextMenuHelper.delegate = self tab.addHelper(contextMenuHelper, name: ContextMenuHelper.name()) #endif let errorHelper = ErrorPageHelper() tab.addHelper(errorHelper, name: ErrorPageHelper.name()) if #available(iOS 9, *) {} else { let windowCloseHelper = WindowCloseHelper(tab: tab) windowCloseHelper.delegate = self tab.addHelper(windowCloseHelper, name: WindowCloseHelper.name()) } let sessionRestoreHelper = SessionRestoreHelper(tab: tab) sessionRestoreHelper.delegate = self tab.addHelper(sessionRestoreHelper, name: SessionRestoreHelper.name()) let findInPageHelper = FindInPageHelper(tab: tab) findInPageHelper.delegate = self tab.addHelper(findInPageHelper, name: FindInPageHelper.name()) #if !CLIQZ // Cliqz: disable adding hide image helper as it is not used let noImageModeHelper = NoImageModeHelper(tab: tab) tab.addHelper(noImageModeHelper, name: NoImageModeHelper.name()) #endif let printHelper = PrintHelper(tab: tab) tab.addHelper(printHelper, name: PrintHelper.name()) let customSearchHelper = CustomSearchHelper(tab: tab) tab.addHelper(customSearchHelper, name: CustomSearchHelper.name()) let openURL = {(url: URL) -> Void in self.switchToTabForURLOrOpen(url) } #if !CLIQZ // Cliqz: disable adding night mode and spot light helpers as ther are not used let nightModeHelper = NightModeHelper(tab: tab) tab.addHelper(nightModeHelper, name: NightModeHelper.name()) let spotlightHelper = SpotlightHelper(tab: tab, openURL: openURL) tab.addHelper(spotlightHelper, name: SpotlightHelper.name()) #endif tab.addHelper(LocalRequestHelper(), name: LocalRequestHelper.name()) // Cliqz: Add custom user scripts addCustomUserScripts(tab) } // Cliqz:[UIWebView] Type change // func tab(tab: Tab, willDeleteWebView webView: WKWebView) { func tab(_ tab: Tab, willDeleteWebView webView: CliqzWebView) { tab.cancelQueuedAlerts() webView.removeObserver(self, forKeyPath: KVOEstimatedProgress) webView.removeObserver(self, forKeyPath: KVOLoading) webView.removeObserver(self, forKeyPath: KVOCanGoBack) webView.removeObserver(self, forKeyPath: KVOCanGoForward) webView.scrollView.removeObserver(self.scrollController, forKeyPath: KVOContentSize) webView.removeObserver(self, forKeyPath: KVOURL) webView.UIDelegate = nil webView.scrollView.delegate = nil webView.removeFromSuperview() } fileprivate func findSnackbar(_ barToFind: SnackBar) -> Int? { let bars = snackBars.subviews for (index, bar) in bars.enumerated() { if bar === barToFind { return index } } return nil } fileprivate func updateSnackBarConstraints() { snackBars.snp_remakeConstraints { make in make.bottom.equalTo(findInPageContainer.snp_top) let bars = self.snackBars.subviews if bars.count > 0 { let view = bars[bars.count-1] make.top.equalTo(view.snp_top) } else { make.height.equalTo(0) } if traitCollection.horizontalSizeClass != .regular { make.leading.trailing.equalTo(self.footer) self.snackBars.layer.borderWidth = 0 } else { make.centerX.equalTo(self.footer) make.width.equalTo(SnackBarUX.MaxWidth) self.snackBars.layer.borderColor = UIConstants.BorderColor.cgColor self.snackBars.layer.borderWidth = 1 } } } // This removes the bar from its superview and updates constraints appropriately fileprivate func finishRemovingBar(_ bar: SnackBar) { // If there was a bar above this one, we need to remake its constraints. if let index = findSnackbar(bar) { // If the bar being removed isn't on the top of the list let bars = snackBars.subviews if index < bars.count-1 { // Move the bar above this one let nextbar = bars[index+1] as! SnackBar nextbar.snp_updateConstraints { make in // If this wasn't the bottom bar, attach to the bar below it if index > 0 { let bar = bars[index-1] as! SnackBar nextbar.bottom = make.bottom.equalTo(bar.snp_top).constraint } else { // Otherwise, we attach it to the bottom of the snackbars nextbar.bottom = make.bottom.equalTo(self.snackBars.snp_bottom).constraint } } } } // Really remove the bar bar.removeFromSuperview() } fileprivate func finishAddingBar(_ bar: SnackBar) { snackBars.addSubview(bar) bar.snp_remakeConstraints { make in // If there are already bars showing, add this on top of them let bars = self.snackBars.subviews // Add the bar on top of the stack // We're the new top bar in the stack, so make sure we ignore ourself if bars.count > 1 { let view = bars[bars.count - 2] bar.bottom = make.bottom.equalTo(view.snp_top).offset(0).constraint } else { bar.bottom = make.bottom.equalTo(self.snackBars.snp_bottom).offset(0).constraint } make.leading.trailing.equalTo(self.snackBars) } } func showBar(_ bar: SnackBar, animated: Bool) { finishAddingBar(bar) updateSnackBarConstraints() bar.hide() view.layoutIfNeeded() UIView.animate(withDuration: animated ? 0.25 : 0, animations: { () -> Void in bar.show() self.view.layoutIfNeeded() }) } func removeBar(_ bar: SnackBar, animated: Bool) { if let _ = findSnackbar(bar) { UIView.animate(withDuration: animated ? 0.25 : 0, animations: { () -> Void in bar.hide() self.view.layoutIfNeeded() }, completion: { success in // Really remove the bar self.finishRemovingBar(bar) self.updateSnackBarConstraints() }) } } func removeAllBars() { let bars = snackBars.subviews for bar in bars { if let bar = bar as? SnackBar { bar.removeFromSuperview() } } self.updateSnackBarConstraints() } func tab(_ tab: Tab, didAddSnackbar bar: SnackBar) { showBar(bar, animated: true) } func tab(_ tab: Tab, didRemoveSnackbar bar: SnackBar) { removeBar(bar, animated: true) } func tab(_ tab: Tab, didSelectFindInPageForSelection selection: String) { updateFindInPageVisibility(visible: true) findInPageBar?.text = selection } } extension BrowserViewController: HomePanelViewControllerDelegate { func homePanelViewController(_ homePanelViewController: HomePanelViewController, didSelectURL url: URL, visitType: VisitType) { finishEditingAndSubmit(url, visitType: visitType) } func homePanelViewController(_ homePanelViewController: HomePanelViewController, didSelectPanel panel: Int) { if AboutUtils.isAboutHomeURL(tabManager.selectedTab?.url) { tabManager.selectedTab?.webView?.evaluateJavaScript("history.replaceState({}, '', '#panel=\(panel)')", completionHandler: nil) } } func homePanelViewControllerDidRequestToCreateAccount(_ homePanelViewController: HomePanelViewController) { presentSignInViewController() // TODO UX Right now the flow for sign in and create account is the same } func homePanelViewControllerDidRequestToSignIn(_ homePanelViewController: HomePanelViewController) { presentSignInViewController() // TODO UX Right now the flow for sign in and create account is the same } } extension BrowserViewController: SearchViewControllerDelegate { func searchViewController(_ searchViewController: SearchViewController, didSelectURL url: URL) { finishEditingAndSubmit(url, visitType: VisitType.Typed) } func presentSearchSettingsController() { let settingsNavigationController = SearchSettingsTableViewController() settingsNavigationController.model = self.profile.searchEngines let navController = UINavigationController(rootViewController: settingsNavigationController) self.present(navController, animated: true, completion: nil) } } extension BrowserViewController: TabManagerDelegate { func tabManager(_ tabManager: TabManager, didSelectedTabChange selected: Tab?, previous: Tab?) { // Remove the old accessibilityLabel. Since this webview shouldn't be visible, it doesn't need it // and having multiple views with the same label confuses tests. if let wv = previous?.webView { removeOpenInView() wv.endEditing(true) wv.accessibilityLabel = nil wv.accessibilityElementsHidden = true wv.accessibilityIdentifier = nil wv.removeFromSuperview() } if let tab = selected, let webView = tab.webView { updateURLBarDisplayURL(tab) TelemetryLogger.sharedInstance.updateForgetModeStatue(tab.isPrivate) if self.navigationController?.topViewController == self { if tab.isPrivate { readerModeCache = MemoryReaderModeCache.sharedInstance applyTheme(Theme.PrivateMode) } else { readerModeCache = DiskReaderModeCache.sharedInstance applyTheme(Theme.NormalMode) } } ReaderModeHandlers.readerModeCache = readerModeCache scrollController.tab = selected webViewContainer.addSubview(webView) webView.snp.makeConstraints { make in make.top.equalTo(webViewContainerToolbar.snp.bottom) make.left.right.bottom.equalTo(self.webViewContainer) } webView.accessibilityLabel = NSLocalizedString("Web content", comment: "Accessibility label for the main web content view") webView.accessibilityIdentifier = "contentView" webView.accessibilityElementsHidden = false #if CLIQZ // Cliqz: back and forward swipe for swipe in [historySwiper.goBackSwipe, historySwiper.goForwardSwipe] { tab.webView?.scrollView.panGestureRecognizer.require(toFail: swipe) } #endif if let url = webView.url?.absoluteString { // Don't bother fetching bookmark state for about/sessionrestore and about/home. if AboutUtils.isAboutURL(webView.url) { // Indeed, because we don't show the toolbar at all, don't even blank the star. } else { profile.bookmarks.modelFactory >>== { [weak tab] in $0.isBookmarked(url) .uponQueue(DispatchQueue.main) { guard let isBookmarked = $0.successValue else { log.error("Error getting bookmark status: \(String(describing: $0.failureValue)).") return } tab?.isBookmarked = isBookmarked if !AppConstants.MOZ_MENU { self.toolbar?.updateBookmarkStatus(isBookmarked) self.urlBar.updateBookmarkStatus(isBookmarked) } } } } } else { // The web view can go gray if it was zombified due to memory pressure. // When this happens, the URL is nil, so try restoring the page upon selection. tab.reload() } //Cliqz: update private mode in search view to notify JavaScript when switching between normal and private mode searchController?.updatePrivateMode(tab.isPrivate) homePanelController?.isForgetMode = tab.isPrivate } if let selected = selected, let previous = previous, selected.isPrivate != previous.isPrivate { updateTabCountUsingTabManager(tabManager) } removeAllBars() if let bars = selected?.bars { for bar in bars { showBar(bar, animated: true) } } updateFindInPageVisibility(visible: false) navigationToolbar.updateReloadStatus(selected?.loading ?? false) navigationToolbar.updateBackStatus(selected?.canGoBack ?? false) navigationToolbar.updateForwardStatus(selected?.canGoForward ?? false) self.urlBar.updateProgressBar(Float(selected?.estimatedProgress ?? 0)) if let readerMode = selected?.getHelper(ReaderMode.name()) as? ReaderMode { urlBar.updateReaderModeState(readerMode.state) if readerMode.state == .Active { showReaderModeBar(animated: false) } else { hideReaderModeBar(animated: false) } } else { urlBar.updateReaderModeState(ReaderModeState.Unavailable) } updateInContentHomePanel(selected?.url as URL?) } func tabManager(_ tabManager: TabManager, didCreateTab tab: Tab) { } func tabManager(_ tabManager: TabManager, didAddTab tab: Tab) { // If we are restoring tabs then we update the count once at the end if !tabManager.isRestoring { updateTabCountUsingTabManager(tabManager) } tab.tabDelegate = self tab.appStateDelegate = self } // Cliqz: Added removeIndex to didRemoveTab method // func tabManager(tabManager: TabManager, didRemoveTab tab: Tab) { func tabManager(_ tabManager: TabManager, didRemoveTab tab: Tab, removeIndex: Int) { updateTabCountUsingTabManager(tabManager) // tabDelegate is a weak ref (and the tab's webView may not be destroyed yet) // so we don't expcitly unset it. if let url = tab.url, !AboutUtils.isAboutURL(tab.url) && !tab.isPrivate { profile.recentlyClosedTabs.addTab(url, title: tab.title, faviconURL: tab.displayFavicon?.url) } hideNetworkActivitySpinner() } func tabManagerDidAddTabs(_ tabManager: TabManager) { updateTabCountUsingTabManager(tabManager) } func tabManagerDidRestoreTabs(_ tabManager: TabManager) { updateTabCountUsingTabManager(tabManager) } func tabManagerDidRemoveAllTabs(_ tabManager: TabManager, toast:ButtonToast?) { guard !tabTrayController.privateMode else { return } if let undoToast = toast { let time = DispatchTime(uptimeNanoseconds: DispatchTime.now().uptimeNanoseconds + UInt64(ButtonToastUX.ToastDelay * Double(NSEC_PER_SEC))) DispatchQueue.main.asyncAfter(deadline: time) { self.view.addSubview(undoToast) undoToast.snp.makeConstraints { make in make.left.right.equalTo(self.view) make.bottom.equalTo(self.webViewContainer) } undoToast.showToast() } } } fileprivate func updateTabCountUsingTabManager(_ tabManager: TabManager, animated: Bool = true) { if let selectedTab = tabManager.selectedTab { // Cliqz: Changes Tabs count on the Tabs button according to our requirements. Now we show all tabs count, no seperation between private/not private // let count = selectedTab.isPrivate ? tabManager.privateTabs.count : tabManager.normalTabs.count let count = tabManager.tabs.count urlBar.updateTabCount(max(count, 1), animated: animated) toolbar?.updateTabCount(max(count, 1)) } } } extension BrowserViewController: WKNavigationDelegate { func webView(_ webView: WKWebView, didStartProvisionalNavigation navigation: WKNavigation!) { if let containerWebView = webView as? ContainerWebView, tabManager.selectedTab?.webView !== containerWebView.legacyWebView { return } UIApplication.shared.isNetworkActivityIndicatorVisible = true updateFindInPageVisibility(visible: false) // If we are going to navigate to a new page, hide the reader mode button. Unless we // are going to a about:reader page. Then we keep it on screen: it will change status // (orange color) as soon as the page has loaded. if let url = webView.url { if !ReaderModeUtils.isReaderModeURL(url) { urlBar.updateReaderModeState(ReaderModeState.Unavailable) hideReaderModeBar(animated: false) } // remove the open in overlay view if it is present removeOpenInView() } } // Recognize an Apple Maps URL. This will trigger the native app. But only if a search query is present. Otherwise // it could just be a visit to a regular page on maps.apple.com. fileprivate func isAppleMapsURL(_ url: URL) -> Bool { if url.scheme == "http" || url.scheme == "https" { if url.host == "maps.apple.com" && url.query != nil { return true } } return false } // Recognize a iTunes Store URL. These all trigger the native apps. Note that appstore.com and phobos.apple.com // used to be in this list. I have removed them because they now redirect to itunes.apple.com. If we special case // them then iOS will actually first open Safari, which then redirects to the app store. This works but it will // leave a 'Back to Safari' button in the status bar, which we do not want. fileprivate func isStoreURL(_ url: URL) -> Bool { if url.scheme == "http" || url.scheme == "https" { if url.host == "itunes.apple.com" { return true } } return false } // This is the place where we decide what to do with a new navigation action. There are a number of special schemes // and http(s) urls that need to be handled in a different way. All the logic for that is inside this delegate // method. func webView(_ webView: WKWebView, decidePolicyFor navigationAction: WKNavigationAction, decisionHandler: @escaping (WKNavigationActionPolicy) -> Void) { guard let url = navigationAction.request.url else { decisionHandler(WKNavigationActionPolicy.cancel) return } // Fixes 1261457 - Rich text editor fails because requests to about:blank are blocked if url.scheme == "about" { decisionHandler(WKNavigationActionPolicy.allow) return } if !navigationAction.isAllowed && navigationAction.navigationType != .backForward { log.warning("Denying unprivileged request: \(navigationAction.request)") decisionHandler(WKNavigationActionPolicy.allow) return } //Cliqz: Navigation telemetry signal if url.absoluteString.range(of: "localhost") == nil { startNavigation(webView, navigationAction: navigationAction) } // First special case are some schemes that are about Calling. We prompt the user to confirm this action. This // gives us the exact same behaviour as Safari. if url.scheme == "tel" || url.scheme == "facetime" || url.scheme == "facetime-audio" { if let components = NSURLComponents(url: url, resolvingAgainstBaseURL: false), let phoneNumber = components.path, !phoneNumber.isEmpty { let formatter = PhoneNumberFormatter() let formattedPhoneNumber = formatter.formatPhoneNumber(phoneNumber) let alert = UIAlertController(title: formattedPhoneNumber, message: nil, preferredStyle: UIAlertControllerStyle.alert) alert.addAction(UIAlertAction(title: NSLocalizedString("Cancel", comment:"Label for Cancel button"), style: UIAlertActionStyle.cancel, handler: nil)) alert.addAction(UIAlertAction(title: NSLocalizedString("Call", comment:"Alert Call Button"), style: UIAlertActionStyle.default, handler: { (action: UIAlertAction!) in UIApplication.shared.openURL(url) })) present(alert, animated: true, completion: nil) } decisionHandler(WKNavigationActionPolicy.cancel) return } // Second special case are a set of URLs that look like regular http links, but should be handed over to iOS // instead of being loaded in the webview. Note that there is no point in calling canOpenURL() here, because // iOS will always say yes. TODO Is this the same as isWhitelisted? if isAppleMapsURL(url) || isStoreURL(url) { UIApplication.shared.openURL(url) decisionHandler(WKNavigationActionPolicy.cancel) return } // Cliqz: display AntiPhishing Alert to warn the user of in case of anti-phishing website // Cliqz: (Tim) - Antiphising should only check the mainDocumentURL. if navigationAction.request.mainDocumentURL == url, let host = url.host { AntiPhishingDetector.isPhishingURL(url) { (isPhishingSite) in if isPhishingSite { self.showAntiPhishingAlert(host) } } } // This is the normal case, opening a http or https url, which we handle by loading them in this WKWebView. We // always allow this. if url.scheme == "http" || url.scheme == "https" { // Cliqz: Added handling for back/forward functionality if url.absoluteString.contains("cliqz/goto.html") { if let q = url.query { let comp = q.components(separatedBy: "=") if comp.count == 2 { webView.goBack() let query = comp[1].removingPercentEncoding! self.urlBar.enterOverlayMode(query, pasted: true) } } self.urlBar.currentURL = nil decisionHandler(WKNavigationActionPolicy.allow) } else if navigationAction.navigationType == .linkActivated { resetSpoofedUserAgentIfRequired(webView, newURL: url) } else if navigationAction.navigationType == .backForward { restoreSpoofedUserAgentIfRequired(webView, newRequest: navigationAction.request) } decisionHandler(WKNavigationActionPolicy.allow) return } // Default to calling openURL(). What this does depends on the iOS version. On iOS 8, it will just work without // prompting. On iOS9, depending on the scheme, iOS will prompt: "Firefox" wants to open "Twitter". It will ask // every time. There is no way around this prompt. (TODO Confirm this is true by adding them to the Info.plist) UIApplication.shared.openURL(url) decisionHandler(WKNavigationActionPolicy.cancel) } func webView(_ webView: WKWebView, didReceive challenge: URLAuthenticationChallenge, completionHandler: @escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Void) { // If this is a certificate challenge, see if the certificate has previously been // accepted by the user. let origin = "\(challenge.protectionSpace.host):\(challenge.protectionSpace.port)" if challenge.protectionSpace.authenticationMethod == NSURLAuthenticationMethodServerTrust, let trust = challenge.protectionSpace.serverTrust, let cert = SecTrustGetCertificateAtIndex(trust, 0), profile.certStore.containsCertificate(cert, forOrigin: origin) { completionHandler(URLSession.AuthChallengeDisposition.useCredential, URLCredential(trust: trust)) return } guard challenge.protectionSpace.authenticationMethod == NSURLAuthenticationMethodHTTPBasic || challenge.protectionSpace.authenticationMethod == NSURLAuthenticationMethodHTTPDigest || challenge.protectionSpace.authenticationMethod == NSURLAuthenticationMethodNTLM, let tab = tabManager[webView] else { completionHandler(URLSession.AuthChallengeDisposition.performDefaultHandling, nil) return } // The challenge may come from a background tab, so ensure it's the one visible. tabManager.selectTab(tab) let loginsHelper = tab.getHelper(LoginsHelper.name()) as? LoginsHelper Authenticator.handleAuthRequest(self, challenge: challenge, loginsHelper: loginsHelper).uponQueue(DispatchQueue.main) { res in if let credentials = res.successValue { completionHandler(.useCredential, credentials.credentials) } else { completionHandler(URLSession.AuthChallengeDisposition.rejectProtectionSpace, nil) } } } func webView(_ _webView: WKWebView, didCommit navigation: WKNavigation!) { #if CLIQZ guard let container = _webView as? ContainerWebView else { return } guard let webView = container.legacyWebView else { return } guard let tab = tabManager.tabForWebView(webView) else { return } #else guard let tab = tabManager[webView] else { return } #endif tab.url = webView.url if tabManager.selectedTab === tab { updateUIForReaderHomeStateForTab(tab) appDidUpdateState(getCurrentAppState()) } } func webView(_ _webView: WKWebView, didFinish navigation: WKNavigation!) { #if CLIQZ guard let container = _webView as? ContainerWebView else { return } guard let webView = container.legacyWebView else { return } guard let tab = tabManager.tabForWebView(webView) else { return } #else let tab: Tab! = tabManager[webView] #endif hideNetworkActivitySpinner() tabManager.expireSnackbars() if let url = webView.url, !ErrorPageHelper.isErrorPageURL(url) && !AboutUtils.isAboutHomeURL(url) { tab.lastExecutedTime = Date.now() if navigation == nil { log.warning("Implicitly unwrapped optional navigation was nil.") } // Cliqz: prevented adding all 4XX & 5XX urls to local history // postLocationChangeNotificationForTab(tab, navigation: navigation) if currentResponseStatusCode < 400 { postLocationChangeNotificationForTab(tab, navigation: navigation) } // Fire the readability check. This is here and not in the pageShow event handler in ReaderMode.js anymore // because that event wil not always fire due to unreliable page caching. This will either let us know that // the currently loaded page can be turned into reading mode or if the page already is in reading mode. We // ignore the result because we are being called back asynchronous when the readermode status changes. webView.evaluateJavaScript("_firefox_ReaderMode.checkReadability()", completionHandler: nil) // Cliqz: update the url bar and home panel to fix the problem of opening url fron either notification of widget while the app is not running updateURLBarDisplayURL(tab) updateInContentHomePanel(tab.url as URL?) } if tab === tabManager.selectedTab { UIAccessibilityPostNotification(UIAccessibilityScreenChangedNotification, nil) // must be followed by LayoutChanged, as ScreenChanged will make VoiceOver // cursor land on the correct initial element, but if not followed by LayoutChanged, // VoiceOver will sometimes be stuck on the element, not allowing user to move // forward/backward. Strange, but LayoutChanged fixes that. UIAccessibilityPostNotification(UIAccessibilityLayoutChangedNotification, nil) } else { // To Screenshot a tab that is hidden we must add the webView, // then wait enough time for the webview to render. if let webView = tab.webView { view.insertSubview(webView, at: 0) let time = DispatchTime.now() + Double(Int64(500 * NSEC_PER_MSEC)) / Double(NSEC_PER_SEC) DispatchQueue.main.asyncAfter(deadline: time) { self.screenshotHelper.takeScreenshot(tab) if webView.superview == self.view { webView.removeFromSuperview() } } } } //Cliqz: Navigation telemetry signal if webView.url?.absoluteString.range(of: "localhost") == nil { finishNavigation(webView) } // Cliqz: save last visited website for 3D touch action saveLastVisitedWebSite() // Remember whether or not a desktop site was requested if #available(iOS 9.0, *) { tab.desktopSite = webView.customUserAgent?.isEmpty == false } //Cliqz: store changes of tabs if let url = tab.url, !tab.isPrivate { if !ErrorPageHelper.isErrorPageURL(url) { self.tabManager.storeChanges() } } } #if CLIQZ func webView(_ _webView: WKWebView, didFail navigation: WKNavigation!, withError error: Error) { guard let container = _webView as? ContainerWebView else { return } guard let webView = container.legacyWebView else { return } guard let tab = tabManager.tabForWebView(webView) else { return } hideNetworkActivitySpinner() // Ignore the "Frame load interrupted" error that is triggered when we cancel a request // to open an external application and hand it over to UIApplication.openURL(). The result // will be that we switch to the external app, for example the app store, while keeping the // original web page in the tab instead of replacing it with an error page. let error = error as NSError if error.domain == "WebKitErrorDomain" && error.code == 102 { return } if error.code == Int(CFNetworkErrors.cfurlErrorCancelled.rawValue) { if tab === tabManager.selectedTab { urlBar.currentURL = tab.displayURL } return } if let url = error.userInfo[NSURLErrorFailingURLErrorKey] as? URL { ErrorPageHelper().showPage(error, forUrl: url, inWebView: webView) } } #endif fileprivate func addViewForOpenInHelper(_ openInHelper: OpenInHelper) { guard let view = openInHelper.openInView else { return } webViewContainerToolbar.addSubview(view) webViewContainerToolbar.snp_updateConstraints { make in make.height.equalTo(OpenInViewUX.ViewHeight) } view.snp.makeConstraints { make in make.edges.equalTo(webViewContainerToolbar) } self.openInHelper = openInHelper } fileprivate func removeOpenInView() { guard let _ = self.openInHelper else { return } webViewContainerToolbar.subviews.forEach { $0.removeFromSuperview() } webViewContainerToolbar.snp_updateConstraints { make in make.height.equalTo(0) } self.openInHelper = nil } fileprivate func postLocationChangeNotificationForTab(_ tab: Tab, navigation: WKNavigation?) { guard let tabUrl = tab.displayURL, !isTrampolineURL(tabUrl) else { return } let notificationCenter = NotificationCenter.default var info = [AnyHashable: Any]() info["url"] = tab.displayURL info["title"] = tab.title if let visitType = self.getVisitTypeForTab(tab, navigation: navigation)?.rawValue { info["visitType"] = visitType } info["isPrivate"] = tab.isPrivate if let query = tab.query { info["query"] = query.trim().escape() tab.query = nil } notificationCenter.post(name: NotificationOnLocationChange, object: self, userInfo: info) } } /// List of schemes that are allowed to open a popup window private let SchemesAllowedToOpenPopups = ["http", "https", "javascript", "data"] extension BrowserViewController: WKUIDelegate { func webView(_ webView: WKWebView, createWebViewWith configuration: WKWebViewConfiguration, for navigationAction: WKNavigationAction, windowFeatures: WKWindowFeatures) -> WKWebView? { guard let currentTab = tabManager.selectedTab else { return nil } if !navigationAction.isAllowed { log.warning("Denying unprivileged request: \(navigationAction.request)") return nil } screenshotHelper.takeScreenshot(currentTab) // If the page uses window.open() or target="_blank", open the page in a new tab. // TODO: This doesn't work for window.open() without user action (bug 1124942). let newTab: Tab if #available(iOS 9, *) { newTab = tabManager.addTab(navigationAction.request, configuration: configuration, isPrivate: currentTab.isPrivate) } else { newTab = tabManager.addTab(navigationAction.request, configuration: configuration) } tabManager.selectTab(newTab) // If the page we just opened has a bad scheme, we return nil here so that JavaScript does not // get a reference to it which it can return from window.open() - this will end up as a // CFErrorHTTPBadURL being presented. guard let scheme = (navigationAction.request as NSURLRequest).url?.scheme!.lowercased(), SchemesAllowedToOpenPopups.contains(scheme) else { return nil } return webView } fileprivate func canDisplayJSAlertForWebView(_ webView: WKWebView) -> Bool { // Only display a JS Alert if we are selected and there isn't anything being shown return (tabManager.selectedTab == nil ? false : tabManager.selectedTab!.webView == webView) && (self.presentedViewController == nil) } func webView(_ webView: WKWebView, runJavaScriptAlertPanelWithMessage message: String, initiatedByFrame frame: WKFrameInfo, completionHandler: @escaping () -> Void) { let messageAlert = MessageAlert(message: message, frame: frame, completionHandler: completionHandler) if canDisplayJSAlertForWebView(webView) { present(messageAlert.alertController(), animated: true, completion: nil) } else if let promptingTab = tabManager[webView] { promptingTab.queueJavascriptAlertPrompt(messageAlert) } else { // This should never happen since an alert needs to come from a web view but just in case call the handler // since not calling it will result in a runtime exception. completionHandler() } } func webView(_ webView: WKWebView, runJavaScriptConfirmPanelWithMessage message: String, initiatedByFrame frame: WKFrameInfo, completionHandler: @escaping (Bool) -> Void) { let confirmAlert = ConfirmPanelAlert(message: message, frame: frame, completionHandler: completionHandler) if canDisplayJSAlertForWebView(webView) { present(confirmAlert.alertController(), animated: true, completion: nil) } else if let promptingTab = tabManager[webView] { promptingTab.queueJavascriptAlertPrompt(confirmAlert) } else { completionHandler(false) } } func webView(_ webView: WKWebView, runJavaScriptTextInputPanelWithPrompt prompt: String, defaultText: String?, initiatedByFrame frame: WKFrameInfo, completionHandler: @escaping (String?) -> Void) { let textInputAlert = TextInputAlert(message: prompt, frame: frame, completionHandler: completionHandler, defaultText: defaultText) if canDisplayJSAlertForWebView(webView) { present(textInputAlert.alertController(), animated: true, completion: nil) } else if let promptingTab = tabManager[webView] { promptingTab.queueJavascriptAlertPrompt(textInputAlert) } else { completionHandler(nil) } } /// Invoked when an error occurs while starting to load data for the main frame. func webView(_ webView: WKWebView, didFailProvisionalNavigation navigation: WKNavigation!, withError error: Error) { // Cliqz: [UIWebView] use the UIWebView to display the error page #if CLIQZ guard let container = webView as? ContainerWebView else { return } guard let cliqzWebView = container.legacyWebView else { return } #endif // Ignore the "Frame load interrupted" error that is triggered when we cancel a request // to open an external application and hand it over to UIApplication.openURL(). The result // will be that we switch to the external app, for example the app store, while keeping the // original web page in the tab instead of replacing it with an error page. let error = error as NSError if error.domain == "WebKitErrorDomain" && error.code == 102 { return } // Cliqz: [UIWebView] use cliqz webview instead of the WKWebView to check if the web content is creashed if checkIfWebContentProcessHasCrashed(cliqzWebView, error: error) { return } if error._code == Int(CFNetworkErrors.cfurlErrorCancelled.rawValue) { #if Cliqz if let tab = tabManager.tabForWebView(cliqzWebView), tab === tabManager.selectedTab { urlBar.currentURL = tab.displayURL } #else if let tab = tabManager[webView], tab === tabManager.selectedTab { urlBar.currentURL = tab.displayURL } #endif return } if let url = (error as NSError).userInfo[NSURLErrorFailingURLErrorKey] as? URL { // Cliqz: [UIWebView] use cliqz webview instead of the WKWebView for displaying the error page // ErrorPageHelper().showPage(error, forUrl: url, inWebView: WebView) ErrorPageHelper().showPage(error, forUrl: url, inWebView: cliqzWebView) // If the local web server isn't working for some reason (Firefox cellular data is // disabled in settings, for example), we'll fail to load the session restore URL. // We rely on loading that page to get the restore callback to reset the restoring // flag, so if we fail to load that page, reset it here. if AboutUtils.getAboutComponent(url) == "sessionrestore" { tabManager.tabs.filter { $0.webView == webView }.first?.restoring = false } } } // Cliqz: [UIWebView] change type // private func checkIfWebContentProcessHasCrashed(webView: WKWebView, error: NSError) -> Bool { fileprivate func checkIfWebContentProcessHasCrashed(_ webView: CliqzWebView, error: NSError) -> Bool { if error.code == WKError.webContentProcessTerminated.rawValue && error.domain == "WebKitErrorDomain" { log.debug("WebContent process has crashed. Trying to reloadFromOrigin to restart it.") webView.reloadFromOrigin() return true } return false } func webView(_ webView: WKWebView, decidePolicyFor navigationResponse: WKNavigationResponse, decisionHandler: @escaping (WKNavigationResponsePolicy) -> Void) { // Cliqz: get the response code of the current response from the navigationResponse if let response = navigationResponse.response as? HTTPURLResponse { currentResponseStatusCode = response.statusCode } let helperForURL = OpenIn.helperForResponse(response: navigationResponse.response) if navigationResponse.canShowMIMEType { if let openInHelper = helperForURL { addViewForOpenInHelper(openInHelper) } decisionHandler(WKNavigationResponsePolicy.allow) return } guard let openInHelper = helperForURL else { let error = NSError(domain: ErrorPageHelper.MozDomain, code: Int(ErrorPageHelper.MozErrorDownloadsNotEnabled), userInfo: [NSLocalizedDescriptionKey: Strings.UnableToDownloadError]) // Cliqz: [UIWebView] use cliqz webview instead of the WKWebView for displaying the error page #if Cliqz // ErrorPageHelper().showPage(error, forUrl: navigationResponse.response.URL!, inWebView: webView) let container = webView as? ContainerWebView let cliqzWebView = container.legacyWebView ErrorPageHelper().showPage(error, forUrl: navigationResponse.response.url!, inWebView: cliqzWebView) #endif return decisionHandler(WKNavigationResponsePolicy.allow) } openInHelper.open() decisionHandler(WKNavigationResponsePolicy.cancel) } @available(iOS 9, *) func webViewDidClose(_ webView: WKWebView) { if let tab = tabManager[webView] { self.tabManager.removeTab(tab) } } } extension BrowserViewController: ReaderModeDelegate { func readerMode(_ readerMode: ReaderMode, didChangeReaderModeState state: ReaderModeState, forTab tab: Tab) { // If this reader mode availability state change is for the tab that we currently show, then update // the button. Otherwise do nothing and the button will be updated when the tab is made active. if tabManager.selectedTab === tab { urlBar.updateReaderModeState(state) // Cliqz:[UIWebView] explictly call configure reader mode as it is not called from JavaScript because of replacing WKWebView if state == .Active { tab.webView!.evaluateJavaScript("_firefox_ReaderMode.configureReader()", completionHandler: nil) } } } func readerMode(_ readerMode: ReaderMode, didDisplayReaderizedContentForTab tab: Tab) { self.showReaderModeBar(animated: true) tab.showContent(true) } } // MARK: - UIPopoverPresentationControllerDelegate extension BrowserViewController: UIPopoverPresentationControllerDelegate { func popoverPresentationControllerDidDismissPopover(_ popoverPresentationController: UIPopoverPresentationController) { displayedPopoverController = nil updateDisplayedPopoverProperties = nil } } extension BrowserViewController: UIAdaptivePresentationControllerDelegate { // Returning None here makes sure that the Popover is actually presented as a Popover and // not as a full-screen modal, which is the default on compact device classes. func adaptivePresentationStyle(for controller: UIPresentationController, traitCollection: UITraitCollection) -> UIModalPresentationStyle { return UIModalPresentationStyle.none } } // MARK: - ReaderModeStyleViewControllerDelegate extension BrowserViewController: ReaderModeStyleViewControllerDelegate { func readerModeStyleViewController(_ readerModeStyleViewController: ReaderModeStyleViewController, didConfigureStyle style: ReaderModeStyle) { // Persist the new style to the profile let encodedStyle: [String:Any] = style.encodeAsDictionary() profile.prefs.setObject(encodedStyle, forKey: ReaderModeProfileKeyStyle) // Change the reader mode style on all tabs that have reader mode active for tabIndex in 0..<tabManager.count { if let tab = tabManager[tabIndex] { if let readerMode = tab.getHelper("ReaderMode") as? ReaderMode { if readerMode.state == ReaderModeState.Active { readerMode.style = style } } } } } } extension BrowserViewController { func updateReaderModeBar() { if let readerModeBar = readerModeBar { if let tab = self.tabManager.selectedTab, tab.isPrivate { readerModeBar.applyTheme(Theme.PrivateMode) } else { readerModeBar.applyTheme(Theme.NormalMode) } if let url = self.tabManager.selectedTab?.displayURL?.absoluteString, let result = profile.readingList?.getRecordWithURL(url) { if let successValue = result.successValue, let record = successValue { readerModeBar.unread = record.unread readerModeBar.added = true } else { readerModeBar.unread = true readerModeBar.added = false } } else { readerModeBar.unread = true readerModeBar.added = false } } } func showReaderModeBar(animated: Bool) { if self.readerModeBar == nil { let readerModeBar = ReaderModeBarView(frame: CGRect.zero) readerModeBar.delegate = self view.insertSubview(readerModeBar, belowSubview: header) self.readerModeBar = readerModeBar } updateReaderModeBar() self.updateViewConstraints() } func hideReaderModeBar(animated: Bool) { if let readerModeBar = self.readerModeBar { readerModeBar.removeFromSuperview() self.readerModeBar = nil self.updateViewConstraints() } } /// There are two ways we can enable reader mode. In the simplest case we open a URL to our internal reader mode /// and be done with it. In the more complicated case, reader mode was already open for this page and we simply /// navigated away from it. So we look to the left and right in the BackForwardList to see if a readerized version /// of the current page is there. And if so, we go there. func enableReaderMode() { guard let tab = tabManager.selectedTab, let webView = tab.webView else { return } let backList = webView.backForwardList.backList let forwardList = webView.backForwardList.forwardList // Cliqz:[UIWebView] backForwardList are dummy and do not have any itmes at all #if CLIQZ guard let currentURL = webView.url, let readerModeURL = ReaderModeUtils.encodeURL(currentURL) else { return } #else guard let currentURL = webView.backForwardList.currentItem?.url, let readerModeURL = ReaderModeUtils.encodeURL(currentURL) else { return } #endif if backList.count > 1 && backList.last?.url == readerModeURL { webView.goToBackForwardListItem(item: backList.last!) } else if forwardList.count > 0 && forwardList.first?.url == readerModeURL { webView.goToBackForwardListItem(item: forwardList.first!) } else { // Store the readability result in the cache and load it. This will later move to the ReadabilityHelper. webView.evaluateJavaScript("\(ReaderModeNamespace).readerize()", completionHandler: { (object, error) -> Void in if let readabilityResult = ReadabilityResult(object: object) { do { try self.readerModeCache.put(currentURL, readabilityResult) } catch _ { } // Cliqz:[UIWebView] Replaced load request with ours which doesn't return WKNavigation #if CLIQZ webView.loadRequest(PrivilegedRequest(url: readerModeURL) as URLRequest) #else if let nav = webView.loadRequest(PrivilegedRequest(url: readerModeURL) as URLRequest) { self.ignoreNavigationInTab(tab, navigation: nav) } #endif } }) } } /// Disabling reader mode can mean two things. In the simplest case we were opened from the reading list, which /// means that there is nothing in the BackForwardList except the internal url for the reader mode page. In that /// case we simply open a new page with the original url. In the more complicated page, the non-readerized version /// of the page is either to the left or right in the BackForwardList. If that is the case, we navigate there. func disableReaderMode() { if let tab = tabManager.selectedTab, let webView = tab.webView { let backList = webView.backForwardList.backList let forwardList = webView.backForwardList.forwardList // Cliqz:[UIWebView] backForwardList are dummy and do not have any itmes at all // if let currentURL = webView.backForwardList.currentItem?.URL { if let currentURL = webView.url { if let originalURL = ReaderModeUtils.decodeURL(currentURL) { if backList.count > 1 && backList.last?.url == originalURL { webView.goToBackForwardListItem(item: backList.last!) } else if forwardList.count > 0 && forwardList.first?.url == originalURL { webView.goToBackForwardListItem(item: forwardList.first!) } else { // Cliqz:[UIWebView] Replaced load request with ours which doesn't return WKNavigation #if CLIQZ webView.loadRequest(URLRequest(url: originalURL)) #else if let nav = webView.loadRequest(URLRequest(url: originalURL)) { self.ignoreNavigationInTab(tab, navigation: nav) } #endif } } } } } func SELDynamicFontChanged(_ notification: Notification) { guard notification.name == NotificationDynamicFontChanged else { return } var readerModeStyle = DefaultReaderModeStyle if let dict = profile.prefs.dictionaryForKey(ReaderModeProfileKeyStyle) { if let style = ReaderModeStyle(dict: dict) { readerModeStyle = style } } readerModeStyle.fontSize = ReaderModeFontSize.defaultSize self.readerModeStyleViewController(ReaderModeStyleViewController(), didConfigureStyle: readerModeStyle) } } extension BrowserViewController: ReaderModeBarViewDelegate { func readerModeBar(_ readerModeBar: ReaderModeBarView, didSelectButton buttonType: ReaderModeBarButtonType) { switch buttonType { case .settings: if let readerMode = tabManager.selectedTab?.getHelper("ReaderMode") as? ReaderMode, readerMode.state == ReaderModeState.Active { var readerModeStyle = DefaultReaderModeStyle if let dict = profile.prefs.dictionaryForKey(ReaderModeProfileKeyStyle) { if let style = ReaderModeStyle(dict: dict) { readerModeStyle = style } } let readerModeStyleViewController = ReaderModeStyleViewController() readerModeStyleViewController.delegate = self readerModeStyleViewController.readerModeStyle = readerModeStyle readerModeStyleViewController.modalPresentationStyle = UIModalPresentationStyle.popover let setupPopover = { [unowned self] in if let popoverPresentationController = readerModeStyleViewController.popoverPresentationController { popoverPresentationController.backgroundColor = UIColor.white popoverPresentationController.delegate = self popoverPresentationController.sourceView = readerModeBar popoverPresentationController.sourceRect = CGRect(x: readerModeBar.frame.width/2, y: UIConstants.ToolbarHeight, width: 1, height: 1) popoverPresentationController.permittedArrowDirections = UIPopoverArrowDirection.up } } setupPopover() if readerModeStyleViewController.popoverPresentationController != nil { displayedPopoverController = readerModeStyleViewController updateDisplayedPopoverProperties = setupPopover } self.present(readerModeStyleViewController, animated: true, completion: nil) } case .markAsRead: if let url = self.tabManager.selectedTab?.displayURL?.absoluteString, let result = profile.readingList?.getRecordWithURL(url) { if let successValue = result.successValue, let record = successValue { profile.readingList?.updateRecord(record, unread: false) // TODO Check result, can this fail? readerModeBar.unread = false } } case .markAsUnread: if let url = self.tabManager.selectedTab?.displayURL?.absoluteString, let result = profile.readingList?.getRecordWithURL(url) { if let successValue = result.successValue, let record = successValue { profile.readingList?.updateRecord(record, unread: true) // TODO Check result, can this fail? readerModeBar.unread = true } } case .addToReadingList: if let tab = tabManager.selectedTab, let url = tab.url, ReaderModeUtils.isReaderModeURL(url) { if let url = ReaderModeUtils.decodeURL(url) { profile.readingList?.createRecordWithURL(url.absoluteString, title: tab.title ?? "", addedBy: UIDevice.current.name) // TODO Check result, can this fail? readerModeBar.added = true readerModeBar.unread = true } } case .removeFromReadingList: if let url = self.tabManager.selectedTab?.displayURL?.absoluteString, let result = profile.readingList?.getRecordWithURL(url) { if let successValue = result.successValue, let record = successValue { profile.readingList?.deleteRecord(record) // TODO Check result, can this fail? readerModeBar.added = false readerModeBar.unread = false } } } } } extension BrowserViewController: IntroViewControllerDelegate { func presentIntroViewController(_ force: Bool = false) -> Bool{ if force || profile.prefs.intForKey(IntroViewControllerSeenProfileKey) == nil { let introViewController = IntroViewController() introViewController.delegate = self // On iPad we present it modally in a controller if UIDevice.current.userInterfaceIdiom == .pad { introViewController.preferredContentSize = CGSize(width: IntroViewControllerUX.Width, height: IntroViewControllerUX.Height) introViewController.modalPresentationStyle = UIModalPresentationStyle.formSheet } present(introViewController, animated: true) { self.profile.prefs.setInt(1, forKey: IntroViewControllerSeenProfileKey) } return true } return false } func introViewControllerDidFinish() { // Cliqz: focus on the search bar after dimissing on-boarding if it is on home view if urlBar.currentURL == nil || AboutUtils.isAboutHomeURL(urlBar.currentURL) { self.urlBar.enterOverlayMode("", pasted: false) } } func presentSignInViewController() { // Show the settings page if we have already signed in. If we haven't then show the signin page let vcToPresent: UIViewController if profile.hasAccount() { let settingsTableViewController = AppSettingsTableViewController() settingsTableViewController.profile = profile settingsTableViewController.tabManager = tabManager vcToPresent = settingsTableViewController } else { let signInVC = FxAContentViewController() signInVC.delegate = self signInVC.url = profile.accountConfiguration.signInURL signInVC.navigationItem.leftBarButtonItem = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.cancel, target: self, action: #selector(BrowserViewController.dismissSignInViewController)) vcToPresent = signInVC } let settingsNavigationController = SettingsNavigationController(rootViewController: vcToPresent) settingsNavigationController.modalPresentationStyle = .formSheet self.present(settingsNavigationController, animated: true, completion: nil) } func dismissSignInViewController() { self.dismiss(animated: true, completion: nil) } func introViewControllerDidRequestToLogin(_ introViewController: IntroViewController) { introViewController.dismiss(animated: true, completion: { () -> Void in self.presentSignInViewController() }) } } extension BrowserViewController: FxAContentViewControllerDelegate { func contentViewControllerDidSignIn(_ viewController: FxAContentViewController, data: JSON) -> Void { if data["keyFetchToken"].string == nil || data["unwrapBKey"].string == nil { // The /settings endpoint sends a partial "login"; ignore it entirely. log.debug("Ignoring didSignIn with keyFetchToken or unwrapBKey missing.") return } // TODO: Error handling. let account = FirefoxAccount.from(profile.accountConfiguration, andJSON: data)! profile.setAccount(account) if let account = self.profile.getAccount() { account.advance() } self.dismiss(animated: true, completion: nil) } func contentViewControllerDidCancel(_ viewController: FxAContentViewController) { log.info("Did cancel out of FxA signin") self.dismiss(animated: true, completion: nil) } } extension BrowserViewController: ContextMenuHelperDelegate { func contextMenuHelper(_ contextMenuHelper: ContextMenuHelper, didLongPressElements elements: ContextMenuHelper.Elements, gestureRecognizer: UILongPressGestureRecognizer) { // locationInView can return (0, 0) when the long press is triggered in an invalid page // state (e.g., long pressing a link before the document changes, then releasing after a // different page loads). // Cliqz: Moved the code to `showContextMenu` as it is now called from `CliqzContextMenu` which does not use `ContextMenuHelper` object } // Cliqz: called from `CliqzContextMenu` when long press is detected func showContextMenu(elements: ContextMenuHelper.Elements, touchPoint: CGPoint) { let touchSize = CGSize(width: 0, height: 16) let actionSheetController = UIAlertController(title: nil, message: nil, preferredStyle: UIAlertControllerStyle.actionSheet) var dialogTitle: String? let telemetryView = getTelemetryView(elements.link) if let url = elements.link, let currentTab = tabManager.selectedTab { dialogTitle = url.absoluteString let isPrivate = currentTab.isPrivate if !isPrivate { let newTabTitle = NSLocalizedString("Open In New Tab", comment: "Context menu item for opening a link in a new tab") let openNewTabAction = UIAlertAction(title: newTabTitle, style: UIAlertActionStyle.default) { (action: UIAlertAction) in self.scrollController.showToolbars(!self.scrollController.toolbarsShowing, completion: { _ in self.tabManager.addTab(URLRequest(url: url as URL)) TelemetryLogger.sharedInstance.logEvent(.ContextMenu("new_tab", telemetryView, nil)) }) } actionSheetController.addAction(openNewTabAction) } if #available(iOS 9, *) { // Cliqz: changed localized string for open in new private tab option to open in froget mode tab // let openNewPrivateTabTitle = NSLocalizedString("Open In New Private Tab", tableName: "PrivateBrowsing", comment: "Context menu option for opening a link in a new private tab") let openNewPrivateTabTitle = NSLocalizedString("Open In New Forget Tab", tableName: "Cliqz", comment: "Context menu option for opening a link in a new private tab") let openNewPrivateTabAction = UIAlertAction(title: openNewPrivateTabTitle, style: UIAlertActionStyle.default) { (action: UIAlertAction) in self.scrollController.showToolbars(!self.scrollController.toolbarsShowing, completion: { _ in TelemetryLogger.sharedInstance.logEvent(.ContextMenu("new_forget_tab", telemetryView, nil)) self.tabManager.addTab(URLRequest(url: url as URL), isPrivate: true) }) } actionSheetController.addAction(openNewPrivateTabAction) } // Cliqz: Added Action handler for the long press to download Youtube videos if YoutubeVideoDownloader.isYoutubeURL(url) { let downloadVideoTitle = NSLocalizedString("Download youtube video", tableName: "Cliqz", comment: "Context menu item for opening a link in a new tab") let downloadVideo = UIAlertAction(title: downloadVideoTitle, style: UIAlertActionStyle.default) { (action: UIAlertAction) in self.downloadVideoFromURL(dialogTitle!, sourceRect: CGRect(origin: touchPoint, size: touchSize)) TelemetryLogger.sharedInstance.logEvent(.ContextMenu("download_video", telemetryView, nil)) } actionSheetController.addAction(downloadVideo) } let copyTitle = NSLocalizedString("Copy Link", comment: "Context menu item for copying a link URL to the clipboard") let copyAction = UIAlertAction(title: copyTitle, style: UIAlertActionStyle.default) { (action: UIAlertAction) -> Void in let pasteBoard = UIPasteboard.general pasteBoard.url = url as URL TelemetryLogger.sharedInstance.logEvent(.ContextMenu("copy", telemetryView, nil)) } actionSheetController.addAction(copyAction) let shareTitle = NSLocalizedString("Share Link", comment: "Context menu item for sharing a link URL") let shareAction = UIAlertAction(title: shareTitle, style: UIAlertActionStyle.default) { _ in self.presentActivityViewController(url as URL, sourceView: self.view, sourceRect: CGRect(origin: touchPoint, size: touchSize), arrowDirection: .any) TelemetryLogger.sharedInstance.logEvent(.ContextMenu("share", telemetryView, nil)) } actionSheetController.addAction(shareAction) } if let url = elements.image { if dialogTitle == nil { dialogTitle = url.absoluteString } let photoAuthorizeStatus = PHPhotoLibrary.authorizationStatus() let saveImageTitle = NSLocalizedString("Save Image", comment: "Context menu item for saving an image") let saveImageAction = UIAlertAction(title: saveImageTitle, style: UIAlertActionStyle.default) { (action: UIAlertAction) -> Void in if photoAuthorizeStatus == PHAuthorizationStatus.authorized || photoAuthorizeStatus == PHAuthorizationStatus.notDetermined { self.getImage(url as URL) { UIImageWriteToSavedPhotosAlbum($0, nil, nil, nil) } TelemetryLogger.sharedInstance.logEvent(.ContextMenu("save", "image", nil)) } else { //TODO: provide our own wording if the app is not authorized to save photos to device // let accessDenied = UIAlertController(title: NSLocalizedString("Firefox would like to access your Photos", comment: "See http://mzl.la/1G7uHo7"), message: NSLocalizedString("This allows you to save the image to your Camera Roll.", comment: "See http://mzl.la/1G7uHo7"), preferredStyle: UIAlertControllerStyle.alert) // let dismissAction = UIAlertAction(title: UIConstants.CancelString, style: UIAlertActionStyle.default, handler: nil) // accessDenied.addAction(dismissAction) // let settingsAction = UIAlertAction(title: NSLocalizedString("Open Settings", comment: "See http://mzl.la/1G7uHo7"), style: UIAlertActionStyle.default ) { (action: UIAlertAction!) -> Void in // UIApplication.shared.openURL(URL(string: UIApplicationOpenSettingsURLString)!) // } // accessDenied.addAction(settingsAction) // self.present(accessDenied, animated: true, completion: nil) } } actionSheetController.addAction(saveImageAction) let copyImageTitle = NSLocalizedString("Copy Image", comment: "Context menu item for copying an image to the clipboard") let copyAction = UIAlertAction(title: copyImageTitle, style: UIAlertActionStyle.default) { (action: UIAlertAction) -> Void in // put the actual image on the clipboard // do this asynchronously just in case we're in a low bandwidth situation let pasteboard = UIPasteboard.general pasteboard.url = url as URL let changeCount = pasteboard.changeCount let application = UIApplication.shared var taskId: UIBackgroundTaskIdentifier = 0 taskId = application.beginBackgroundTask (expirationHandler: { _ in application.endBackgroundTask(taskId) }) Alamofire.request(url, method: .get) .validate(statusCode: 200..<300) .response { response in // Only set the image onto the pasteboard if the pasteboard hasn't changed since // fetching the image; otherwise, in low-bandwidth situations, // we might be overwriting something that the user has subsequently added. if changeCount == pasteboard.changeCount, let imageData = response.data, response.error == nil { pasteboard.addImageWithData(imageData, forURL: url) } application.endBackgroundTask(taskId) } TelemetryLogger.sharedInstance.logEvent(.ContextMenu("copy", "image", nil)) } actionSheetController.addAction(copyAction) } // If we're showing an arrow popup, set the anchor to the long press location. if let popoverPresentationController = actionSheetController.popoverPresentationController { popoverPresentationController.sourceView = view popoverPresentationController.sourceRect = CGRect(origin: touchPoint, size: touchSize) popoverPresentationController.permittedArrowDirections = .any } actionSheetController.title = dialogTitle?.ellipsize(maxLength: ActionSheetTitleMaxLength) let cancelAction = UIAlertAction(title: UIConstants.CancelString, style: UIAlertActionStyle.cancel){ (action: UIAlertAction) -> Void in TelemetryLogger.sharedInstance.logEvent(.ContextMenu("cancel", telemetryView, nil)) } actionSheetController.addAction(cancelAction) self.present(actionSheetController, animated: true, completion: nil) } private func getTelemetryView(_ url: URL?) -> String { guard let url = url else {return "image"} return YoutubeVideoDownloader.isYoutubeURL(url) ? "video" : "link" } fileprivate func getImage(_ url: URL, success: @escaping (UIImage) -> ()) { Alamofire.request(url, method: .get) .validate(statusCode: 200..<300) .response { response in if let data = response.data, let image = UIImage.dataIsGIF(data) ? UIImage.imageFromGIFDataThreadSafe(data) : UIImage.imageFromDataThreadSafe(data) { success(image) } } } } /** A third party search engine Browser extension **/ extension BrowserViewController { // Cliqz:[UIWebView] Type change // func addCustomSearchButtonToWebView(webView: WKWebView) { func addCustomSearchButtonToWebView(_ webView: CliqzWebView) { //check if the search engine has already been added. let domain = webView.url?.domainURL().host let matches = self.profile.searchEngines.orderedEngines.filter {$0.shortName == domain} if !matches.isEmpty { self.customSearchEngineButton.tintColor = UIColor.gray self.customSearchEngineButton.isUserInteractionEnabled = false } else { self.customSearchEngineButton.tintColor = UIConstants.SystemBlueColor self.customSearchEngineButton.isUserInteractionEnabled = true } /* This is how we access hidden views in the WKContentView Using the public headers we can find the keyboard accessoryView which is not usually available. Specific values here are from the WKContentView headers. https://github.com/JaviSoto/iOS9-Runtime-Headers/blob/master/Frameworks/WebKit.framework/WKContentView.h */ guard let webContentView = UIView.findSubViewWithFirstResponder(webView) else { /* In some cases the URL bar can trigger the keyboard notification. In that case the webview isnt the first responder and a search button should not be added. */ return } guard let input = webContentView.perform(Selector("inputAccessoryView")), let inputView = input.takeUnretainedValue() as? UIInputView, let nextButton = inputView.value(forKey: "_nextItem") as? UIBarButtonItem, let nextButtonView = nextButton.value(forKey: "view") as? UIView else { //failed to find the inputView instead lets use the inputAssistant addCustomSearchButtonToInputAssistant(webContentView) return } inputView.addSubview(self.customSearchEngineButton) self.customSearchEngineButton.snp_remakeConstraints { make in make.leading.equalTo(nextButtonView.snp_trailing).offset(20) make.width.equalTo(inputView.snp_height) make.top.equalTo(nextButtonView.snp_top) make.height.equalTo(inputView.snp_height) } } /** This adds the customSearchButton to the inputAssistant for cases where the inputAccessoryView could not be found for example on the iPad where it does not exist. However this only works on iOS9 **/ func addCustomSearchButtonToInputAssistant(_ webContentView: UIView) { if #available(iOS 9.0, *) { guard customSearchBarButton == nil else { return //The searchButton is already on the keyboard } let inputAssistant = webContentView.inputAssistantItem let item = UIBarButtonItem(customView: customSearchEngineButton) customSearchBarButton = item inputAssistant.trailingBarButtonGroups.last?.barButtonItems.append(item) } } func addCustomSearchEngineForFocusedElement() { guard let webView = tabManager.selectedTab?.webView else { return } webView.evaluateJavaScript("__firefox__.searchQueryForField()") { (result, _) in guard let searchParams = result as? [String: String] else { //Javascript responded with an incorrectly formatted message. Show an error. let alert = ThirdPartySearchAlerts.failedToAddThirdPartySearch() self.present(alert, animated: true, completion: nil) return } self.addSearchEngine(searchParams) self.customSearchEngineButton.tintColor = UIColor.gray self.customSearchEngineButton.isUserInteractionEnabled = false } } func addSearchEngine(_ params: [String: String]) { guard let template = params["url"], template != "", let iconString = params["icon"], let iconURL = URL(string: iconString), let url = URL(string: template.addingPercentEncoding(withAllowedCharacters: CharacterSet.urlFragmentAllowed)!), let shortName = url.domainURL().host else { let alert = ThirdPartySearchAlerts.failedToAddThirdPartySearch() self.present(alert, animated: true, completion: nil) return } let alert = ThirdPartySearchAlerts.addThirdPartySearchEngine { alert in self.customSearchEngineButton.tintColor = UIColor.gray self.customSearchEngineButton.isUserInteractionEnabled = false SDWebImageManager.shared().downloadImage(with: iconURL, options: SDWebImageOptions.continueInBackground, progress: nil) { (image, error, cacheType, success, url) in guard image != nil else { let alert = ThirdPartySearchAlerts.failedToAddThirdPartySearch() self.present(alert, animated: true, completion: nil) return } self.profile.searchEngines.addSearchEngine(OpenSearchEngine(engineID: nil, shortName: shortName, image: image!, searchTemplate: template, suggestTemplate: nil, isCustomEngine: true)) let Toast = SimpleToast() Toast.showAlertWithText(Strings.ThirdPartySearchEngineAdded) } } self.present(alert, animated: true, completion: {}) } } extension BrowserViewController: KeyboardHelperDelegate { func keyboardHelper(_ keyboardHelper: KeyboardHelper, keyboardWillShowWithState state: KeyboardState) { keyboardState = state updateViewConstraints() UIView.animate(withDuration: state.animationDuration) { UIView.setAnimationCurve(state.animationCurve) self.findInPageContainer.layoutIfNeeded() self.snackBars.layoutIfNeeded() } if let webView = tabManager.selectedTab?.webView { webView.evaluateJavaScript("__firefox__.searchQueryForField()") { (result, _) in guard let _ = result as? [String: String] else { return } // Cliqz: disable showing custom search button as this feature is not needed and crashes on iPad // self.addCustomSearchButtonToWebView(webView) } } } func keyboardHelper(_ keyboardHelper: KeyboardHelper, keyboardDidShowWithState state: KeyboardState) { } func keyboardHelper(_ keyboardHelper: KeyboardHelper, keyboardWillHideWithState state: KeyboardState) { keyboardState = nil updateViewConstraints() //If the searchEngineButton exists remove it form the keyboard if #available(iOS 9.0, *) { if let buttonGroup = customSearchBarButton?.buttonGroup { buttonGroup.barButtonItems = buttonGroup.barButtonItems.filter { $0 != customSearchBarButton } customSearchBarButton = nil } } if self.customSearchEngineButton.superview != nil { self.customSearchEngineButton.removeFromSuperview() } UIView.animate(withDuration: state.animationDuration) { UIView.setAnimationCurve(state.animationCurve) self.findInPageContainer.layoutIfNeeded() self.snackBars.layoutIfNeeded() } } } extension BrowserViewController: SessionRestoreHelperDelegate { func sessionRestoreHelper(_ helper: SessionRestoreHelper, didRestoreSessionForTab tab: Tab) { tab.restoring = false if let tab = tabManager.selectedTab, tab.webView === tab.webView { updateUIForReaderHomeStateForTab(tab) // Cliqz: restore the tab url and urlBar currentURL tab.url = tab.restoringUrl urlBar.currentURL = tab.restoringUrl } } } extension BrowserViewController: TabTrayDelegate { // This function animates and resets the tab chrome transforms when // the tab tray dismisses. func tabTrayDidDismiss(_ tabTray: TabTrayController) { resetBrowserChrome() } func tabTrayDidAddBookmark(_ tab: Tab) { guard let url = tab.url?.absoluteString, url.characters.count > 0 else { return } self.addBookmark(tab.tabState) } func tabTrayDidAddToReadingList(_ tab: Tab) -> ReadingListClientRecord? { guard let url = tab.url?.absoluteString, url.characters.count > 0 else { return nil } return profile.readingList?.createRecordWithURL(url, title: tab.title ?? url, addedBy: UIDevice.current.name).successValue } func tabTrayRequestsPresentationOf(_ viewController: UIViewController) { self.present(viewController, animated: false, completion: nil) } } // MARK: Browser Chrome Theming extension BrowserViewController: Themeable { func applyTheme(_ themeName: String) { urlBar.applyTheme(themeName) toolbar?.applyTheme(themeName) readerModeBar?.applyTheme(themeName) switch(themeName) { case Theme.NormalMode: // Cliqz: Commented because header is now UIView which doesn't have style // header.blurStyle = .ExtraLight footerBackground?.blurStyle = .extraLight // Cliqz: changed status bar look and feel in normal mode case Theme.PrivateMode: // Cliqz: Commented because header is now UIView which doesn't have style // header.blurStyle = .Dark footerBackground?.blurStyle = .dark // Cliqz: changed status bar look and feel in forget mode default: log.debug("Unknown Theme \(themeName)") } } } // A small convienent class for wrapping a view with a blur background that can be modified class BlurWrapper: UIView { var blurStyle: UIBlurEffectStyle = .extraLight { didSet { let newEffect = UIVisualEffectView(effect: UIBlurEffect(style: blurStyle)) effectView.removeFromSuperview() effectView = newEffect insertSubview(effectView, belowSubview: wrappedView) effectView.snp_remakeConstraints { make in make.edges.equalTo(self) } } } fileprivate var effectView: UIVisualEffectView fileprivate var wrappedView: UIView init(view: UIView) { wrappedView = view effectView = UIVisualEffectView(effect: UIBlurEffect(style: blurStyle)) super.init(frame: CGRect.zero) addSubview(effectView) addSubview(wrappedView) effectView.snp_makeConstraints { make in make.edges.equalTo(self) } wrappedView.snp_makeConstraints { make in make.edges.equalTo(self) } } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } } protocol Themeable { func applyTheme(_ themeName: String) } extension BrowserViewController: FindInPageBarDelegate, FindInPageHelperDelegate { func findInPage(_ findInPage: FindInPageBar, didTextChange text: String) { find(text, function: "find") } func findInPage(_ findInPage: FindInPageBar, didFindNextWithText text: String) { findInPageBar?.endEditing(true) find(text, function: "findNext") } func findInPage(_ findInPage: FindInPageBar, didFindPreviousWithText text: String) { findInPageBar?.endEditing(true) find(text, function: "findPrevious") } func findInPageDidPressClose(_ findInPage: FindInPageBar) { updateFindInPageVisibility(visible: false) } fileprivate func find(_ text: String, function: String) { guard let webView = tabManager.selectedTab?.webView else { return } let escaped = text.replacingOccurrences(of: "\\", with: "\\\\") .replacingOccurrences(of: "\"", with: "\\\"") webView.evaluateJavaScript("__firefox__.\(function)(\"\(escaped)\")", completionHandler: nil) } func findInPageHelper(_ findInPageHelper: FindInPageHelper, didUpdateCurrentResult currentResult: Int) { findInPageBar?.currentResult = currentResult } func findInPageHelper(_ findInPageHelper: FindInPageHelper, didUpdateTotalResults totalResults: Int) { findInPageBar?.totalResults = totalResults } } extension BrowserViewController: JSPromptAlertControllerDelegate { func promptAlertControllerDidDismiss(_ alertController: JSPromptAlertController) { showQueuedAlertIfAvailable() } } private extension WKNavigationAction { /// Allow local requests only if the request is privileged. var isAllowed: Bool { guard let url = request.url else { return true } return !url.isWebPage() || !url.isLocal || request.isPrivileged } } //MARK: - Cliqz // CLiqz: Added extension for HomePanelDelegate to react for didSelectURL from SearchHistoryViewController extension BrowserViewController: HomePanelDelegate { func homePanelDidRequestToSignIn(_ homePanel: HomePanel) { } func homePanelDidRequestToCreateAccount(_ homePanel: HomePanel) { } func homePanel(_ homePanel: HomePanel, didSelectURL url: URL, visitType: VisitType) { // Delegate method for History panel finishEditingAndSubmit(url, visitType: VisitType.Typed) } func homePanel(_ homePanel: HomePanel, didSelectURLString url: String, visitType: VisitType) { } } // Cliqz: Added TransitioningDelegate to maintain layers change animations extension BrowserViewController: UIViewControllerTransitioningDelegate { func animationController(forPresented presented: UIViewController, presenting: UIViewController, source: UIViewController) -> UIViewControllerAnimatedTransitioning? { transition.presenting = true return transition } func animationController(forDismissed dismissed: UIViewController) -> UIViewControllerAnimatedTransitioning? { transition.presenting = false return transition } } // Cliqz: combined the two extensions for SearchViewDelegate and BrowserNavigationDelegate into one extension //listens to autocomplete notification extension BrowserViewController { @objc func autocomplete(_ notification: Notification) { if let str = notification.object as? String { self.autoCompeleteQuery(str) } } } extension BrowserViewController: SearchViewDelegate, BrowserNavigationDelegate { func didSelectURL(_ url: URL, searchQuery: String?) { self.tabManager.selectedTab?.query = searchQuery navigateToUrl(url, searchQuery: searchQuery) } func searchForQuery(_ query: String) { self.urlBar.enterOverlayMode(query, pasted: true) } func autoCompeleteQuery(_ autoCompleteText: String) { urlBar.setAutocompleteSuggestion(autoCompleteText) } func dismissKeyboard() { urlBar.resignFirstResponder() } func navigateToURL(_ url: URL) { finishEditingAndSubmit(url, visitType: .Link) } func navigateToQuery(_ query: String) { self.urlBar.enterOverlayMode(query, pasted: true) } func navigateToURLInNewTab(_ url: URL) { self.openURLInNewTab(url) } fileprivate func navigateToUrl(_ url: URL, searchQuery: String?) { let query = (searchQuery != nil) ? searchQuery! : "" let forwardUrl = URL(string: "\(WebServer.sharedInstance.base)/cliqz/trampolineForward.html?url=\(url.absoluteString.encodeURL())&q=\(query.encodeURL())") if BloomFilterManager.sharedInstance.shouldOpenInPrivateTab(url: url, currentTab: tabManager.selectedTab) { urlBar.currentURL = url urlBar.leaveOverlayMode() self.openURLInNewTab(url, isPrivate: true) return } if let tab = tabManager.selectedTab, let u = forwardUrl, let nav = tab.loadRequest(PrivilegedRequest(url: u) as URLRequest) { self.recordNavigationInTab(tab, navigation: nav, visitType: .Link) } urlBar.currentURL = url urlBar.leaveOverlayMode() } } // Cliqz: Extension for BrowserViewController to put addes methods extension BrowserViewController { // Cliqz: Added method to show search view if needed fileprivate func switchToSearchModeIfNeeded() { if let selectedTab = self.tabManager.selectedTab { if (selectedTab.inSearchMode) { if self.urlBar.inOverlayMode == false { self.urlBar.enterOverlayMode("", pasted: true) scrollController.showToolbars(false) } } else if self.homePanelController?.view.isHidden == false { self.urlBar.leaveOverlayMode() } } } // Cliqz: Logging the Navigation Telemetry signals fileprivate func startNavigation(_ webView: WKWebView, navigationAction: WKNavigationAction) { // determine if the navigation is back navigation if navigationAction.navigationType == .backForward && backListSize >= webView.backForwardList.backList.count { isBackNavigation = true } else { isBackNavigation = false } backListSize = webView.backForwardList.backList.count } // Cliqz: Logging the Navigation Telemetry signals fileprivate func finishNavigation(_ webView: CliqzWebView) { // calculate the url length guard let urlLength = webView.url?.absoluteString.characters.count else { return } // calculate times let currentTime = Date.getCurrentMillis() let displayTime = currentTime - navigationEndTime navigationEndTime = currentTime // check if back navigation if isBackNavigation { backNavigationStep += 1 logNavigationEvent("back", step: backNavigationStep, urlLength: urlLength, displayTime: displayTime) } else { // discard the first navigation (result navigation is not included) if navigationStep != 0 { logNavigationEvent("location_change", step: navigationStep, urlLength: urlLength, displayTime: displayTime) } navigationStep += 1 backNavigationStep = 0 } } // Cliqz: Method for Telemetry logs fileprivate func logNavigationEvent(_ action: String, step: Int, urlLength: Int, displayTime: Double) { TelemetryLogger.sharedInstance.logEvent(.Navigation(action, step, urlLength, displayTime)) } // Cliqz: Added to diffrentiate between navigating a website or searching for something when app goes to background func SELappDidEnterBackgroundNotification() { displayedPopoverController?.dismiss(animated: false) { self.displayedPopoverController = nil } isAppResponsive = false saveLastVisitedWebSite() } // Cliqz: Method to store last visited sites fileprivate func saveLastVisitedWebSite() { if let selectedTab = self.tabManager.selectedTab, let lastVisitedWebsite = selectedTab.webView?.url?.absoluteString, selectedTab.isPrivate == false && !lastVisitedWebsite.hasPrefix("http://localhost") { // Cliqz: store the last visited website LocalDataStore.setObject(lastVisitedWebsite, forKey: lastVisitedWebsiteKey) } } // Cliqz: added to mark the app being responsive (mainly send telemetry signal) func appDidBecomeResponsive(_ startupType: String) { if isAppResponsive == false { isAppResponsive = true AppStatus.sharedInstance.appDidBecomeResponsive(startupType) } } // Cliqz: Added to navigate to the last visited website (3D quick home actions) func navigateToLastWebsite() { if let lastVisitedWebsite = LocalDataStore.objectForKey(self.lastVisitedWebsiteKey) as? String { self.initialURL = lastVisitedWebsite } } // Cliqz: fix headerTopConstraint for scrollController to work properly during the animation to/from past layer fileprivate func fixHeaderConstraint() { let currentDevice = UIDevice.current let iphoneLandscape = currentDevice.orientation.isLandscape && (currentDevice.userInterfaceIdiom == .phone) if transition.isAnimating && !iphoneLandscape { headerConstraintUpdated = true scrollController.headerTopConstraint?.update(offset: 20) statusBarOverlay.snp_remakeConstraints { make in make.top.left.right.equalTo(self.view) make.height.equalTo(20) } } else if(headerConstraintUpdated) { headerConstraintUpdated = false scrollController.headerTopConstraint?.update(offset: 0) } } // Cliqz: Add custom user scripts fileprivate func addCustomUserScripts(_ browser: Tab) { // Wikipedia scripts to clear expanded sections from local storage if let path = Bundle.main.path(forResource: "wikipediaUserScript", ofType: "js"), let source = try? NSString(contentsOfFile: path, encoding: String.Encoding.utf8.rawValue) as String { let userScript = WKUserScript(source: source, injectionTime: WKUserScriptInjectionTime.atDocumentStart, forMainFrameOnly: false) browser.webView!.configuration.userContentController.addUserScript(userScript) } } // Cliqz: Added to get the current view for telemetry signals func getCurrentView() -> String? { var currentView: String? if self.presentedViewController != nil { currentView = "settings" } else if self.navigationController?.topViewController == dashboard { currentView = "overview" } else if self.searchController?.view.isHidden == false { currentView = "cards" } else if let _ = self.urlBar.currentURL { currentView = "web" } else { currentView = "home" } return currentView } } // TODO: Detect if the app is opened after a crash //extension BrowserViewController: CrashlyticsDelegate { // func crashlyticsDidDetectReport(forLastExecution report: CLSReport, completionHandler: @escaping (Bool) -> Void) { // hasPendingCrashReport = true // DispatchQueue.global(qos: .default).async { // completionHandler(true) // } // } // //}
mpl-2.0
PJayRushton/TeacherTools
TeacherTools/SubscribeToCurrentUser.swift
1
1125
// // SubscribeToCurrentUser.swift // Stats // // Created by Parker Rushton on 3/31/17. // Copyright © 2017 AppsByPJ. All rights reserved. // import Foundation struct Subscribed<T: Identifiable>: Event { var item: T? init(_ item: T?) { self.item = item } } struct SubscribeToCurrentUser: Command { var id: String func execute(state: AppState, core: Core<AppState>) { let ref = networkAccess.usersRef.child(id) self.networkAccess.subscribe(to: ref, completion: { result in let userResult = result.map(User.init) switch userResult { case let .success(user): core.fire(event: Selected<User>(user)) core.fire(event: Subscribed<User>(user)) core.fire(command: SubscribeToGroups()) core.fire(command: SubscribeToStudents()) case let .failure(error): core.fire(event: Selected<User>(nil)) core.fire(event: ErrorEvent(error: error, message: nil)) } }) } }
mit
kasketis/netfox
netfox/iOS/NFXStatisticsController_iOS.swift
1
1332
// // NFXStatisticsController_iOS.swift // netfox // // Copyright © 2016 netfox. All rights reserved. // #if os(iOS) import UIKit class NFXStatisticsController_iOS: NFXStatisticsController { private let scrollView: UIScrollView = UIScrollView() private let textLabel: UILabel = UILabel() override func viewDidLoad() { super.viewDidLoad() title = "Statistics" scrollView.frame = CGRect(x: 0, y: 0, width: view.frame.width, height: view.frame.height) scrollView.autoresizingMask = [.flexibleWidth, .flexibleHeight] scrollView.autoresizesSubviews = true scrollView.backgroundColor = UIColor.clear view.addSubview(scrollView) textLabel.frame = CGRect(x: 20, y: 20, width: scrollView.frame.width - 40, height: scrollView.frame.height - 20); textLabel.font = UIFont.NFXFont(size: 13) textLabel.textColor = UIColor.NFXGray44Color() textLabel.numberOfLines = 0 textLabel.sizeToFit() scrollView.addSubview(textLabel) scrollView.contentSize = CGSize(width: scrollView.frame.width, height: textLabel.frame.maxY) } override func reloadData() { super.reloadData() textLabel.attributedText = getReportString() } } #endif
mit
mownier/Umalahokan
Umalahokan/Source/Util/SendView.swift
1
2413
// // SendView.swift // Umalahokan // // Created by Mounir Ybanez on 20/03/2017. // Copyright © 2017 Ner. All rights reserved. // import UIKit protocol SendViewDelegate: class { func send(_ view: SendView) } class SendView: UIView { weak var delegate: SendViewDelegate? var messageTextView: UmalahokanTextView! var sendButton: UIButton! convenience init() { var rect = CGRect.zero rect.size.height = 52 self.init(frame: rect) initSetup() } override func layoutSubviews() { let spacing: CGFloat = 8 var rect = CGRect.zero rect.size.width = 36 rect.size.height = rect.width rect.origin.x = frame.width - rect.width - spacing rect.origin.y = (frame.height - rect.height) / 2 sendButton.frame = rect sendButton.layer.cornerRadius = rect.width / 2 rect.size.width = rect.origin.x - spacing * 2 rect.size.height = messageTextView.sizeThatFits(rect.size).height + spacing * 2 rect.origin.x = spacing rect.origin.y = (frame.height - rect.height) / 2 messageTextView.frame = rect } func initSetup() { let theme = UITheme() backgroundColor = theme.color.gray3 messageTextView = UmalahokanTextView() messageTextView.font = theme.font.medium.size(12) messageTextView.textColor = theme.color.gray messageTextView.tintColor = theme.color.gray messageTextView.keyboardAppearance = .dark messageTextView.backgroundColor = .clear messageTextView.placeholderLabel.text = "Your message" messageTextView.placeholderLabel.font = messageTextView.font messageTextView.placeholderLabel.textColor = messageTextView.textColor sendButton = UIButton() sendButton.addTarget(self, action: #selector(self.didTapSend), for: .touchUpInside) sendButton.setImage(#imageLiteral(resourceName: "airplane-icon"), for: .normal) sendButton.tintColor = UIColor.white sendButton.backgroundColor = theme.color.violet2 sendButton.layer.masksToBounds = true sendButton.imageEdgeInsets = UIEdgeInsetsMake(2, 0, 0, 2) addSubview(messageTextView) addSubview(sendButton) } func didTapSend() { delegate?.send(self) } }
mit
cweatureapps/SwiftScraper
Sources/SwiftScraperError.swift
1
1560
// // SwiftScraperError.swift // SwiftScraper // // Created by Ken Ko on 21/04/2017. // Copyright © 2017 Ken Ko. All rights reserved. // import Foundation public enum SwiftScraperError: Error, LocalizedError { /// Problem with serializing parameters to pass to the JavaScript. case parameterSerialization /// An assertion failed, the page contents was not what was expected. case contentUnexpected /// JavaScript error occurred when trying to process the page. case javascriptError(errorMessage: String) /// Page navigation failed with the given error. case navigationFailed(error: Error) /// The step which was specified could not be found to be run, e.g. if an incorrect index was specified for `StepFlowResult.jumpToStep(Int)`. case incorrectStep /// Timeout occurred while waiting for a step to complete. case timeout public var errorDescription: String? { switch self { case .parameterSerialization: return "Could not serialize the parameters to pass to the script" case .contentUnexpected: return "Something went wrong, the page contents was not what was expected" case .javascriptError(let errorMessage): return "A JavaScript error occurred when trying to process the page: \(errorMessage)" case .navigationFailed: return "Something went wrong when navigating to the page" case .incorrectStep: return "An incorrect step was specified" case .timeout: return "Timeout occurred while waiting for a step to complete" } } }
mit
zarghol/documentation-provider
Sources/DocumentationProvider/RouteDocumentation.swift
1
2708
// // RouteDocument.swift // econotouchWS // // Created by Clément NONN on 29/07/2017. // // import Vapor public struct RouteDocumentation { public struct AdditionalInfos { var description: String var pathParameters: [String: String] var queryParameters: [String: String] var parametersRepresentation: NodeRepresentable { return [ "path" : pathParameters.map { ["key": $0.key, "value": $0.value] }, "query": queryParameters.map { ["key": $0.key, "value": $0.value] } ] } public init(description: String, pathParameters: [String: String] = [:], queryParameters: [String: String] = [:]) { self.description = description self.pathParameters = pathParameters self.queryParameters = queryParameters } } let host: String let method: String let path: String var additionalInfos: AdditionalInfos var hasParameter: Bool { return additionalInfos.pathParameters.count > 0 || additionalInfos.queryParameters.count > 0 } } extension RouteDocumentation { public init(route: String) { let components = route.components(separatedBy: .whitespaces) let host = components[0] let method = components[1] let path = components[2] var pathParameters = [String: String]() for parameterName in RouteDocumentation.getPathParametersNames(for: path) { pathParameters[parameterName] = "no description" } self.host = host self.path = path self.method = method self.additionalInfos = AdditionalInfos( description: "no description", pathParameters: pathParameters, queryParameters: [String: String]() ) } private static func getPathParametersNames(for path: String) -> [String] { var pathParametersComponents = path.components(separatedBy: ":") if pathParametersComponents.count > 1 { pathParametersComponents.remove(at: 0) let pathParametersNames = pathParametersComponents.flatMap { $0.components(separatedBy: "/").first } return pathParametersNames } return [] } } extension RouteDocumentation: NodeRepresentable { public func makeNode(in context: Context?) throws -> Node { return try [ "method": method, "path": path, "description": additionalInfos.description, "hasParameter": hasParameter, "parameters": additionalInfos.parametersRepresentation ].makeNode(in: context) } }
mit
astrokin/EZSwiftExtensions
EZSwiftExtensionsTests/UIImageViewTests.swift
3
220
// // UIImageViewTests.swift // EZSwiftExtensions // // Created by Goktug Yilmaz on 8/25/16. // Copyright © 2016 Goktug Yilmaz. All rights reserved. // import XCTest class UIImageViewTests: XCTestCase { }
mit
khizkhiz/swift
validation-test/compiler_crashers_fixed/28163-swift-astcontext-getoptionaldecl.swift
1
340
// RUN: not %target-swift-frontend %s -parse // Distributed under the terms of the MIT license // Test case submitted to project by https://github.com/practicalswift (practicalswift) // Test case found by fuzzing class A{{}let a{a:{struct c{var:Collection{class d{struct d{enum E<T where B:a{struct B{{}struct B<g{class B{class d{var _=B
apache-2.0
Raizlabs/RIGImageGallery
RIGImageGallery/RIGImageGalleryItem.swift
1
1083
// // RIGImageGalleryItem.swift // RIGPhotoViewer // // Created by Michael Skiba on 2/9/16. // Copyright © 2016 Raizlabs. All rights reserved. // import UIKit /** * RIGImageGalleryItem stores an image, placeholder Image, and title to associate with each image */ public struct RIGImageGalleryItem: Equatable { /// The image to display public var image: UIImage? /// A placeholder image to display if the display image is nil or becomes nil public var placeholderImage: UIImage? /// The title of the image public var title: String? // The loading state public var isLoading: Bool public init(image: UIImage? = nil, placeholderImage: UIImage? = nil, title: String? = nil, isLoading: Bool = false) { self.image = image self.placeholderImage = placeholderImage self.title = title self.isLoading = isLoading } } public func == (lhs: RIGImageGalleryItem, rhs: RIGImageGalleryItem) -> Bool { return lhs.image === rhs.image && lhs.placeholderImage === rhs.placeholderImage && lhs.title == rhs.title }
mit
caicai0/ios_demo
load/thirdpart/SwiftKuery/ConnectionPool.swift
1
5886
/** Copyright IBM Corporation 2017 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 Dispatch #if os(Linux) import Glibc #else import Darwin #endif // MARK: ConnectionPool /// A connection pool implementation. /// The pool is FIFO. public class ConnectionPool { private var pool = [Connection]() // A serial dispatch queue used to ensure thread safety when accessing the pool // (at time of writing, serial is the default, and cannot be explicitly specified). private var poolLock = DispatchSemaphore(value: 1) // A generator function for items in the pool, which allows future expansion. private let generator: () -> Connection? // A releaser function for connections in the pool. private let releaser: (Connection) -> () // The maximum size of this pool. private let limit: Int // The initial size of this pool. private var capacity: Int // A semaphore to enable take() to block when the pool is empty. private var semaphore: DispatchSemaphore // A timeout value (in nanoseconds) to wait before returning nil from a take(). private let timeoutNs: Int64 private let timeout: Int /// Creates an instance of `ConnectionPool` containing `ConnectionPoolOptions.initialCapacity` connections. /// The `connectionGenerator` will be invoked `ConnectionPoolOptions.initialCapacity` times to fill /// the pool to the initial capacity. /// /// - Parameter options: `ConnectionPoolOptions` describing pool configuration. /// - Parameter connectionGenerator: A closure that returns a new connection for the pool. /// - Parameter connectionReleaser: A closure to be used to release a connection from the pool. public init(options: ConnectionPoolOptions, connectionGenerator: @escaping () -> Connection?, connectionReleaser: @escaping (Connection) -> ()) { capacity = options.initialCapacity if capacity < 1 { capacity = 1 } limit = options.maxCapacity timeout = options.timeout timeoutNs = Int64(timeout) * 1000000 // Convert ms to ns generator = connectionGenerator releaser = connectionReleaser semaphore = DispatchSemaphore(value: capacity) for _ in 0 ..< capacity { if let item = generator() { pool.append(item) } else {} // TODO: Handle generation failure. } } deinit { disconnect() } /// Get a connection from the pool. /// This function will block until a connection can be obtained from the pool or for `ConnectionPoolOptions.timeout`. /// /// - Returns: A `Connection` or nil if the wait for a free connection timed out. public func getConnection() -> Connection? { if let connection = take() { return ConnectionPoolConnection(connection: connection, pool: self) } return nil } func release(connection: Connection) { give(connection) } /// Release all the connections in the pool by calling connectionReleaser closure on each connection, /// and empty the pool. public func disconnect() { release() } // Take an item from the pool. The item will not magically rejoin the pool when no longer // needed, so MUST later be returned to the pool with give() if it is to be reused. // Items can therefore be borrowed or permanently removed with this method. // // This function will block until an item can be obtained from the pool. private func take() -> Connection? { var item: Connection! // Indicate that we are going to take an item from the pool. The semaphore will // block if there are currently no items to take, until one is returned via give() let result = semaphore.wait(timeout: (timeout == 0) ? .distantFuture : .now() + DispatchTimeInterval.milliseconds(timeout)) if result == DispatchTimeoutResult.timedOut { return nil } // We have permission to take an item - do so in a thread-safe way lockPoolLock() if (pool.count < 1) { unlockPoolLock() return nil } item = pool[0] pool.removeFirst() // If we took the last item, we can choose to grow the pool if (pool.count == 0 && capacity < limit) { capacity += 1 if let newItem = generator() { pool.append(newItem) semaphore.signal() } } unlockPoolLock() return item } // Give an item back to the pool. Whilst this item would normally be one that was earlier // take()n from the pool, a new item could be added to the pool via this method. private func give(_ item: Connection) { lockPoolLock() pool.append(item) // Signal that an item is now available semaphore.signal() unlockPoolLock() } private func release() { lockPoolLock() for item in pool { releaser(item) } pool.removeAll() unlockPoolLock() } private func lockPoolLock() { _ = poolLock.wait(timeout: DispatchTime.distantFuture) } private func unlockPoolLock() { poolLock.signal() } }
mit
youweit/Delicacy
Delicacy/Article.swift
1
2382
// // Article.swift // Delicacy // // Created by Youwei Teng on 9/5/15. // Copyright (c) 2015 Dcard. All rights reserved. // import Foundation import SwiftyJSON import Alamofire enum Gender { case Male case Female case None } class Article { var identifier: NSNumber? var title: String? var coverPhotoUrl: NSURL? var originalUrl: String? var content: String? var likeCount: NSNumber? var commentCount: NSNumber? var createdAt: NSDate? var updatedAt: NSDate? var contentLoaded: Bool var school: String? var department: String? var gender: Gender = .None init(){ self.contentLoaded = false; self.coverPhotoUrl = NSURL() } func initWithJSON(articleJSON: JSON) -> Article { //Article Info if let identifier = articleJSON["id"].number { self.identifier = identifier } self.title = articleJSON["version",0,"title"].string self.content = articleJSON["version",0,"content"].string self.likeCount = articleJSON["likeCount"].number; self.commentCount = articleJSON["comment"].number; //Member Info self.school = articleJSON["member","school"].string self.department = articleJSON["member","department"].string self.gender = articleJSON["member","gender"].string == "M" ? .Male:.Female return self; } } extension Article { func loadContent(completion:() -> Void) { if !contentLoaded { //print("loadContent request url = https://www.dcard.tw/api/post/all/\(self.identifier!)") Alamofire .request(.GET,"https://www.dcard.tw/api/post/all/\(self.identifier!)") .responseJSON { _, _, responseResult in self.initWithJSON(JSON(responseResult.value!)) self.extractPhotos() self.contentLoaded = true completion() } } else { completion() } } func extractPhotos() -> [String] { let photos = Utils.matchesForRegexInText("(https?:\\/\\/(?:i\\.)?imgur\\.com\\/(?:\\w*)(?:.\\w*))", text: self.content); if photos.count > 0 { print(photos.first!) if photos.first!.containsString("http://imgur.com") || photos.first!.containsString("https://imgur.com") { let imgurLink: String = photos.first!.stringByReplacingOccurrencesOfString("imgur", withString: "i.imgur") let thumbnailUrl: String = "\(imgurLink)l.jpg" self.coverPhotoUrl = NSURL(string: thumbnailUrl) } else { self.coverPhotoUrl = NSURL(string: photos.first!) } } return photos; } }
mit
stevebrambilla/Runes
Tests/Tests/OptionalSpec.swift
3
2997
import SwiftCheck import XCTest import Runes class OptionalSpec: XCTestCase { func testFunctor() { // fmap id = id property("identity law") <- forAll { (x: Int?) in let lhs = id <^> x let rhs = x return lhs == rhs } // fmap (f . g) = (fmap f) . (fmap g) property("function composition law") <- forAll { (o: OptionalOf<Int>, fa: ArrowOf<Int, Int>, fb: ArrowOf<Int, Int>) in let f = fa.getArrow let g = fb.getArrow let x = o.getOptional let lhs = compose(f, g) <^> x let rhs = compose(curry(<^>)(f), curry(<^>)(g))(x) return lhs == rhs } } func testApplicative() { // pure id <*> v = v property("identity law") <- forAll { (x: Int?) in let lhs = pure(id) <*> x let rhs = x return lhs == rhs } // pure f <*> pure x = pure (f x) property("homomorphism law") <- forAll { (x: Int, fa: ArrowOf<Int, Int>) in let f = fa.getArrow let lhs: Int? = pure(f) <*> pure(x) let rhs: Int? = pure(f(x)) return rhs == lhs } // f <*> pure x = pure ($ x) <*> f property("interchange law") <- forAll { (x: Int, fa: OptionalOf<ArrowOf<Int, Int>>) in let f = fa.getOptional?.getArrow let lhs = f <*> pure(x) let rhs = pure({ $0(x) }) <*> f return lhs == rhs } // f <*> (g <*> x) = pure (.) <*> f <*> g <*> x property("composition law") <- forAll { (o: OptionalOf<Int>, fa: OptionalOf<ArrowOf<Int, Int>>, fb: OptionalOf<ArrowOf<Int, Int>>) in let x = o.getOptional let f = fa.getOptional?.getArrow let g = fb.getOptional?.getArrow let lhs = f <*> (g <*> x) let rhs = pure(curry(compose)) <*> f <*> g <*> x return lhs == rhs } } func testMonad() { // return x >>= f = f x property("left identity law") <- forAll { (x: Int, fa: ArrowOf<Int, Int>) in let f: Int -> Int? = compose(pure, fa.getArrow) let lhs = pure(x) >>- f let rhs = f(x) return lhs == rhs } // m >>= return = m property("right identity law") <- forAll { (o: OptionalOf<Int>) in let x = o.getOptional let lhs = x >>- pure let rhs = x return lhs == rhs } // (m >>= f) >>= g = m >>= (\x -> f x >>= g) property("associativity law") <- forAll { (o: OptionalOf<Int>, fa: ArrowOf<Int, Int>, fb: ArrowOf<Int, Int>) in let m = o.getOptional let f: Int -> Int? = compose(pure, fa.getArrow) let g: Int -> Int? = compose(pure, fb.getArrow) let lhs = (m >>- f) >>- g let rhs = m >>- { x in f(x) >>- g } return lhs == rhs } } }
mit