repo_name
stringlengths 6
91
| path
stringlengths 8
968
| copies
stringclasses 210
values | size
stringlengths 2
7
| content
stringlengths 61
1.01M
| license
stringclasses 15
values | hash
stringlengths 32
32
| line_mean
float64 6
99.8
| line_max
int64 12
1k
| alpha_frac
float64 0.3
0.91
| ratio
float64 2
9.89
| autogenerated
bool 1
class | config_or_test
bool 2
classes | has_no_keywords
bool 2
classes | has_few_assignments
bool 1
class |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
ken0nek/swift | validation-test/Reflection/reflect_Int32.swift | 1 | 2123 | // RUN: rm -rf %t && mkdir -p %t
// RUN: %target-build-swift -lswiftSwiftReflectionTest %s -o %t/reflect_Int32
// RUN: %target-run %target-swift-reflection-test %t/reflect_Int32 2>&1 | FileCheck %s --check-prefix=CHECK-%target-ptrsize
// REQUIRES: objc_interop
import SwiftReflectionTest
class TestClass {
var t: Int32
init(t: Int32) {
self.t = t
}
}
var obj = TestClass(t: 123)
reflect(object: obj)
// CHECK-64: Reflecting an object.
// CHECK-64: Instance pointer in child address space: 0x{{[0-9a-fA-F]+}}
// CHECK-64: Type reference:
// CHECK-64: (class reflect_Int32.TestClass)
// CHECK-64: Type info:
// CHECK-64: (class_instance size=20 alignment=16 stride=32 num_extra_inhabitants=0
// CHECK-64: (field name=t offset=16
// CHECK-64: (struct size=4 alignment=4 stride=4 num_extra_inhabitants=0
// CHECK-64: (field name=_value offset=0
// CHECK-64: (builtin size=4 alignment=4 stride=4 num_extra_inhabitants=0)))))
// CHECK-32: Reflecting an object.
// CHECK-32: Instance pointer in child address space: 0x{{[0-9a-fA-F]+}}
// CHECK-32: Type reference:
// CHECK-32: (class reflect_Int32.TestClass)
// CHECK-32: Type info:
// CHECK-32: (class_instance size=16 alignment=16 stride=16 num_extra_inhabitants=0
// CHECK-32: (field name=t offset=12
// CHECK-32: (struct size=4 alignment=4 stride=4 num_extra_inhabitants=0
// CHECK-32: (field name=_value offset=0
// CHECK-32: (builtin size=4 alignment=4 stride=4 num_extra_inhabitants=0)))))
reflect(any: obj)
// CHECK-64: Reflecting an existential.
// CHECK-64: Instance pointer in child address space: 0x{{[0-9a-fA-F]+}}
// CHECK-64: Type reference:
// CHECK-64: (class reflect_Int32.TestClass)
// CHECK-64: Type info:
// CHECK-64: (reference kind=strong refcounting=native)
// CHECK-32: Reflecting an existential.
// CHECK-32: Instance pointer in child address space: 0x{{[0-9a-fA-F]+}}
// CHECK-32: Type reference:
// CHECK-32: (class reflect_Int32.TestClass)
// CHECK-32: Type info:
// CHECK-32: (reference kind=strong refcounting=native)
doneReflecting()
// CHECK-64: Done.
// CHECK-32: Done.
| apache-2.0 | 8258756ebcd0119f14a57cfcf46aee43 | 31.661538 | 123 | 0.68488 | 3.067919 | false | true | false | false |
ByteriX/BxInputController | BxInputController/Sources/Common/View/StandartText/BxInputStandartTextRowBinder.swift | 1 | 3427 | /**
* @file BxInputStandartTextRowBinder.swift
* @namespace BxInputController
*
* @details Binder for a standart text row
* @date 06.03.2017
* @author Sergey Balalaev
*
* @version last in https://github.com/ByteriX/BxInputController.git
* @copyright The MIT License (MIT) https://opensource.org/licenses/MIT
* Copyright (c) 2017 ByteriX. See http://byterix.com
*/
import UIKit
/// Binder for a standart text row
open class BxInputStandartTextRowBinder<Row: BxInputRow, Cell> : BxInputBaseFieldRowBinder<Row, Cell>, UITextFieldDelegate
where Cell : UITableViewCell, Cell : BxInputFieldCell
{
/// call when user selected this cell
override open func didSelected()
{
super.didSelected()
cell?.valueTextField.becomeFirstResponder()
}
/// this call after common update for text attributes updating
open func updateCell() {
cell?.valueTextField.isEnabled = true
cell?.accessoryType = .none
cell?.selectionStyle = .none
}
/// Update text input settings. If you want to specialize you can override this
open func updateTextSettings() {
cell?.valueTextField.update(from: BxInputTextSettings.standart)
}
/// update cell from model data
override open func update()
{
super.update()
//
cell?.valueTextField.changeTarget(self, action: #selector(valueChanged(valueTextField:)), for: .editingChanged)
cell?.valueTextField.delegate = self
//
updateTextSettings()
updateCell()
}
/// resign value editing
@discardableResult
override open func resignFirstResponder() -> Bool {
return cell?.valueTextField.resignFirstResponder() ?? false
}
/// event when value is changed. Need reload this in inherited classes
@objc open func valueChanged(valueTextField: UITextField) {
// empty
}
// MARK - UITextFieldDelegate delegates
/// start editing
open func textFieldShouldBeginEditing(_ textField: UITextField) -> Bool
{
if !isEnabled {
return false
}
if let owner = owner, owner.settings.isAutodissmissSelector {
owner.dissmissSelectors()
}
owner?.activeRow = row
owner?.activeControl = textField
return true
}
/// end editing
open func textFieldDidEndEditing(_ textField: UITextField)
{
if owner?.activeControl === textField {
owner?.activeControl = nil
}
if owner?.activeRow === row {
owner?.activeRow = nil
}
}
/// changing value event for correct showing
open func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool
{
if let text = textField.text,
range.location == text.chars.count && string == " "
{
textField.text = text + "\u{00a0}"
return false
}
return true
}
/// clear event, when user click clear button
open func textFieldShouldClear(_ textField: UITextField) -> Bool
{
textField.text = ""
return true
}
/// user click Done
open func textFieldShouldReturn(_ textField: UITextField) -> Bool
{
textField.resignFirstResponder()
return true
}
}
| mit | 8ca1a82692d33514d83ff20bebafa796 | 27.558333 | 132 | 0.624453 | 4.966667 | false | false | false | false |
AlexMcArdle/LooseFoot | LooseFoot/AppDelegate.swift | 1 | 10416 | //
// AppDelegate.swift
// LooseFoot
//
// Created by Alexander McArdle on 1/22/17.
// Copyright © 2017 Alexander McArdle. All rights reserved.
//
import UserNotifications
import UIKit
import reddift
import ChameleonFramework
import FPSCounter
import Firebase
/// Posted when the OAuth2TokenRepository object succeed in saving a token successfully into Keychain.
public let OAuth2TokenRepositoryDidSaveToken = "OAuth2TokenRepositoryDidSaveToken"
/// Posted when the OAuth2TokenRepository object failed to save a token successfully into Keychain.
public let OAuth2TokenRepositoryDidFailToSaveToken = "OAuth2TokenRepositoryDidFailToSaveToken"
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
let gcmMessageIDKey = "gcm.message_id"
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
//FPSCounter.showInStatusBar(UIApplication.shared)
window = UIWindow(frame: UIScreen.main.bounds)
window?.backgroundColor = UIColor.black
registerForPushNotifications(application: application)
FIRApp.configure()
Chameleon.setGlobalThemeUsingPrimaryColor(UIColor.flatBlackDark, with: .contrast)
let nav = CustomNavigationController(navigationBarClass: AMNavigationBar.self, toolbarClass: AMToolbar.self)
//let nav = CustomNavigationController(navigationBarClass: CustomNavigationBar.self, toolbarClass: nil)
//nav.pushViewController(AMSubredditViewController(subreddit: "powerlanguagetest", firstRun: true), animated: true)
nav.pushViewController(AMSubredditViewController(firstRun: true), animated: true)
//window?.rootViewController = AMHomeViewController()
window?.rootViewController = nav
window?.makeKeyAndVisible()
// [START add_token_refresh_observer]
// Add observer for InstanceID token refresh callback.
NotificationCenter.default.addObserver(self,
selector: #selector(self.tokenRefreshNotification),
name: .firInstanceIDTokenRefresh,
object: nil)
// [END add_token_refresh_observer]
return true
}
func registerForPushNotifications(application: UIApplication) {
// Register for remote notifications. This shows a permission dialog on first run, to
// show the dialog at a more appropriate time move this registration accordingly.
// [START register_for_notifications]
if #available(iOS 10.0, *) {
let authOptions: UNAuthorizationOptions = [.alert, .badge, .sound]
UNUserNotificationCenter.current().requestAuthorization(
options: authOptions,
completionHandler: {_, _ in })
// For iOS 10 display notification (sent via APNS)
UNUserNotificationCenter.current().delegate = self
// For iOS 10 data message (sent via FCM)
FIRMessaging.messaging().remoteMessageDelegate = self
} else {
let settings: UIUserNotificationSettings =
UIUserNotificationSettings(types: [.alert, .badge, .sound], categories: nil)
application.registerUserNotificationSettings(settings)
}
application.registerForRemoteNotifications()
// [END register_for_notifications]
}
func application(_ app: UIApplication, open url: URL, sourceApplication: String?, annotation: Any) -> Bool {
print("url: \(url)")
return OAuth2Authorizer.sharedInstance.receiveRedirect(url, completion: {(result) -> Void in
switch result {
case .failure(let error):
print(error)
case .success(let token):
DispatchQueue.main.async(execute: { () -> Void in
do {
try OAuth2TokenRepository.save(token: token, of: token.name)
NotificationCenter.default.post(name: Notification.Name(rawValue: OAuth2TokenRepositoryDidSaveToken), object: nil, userInfo: nil)
debugPrint(token)
} catch {
NotificationCenter.default.post(name: Notification.Name(rawValue: OAuth2TokenRepositoryDidFailToSaveToken), object: nil, userInfo: nil)
print(error)
}
})
}
})
}
// [START receive_message]
func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable: Any]) {
// If you are receiving a notification message while your app is in the background,
// this callback will not be fired till the user taps on the notification launching the application.
// TODO: Handle data of notification
// Print message ID.
if let messageID = userInfo[gcmMessageIDKey] {
print("Message ID: \(messageID)")
}
// Print full message.
print(userInfo)
}
func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable: Any],
fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) {
// If you are receiving a notification message while your app is in the background,
// this callback will not be fired till the user taps on the notification launching the application.
// TODO: Handle data of notification
// Print message ID.
if let messageID = userInfo[gcmMessageIDKey] {
print("Message ID: \(messageID)")
}
// Print full message.
print(userInfo)
completionHandler(UIBackgroundFetchResult.newData)
}
// [END receive_message]
// [START refresh_token]
func tokenRefreshNotification(_ notification: Notification) {
if let refreshedToken = FIRInstanceID.instanceID().token() {
print("InstanceID token: \(refreshedToken)")
}
// Connect to FCM since connection may have failed when attempted before having a token.
connectToFcm()
}
// [END refresh_token]
// [START connect_to_fcm]
func connectToFcm() {
// Won't connect since there is no token
guard FIRInstanceID.instanceID().token() != nil else {
return;
}
// Disconnect previous FCM connection if it exists.
FIRMessaging.messaging().disconnect()
FIRMessaging.messaging().connect { (error) in
if error != nil {
print("Unable to connect with FCM. \(error)")
} else {
print("Connected to FCM.")
}
}
}
// [END connect_to_fcm]
func application(_ application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: Error) {
print("Unable to register for remote notifications: \(error.localizedDescription)")
}
// [START connect_on_active]
func applicationDidBecomeActive(_ application: UIApplication) {
connectToFcm()
}
// [END connect_on_active]
// [START disconnect_from_fcm]
func applicationDidEnterBackground(_ application: UIApplication) {
FIRMessaging.messaging().disconnect()
print("Disconnected from FCM.")
}
// [END disconnect_from_fcm]
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 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 applicationWillTerminate(_ application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}
}
// [START ios_10_message_handling]
@available(iOS 10, *)
extension AppDelegate : UNUserNotificationCenterDelegate {
// Receive displayed notifications for iOS 10 devices.
func userNotificationCenter(_ center: UNUserNotificationCenter,
willPresent notification: UNNotification,
withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
let userInfo = notification.request.content.userInfo
// Print message ID.
if let messageID = userInfo[gcmMessageIDKey] {
print("Message ID: \(messageID)")
}
// Print full message.
print(userInfo)
// Change this to your preferred presentation option
completionHandler([])
}
func userNotificationCenter(_ center: UNUserNotificationCenter,
didReceive response: UNNotificationResponse,
withCompletionHandler completionHandler: @escaping () -> Void) {
let userInfo = response.notification.request.content.userInfo
// Print message ID.
if let messageID = userInfo[gcmMessageIDKey] {
print("Message ID: \(messageID)")
}
// Print full message.
print(userInfo)
completionHandler()
}
}
// [END ios_10_message_handling]
// [START ios_10_data_message_handling]
extension AppDelegate : FIRMessagingDelegate {
// Receive data message on iOS 10 devices while app is in the foreground.
func applicationReceivedRemoteMessage(_ remoteMessage: FIRMessagingRemoteMessage) {
print(remoteMessage.appData)
}
}
// [END ios_10_data_message_handling]
| gpl-3.0 | e4e108d96398b93258b12719318d917f | 42.03719 | 285 | 0.648488 | 5.569519 | false | false | false | false |
gottesmm/swift | test/DebugInfo/generic_args.swift | 3 | 2220 | // RUN: %target-swift-frontend -Xllvm -new-mangling-for-tests -primary-file %s -emit-ir -verify -g -o - | %FileCheck %s
func markUsed<T>(_ t: T) {}
protocol AProtocol {
func f() -> String
}
class AClass : AProtocol {
func f() -> String { return "A" }
}
class AnotherClass : AProtocol {
func f() -> String { return "B" }
}
// CHECK-DAG: !DICompositeType(tag: DW_TAG_structure_type, name: "_T012generic_args9aFunction{{.*}}D",{{.*}} elements: ![[PROTOS:[0-9]+]]
// CHECK-DAG: ![[PROTOS]] = !{![[INHERIT:.*]]}
// CHECK-DAG: ![[INHERIT]] = !DIDerivedType(tag: DW_TAG_inheritance,{{.*}} baseType: ![[PROTOCOL:[0-9]+]]
// CHECK-DAG: ![[PROTOCOL]] = !DICompositeType(tag: DW_TAG_structure_type, name: "_T012generic_args9AProtocol_pmD",
// CHECK-DAG: !DILocalVariable(name: "x", arg: 1,{{.*}} type: ![[T:.*]])
// CHECK-DAG: ![[T]] = !DICompositeType(tag: DW_TAG_structure_type, name: "_T012generic_args9aFunction
// CHECK-DAG: !DILocalVariable(name: "y", arg: 2,{{.*}} type: ![[Q:.*]])
// CHECK-DAG: ![[Q]] = !DICompositeType(tag: DW_TAG_structure_type, name: "_T012generic_args9aFunction
func aFunction<T : AProtocol, Q : AProtocol>(_ x: T, _ y: Q, _ z: String) {
markUsed("I am in \(z): \(x.f()) \(y.f())")
}
aFunction(AClass(),AnotherClass(),"aFunction")
struct Wrapper<T: AProtocol> {
init<U: AProtocol>(from : Wrapper<U>) {
// CHECK-DAG: !DICompositeType(tag: DW_TAG_structure_type, name: "Wrapper",{{.*}} identifier: "_T012generic_args7WrapperVyAcCyxGACyqd__G4from_tcAA9AProtocolRd__lufcQq_GD")
var wrapped = from
wrapped = from
_ = wrapped
}
func passthrough(_ t: T) -> T {
// The type of local should have the context Wrapper<T>.
// CHECK-DAG: ![[WRAPPER:.*]] = !DICompositeType({{.*}}identifier: "_T012generic_args7WrapperVQq_D")
// CHECK-DAG: !DILocalVariable(name: "local",{{.*}} line: [[@LINE+1]],{{.*}} type: ![[WRAPPER]]
var local = t
local = t
return local
}
}
// CHECK-DAG: ![[FNTY:.*]] = !DICompositeType({{.*}}identifier: "_T012generic_args5applyq_x_q_xc1ftr0_lFQq_AaBq_x_q_xcACtr0_lFQq0_Ixir_D"
// CHECK-DAG: !DILocalVariable(name: "f", {{.*}}, line: [[@LINE+1]], type: ![[FNTY]])
func apply<T, U> (_ x: T, f: (T) -> (U)) -> U {
return f(x)
}
| apache-2.0 | 7330e8b3b9f1d19f7f7c4e67c1d96e1c | 40.886792 | 173 | 0.616667 | 3.020408 | false | false | false | false |
Superkazuya/zimcher2015 | Zimcher/Constants/Palette.swift | 1 | 647 | import UIKit
extension UIColor
{
convenience init(r: UInt8, g: UInt8, b: UInt8) {
self.init(red: CGFloat(r)/255, green: CGFloat(g)/255, blue: CGFloat(b)/255, alpha: 1)
}
}
struct PALETTE {
static let BLUE = UIColor(red: 96/256.0, green: 111/256.0, blue: 214/256.0, alpha: 1)
static let DARK_BLUE = UIColor(red: 22/256.0, green: 24/256.0, blue: 45/256.0, alpha: 1)
static let SLATE_BLUE = UIColor(red: 95/256.0, green: 108/256.0, blue: 217/256.0, alpha: 1)
static let CORN_FLOWER_BLUE = UIColor(red: 95/256.0, green: 108/256.0, blue: 217/256.0, alpha: 1)
static let WARM_GARY = UIColor(r: 145, g: 145, b: 145)
} | apache-2.0 | e552ffd743b32b9591da6d38a0d46ee9 | 39.5 | 101 | 0.644513 | 2.577689 | false | false | false | false |
AzAli71/AZGradientView | AZGradientViewSample/AZGradientViewSample/classes/AZVerticalGradientView.swift | 1 | 814 | //
// AZVerticalGradientView.swift
// AZGradientViewSample
//
// Created by Ali on 8/28/17.
// Copyright © 2017 Ali Azadeh. All rights reserved.
//
import Foundation
import UIKit
@IBDesignable final class AZVerticalGradientView: AZGradientView {
@IBInspectable var topColor: UIColor = UIColor.clear
@IBInspectable var bottomColor: UIColor = UIColor.clear
override func draw(_ rect: CGRect) {
let gradient: CAGradientLayer = CAGradientLayer()
gradient.frame = CGRect(x: CGFloat(0),
y: CGFloat(0),
width: self.frame.size.width,
height: self.frame.size.height)
gradient.colors = [topColor.cgColor, bottomColor.cgColor]
layer.addSublayer(gradient)
}
}
| mit | a3aeb4f6c402f00a34dd7dff9af49698 | 29.111111 | 66 | 0.617466 | 4.619318 | false | false | false | false |
rmirabelli/UofD-Fall2017 | RecipieReader/RecipieReader/TableViewController.swift | 1 | 1991 | //
// ViewController.swift
// RecipieReader
//
// Created by Russell Mirabelli on 9/26/17.
// Copyright © 2017 Russell Mirabelli. All rights reserved.
//
import UIKit
class TableViewController: UIViewController {
var recipies: [Recipie] = []
@IBOutlet weak var tableView: UITableView!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
tableView.dataSource = self
fetchData()
}
func fetchData() {
let url = URL(string: "https://git.io/vdtMM")!
let session = URLSession(configuration: .default)
let task = session.dataTask(with: url) { (data, response, err) in
let data = data!
let json = try! JSONSerialization.jsonObject(with: data, options: [])
let array = json as! [[String: Any]]
self.recipies = array.map { Recipie(dictionary: $0) }
DispatchQueue.main.async {
self.tableView.reloadData()
}
}
task.resume()
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
guard let destination = segue.destination as? RecipieViewController else { return }
guard let source = sender as? RecipieCell else { return }
destination.recipie = source.recipie
}
}
extension TableViewController: UITableViewDataSource {
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return recipies.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let recipie = recipies[indexPath.item]
let cell = tableView.dequeueReusableCell(withIdentifier: "RecipieCell", for: indexPath) as! RecipieCell
cell.recipie = recipie
return cell
}
}
| mit | 3d53dd251875b58c92e7f7c9b4714f18 | 30.09375 | 111 | 0.629648 | 4.432071 | false | false | false | false |
i-schuetz/clojushop_client_ios_swift | clojushop_client_ios/BaseViewController.swift | 1 | 1909 | //
// BaseViewController.swift
//
// Created by ischuetz on 07/06/2014.
// Copyright (c) 2014 ivanschuetz. All rights reserved.
//
import Foundation
class BaseViewController: UIViewController {
var opaqueIndicator: ProgressIndicator!
var transparentIndicator: ProgressIndicator!
init(nibName nibNameOrNil: String!, bundle nibBundleOrNil: NSBundle!) {
super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil)
}
func getProgressBarBounds() -> CGRect {
var bounds:CGRect = UIScreen.mainScreen().bounds
let viewSize = self.tabBarController.view.frame.size
let tabBarSize = self.tabBarController.tabBar.frame.size
bounds.size.height = viewSize.height - tabBarSize.height
return bounds
}
func initProgressIndicator() {
self.opaqueIndicator = ProgressIndicator(frame: getProgressBarBounds(), backgroundColor: UIColor.whiteColor())
self.transparentIndicator = ProgressIndicator(frame: getProgressBarBounds(), backgroundColor: UIColor.clearColor())
self.view.addSubview(opaqueIndicator)
self.view.addSubview(transparentIndicator)
self.setProgressHidden(true, transparent: true)
self.setProgressHidden(true, transparent: false)
}
override func viewDidLoad() {
self.initProgressIndicator()
}
override func shouldAutorotate() -> Bool {
return true //iOS 5- compatibility
}
override func viewWillUnload() {
NSNotificationCenter.defaultCenter().removeObserver(self)
}
func setProgressHidden(hidden: Bool, transparent: Bool) {
let indicator = transparent ? transparentIndicator : opaqueIndicator
indicator.hidden = hidden
}
func setProgressHidden(hidden: Bool) {
self.setProgressHidden(hidden, transparent: false)
}
} | apache-2.0 | ff989d62bf0e15dc4e09f50e44784942 | 30.833333 | 123 | 0.679413 | 5.244505 | false | false | false | false |
ReSwift/ReSwift-Todo-Example | ReSwift-Todo/ToDo.swift | 1 | 1987 | //
// ToDo.swift
// ReSwift-Todo
//
// Created by Christian Tietze on 30/01/16.
// Copyright © 2016 ReSwift. All rights reserved.
//
import Foundation
enum Completion {
case unfinished
case finished(when: Date?)
var isFinished: Bool {
switch self {
case .unfinished: return false
case .finished: return true
}
}
var date: Date? {
switch self {
case .unfinished: return nil
case .finished(when: let date): return date
}
}
}
struct ToDo {
static var empty: ToDo { return ToDo(title: "New Task") }
let toDoID: ToDoID
var title: String
var completion: Completion
var tags: Set<String>
var isFinished: Bool { return completion.isFinished }
var finishedAt: Date? { return completion.date }
init(toDoID: ToDoID = ToDoID(), title: String, tags: Set<String> = Set(), completion: Completion = .unfinished) {
self.toDoID = toDoID
self.title = title
self.completion = completion
self.tags = tags
}
}
// MARK: ToDo (sub)type equatability
extension ToDo: Equatable {
/// Equality check ignoring the `ToDoID`.
func hasEqualContent(_ other: ToDo) -> Bool {
return title == other.title && completion == other.completion && tags == other.tags
}
}
func ==(lhs: ToDo, rhs: ToDo) -> Bool {
return lhs.toDoID == rhs.toDoID && lhs.title == rhs.title && lhs.completion == rhs.completion && lhs.tags == rhs.tags
}
extension Completion: Equatable { }
func ==(lhs: Completion, rhs: Completion) -> Bool {
switch (lhs, rhs) {
case (.unfinished, .unfinished): return true
case let (.finished(when: lDate), .finished(when: rDate)):
return {
switch (lDate, rDate) {
case (.none, .none): return true
case let (.some(lhs), .some(rhs)): return (lhs == rhs)
default: return false
}
}()
default: return false
}
}
| mit | 5400b6a4e0b1b80679dcf334ff364fbe | 22.093023 | 121 | 0.594663 | 3.940476 | false | false | false | false |
VivaReal/Compose | Compose/Classes/Extensions/UIKit/UIEdgeInsets+Insets.swift | 1 | 1759 | //
// UIEdgeInsets+Insets.swift
// Compose
//
// Created by Bruno Bilescky on 04/10/16.
// Copyright © 2016 VivaReal. All rights reserved.
//
import UIKit
/**
Adding simple inits to help create insets
*/
public extension UIEdgeInsets {
/// Init with optional values. If any value is not provided, it will be treated as `0`
///
/// - parameter top: top inset
/// - parameter leading: left inset
/// - parameter bottom: bottom inset
/// - parameter trailing: right inset
public init(top: CGFloat = 0, leading: CGFloat = 0, bottom: CGFloat = 0, trailing: CGFloat = 0) {
self = UIEdgeInsets(top: top, left: leading, bottom: bottom, right: trailing)
}
/// Init with same value for Left/Right and also 0 for Top/Bottom
///
/// - parameter horizontal: value to use for `left` and `right`
public init(horizontal: CGFloat) {
self = UIEdgeInsets(top: 0, left: horizontal, bottom: 0, right: horizontal)
}
/// Init with same value for Top/Bottom and also 0 for Left/Right
///
/// - parameter vertical: value to use for `Top` and `Bottom`
public init(vertical: CGFloat) {
self = UIEdgeInsets(top: vertical, left: 0, bottom: vertical, right: 0)
}
/// Init with same value for all insets
///
/// - parameter all: value to use for all insets
public init(_ all: CGFloat) {
self = UIEdgeInsets(top: all, left: all, bottom: all, right: all)
}
/// Sum for `Left` and 'Right` insets
public var horizontalInsets: CGFloat {
return self.left + self.right
}
/// Sum for `Top` and 'Bottom` insets
public var verticalInsets: CGFloat {
return self.top + self.bottom
}
}
| mit | 15ead515c0c18eb135901605051c4947 | 29.842105 | 101 | 0.617179 | 4.022883 | false | false | false | false |
icelemon1989/Tipper | SettingsViewController.swift | 1 | 2883 | //
// SettingsViewController.swift
// Tipper
//
// Created by Yang Ruan on 9/29/15.
// Copyright © 2015 Yang Ji. All rights reserved.
//
import UIKit
class SettingsViewController: UIViewController {
@IBOutlet weak var defaultTipControl: UISegmentedControl!
@IBOutlet weak var switchValue: UISwitch!
//Set dark color theme
@IBAction func turnSwitch(sender: UISwitch) {
updateDefaultColor()
}
func updateDefaultColor() {
//save the default color
let defaultDarkSetting = NSUserDefaults.standardUserDefaults()
if switchValue.on {
defaultDarkSetting.setBool(true, forKey: "Default_Dark_Setting")
} else {
defaultDarkSetting.setBool(false, forKey: "Default_Dark_Setting")
}
}
func updateDefaulTip() {
// Save the default tip percentage
let tipDefault = NSUserDefaults.standardUserDefaults()
tipDefault.setInteger(defaultTipControl.selectedSegmentIndex, forKey: "default_tip_segment_index")
tipDefault.synchronize()
}
override func viewDidLoad() {
super.viewDidLoad()
//change the navigationbar tint color
self.navigationController?.navigationBar.tintColor = UIColor(red: 247/255, green: 0, blue: 148/255, alpha: 1)
// Initialize the view with the current default tip percentage
let tipDefault = NSUserDefaults.standardUserDefaults()
let defaultTipSegmentIndex = tipDefault.integerForKey("default_tip_segment_index")
defaultTipControl.selectedSegmentIndex = defaultTipSegmentIndex
//Initialize the swtich with current default switch
let colorDefault = NSUserDefaults.standardUserDefaults()
if colorDefault.boolForKey("Default_Dark_Setting") {
switchValue.setOn(true, animated: false)
} else {
switchValue.setOn(false, animated: false)
}
}
override func viewWillDisappear(animated: Bool) {
updateDefaulTip()
updateDefaultColor()
super.viewWillDisappear(animated)
}
@IBAction func defaultTipControlChange(sender: UISegmentedControl) {
//update default tip control
updateDefaulTip()
}
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 | 360935e8f402c76aed9ecd0b4f436f1e | 29.020833 | 117 | 0.650243 | 5.307551 | false | false | false | false |
ahoppen/swift | test/SILGen/dynamically_replaceable.swift | 21 | 19528 | // RUN: %target-swift-emit-silgen -swift-version 5 %s | %FileCheck %s
// RUN: %target-swift-emit-silgen -swift-version 5 %s -enable-implicit-dynamic | %FileCheck %s --check-prefix=IMPLICIT
// RUN: %target-swift-emit-silgen -swift-version 5 %s -disable-previous-implementation-calls-in-dynamic-replacements | %FileCheck %s --check-prefix=NOPREVIOUS
// CHECK-LABEL: sil hidden [ossa] @$s23dynamically_replaceable014maybe_dynamic_B0yyF : $@convention(thin) () -> () {
// IMPLICIT-LABEL: sil hidden [dynamically_replacable] [ossa] @$s23dynamically_replaceable014maybe_dynamic_B0yyF : $@convention(thin) () -> () {
func maybe_dynamic_replaceable() {
}
// CHECK-LABEL: sil hidden [dynamically_replacable] [ossa] @$s23dynamically_replaceable08dynamic_B0yyF : $@convention(thin) () -> () {
dynamic func dynamic_replaceable() {
}
// CHECK-LABEL: sil hidden [dynamically_replacable] [ossa] @$s23dynamically_replaceable6StruktV1xACSi_tcfC : $@convention(method) (Int, @thin Strukt.Type) -> Strukt
// CHECK-LABEL: sil hidden [dynamically_replacable] [ossa] @$s23dynamically_replaceable6StruktV08dynamic_B0yyF : $@convention(method) (Strukt) -> () {
// CHECK-LABEL: sil hidden [dynamically_replacable] [ossa] @$s23dynamically_replaceable6StruktV08dynamic_B4_varSivg
// CHECK-LABEL: sil hidden [dynamically_replacable] [ossa] @$s23dynamically_replaceable6StruktV08dynamic_B4_varSivs
// CHECK-LABEL: sil hidden [dynamically_replacable] [ossa] @$s23dynamically_replaceable6StruktVyS2icig : $@convention(method) (Int, Strukt) -> Int
// CHECK-LABEL: sil hidden [dynamically_replacable] [ossa] @$s23dynamically_replaceable6StruktVyS2icis : $@convention(method) (Int, Int, @inout Strukt) -> ()
// CHECK-LABEL: sil private [dynamically_replacable] [ossa] @$s23dynamically_replaceable6StruktV22property_with_observerSivW
// CHECK-LABEL: sil private [dynamically_replacable] [ossa] @$s23dynamically_replaceable6StruktV22property_with_observerSivw
struct Strukt {
dynamic init(x: Int) {
}
dynamic func dynamic_replaceable() {
}
dynamic var dynamic_replaceable_var : Int {
get {
return 10
}
set {
}
}
dynamic subscript(x : Int) -> Int {
get {
return 10
}
set {
}
}
dynamic var property_with_observer : Int {
didSet {
}
willSet {
}
}
}
// CHECK-LABEL: sil hidden [dynamically_replacable] [ossa] @$s23dynamically_replaceable5KlassC1xACSi_tcfc : $@convention(method) (Int, @owned Klass) -> @owned Klass
// CHECK-LABEL: sil hidden [dynamically_replacable] [ossa] @$s23dynamically_replaceable5KlassC08dynamic_B0yyF : $@convention(method) (@guaranteed Klass) -> () {
// CHECK-LABEL: sil hidden [dynamically_replacable] [ossa] @$s23dynamically_replaceable5KlassC08dynamic_B4_varSivg
// CHECK-LABEL: sil hidden [dynamically_replacable] [ossa] @$s23dynamically_replaceable5KlassC08dynamic_B4_varSivs
// CHECK-LABEL: sil hidden [dynamically_replacable] [ossa] @$s23dynamically_replaceable5KlassCyS2icig : $@convention(method) (Int, @guaranteed Klass) -> Int
// CHECK-LABEL: sil hidden [dynamically_replacable] [ossa] @$s23dynamically_replaceable5KlassCyS2icis : $@convention(method) (Int, Int, @guaranteed Klass) -> ()
// CHECK-LABEL: sil private [dynamically_replacable] [ossa] @$s23dynamically_replaceable5KlassC22property_with_observerSivW
// CHECK-LABEL: sil private [dynamically_replacable] [ossa] @$s23dynamically_replaceable5KlassC22property_with_observerSivw
class Klass {
dynamic init(x: Int) {
}
dynamic convenience init(c: Int) {
self.init(x: c)
}
dynamic convenience init(a: Int, b: Int) {
}
dynamic func dynamic_replaceable() {
}
dynamic func dynamic_replaceable2() {
}
dynamic var dynamic_replaceable_var : Int {
get {
return 10
}
set {
}
}
dynamic subscript(x : Int) -> Int {
get {
return 10
}
set {
}
}
dynamic var property_with_observer : Int {
didSet {
}
willSet {
}
}
}
class SubKlass : Klass {
// CHECK-LABEL: sil hidden [dynamically_replacable] [ossa] @$s23dynamically_replaceable8SubKlassC1xACSi_tcfc
// CHECK: // dynamic_function_ref Klass.init(x:)
// CHECK: [[FUN:%.*]] = dynamic_function_ref @$s23dynamically_replaceable5KlassC1xACSi_tcfc
// CHECK: apply [[FUN]]
dynamic override init(x: Int) {
super.init(x: x)
}
}
// CHECK-LABEL: sil hidden [dynamically_replacable] [ossa] @$s23dynamically_replaceable6globalSivg : $@convention(thin) () -> Int {
dynamic var global : Int {
return 1
}
// CHECK-LABEL: sil hidden [dynamic_replacement_for "$s23dynamically_replaceable08dynamic_B0yyF"] [ossa] @$s23dynamically_replaceable11replacementyyF : $@convention(thin) () -> () {
@_dynamicReplacement(for: dynamic_replaceable())
func replacement() {
}
extension Klass {
// Calls to the replaced function inside the replacing function should be
// statically dispatched.
// CHECK-LABEL: sil hidden [dynamic_replacement_for "$s23dynamically_replaceable5KlassC08dynamic_B0yyF"] [ossa] @$s23dynamically_replaceable5KlassC11replacementyyF : $@convention(method) (@guaranteed Klass) -> () {
// CHECK: [[FN:%.*]] = prev_dynamic_function_ref @$s23dynamically_replaceable5KlassC11replacementyyF
// CHECK: apply [[FN]](%0) : $@convention(method) (@guaranteed Klass) -> ()
// CHECK: [[METHOD:%.*]] = class_method %0 : $Klass, #Klass.dynamic_replaceable2 :
// CHECK: = apply [[METHOD]](%0) : $@convention(method) (@guaranteed Klass) -> ()
// CHECK: return
// NOPREVIOUS-LABEL: sil hidden [dynamic_replacement_for "$s23dynamically_replaceable5KlassC08dynamic_B0yyF"] [ossa] @$s23dynamically_replaceable5KlassC11replacementyyF : $@convention(method) (@guaranteed Klass) -> () {
// NOPREVIOUS: [[FN:%.*]] = class_method %0 : $Klass, #Klass.dynamic_replaceable
// NOPREVIOUS: apply [[FN]](%0) : $@convention(method) (@guaranteed Klass) -> ()
// NOPREVIOUS: [[METHOD:%.*]] = class_method %0 : $Klass, #Klass.dynamic_replaceable2 :
// NOPREVIOUS: = apply [[METHOD]](%0) : $@convention(method) (@guaranteed Klass) -> ()
// NOPREVIOUS: return
@_dynamicReplacement(for: dynamic_replaceable())
func replacement() {
dynamic_replaceable()
dynamic_replaceable2()
}
// CHECK-LABEL: sil hidden [dynamic_replacement_for "$s23dynamically_replaceable5KlassC1cACSi_tcfC"] [ossa] @$s23dynamically_replaceable5KlassC2crACSi_tcfC : $@convention(method) (Int, @thick Klass.Type) -> @owned Klass {
// CHECK: [[FUN:%.*]] = prev_dynamic_function_ref @$s23dynamically_replaceable5KlassC2crACSi_tcfC
// CHECK: apply [[FUN]]({{.*}}, %1)
// NOPREVIOUS-LABEL: sil hidden [dynamic_replacement_for "$s23dynamically_replaceable5KlassC1cACSi_tcfC"] [ossa] @$s23dynamically_replaceable5KlassC2crACSi_tcfC : $@convention(method) (Int, @thick Klass.Type) -> @owned Klass {
// NOPREVIOUS: [[FUN:%.*]] = dynamic_function_ref @$s23dynamically_replaceable5KlassC1cACSi_tcfC
// NOPREVIOUS: apply [[FUN]]({{.*}}, %1)
@_dynamicReplacement(for: init(c:))
convenience init(cr: Int) {
self.init(c: cr + 1)
}
// CHECK-LABEL: sil hidden [dynamic_replacement_for "$s23dynamically_replaceable5KlassC1a1bACSi_SitcfC"] [ossa] @$s23dynamically_replaceable5KlassC2ar2brACSi_SitcfC
// CHECK: // dynamic_function_ref Klass.__allocating_init(c:)
// CHECK: [[FUN:%.*]] = dynamic_function_ref @$s23dynamically_replaceable5KlassC1cACSi_tcfC
// CHECK: apply [[FUN]]({{.*}}, %2)
// NOPREVIOUS-LABEL: sil hidden [dynamic_replacement_for "$s23dynamically_replaceable5KlassC1a1bACSi_SitcfC"] [ossa] @$s23dynamically_replaceable5KlassC2ar2brACSi_SitcfC
// NOPREVIOUS: // dynamic_function_ref Klass.__allocating_init(c:)
// NOPREVIOUS: [[FUN:%.*]] = dynamic_function_ref @$s23dynamically_replaceable5KlassC1cACSi_tcfC
// NOPREVIOUS: apply [[FUN]]({{.*}}, %2)
@_dynamicReplacement(for: init(a: b:))
convenience init(ar: Int, br: Int) {
self.init(c: ar + br)
}
@_dynamicReplacement(for: init(x:))
init(xr: Int) {
}
// CHECK-LABEL: sil hidden [dynamic_replacement_for "$s23dynamically_replaceable5KlassC08dynamic_B4_varSivg"] [ossa] @$s23dynamically_replaceable5KlassC1rSivg : $@convention(method) (@guaranteed Klass) -> Int {
// CHECK: bb0([[ARG:%.*]] : @guaranteed $Klass):
// CHECK: [[ORIG:%.*]] = prev_dynamic_function_ref @$s23dynamically_replaceable5KlassC1rSivg
// CHECK: apply [[ORIG]]([[ARG]]) : $@convention(method) (@guaranteed Klass) -> Int
// NOPREVIOUS-LABEL: sil hidden [dynamic_replacement_for "$s23dynamically_replaceable5KlassC08dynamic_B4_varSivg"] [ossa] @$s23dynamically_replaceable5KlassC1rSivg : $@convention(method) (@guaranteed Klass) -> Int {
// NOPREVIOUS: bb0([[ARG:%.*]] : @guaranteed $Klass):
// NOPREVIOUS: [[ORIG:%.*]] = class_method [[ARG]] : $Klass, #Klass.dynamic_replaceable_var!getter
// NOPREVIOUS: apply [[ORIG]]([[ARG]]) : $@convention(method) (@guaranteed Klass) -> Int
// CHECK-LABEL: sil hidden [dynamic_replacement_for "$s23dynamically_replaceable5KlassC08dynamic_B4_varSivs"] [ossa] @$s23dynamically_replaceable5KlassC1rSivs : $@convention(method) (Int, @guaranteed Klass) -> () {
// CHECK: bb0({{.*}} : $Int, [[SELF:%.*]] : @guaranteed $Klass):
// CHECK: [[ORIG:%.*]] = prev_dynamic_function_ref @$s23dynamically_replaceable5KlassC1rSivs
// CHECK: apply [[ORIG]]({{.*}}, [[SELF]]) : $@convention(method)
// NOPREVIOUS-LABEL: sil hidden [dynamic_replacement_for "$s23dynamically_replaceable5KlassC08dynamic_B4_varSivs"] [ossa] @$s23dynamically_replaceable5KlassC1rSivs : $@convention(method) (Int, @guaranteed Klass) -> () {
// NOPREVIOUS: bb0({{.*}} : $Int, [[SELF:%.*]] : @guaranteed $Klass):
// NOPREVIOUS: [[ORIG:%.*]] = class_method [[SELF]] : $Klass, #Klass.dynamic_replaceable_var!setter
// NOPREVIOUS: apply [[ORIG]]({{.*}}, [[SELF]]) : $@convention(method)
@_dynamicReplacement(for: dynamic_replaceable_var)
var r : Int {
get {
return dynamic_replaceable_var + 1
}
set {
dynamic_replaceable_var = newValue + 1
}
}
// CHECK-LABEL: sil hidden [dynamic_replacement_for "$s23dynamically_replaceable5KlassCyS2icig"] [ossa] @$s23dynamically_replaceable5KlassC1xS2i_tcig
// CHECK: bb0({{.*}} : $Int, [[SELF:%.*]] : @guaranteed $Klass):
// CHECK: [[ORIG:%.*]] = prev_dynamic_function_ref @$s23dynamically_replaceable5KlassC1xS2i_tcig
// CHECK: apply [[ORIG]]({{.*}}, [[SELF]]) : $@convention(method) (Int, @guaranteed Klass) -> Int
// CHECK-LABEL: sil hidden [dynamic_replacement_for "$s23dynamically_replaceable5KlassCyS2icis"] [ossa] @$s23dynamically_replaceable5KlassC1xS2i_tcis
// CHECK: bb0({{.*}} : $Int, {{.*}} : $Int, [[SELF:%.*]] : @guaranteed $Klass):
// CHECK: [[ORIG:%.*]] = prev_dynamic_function_ref @$s23dynamically_replaceable5KlassC1xS2i_tcis
// CHECK: apply [[ORIG]]({{.*}}, {{.*}}, [[SELF]]) : $@convention(method) (Int, Int, @guaranteed Klass) -> ()
@_dynamicReplacement(for: subscript(_:))
subscript(x y: Int) -> Int {
get {
return self[y]
}
set {
self[y] = newValue
}
}
}
extension Strukt {
// CHECK-LABEL: sil hidden [dynamic_replacement_for "$s23dynamically_replaceable6StruktV08dynamic_B0yyF"] [ossa] @$s23dynamically_replaceable6StruktV11replacementyyF : $@convention(method) (Strukt) -> () {
// CHECK: [[FUN:%.*]] = prev_dynamic_function_ref @$s23dynamically_replaceable6StruktV11replacementyyF
// CHECK: apply [[FUN]](%0) : $@convention(method) (Strukt) -> ()
@_dynamicReplacement(for: dynamic_replaceable())
func replacement() {
dynamic_replaceable()
}
// CHECK-LABEL: sil hidden [dynamic_replacement_for "$s23dynamically_replaceable6StruktV1xACSi_tcfC"] [ossa] @$s23dynamically_replaceable6StruktV1yACSi_tcfC : $@convention(method) (Int, @thin Strukt.Type) -> Strukt {
// CHECK: [[FUN:%.*]] = prev_dynamic_function_ref @$s23dynamically_replaceable6StruktV1yACSi_tcfC
// CHECK: apply [[FUN]]({{.*}}, %1)
@_dynamicReplacement(for: init(x:))
init(y: Int) {
self.init(x: y + 1)
}
// CHECK-LABEL: sil hidden [dynamic_replacement_for "$s23dynamically_replaceable6StruktV08dynamic_B4_varSivg"] [ossa] @$s23dynamically_replaceable6StruktV1rSivg
// CHECK: bb0([[ARG:%.*]] : $Strukt):
// CHECK: [[ORIG:%.*]] = prev_dynamic_function_ref @$s23dynamically_replaceable6StruktV1rSivg
// CHECK: apply [[ORIG]]([[ARG]]) : $@convention(method) (Strukt) -> Int
// CHECK-LABEL: sil hidden [dynamic_replacement_for "$s23dynamically_replaceable6StruktV08dynamic_B4_varSivs"] [ossa] @$s23dynamically_replaceable6StruktV1rSivs
// CHECK: bb0({{.*}} : $Int, [[ARG:%.*]] : $*Strukt):
// CHECK: [[BA:%.*]] = begin_access [modify] [unknown] [[ARG]] : $*Strukt
// CHECK: [[ORIG:%.*]] = prev_dynamic_function_ref @$s23dynamically_replaceable6StruktV1rSivs
// CHECK: apply [[ORIG]]({{.*}}, [[BA]]) : $@convention(method) (Int, @inout Strukt) -> ()
// CHECK: end_access [[BA]] : $*Strukt
@_dynamicReplacement(for: dynamic_replaceable_var)
var r : Int {
get {
return dynamic_replaceable_var + 1
}
set {
dynamic_replaceable_var = newValue + 1
}
}
// CHECK-LABEL: sil hidden [dynamic_replacement_for "$s23dynamically_replaceable6StruktVyS2icig"] [ossa] @$s23dynamically_replaceable6StruktV1xS2i_tcig
// CHECK: bb0({{.*}} : $Int, [[SELF:%.*]] : $Strukt):
// CHECK: [[ORIG:%.*]] = prev_dynamic_function_ref @$s23dynamically_replaceable6StruktV1xS2i_tcig
// CHECK: apply [[ORIG]]({{.*}}, [[SELF]]) : $@convention(method) (Int, Strukt) -> Int
// CHECK-LABEL: sil hidden [dynamic_replacement_for "$s23dynamically_replaceable6StruktVyS2icis"] [ossa] @$s23dynamically_replaceable6StruktV1xS2i_tcis
// CHECK: bb0({{.*}} : $Int, {{.*}} : $Int, [[SELF:%.*]] : $*Strukt):
// CHECK: [[BA:%.*]] = begin_access [modify] [unknown] [[SELF]] : $*Strukt
// CHECK: [[ORIG:%.*]] = prev_dynamic_function_ref @$s23dynamically_replaceable6StruktV1xS2i_tcis
// CHECK: apply [[ORIG]]({{.*}}, {{.*}}, [[BA]]) : $@convention(method) (Int, Int, @inout Strukt) -> ()
// CHECK: end_access [[BA]] : $*Strukt
@_dynamicReplacement(for: subscript(_:))
subscript(x y: Int) -> Int {
get {
return self[y]
}
set {
self[y] = newValue
}
}
}
struct GenericS<T> {
dynamic init(x: Int) {
}
dynamic func dynamic_replaceable() {
}
dynamic var dynamic_replaceable_var : Int {
get {
return 10
}
set {
}
}
dynamic subscript(x : Int) -> Int {
get {
return 10
}
set {
}
}
// CHECK-LABEL: sil private [dynamically_replacable] [ossa] @$s23dynamically_replaceable8GenericSV22property_with_observerSivW
// CHECK-LABEL: sil private [dynamically_replacable] [ossa] @$s23dynamically_replaceable8GenericSV22property_with_observerSivw
dynamic var property_with_observer : Int {
didSet {
}
willSet {
}
}
}
extension GenericS {
// CHECK-LABEL: sil hidden [dynamic_replacement_for "$s23dynamically_replaceable8GenericSV08dynamic_B0yyF"] [ossa] @$s23dynamically_replaceable8GenericSV11replacementyyF
// CHECK: prev_dynamic_function_ref @$s23dynamically_replaceable8GenericSV11replacementyyF
@_dynamicReplacement(for: dynamic_replaceable())
func replacement() {
dynamic_replaceable()
}
// CHECK-LABEL: sil hidden [dynamic_replacement_for "$s23dynamically_replaceable8GenericSV1xACyxGSi_tcfC"] [ossa] @$s23dynamically_replaceable8GenericSV1yACyxGSi_tcfC
// CHECK: prev_dynamic_function_ref @$s23dynamically_replaceable8GenericSV1yACyxGSi_tcfC
@_dynamicReplacement(for: init(x:))
init(y: Int) {
self.init(x: y + 1)
}
// CHECK-LABEL: sil hidden [dynamic_replacement_for "$s23dynamically_replaceable8GenericSV08dynamic_B4_varSivg"] [ossa] @$s23dynamically_replaceable8GenericSV1rSivg
// CHECK: prev_dynamic_function_ref @$s23dynamically_replaceable8GenericSV1rSivg
// CHECK-LABEL: sil hidden [dynamic_replacement_for "$s23dynamically_replaceable8GenericSV08dynamic_B4_varSivs"] [ossa] @$s23dynamically_replaceable8GenericSV1rSivs
// CHECK: prev_dynamic_function_ref @$s23dynamically_replaceable8GenericSV1rSivs
@_dynamicReplacement(for: dynamic_replaceable_var)
var r : Int {
get {
return dynamic_replaceable_var + 1
}
set {
dynamic_replaceable_var = newValue + 1
}
}
// CHECK-LABEL: sil hidden [dynamic_replacement_for "$s23dynamically_replaceable8GenericSVyS2icig"] [ossa] @$s23dynamically_replaceable8GenericSV1xS2i_tcig
// CHECK: prev_dynamic_function_ref @$s23dynamically_replaceable8GenericSV1xS2i_tcig
// CHECK-LABEL: sil hidden [dynamic_replacement_for "$s23dynamically_replaceable8GenericSVyS2icis"] [ossa] @$s23dynamically_replaceable8GenericSV1xS2i_tcis
// CHECK: prev_dynamic_function_ref @$s23dynamically_replaceable8GenericSV1xS2i_tcis
@_dynamicReplacement(for: subscript(_:))
subscript(x y: Int) -> Int {
get {
return self[y]
}
set {
self[y] = newValue
}
}
// CHECK-LABEL: sil private [dynamic_replacement_for "$s23dynamically_replaceable8GenericSV22property_with_observerSivW"] [ossa] @$s23dynamically_replaceable8GenericSV34replacement_property_with_observerSivW
// CHECK-LABEL: sil private [dynamic_replacement_for "$s23dynamically_replaceable8GenericSV22property_with_observerSivw"] [ossa] @$s23dynamically_replaceable8GenericSV34replacement_property_with_observerSivw
@_dynamicReplacement(for: property_with_observer)
var replacement_property_with_observer : Int {
didSet {
}
willSet {
}
}
}
dynamic var globalX = 0
// CHECK-LABEL: sil hidden [dynamically_replacable] [ossa] @$s23dynamically_replaceable7globalXSivg : $@convention(thin) () -> Int
// CHECK-LABEL: sil hidden [dynamically_replacable] [ossa] @$s23dynamically_replaceable7globalXSivs : $@convention(thin) (Int) -> ()
// CHECK-LABEL: sil hidden [ossa] @$s23dynamically_replaceable7getsetXyS2iF
// CHECK: dynamic_function_ref @$s23dynamically_replaceable7globalXSivs
// CHECK: dynamic_function_ref @$s23dynamically_replaceable7globalXSivg
func getsetX(_ x: Int) -> Int {
globalX = x
return globalX
}
// CHECK-LABEL: sil hidden [ossa] @$s23dynamically_replaceable18funcWithDefaultArgyySSFfA_
// CHECK-LABEL: sil hidden [dynamically_replacable] [ossa] @$s23dynamically_replaceable18funcWithDefaultArgyySSF
dynamic func funcWithDefaultArg(_ arg : String = String("hello")) {
print("hello")
}
// IMPLICIT-LABEL: sil hidden [thunk] [ossa] @barfoo
@_cdecl("barfoo")
func foobar() {
}
// IMPLICIT-LABEL: sil private [ossa] @$s23dynamically_replaceable6$deferL_yyF
var x = 10
defer {
let y = x
}
// IMPLICIT-LABEL: sil [dynamically_replacable] [ossa] @$s23dynamically_replaceable16testWithLocalFunyyF
// IMPLICIT-LABEL: sil private [ossa] @$s23dynamically_replaceable16testWithLocalFunyyF05localF0L_yyF
// IMPLICIT-LABEL: sil private [ossa] @$s23dynamically_replaceable16testWithLocalFunyyF05localF0L_yyF0geF0L_yyF
// IMPLICIT-LABEL: sil private [ossa] @$s23dynamically_replaceable16testWithLocalFunyyFyycfU_
public func testWithLocalFun() {
func localFun() {
func localLocalFun() { print("bar") }
print("foo")
localLocalFun()
}
localFun()
let unamedClosure = { print("foo") }
unamedClosure()
}
@propertyWrapper
struct WrapperWithInitialValue<T> {
var wrappedValue: T
init(wrappedValue initialValue: T) {
self.wrappedValue = initialValue
}
}
// CHECK-NOT: sil hidden [ossa] @$s23dynamically_replaceable10SomeStructV1tSbvpfP
public struct SomeStruct {
@WrapperWithInitialValue var t = false
}
// Make sure that declaring the replacement before the original does not assert.
@_dynamicReplacement(for: orig)
func opaqueReplacement() -> Int {
return 2
}
dynamic func orig() -> Int {
return 1
}
| apache-2.0 | c9cd25473d63a591c982ac088f4b95d6 | 44.413953 | 228 | 0.703451 | 3.652141 | false | false | false | false |
jiecao-fm/SwiftTheme | Source/ThemeManager.swift | 3 | 2191 | //
// ThemeManager.swift
// SwiftTheme
//
// Created by Gesen on 16/1/22.
// Copyright © 2016年 Gesen. All rights reserved.
//
import Foundation
public let ThemeUpdateNotification = "ThemeUpdateNotification"
public enum ThemePath {
case mainBundle
case sandbox(Foundation.URL)
public var URL: Foundation.URL? {
switch self {
case .mainBundle : return nil
case .sandbox(let path) : return path
}
}
public func plistPath(name: String) -> String? {
switch self {
case .mainBundle:
return Bundle.main.path(forResource: name, ofType: "plist")
case .sandbox(let path):
let name = name.hasSuffix(".plist") ? name : name + ".plist"
let url = path.appendingPathComponent(name)
return url.path
}
}
}
@objc public final class ThemeManager: NSObject {
@objc public static var animationDuration = 0.3
@objc public fileprivate(set) static var currentTheme: NSDictionary?
@objc public fileprivate(set) static var currentThemeIndex: Int = 0
public fileprivate(set) static var currentThemePath: ThemePath?
}
public extension ThemeManager {
@objc class func setTheme(index: Int) {
currentThemeIndex = index
NotificationCenter.default.post(name: Notification.Name(rawValue: ThemeUpdateNotification), object: nil)
}
class func setTheme(plistName: String, path: ThemePath) {
guard let plistPath = path.plistPath(name: plistName) else {
print("SwiftTheme WARNING: Can't find plist '\(plistName)' at: \(path)")
return
}
guard let plistDict = NSDictionary(contentsOfFile: plistPath) else {
print("SwiftTheme WARNING: Can't read plist '\(plistName)' at: \(plistPath)")
return
}
self.setTheme(dict: plistDict, path: path)
}
class func setTheme(dict: NSDictionary, path: ThemePath) {
currentTheme = dict
currentThemePath = path
NotificationCenter.default.post(name: Notification.Name(rawValue: ThemeUpdateNotification), object: nil)
}
}
| mit | 24ba35c5a6f0db9e19cb98f1e0a47541 | 28.972603 | 112 | 0.633912 | 4.645435 | false | false | false | false |
suragch/MongolAppDevelopment-iOS | Mongol App Componants/UIMongolTableView.swift | 1 | 4853 |
import UIKit
@IBDesignable class UIMongolTableView: UIView {
// MARK:- Unique to TableView
// ********* Unique to TableView *********
fileprivate var view = UITableView()
fileprivate let rotationView = UIView()
fileprivate var userInteractionEnabledForSubviews = true
// read only refernce to the underlying tableview
var tableView: UITableView {
get {
return view
}
}
var setTableFooterView: UIView? {
get {
return view.tableFooterView
}
set {
view.tableFooterView = newValue
}
}
var backgroundView: UIView? {
get {
return view.backgroundView
}
set {
view.backgroundView = newValue
}
}
var estimatedRowHeight: CGFloat {
get {
return view.estimatedRowHeight
}
set {
view.estimatedRowHeight = newValue
}
}
var rowHeight: CGFloat {
get {
return view.rowHeight
}
set {
view.rowHeight = newValue
}
}
var separatorInset: UIEdgeInsets {
get {
return view.separatorInset
}
set {
view.separatorInset = newValue
}
}
override var backgroundColor: UIColor? {
get {
return view.backgroundColor
}
set {
view.backgroundColor = newValue
}
}
func registerNib(_ nib: UINib?, forCellReuseIdentifier identifier: String) {
view.register(nib, forCellReuseIdentifier: identifier)
}
func setup() {
// do any setup necessary
self.addSubview(rotationView)
rotationView.addSubview(view)
self.backgroundColor = UIColor.clear
view.layoutMargins = UIEdgeInsets.zero
view.separatorInset = UIEdgeInsets.zero
}
// FIXME: @IBOutlet still can't be set in IB
@IBOutlet weak var delegate: UITableViewDelegate? {
get {
return view.delegate
}
set {
view.delegate = newValue
}
}
// FIXME: @IBOutlet still can't be set in IB
@IBOutlet weak var dataSource: UITableViewDataSource? {
get {
return view.dataSource
}
set {
view.dataSource = newValue
}
}
@IBInspectable var scrollEnabled: Bool {
get {
return view.isScrollEnabled
}
set {
view.isScrollEnabled = newValue
}
}
func scrollToRowAtIndexPath(_ indexPath: IndexPath, atScrollPosition: UITableViewScrollPosition, animated: Bool) {
view.scrollToRow(at: indexPath, at: atScrollPosition, animated: animated)
}
func registerClass(_ cellClass: AnyClass?, forCellReuseIdentifier identifier: String) {
view.register(cellClass, forCellReuseIdentifier: identifier)
}
func dequeueReusableCellWithIdentifier(_ identifier: String) -> UITableViewCell? {
return view.dequeueReusableCell(withIdentifier: identifier)
}
func reloadData() {
view.reloadData()
}
// MARK:- General code for Mongol views
// *******************************************
// ****** General code for Mongol views ******
// *******************************************
// This method gets called if you create the view in the Interface Builder
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
// This method gets called if you create the view in code
override init(frame: CGRect){
super.init(frame: frame)
self.setup()
}
override func awakeFromNib() {
super.awakeFromNib()
self.setup()
}
override func layoutSubviews() {
super.layoutSubviews()
rotationView.transform = CGAffineTransform.identity
rotationView.frame = CGRect(origin: CGPoint.zero, size: CGSize(width: self.bounds.height, height: self.bounds.width))
rotationView.transform = translateRotateFlip()
view.frame = rotationView.bounds
}
func translateRotateFlip() -> CGAffineTransform {
var transform = CGAffineTransform.identity
// translate to new center
transform = transform.translatedBy(x: (self.bounds.width / 2)-(self.bounds.height / 2), y: (self.bounds.height / 2)-(self.bounds.width / 2))
// rotate counterclockwise around center
transform = transform.rotated(by: CGFloat(-M_PI_2))
// flip vertically
transform = transform.scaledBy(x: -1, y: 1)
return transform
}
}
| mit | e1f606e30f3ddcfb62bc598e91db7fa0 | 25.091398 | 148 | 0.55883 | 5.591014 | false | false | false | false |
dreamsxin/swift | benchmark/single-source/StringBuilder.swift | 7 | 778 | //===--- StringBuilder.swift ----------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
import TestsUtils
@inline(never)
func buildString() -> String {
var sb = "a"
for str in ["b","c","d","pizza"] {
sb += str
}
return sb
}
@inline(never)
public func run_StringBuilder(_ N: Int) {
for _ in 1...5000*N {
_ = buildString()
}
}
| apache-2.0 | b5fce148557310c79ca8cd8aac3d1f90 | 24.933333 | 80 | 0.550129 | 4.228261 | false | false | false | false |
RocketChat/Rocket.Chat.iOS | Rocket.ChatTests/API/Requests/Room/RoomRolesRequestSpec.swift | 1 | 5932 | //
// RoomRolesRequestSpec.swift
// Rocket.ChatTests
//
// Created by Rafael Kellermann Streit on 11/05/18.
// Copyright © 2018 Rocket.Chat. All rights reserved.
//
import XCTest
import SwiftyJSON
@testable import Rocket_Chat
class RoomRolesRequestSpec: APITestCase {
func testRequest() {
let reactRequest = RoomRolesRequest(roomName: "general", subscriptionType: .channel)
guard let request = reactRequest.request(for: api) else {
return XCTFail("request is not nil")
}
XCTAssertEqual(request.url?.path, "/api/v1/channels.roles", "path is correct")
XCTAssertEqual(request.httpMethod, "GET", "http method is correct")
XCTAssertEqual(request.url?.query, "roomName=general", "query value is correct")
XCTAssertEqual(request.value(forHTTPHeaderField: "Content-Type"), "application/json", "content type is correct")
}
func testResult() {
let jsonString = """
{
"roles": [{
"u": {
"name": "John Appleseed",
"username": "john.appleseed",
"_id": "Xx6KW6XQsFkmDPGdE"
},
"_id": "j2pdXnucQbLg5WXRu",
"rid": "ABsnusN6m9h7Z7KnR",
"roles": [
"owner",
"moderator",
"leader"
]
},{
"u": {
"name": "John Applesee 2",
"username": "john.appleseed.2",
"_id": "xyJPCay3ShCQyuezh"
},
"_id": "oCMaLjQ74HuhSEW9g",
"rid": "ABsnusN6m9h7Z7KnR",
"roles": [
"moderator"
]
}
],
"success": true
}
"""
let json = JSON(parseJSON: jsonString)
let result = RoomRolesResource(raw: json)
XCTAssertEqual(result.roomRoles?.count, 2)
XCTAssertEqual(result.roomRoles?.first?.user?.username, "john.appleseed")
XCTAssertEqual(result.roomRoles?.first?.roles.count, 3)
XCTAssertEqual(result.roomRoles?.first?.roles.first, Role.owner.rawValue)
XCTAssertTrue(result.success)
}
func testNullUserObject() {
let jsonString = """
{
"roles": [{
"u": null,
"_id": "j2pdXnucQbLg5WXRu",
"rid": "ABsnusN6m9h7Z7KnR",
"roles": [
"owner",
"moderator",
"leader"
]
}
],
"success": true
}
"""
let json = JSON(parseJSON: jsonString)
let result = RoomRolesResource(raw: json)
XCTAssertTrue(result.success)
XCTAssertEqual(result.roomRoles?.count, 1)
XCTAssertEqual(result.roomRoles?.first?.roles.count, 3)
XCTAssertNotNil(result.roomRoles?.first?.user)
XCTAssertNil(result.roomRoles?.first?.user?.identifier)
}
func testInvalidUserObject() {
let jsonString = """
{
"roles": [{
"u": {
"foo": "bar"
},
"_id": "j2pdXnucQbLg5WXRu",
"rid": "ABsnusN6m9h7Z7KnR",
"roles": [
"owner",
"moderator",
"leader"
]
}
],
"success": true
}
"""
let json = JSON(parseJSON: jsonString)
let result = RoomRolesResource(raw: json)
XCTAssertTrue(result.success)
XCTAssertEqual(result.roomRoles?.count, 1)
XCTAssertEqual(result.roomRoles?.first?.roles.count, 3)
XCTAssertNotNil(result.roomRoles?.first?.user)
XCTAssertNil(result.roomRoles?.first?.user?.identifier)
}
func testArrayUserObject() {
let jsonString = """
{
"roles": [{
"u": ["foo"],
"_id": "j2pdXnucQbLg5WXRu",
"rid": "ABsnusN6m9h7Z7KnR",
"roles": [
"owner",
"moderator",
"leader"
]
}
],
"success": true
}
"""
let json = JSON(parseJSON: jsonString)
let result = RoomRolesResource(raw: json)
XCTAssertTrue(result.success)
XCTAssertEqual(result.roomRoles?.count, 1)
XCTAssertEqual(result.roomRoles?.first?.roles.count, 3)
XCTAssertNotNil(result.roomRoles?.first?.user)
XCTAssertNil(result.roomRoles?.first?.user?.identifier)
}
func testEmtpyRolesObject() {
let jsonString = """
{
"roles": [{
"u": {
"name": "John Appleseed",
"username": "john.appleseed",
"_id": "Xx6KW6XQsFkmDPGdE"
},
"_id": "j2pdXnucQbLg5WXRu",
"rid": "ABsnusN6m9h7Z7KnR",
"roles": [ ]
}
],
"success": true
}
"""
let json = JSON(parseJSON: jsonString)
let result = RoomRolesResource(raw: json)
XCTAssertTrue(result.success)
XCTAssertEqual(result.roomRoles?.count, 1)
XCTAssertEqual(result.roomRoles?.first?.roles.count, 0)
XCTAssertEqual(result.roomRoles?.first?.user?.username, "john.appleseed")
}
func testEmptyResults() {
let nilResult = RoomRolesResource(raw: nil)
XCTAssertNil(nilResult.roomRoles)
}
}
| mit | 1ed9509e3832ad509e4b2f0d510935ee | 30.380952 | 120 | 0.470241 | 4.496588 | false | true | false | false |
hermantai/samples | ios/cs193p/CardMatching/CardMatching/GameThemeStore.swift | 1 | 3030 | //
// GameThemeStore.swift
// CardMatching
//
// Created by Herman (Heung) Tai on 11/7/21.
//
import Foundation
class GameThemeStore: ObservableObject {
@Published var gameThemes = [GameTheme]() {
didSet {
storeInUserDefaults()
}
}
let name: String
private var userDefaultsKey: String {
"GameThemeStore:" + name
}
private func storeInUserDefaults() {
UserDefaults.standard.set(try? JSONEncoder().encode(gameThemes), forKey: userDefaultsKey)
}
private func restoreFromUserDefaults() {
if let jsonData = UserDefaults.standard.data(forKey: userDefaultsKey),
let decodedPalettes = try? JSONDecoder().decode(Array<GameTheme>.self, from: jsonData) {
gameThemes = decodedPalettes
}
}
init(named name: String) {
self.name = name
restoreFromUserDefaults()
if gameThemes.isEmpty {
insertTheme(named: "Animals",
emojis: "🐶🐱🐭🐹🐰🦊🐻🐼🐻❄️🐨🐯🦁🐮🐷🐸🐵",
color: RGBAColor(color: .red))
insertTheme(
named: "Food",
emojis: "🍎🍐🍊🍋🍌🍉🍇🍓🫐🍈🍒🍑🥭🍍🥥🥝🍅🍆🥑🥦",
color: RGBAColor(color: .orange))
insertTheme(
named: "Vehicles",
emojis: "🚗🚕🚙🚌🚎🏎🚓🚑🚒🚐🛻🚚🚛🚜🚀🚁⛵️🚤🦼🛴🚍✈️🚂🚊",
color: RGBAColor(color: .yellow))
insertTheme(
named: "Halloween",
emojis: "👻🎃🕷",
color: RGBAColor(color: .gray))
}
}
// MARK: - Intent
func gameTheme(at index: Int) -> GameTheme {
let safeIndex = min(max(index, 0), gameThemes.count - 1)
return gameThemes[safeIndex]
}
@discardableResult
func removeTheme(at index: Int) -> Int {
if gameThemes.count > 1, gameThemes.indices.contains(index) {
gameThemes.remove(at: index)
}
return index % gameThemes.count
}
func insertTheme(named name: String, emojis: String, color: RGBAColor, at index: Int = 0) {
let unique = (gameThemes.max(by: { $0.id < $1.id })?.id ?? 0) + 1
let gameTheme = GameTheme(name: name, emojis: emojis, color: color, id: unique)
let safeIndex = min(max(index, 0), gameThemes.count)
gameThemes.insert(gameTheme, at: safeIndex)
}
}
/// A Theme consists of a name
/// for the theme, a set of emoji to use, a number of pairs of cards to show, and an
/// appropriate color to use to draw the cards.
struct GameTheme: Identifiable, Codable, Hashable {
let name: String
let emojis: String
let color: RGBAColor
let id: Int
}
struct RGBAColor: Codable, Equatable, Hashable {
let red: Double
let green: Double
let blue: Double
let alpha: Double
}
| apache-2.0 | 74fae5113ee6945354299c4732aedca6 | 28.510417 | 99 | 0.56089 | 3.599746 | false | false | false | false |
RocketChat/Rocket.Chat.iOS | Rocket.ChatTests/Extensions/API/APIExtensionsSpec.swift | 1 | 1145 | //
// APIExtensionsSpec.swift
// Rocket.ChatTests
//
// Created by Matheus Cardoso on 11/28/17.
// Copyright © 2017 Rocket.Chat. All rights reserved.
//
import XCTest
import RealmSwift
@testable import Rocket_Chat
class APIExtensionsSpec: XCTestCase {
func testCurrent() {
guard let realm = Realm.current else {
XCTFail("realm could not be instantiated")
return
}
var auth = Auth.testInstance()
realm.execute({ realm in
realm.add(auth)
})
var api = API.current(realm: realm)
XCTAssertEqual(api?.userId, "auth-userid")
XCTAssertEqual(api?.authToken, "auth-token")
XCTAssertEqual(api?.version, Version(1, 2, 3))
Realm.execute({ realm in
auth.serverVersion = "invalid"
realm.add(auth, update: true)
})
api = API.current(realm: realm)
XCTAssertEqual(api?.version, Version.zero)
auth = Auth()
api = API.current(realm: realm)
XCTAssertNotNil(api)
auth = Auth()
api = API.current(realm: nil)
XCTAssertNil(api)
}
}
| mit | bee2ec4cffb31a46a26fde79901ba49a | 21.431373 | 54 | 0.589161 | 4.252788 | false | true | false | false |
velvetroom/columbus | Source/View/CreateSave/VCreateSaveStatusError+Constants.swift | 1 | 494 | import UIKit
extension VCreateSaveStatusError
{
struct Constants
{
static let labelBottom:CGFloat = -200
static let labelHeight:CGFloat = 220
static let titleFontSize:CGFloat = 20
static let descrFontSize:CGFloat = 14
static let buttonWidth:CGFloat = 120
static let buttonHeight:CGFloat = 40
static let cancelFontSize:CGFloat = 16
static let retryFontSize:CGFloat = 18
static let imageHeight:CGFloat = 80
}
}
| mit | f2482df1fc1c991fff61e81d3f480058 | 28.058824 | 46 | 0.67004 | 4.989899 | false | false | false | false |
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 | 0c86d8cfae7ba0786008e866e6563c29 | 30.677551 | 99 | 0.620667 | 4.3285 | false | false | false | false |
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 | 96cd2c72977606970712ccb7b626b309 | 32.114583 | 136 | 0.67128 | 5.289517 | false | false | false | false |
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 | c1a0bd613f3f2483dffb8c0e494134a2 | 46.25 | 182 | 0.656614 | 5.071556 | false | false | false | false |
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 | 2f4ad7ecbc15b6e373aaf176b08ced98 | 23.226087 | 79 | 0.611989 | 3.864078 | false | false | false | false |
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 | 0549606ce6ad3f63ad99039517128843 | 28.972222 | 103 | 0.656163 | 4.838565 | false | false | false | false |
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 | 16a81d30900c7a8cd47e390d5d3359a9 | 19.156352 | 103 | 0.610537 | 3.409366 | false | false | false | false |
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 | 9d05409b4b16e5531e9f2e79a6deba4d | 21.364198 | 104 | 0.648358 | 3.150435 | false | false | false | false |
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 | 103ec4b51fcdea8cb02ebaba57b5f75e | 26.118321 | 109 | 0.675581 | 5.035436 | false | false | false | false |
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 | 5b3bbbd123ac183f753821133c88f8dd | 26.309524 | 116 | 0.646731 | 5.088731 | false | false | false | false |
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 | 15f8511e8f80e11fe7a499d63c7494c6 | 30.944444 | 160 | 0.637217 | 5.017452 | false | false | false | false |
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 | 63beea9e414401f7796db82d6c8eecf9 | 31.713402 | 200 | 0.56391 | 4.708012 | false | false | false | false |
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 | 902e3a73d5a3890bc02feecf547d90d6 | 39.380208 | 159 | 0.658197 | 5.642649 | false | false | false | false |
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 | ecb93c476c35094492dddd0af6ed09a0 | 37.816514 | 128 | 0.661073 | 4.75928 | false | false | false | false |
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 | cf87b9dd9c2efc5c09b6a680d68fc819 | 43.0798 | 266 | 0.636117 | 5.462299 | false | false | false | false |
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 | c73a28173f6fb1fef4171da63a4cb363 | 25.84375 | 109 | 0.60099 | 4.901569 | false | true | false | false |
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 | 9b33ad8f4fa15250b151feec2e50ca72 | 15.233333 | 47 | 0.50308 | 2.459596 | false | false | false | false |
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 | 3c8d8aec130525ed712b18e301de6297 | 30.367347 | 75 | 0.660377 | 4.615616 | false | false | false | false |
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 | ba7fde8e65f2bc96e82c1564aaa86c83 | 26.130435 | 66 | 0.722756 | 4.425532 | false | false | false | false |
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 | c5707c0aca3664e3bb19e87b96b9a8b2 | 22.266667 | 59 | 0.610315 | 4.230303 | false | false | false | false |
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 | fa0d34e54476f10d28f78b1fb94c1714 | 28.419355 | 139 | 0.649123 | 5.010989 | false | false | false | false |
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 | 80a86b89f123dc075918eaae95170640 | 31.525773 | 156 | 0.670365 | 5.249584 | false | false | false | false |
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 | 6a389added41f9fad0741895f9405044 | 21.973333 | 66 | 0.580383 | 4.88102 | false | false | false | false |
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 | 1568d5ff602a7f8226535ee44dc49b7a | 38.872146 | 163 | 0.684265 | 5.139494 | false | false | false | false |
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 | 1a713070912f791b9f85b585f96ce2a3 | 22.369565 | 99 | 0.617674 | 4.056604 | false | false | false | false |
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 | 37ffdfb647bfc15a2b4d3a0df45914d9 | 29.25 | 125 | 0.652893 | 4.612903 | false | false | false | false |
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 | 992b425fd06250eaa8912258219f8b63 | 18.625 | 79 | 0.591083 | 3.964646 | false | false | false | false |
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 | 266138c8486a3a587d9637b55d1c4772 | 28.661157 | 96 | 0.716634 | 4.469489 | false | false | false | false |
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 | 1406914722b1da04679d727f8f187a64 | 45.818841 | 151 | 0.735645 | 5.868302 | false | false | false | false |
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 | 371cb69a66a62fb1b9450d1616608d35 | 35.141176 | 133 | 0.719727 | 4.868463 | false | false | false | false |
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 | e8d39aeb85fbf2ee7871e5f5179e27ba | 31.45 | 80 | 0.473035 | 5.150794 | false | false | false | false |
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 | 41876e04094c4a7d74d0946d7ca4667a | 47.37037 | 160 | 0.531479 | 6.451153 | false | false | false | false |
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 | af98db454ba7c86500cb005b29a3956b | 35.428571 | 134 | 0.681793 | 5.3125 | false | false | false | false |
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 | ecd0070f91d303ac9e18cae2701c0fd1 | 14.6 | 52 | 0.578158 | 3.706349 | false | false | false | false |
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 | 336452bedf0c4ad2b2f01d5bb92f6b4f | 24.950549 | 151 | 0.525302 | 3.230506 | false | false | false | false |
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 | e1ae54bcbf6db6f48c24f693a3802aa2 | 38.442857 | 158 | 0.670047 | 4.768566 | false | false | false | false |
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 | 380a5c3676402f24166579b6f723af95 | 35.015444 | 110 | 0.508898 | 2.459267 | false | false | false | false |
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 | d463a864e4b324ed4c8def1cc43b6962 | 88.259259 | 200 | 0.635477 | 2.751142 | false | false | true | false |
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 | 77e4e00342a2d174ab50e48000aa7d78 | 40.919355 | 285 | 0.714121 | 5.28252 | false | false | false | false |
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 | 4aaec3b013658ca9adfb218d78f1a4df | 46.771084 | 162 | 0.698108 | 4.720238 | false | false | false | false |
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 | 5324baab9a5363eb24acac79ab7ae5ce | 13.791667 | 87 | 0.653521 | 2.492477 | false | false | false | false |
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 | bc04f9493e58b747710b3db5f96dceb7 | 25.559406 | 128 | 0.605219 | 5.163619 | false | false | false | false |
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 | b3e305ccec16ab4611ccc07da1e5a29f | 27.348837 | 159 | 0.702215 | 4.063333 | false | false | false | false |
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 | da3b71e379554291d5d0cca921495158 | 35.084746 | 147 | 0.621419 | 5.13012 | false | false | false | false |
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 | d52723c507bcd5390d3f47c2b4af3c8b | 24.295455 | 111 | 0.604672 | 5.707692 | false | false | false | false |
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 | a29ae3ee3b28d5e74a9abf30764425d6 | 38.117481 | 313 | 0.640278 | 6.213944 | false | false | false | false |
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 | b57e7000890bd1a6d0cda3aba060613b | 34.326633 | 103 | 0.683357 | 4.145047 | false | false | false | false |
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 | 8a280205512b914c65b83a95bf357d77 | 36.181818 | 170 | 0.760391 | 4.357686 | false | false | false | false |
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 | 3fe07c5de62250688a55c81c34688329 | 40.441176 | 228 | 0.530092 | 2.570699 | false | false | false | false |
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 | 99574f6370f6e43d8471fc676c93be9f | 42.904175 | 406 | 0.651222 | 5.679643 | false | false | false | false |
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 | bff7645d4f912d3305f923e30381f905 | 27.934783 | 121 | 0.65139 | 4.621528 | false | false | false | false |
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 | b3cdbc1d2e19724d7e1d6d853a8b8494 | 29.923077 | 91 | 0.63806 | 4.568182 | false | false | false | false |
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 | 58bf797e6119953617a24b5111ccc4ff | 30.847059 | 123 | 0.609531 | 4.877477 | false | false | false | false |
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 | 8dea9daa414eafdbe56723ebdeb3e5b6 | 29.055556 | 121 | 0.685767 | 4.328 | false | false | false | false |
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 | b48383a6132bcf7ce8dd2c19991e1888 | 34.245509 | 149 | 0.639314 | 4.844444 | false | false | false | false |
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 | 521281bbf054bb9aae09248d4e8d4d19 | 23.822917 | 122 | 0.678002 | 3.432277 | false | false | false | false |
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 | dbc4d2c5f8f9ce3fbf1beee48d01502d | 28.097087 | 141 | 0.447447 | 3.837388 | false | false | false | false |
MengQuietly/MQDouYuTV | MQDouYuTV/MQDouYuTV/Classes/Home/View/MQAmuseTopMenuView.swift | 1 | 2859 | //
// MQAmuseTopMenuView.swift
// MQDouYuTV
//
// Created by mengmeng on 17/1/17.
// Copyright © 2017年 mengQuietly. All rights reserved.
//
import UIKit
/// bgCell
private let kAmuseTopMenuBGCellID = "kAmuseTopMenuBGCellID"
class MQAmuseTopMenuView: UIView {
var groupModelList: [MQAnchorGroupModel]? {
didSet {
amuseTopMenuBgCollectionView.reloadData()
}
}
@IBOutlet weak var amuseTopMenuBgCollectionView: UICollectionView!
@IBOutlet weak var amuseTopMenuPageControl: UIPageControl!
override func awakeFromNib() {
super.awakeFromNib()
autoresizingMask = UIViewAutoresizing(rawValue: 0)
amuseTopMenuBgCollectionView.register(UINib(nibName: "MQAmuseTopMenuCell", bundle: nil), forCellWithReuseIdentifier: kAmuseTopMenuBGCellID)
}
override func layoutSubviews() {
super.layoutSubviews()
let layout = amuseTopMenuBgCollectionView.collectionViewLayout as! UICollectionViewFlowLayout
layout.scrollDirection = .horizontal
layout.itemSize = amuseTopMenuBgCollectionView.bounds.size
}
}
// MARK:-快速实现View
extension MQAmuseTopMenuView {
class func amuseTopMenuView() -> MQAmuseTopMenuView {
return Bundle.main.loadNibNamed("MQAmuseTopMenuView", owner: nil, options: nil)?.first as! MQAmuseTopMenuView
}
}
// MARK:- 实现代理
extension MQAmuseTopMenuView: UICollectionViewDataSource{
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
if groupModelList == nil { return 0 }
let pageNum = (groupModelList!.count - 1) / 8 + 1
print("count = \(groupModelList!.count)")
amuseTopMenuPageControl.numberOfPages = pageNum
return pageNum
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: kAmuseTopMenuBGCellID, for: indexPath) as! MQAmuseTopMenuCell
setupCellDataWithCell(cell: cell, indexPath: indexPath)
return cell
}
// 设置cell 数据
private func setupCellDataWithCell(cell: MQAmuseTopMenuCell, indexPath: IndexPath) {
let startIndex = indexPath.item * 8
var endIndex = (indexPath.item + 1) * 8 - 1
// 判断越界
if endIndex > groupModelList!.count - 1 {
endIndex = groupModelList!.count - 1
}
cell.anchorGroupModelList = Array(groupModelList![startIndex ... endIndex])
}
}
// MARK: - UICollectionViewDelegate
extension MQAmuseTopMenuView:UICollectionViewDelegate {
func scrollViewDidScroll(_ scrollView: UIScrollView) {
amuseTopMenuPageControl.currentPage = Int(scrollView.contentOffset.x / scrollView.bounds.width)
}
}
| mit | bad9c29fecbf8e62b624a76dd2082e3a | 33.439024 | 147 | 0.705737 | 4.762226 | false | false | false | false |
Antondomashnev/ADMozaicCollectionViewLayout | Pods/Nimble/Sources/Nimble/Utils/Stringers.swift | 1 | 6908 | import Foundation
internal func identityAsString(_ value: Any?) -> String {
let anyObject: AnyObject?
#if os(Linux)
anyObject = value as? AnyObject
#else
anyObject = value as AnyObject?
#endif
if let value = anyObject {
return NSString(format: "<%p>", unsafeBitCast(value, to: Int.self)).description
} else {
return "nil"
}
}
internal func arrayAsString<T>(_ items: [T], joiner: String = ", ") -> String {
return items.reduce("") { accum, item in
let prefix = (accum.isEmpty ? "" : joiner)
return accum + prefix + "\(stringify(item))"
}
}
/// A type with a customized test output text representation.
///
/// This textual representation is produced when values will be
/// printed in test runs, and may be useful when producing
/// error messages in custom matchers.
///
/// - SeeAlso: `CustomDebugStringConvertible`
public protocol TestOutputStringConvertible {
var testDescription: String { get }
}
extension Double: TestOutputStringConvertible {
public var testDescription: String {
return NSNumber(value: self).testDescription
}
}
extension Float: TestOutputStringConvertible {
public var testDescription: String {
return NSNumber(value: self).testDescription
}
}
extension NSNumber: TestOutputStringConvertible {
// This is using `NSString(format:)` instead of
// `String(format:)` because the latter somehow breaks
// the travis CI build on linux.
public var testDescription: String {
let description = self.description
if description.contains(".") {
// Travis linux swiftpm build doesn't like casting String to NSString,
// which is why this annoying nested initializer thing is here.
// Maybe this will change in a future snapshot.
let decimalPlaces = NSString(string: NSString(string: description)
.components(separatedBy: ".")[1])
// SeeAlso: https://bugs.swift.org/browse/SR-1464
switch decimalPlaces.length {
case 1:
return NSString(format: "%0.1f", self.doubleValue).description
case 2:
return NSString(format: "%0.2f", self.doubleValue).description
case 3:
return NSString(format: "%0.3f", self.doubleValue).description
default:
return NSString(format: "%0.4f", self.doubleValue).description
}
}
return self.description
}
}
extension Array: TestOutputStringConvertible {
public var testDescription: String {
let list = self.map(Nimble.stringify).joined(separator: ", ")
return "[\(list)]"
}
}
extension AnySequence: TestOutputStringConvertible {
public var testDescription: String {
let generator = self.makeIterator()
var strings = [String]()
var value: AnySequence.Iterator.Element?
repeat {
value = generator.next()
if let value = value {
strings.append(stringify(value))
}
} while value != nil
let list = strings.joined(separator: ", ")
return "[\(list)]"
}
}
extension NSArray: TestOutputStringConvertible {
public var testDescription: String {
let list = Array(self).map(Nimble.stringify).joined(separator: ", ")
return "(\(list))"
}
}
extension NSIndexSet: TestOutputStringConvertible {
public var testDescription: String {
let list = Array(self).map(Nimble.stringify).joined(separator: ", ")
return "(\(list))"
}
}
extension String: TestOutputStringConvertible {
public var testDescription: String {
return self
}
}
extension Data: TestOutputStringConvertible {
public var testDescription: String {
#if os(Linux)
// swiftlint:disable:next todo
// FIXME: Swift on Linux triggers a segfault when calling NSData's hash() (last checked on 03-11-16)
return "Data<length=\(count)>"
#else
return "Data<hash=\((self as NSData).hash),length=\(count)>"
#endif
}
}
///
/// Returns a string appropriate for displaying in test output
/// from the provided value.
///
/// - parameter value: A value that will show up in a test's output.
///
/// - returns: The string that is returned can be
/// customized per type by conforming a type to the `TestOutputStringConvertible`
/// protocol. When stringifying a non-`TestOutputStringConvertible` type, this
/// function will return the value's debug description and then its
/// normal description if available and in that order. Otherwise it
/// will return the result of constructing a string from the value.
///
/// - SeeAlso: `TestOutputStringConvertible`
public func stringify<T>(_ value: T?) -> String {
guard let value = value else { return "nil" }
if let value = value as? TestOutputStringConvertible {
return value.testDescription
}
if let value = value as? CustomDebugStringConvertible {
return value.debugDescription
}
return String(describing: value)
}
#if os(macOS) || os(iOS) || os(tvOS) || os(watchOS)
@objc public class NMBStringer: NSObject {
@objc public class func stringify(_ obj: Any?) -> String {
return Nimble.stringify(obj)
}
}
#endif
// MARK: Collection Type Stringers
/// Attempts to generate a pretty type string for a given value. If the value is of a Objective-C
/// collection type, or a subclass thereof, (e.g. `NSArray`, `NSDictionary`, etc.).
/// This function will return the type name of the root class of the class cluster for better
/// readability (e.g. `NSArray` instead of `__NSArrayI`).
///
/// For values that don't have a type of an Objective-C collection, this function returns the
/// default type description.
///
/// - parameter value: A value that will be used to determine a type name.
///
/// - returns: The name of the class cluster root class for Objective-C collection types, or the
/// the `dynamicType` of the value for values of any other type.
public func prettyCollectionType<T>(_ value: T) -> String {
switch value {
case is NSArray:
return String(describing: NSArray.self)
case is NSDictionary:
return String(describing: NSDictionary.self)
case is NSSet:
return String(describing: NSSet.self)
case is NSIndexSet:
return String(describing: NSIndexSet.self)
default:
return String(describing: value)
}
}
/// Returns the type name for a given collection type. This overload is used by Swift
/// collection types.
///
/// - parameter collection: A Swift `CollectionType` value.
///
/// - returns: A string representing the `dynamicType` of the value.
public func prettyCollectionType<T: Collection>(_ collection: T) -> String {
return String(describing: type(of: collection))
}
| mit | 151bdeead6000031bd19ced237750170 | 32.371981 | 112 | 0.656051 | 4.608406 | false | true | false | false |
Esri/arcgis-runtime-samples-ios | arcgis-ios-sdk-samples/Geometry/Buffer/BufferOptionsViewController.swift | 1 | 2221 | // Copyright 2018 Esri.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
import UIKit
protocol BufferOptionsViewControllerDelegate: AnyObject {
func bufferOptionsViewController(_ bufferOptionsViewController: BufferOptionsViewController, bufferDistanceChangedTo bufferDistance: Measurement<UnitLength>)
}
class BufferOptionsViewController: UITableViewController {
@IBOutlet private weak var distanceSlider: UISlider?
@IBOutlet private weak var distanceLabel: UILabel?
weak var delegate: BufferOptionsViewControllerDelegate?
private let measurementFormatter: MeasurementFormatter = {
// use a measurement formatter so the value is automatically localized
let formatter = MeasurementFormatter()
// don't show decimal places
formatter.numberFormatter.maximumFractionDigits = 0
return formatter
}()
var bufferDistance = Measurement(value: 0, unit: UnitLength.miles) {
didSet {
updateUIForBufferRadius()
}
}
override func viewDidLoad() {
super.viewDidLoad()
updateUIForBufferRadius()
}
private func updateUIForBufferRadius() {
// update the slider and label to match the buffer distance
distanceSlider?.value = Float(bufferDistance.value)
distanceLabel?.text = measurementFormatter.string(from: bufferDistance)
}
@IBAction func bufferSliderAction(_ sender: UISlider) {
// update the buffer distance for the slider value
bufferDistance.value = Double(sender.value)
// notify the delegate with the new value
delegate?.bufferOptionsViewController(self, bufferDistanceChangedTo: bufferDistance)
}
}
| apache-2.0 | 933b41a5d6dc4ca445af91bf54ebb4a2 | 37.293103 | 161 | 0.723548 | 5.275534 | false | false | false | false |
NilStack/NilColorKit | NilColorKit/NilThemeKit.swift | 1 | 6979 | //
// NilThemeKit.swift
// NilThemeKit
//
// Created by Peng on 9/26/14.
// Copyright (c) 2014 peng. All rights reserved.
//
import Foundation
import UIKit
let kDefaultNavigationBarFontSize: CGFloat = 22.0
let kDefaultTabBarFontSize: CGFloat = 14.0
class NilThemeKit {
//MARK: Master Theme
class func setupTheme(#primaryColor:UIColor, secondaryColor:UIColor, fontname:String, lightStatusBar:Bool)
{
if(lightStatusBar)
{
UIApplication.sharedApplication().setStatusBarStyle(UIStatusBarStyle.LightContent, animated: false)
}
customizeNavigationBar(barColor: primaryColor, textColor: secondaryColor, fontName: fontname, fontSize: kDefaultNavigationBarFontSize, buttonColor: secondaryColor)
customizeNavigationBar(buttonColor: secondaryColor)
customizeTabBar(barColor: primaryColor, textColor: secondaryColor, fontName: fontname, fontSize: kDefaultTabBarFontSize)
customizeSwitch(switchOnColor: primaryColor)
customizeSearchBar(barColor: primaryColor, buttonTintColor: secondaryColor)
customizeActivityIndicator(color: primaryColor)
customizeButton(buttonColor: primaryColor)
customizeSegmentedControl(mainColor: primaryColor, secondaryColor: secondaryColor)
customizeSlider(color: primaryColor)
customizePageControl(mainColor: primaryColor)
customizeToolbar(tintColor: primaryColor)
}
//MARK: UINavigationBar
class func customizeNavigationBar(#barColor:UIColor, textColor:UIColor, buttonColor:UIColor)
{
UINavigationBar.appearance().barTintColor = barColor
UINavigationBar.appearance().tintColor = buttonColor
UINavigationBar.appearance().titleTextAttributes?.updateValue(textColor, forKey: NSForegroundColorAttributeName)
}
class func customizeNavigationBar(#barColor:UIColor, textColor:UIColor, fontName:String,fontSize:CGFloat, buttonColor:UIColor)
{
UINavigationBar.appearance().barTintColor = barColor
UINavigationBar.appearance().tintColor = buttonColor
let font: UIFont? = UIFont(name: fontName, size: fontSize)
if((font) != nil)
{
let textAttr = [NSForegroundColorAttributeName: textColor, NSFontAttributeName: font!]
UINavigationBar.appearance().titleTextAttributes = textAttr
}
}
//MARK: UIBarButtonItem
class func customizeNavigationBar(#buttonColor:UIColor)
{
UIBarButtonItem.appearance().tintColor = buttonColor
}
//MARK: UITabBar
class func customizeTabBar(#barColor:UIColor, textColor:UIColor)
{
UITabBar.appearance().barTintColor = barColor
UITabBar.appearance().tintColor = textColor
}
class func customizeTabBar(#barColor:UIColor, textColor:UIColor, fontName:String, fontSize:CGFloat)
{
UITabBar.appearance().barTintColor = barColor
UITabBar.appearance().tintColor = textColor
let font: UIFont? = UIFont(name: fontName, size: fontSize)
if((font) != nil)
{
UITabBarItem.appearance().setTitleTextAttributes([NSFontAttributeName: font!], forState: UIControlState.Normal)
}
}
//MARK: UIButton
class func customizeButton(#buttonColor:UIColor)
{
UIButton.appearance().setTitleColor(buttonColor, forState: UIControlState.Normal)
}
//MARK: UISwitch
class func customizeSwitch(#switchOnColor:UIColor)
{
UISwitch.appearance().onTintColor = switchOnColor
}
//MARK: UISearchBar
class func customizeSearchBar(#barColor:UIColor, buttonTintColor:UIColor)
{
/*
[[UISearchBar appearance] setBarTintColor:barColor];
[[UISearchBar appearance] setTintColor:barColor];
[[UIBarButtonItem appearanceWhenContainedIn:[UISearchBar class], nil] setTitleTextAttributes:@{NSForegroundColorAttributeName: buttonTintColor} forState:UIControlStateNormal];
*/
UISearchBar.appearance().barTintColor = barColor
UISearchBar.appearance().tintColor = barColor
UIBarButtonItem.appearance().setTitleTextAttributes(
[NSForegroundColorAttributeName:buttonTintColor],
forState: UIControlState.Normal)
}
//MARK: UIActivityIndicator
class func customizeActivityIndicator(#color:UIColor)
{
UIActivityIndicatorView.appearance().color = color
}
//MARK: UISegmentedControl
class func customizeSegmentedControl(#mainColor:UIColor, secondaryColor:UIColor)
{
UISegmentedControl.appearance().tintColor = mainColor
}
//MARK: UISlider
class func customizeSlider(#color:UIColor)
{
UISlider.appearance().minimumTrackTintColor = color
}
//MARK: UIToolbar
class func customizeToolbar(#tintColor:UIColor)
{
UIToolbar.appearance().tintColor = tintColor
}
//MARK: UIPageControl
class func customizePageControl(#mainColor:UIColor)
{
UIPageControl.appearance().pageIndicatorTintColor = UIColor.lightGrayColor()
UIPageControl.appearance().currentPageIndicatorTintColor = mainColor
UIPageControl.appearance().backgroundColor = UIColor.clearColor()
}
//MARK: Color utilities
class func color( #r:CGFloat, g:CGFloat, b:CGFloat ) -> UIColor
{
let red: CGFloat = r / 255.0
let green: CGFloat = g / 255.0
let blue: CGFloat = b / 255.0
return UIColor(red: red, green: green, blue: blue, alpha: 1.0)
}
class func colorWithHexString(#hex: String) -> UIColor
{
var cString: String = hex.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceAndNewlineCharacterSet()).uppercaseString
// String should be 6 or 8 characters
if (countElements(cString) < 6)
{
return UIColor.greenColor()
}
// strip 0X if it appears
if cString.hasPrefix("0X")
{
cString = cString.substringFromIndex(advance(cString.startIndex, 2))
}
if (countElements(cString) != 6)
{
return UIColor.grayColor()
}
var rString = cString.substringToIndex(advance(cString.startIndex, 2))
var gString = cString.substringFromIndex(advance(cString.startIndex, 2)).substringToIndex(advance(cString.startIndex, 4))
var bString = cString.substringFromIndex(advance(cString.startIndex, 4)).substringToIndex(advance(cString.startIndex, 6))
var r:CUnsignedInt = 0, g:CUnsignedInt = 0, b:CUnsignedInt = 0;
NSScanner.scannerWithString(rString).scanHexInt(&r)
NSScanner.scannerWithString(gString).scanHexInt(&g)
NSScanner.scannerWithString(bString).scanHexInt(&b)
return NilThemeKit.color(r:CGFloat(r), g:CGFloat(g), b:CGFloat(b) )
}
} | mit | f84710d41075000c60abc48fba60e66b | 35.165803 | 183 | 0.678894 | 5.499606 | false | false | false | false |
testpress/ios-app | ios-app/UI/TimeAnalyticsHeaderViewCell.swift | 1 | 3786 | //
// TimeAnalyticsHeaderViewCell.swift
// ios-app
//
// Copyright © 2017 Testpress. 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 LUExpandableTableView
import UIKit
class TimeAnalyticsHeaderViewCell: LUExpandableTableViewSectionHeader {
@IBOutlet weak var questionIndex: UILabel!
@IBOutlet weak var yourTime: UILabel!
@IBOutlet weak var averageTime: UILabel!
@IBOutlet weak var bestTime: UILabel!
var parentViewController: TimeAnalyticsTableViewController!
var attemptItem: AttemptItem!
var indexPath: IndexPath!
func initCell(attemptItem: AttemptItem,
parentViewController: TimeAnalyticsTableViewController) {
self.attemptItem = attemptItem
self.parentViewController = parentViewController
questionIndex.text = String(attemptItem.index)
yourTime.text = getFormattedValue(attemptItem.duration)
bestTime.text = getFormattedValue(attemptItem.bestDuration)
averageTime.text = getFormattedValue(attemptItem.averageDuration)
let color = getColor(attemptItem)
yourTime.textColor = color
bestTime.textColor = color
averageTime.textColor = color
addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(onTapCell(_:))))
}
@objc func onTapCell(_ sender: UITapGestureRecognizer) {
let expanded = isExpanded
delegate?.expandableSectionHeader(self, shouldExpandOrCollapseAtSection: section)
if !expanded {
parentViewController.tableView
.scrollToRow(at: IndexPath(item: 0, section: section), at: .top, animated: false)
}
}
func getColor(_ attemptItem: AttemptItem) -> UIColor {
var color: String = Colors.GRAY_LIGHT_DARK
if !(attemptItem.selectedAnswers.isEmpty) {
color = Colors.MATERIAL_GREEN;
// If question is attempted & any of the selected option is incorrect then set red color
for attemptAnswer in (attemptItem.question?.answers)! {
if attemptItem.selectedAnswers.contains(attemptAnswer.id) &&
!(attemptAnswer.isCorrect) {
color = Colors.MATERIAL_RED
}
}
}
return Colors.getRGB(color)
}
func getFormattedValue(_ duration: Float?) -> String {
guard let duration = duration else {
return "-"
}
if duration > 60 {
return String(format:"%.0f", duration / 60) + "m"
} else if duration >= 1 {
return String(format:"%.0f", duration) + "s"
}
return String(format:"%.2f", duration) + "s"
}
}
| mit | 55843988eb95a5ed968d26a2f208d469 | 40.141304 | 100 | 0.673976 | 4.743108 | false | false | false | false |
idappthat/UTANow-iOS | Pods/Kingfisher/Kingfisher/KingfisherManager.swift | 1 | 12796 | //
// KingfisherManager.swift
// Kingfisher
//
// Created by Wei Wang on 15/4/6.
//
// Copyright (c) 2015 Wei Wang <[email protected]>
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import UIKit
public typealias DownloadProgressBlock = ((receivedSize: Int64, totalSize: Int64) -> ())
public typealias CompletionHandler = ((image: UIImage?, error: NSError?, cacheType: CacheType, imageURL: NSURL?) -> ())
/// RetrieveImageTask represents a task of image retrieving process.
/// It contains an async task of getting image from disk and from network.
public class RetrieveImageTask {
// If task is canceled before the download task started (which means the `downloadTask` is nil),
// the download task should not begin.
var cancelled: Bool = false
var diskRetrieveTask: RetrieveImageDiskTask?
var downloadTask: RetrieveImageDownloadTask?
/**
Cancel current task. If this task does not begin or already done, do nothing.
*/
public func cancel() {
// From Xcode 7 beta 6, the `dispatch_block_cancel` will crash at runtime.
// It fixed in Xcode 7.1.
// See https://github.com/onevcat/Kingfisher/issues/99 for more.
if let diskRetrieveTask = diskRetrieveTask {
dispatch_block_cancel(diskRetrieveTask)
}
if let downloadTask = downloadTask {
downloadTask.cancel()
}
cancelled = true
}
}
/// Error domain of Kingfisher
public let KingfisherErrorDomain = "com.onevcat.Kingfisher.Error"
private let instance = KingfisherManager()
/// Main manager class of Kingfisher. It connects Kingfisher downloader and cache.
/// You can use this class to retrieve an image via a specified URL from web or cache.
public class KingfisherManager {
/// Options to control some downloader and cache behaviors.
public typealias Options = (forceRefresh: Bool, lowPriority: Bool, cacheMemoryOnly: Bool, shouldDecode: Bool, queue: dispatch_queue_t!, scale: CGFloat)
/// A preset option tuple with all value set to `false`.
public static let OptionsNone: Options = {
return (forceRefresh: false, lowPriority: false, cacheMemoryOnly: false, shouldDecode: false, queue: dispatch_get_main_queue(), scale: 1.0)
}()
/// The default set of options to be used by the manager to control some downloader and cache behaviors.
public static var DefaultOptions: Options = OptionsNone
/// Shared manager used by the extensions across Kingfisher.
public class var sharedManager: KingfisherManager {
return instance
}
/// Cache used by this manager
public var cache: ImageCache
/// Downloader used by this manager
public var downloader: ImageDownloader
/**
Default init method
- returns: A Kingfisher manager object with default cache and default downloader.
*/
public init() {
cache = ImageCache.defaultCache
downloader = ImageDownloader.defaultDownloader
}
/**
Get an image with resource.
If KingfisherOptions.None is used as `options`, Kingfisher will seek the image in memory and disk first.
If not found, it will download the image at `resource.downloadURL` and cache it with `resource.cacheKey`.
These default behaviors could be adjusted by passing different options. See `KingfisherOptions` for more.
- parameter resource: Resource object contains information such as `cacheKey` and `downloadURL`.
- parameter optionsInfo: A dictionary could control some behaviors. See `KingfisherOptionsInfo` for more.
- parameter progressBlock: Called every time downloaded data changed. This could be used as a progress UI.
- parameter completionHandler: Called when the whole retrieving process finished.
- returns: A `RetrieveImageTask` task object. You can use this object to cancel the task.
*/
public func retrieveImageWithResource(resource: Resource,
optionsInfo: KingfisherOptionsInfo?,
progressBlock: DownloadProgressBlock?,
completionHandler: CompletionHandler?) -> RetrieveImageTask
{
let task = RetrieveImageTask()
// There is a bug in Swift compiler which prevents to write `let (options, targetCache) = parseOptionsInfo(optionsInfo)`
// It will cause a compiler error.
let parsedOptions = parseOptionsInfo(optionsInfo)
let (options, targetCache, downloader) = (parsedOptions.0, parsedOptions.1, parsedOptions.2)
if options.forceRefresh {
downloadAndCacheImageWithURL(resource.downloadURL,
forKey: resource.cacheKey,
retrieveImageTask: task,
progressBlock: progressBlock,
completionHandler: completionHandler,
options: options,
targetCache: targetCache,
downloader: downloader)
} else {
let diskTaskCompletionHandler: CompletionHandler = { (image, error, cacheType, imageURL) -> () in
// Break retain cycle created inside diskTask closure below
task.diskRetrieveTask = nil
completionHandler?(image: image, error: error, cacheType: cacheType, imageURL: imageURL)
}
let diskTask = targetCache.retrieveImageForKey(resource.cacheKey, options: options, completionHandler: { (image, cacheType) -> () in
if image != nil {
diskTaskCompletionHandler(image: image, error: nil, cacheType:cacheType, imageURL: resource.downloadURL)
} else {
self.downloadAndCacheImageWithURL(resource.downloadURL,
forKey: resource.cacheKey,
retrieveImageTask: task,
progressBlock: progressBlock,
completionHandler: diskTaskCompletionHandler,
options: options,
targetCache: targetCache,
downloader: downloader)
}
})
task.diskRetrieveTask = diskTask
}
return task
}
/**
Get an image with `URL.absoluteString` as the key.
If KingfisherOptions.None is used as `options`, Kingfisher will seek the image in memory and disk first.
If not found, it will download the image at URL and cache it with `URL.absoluteString` value as its key.
If you need to specify the key other than `URL.absoluteString`, please use resource version of this API with `resource.cacheKey` set to what you want.
These default behaviors could be adjusted by passing different options. See `KingfisherOptions` for more.
- parameter URL: The image URL.
- parameter optionsInfo: A dictionary could control some behaviors. See `KingfisherOptionsInfo` for more.
- parameter progressBlock: Called every time downloaded data changed. This could be used as a progress UI.
- parameter completionHandler: Called when the whole retrieving process finished.
- returns: A `RetrieveImageTask` task object. You can use this object to cancel the task.
*/
public func retrieveImageWithURL(URL: NSURL,
optionsInfo: KingfisherOptionsInfo?,
progressBlock: DownloadProgressBlock?,
completionHandler: CompletionHandler?) -> RetrieveImageTask
{
return retrieveImageWithResource(Resource(downloadURL: URL), optionsInfo: optionsInfo, progressBlock: progressBlock, completionHandler: completionHandler)
}
func downloadAndCacheImageWithURL(URL: NSURL,
forKey key: String,
retrieveImageTask: RetrieveImageTask,
progressBlock: DownloadProgressBlock?,
completionHandler: CompletionHandler?,
options: Options,
targetCache: ImageCache,
downloader: ImageDownloader)
{
downloader.downloadImageWithURL(URL, retrieveImageTask: retrieveImageTask, options: options, progressBlock: { (receivedSize, totalSize) -> () in
progressBlock?(receivedSize: receivedSize, totalSize: totalSize)
}) { (image, error, imageURL, originalData) -> () in
if let error = error where error.code == KingfisherError.NotModified.rawValue {
// Not modified. Try to find the image from cache.
// (The image should be in cache. It should be guaranteed by the framework users.)
targetCache.retrieveImageForKey(key, options: options, completionHandler: { (cacheImage, cacheType) -> () in
completionHandler?(image: cacheImage, error: nil, cacheType: cacheType, imageURL: URL)
})
return
}
if let image = image, originalData = originalData {
targetCache.storeImage(image, originalData: originalData, forKey: key, toDisk: !options.cacheMemoryOnly, completionHandler: nil)
}
completionHandler?(image: image, error: error, cacheType: .None, imageURL: URL)
}
}
func parseOptionsInfo(optionsInfo: KingfisherOptionsInfo?) -> (Options, ImageCache, ImageDownloader) {
var options = KingfisherManager.DefaultOptions
var targetCache = self.cache
var targetDownloader = self.downloader
guard let optionsInfo = optionsInfo else {
return (options, targetCache, targetDownloader)
}
if let optionsItem = optionsInfo.kf_findFirstMatch(.Options(.None)), case .Options(let optionsInOptionsInfo) = optionsItem {
let queue = optionsInOptionsInfo.contains(KingfisherOptions.BackgroundCallback) ? dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0) : KingfisherManager.DefaultOptions.queue
let scale = optionsInOptionsInfo.contains(KingfisherOptions.ScreenScale) ? UIScreen.mainScreen().scale : KingfisherManager.DefaultOptions.scale
options = (forceRefresh: optionsInOptionsInfo.contains(KingfisherOptions.ForceRefresh),
lowPriority: optionsInOptionsInfo.contains(KingfisherOptions.LowPriority),
cacheMemoryOnly: optionsInOptionsInfo.contains(KingfisherOptions.CacheMemoryOnly),
shouldDecode: optionsInOptionsInfo.contains(KingfisherOptions.BackgroundDecode),
queue: queue, scale: scale)
}
if let optionsItem = optionsInfo.kf_findFirstMatch(.TargetCache(self.cache)), case .TargetCache(let cache) = optionsItem {
targetCache = cache
}
if let optionsItem = optionsInfo.kf_findFirstMatch(.Downloader(self.downloader)), case .Downloader(let downloader) = optionsItem {
targetDownloader = downloader
}
return (options, targetCache, targetDownloader)
}
}
// MARK: - Deprecated
public extension KingfisherManager {
@available(*, deprecated=1.2, message="Use -retrieveImageWithURL:optionsInfo:progressBlock:completionHandler: instead.")
public func retrieveImageWithURL(URL: NSURL,
options: KingfisherOptions,
progressBlock: DownloadProgressBlock?,
completionHandler: CompletionHandler?) -> RetrieveImageTask
{
return retrieveImageWithURL(URL, optionsInfo: [.Options(options)], progressBlock: progressBlock, completionHandler: completionHandler)
}
}
| mit | ea7c071a6b7effc14f6446568ed99a88 | 48.02682 | 196 | 0.664505 | 5.525043 | false | false | false | false |
Boss-XP/ChatToolBar | BXPChatToolBar/BXPChatToolBar/Classes/BXPChat/BXPChatToolBar/BXPChatMoreOptions/BXPChatMoreOptionButton.swift | 1 | 920 | //
// BXPChatMoreOptionButton.swift
// BXPChatToolBar
//
// Created by 向攀 on 17/1/23.
// Copyright © 2017年 Yunyun Network Technology Co,Ltd. All rights reserved.
//
import UIKit
class BXPChatMoreOptionButton: UIButton {
override func layoutSubviews() {
super.layoutSubviews()
let buttonWidth:CGFloat = self.frame.size.width
let buttonHeight:CGFloat = self.frame.size.height
let imageViewWH:CGFloat = 50
let imageViewX: CGFloat = (buttonWidth - imageViewWH) * 0.5
let imageViewY: CGFloat = (buttonHeight - imageViewWH) * 0.30;
imageView?.frame = CGRect(x: imageViewX, y: imageViewY, width: imageViewWH, height: imageViewWH)
let labelY: CGFloat = imageViewWH + imageViewY + (buttonHeight - imageViewWH) * 0.1;
titleLabel?.frame = CGRect(x: 0, y: labelY, width: buttonWidth, height: buttonHeight - labelY)
}
}
| apache-2.0 | 4319be3f0bcb816e1b0cac118219663b | 32.814815 | 104 | 0.669222 | 4.207373 | false | false | false | false |
u10int/Kinetic | Pod/Classes/Tween.swift | 1 | 9816 | //
// Tween.swift
// Kinetic
//
// Created by Nicholas Shipes on 12/18/15.
// Copyright © 2015 Urban10 Interactive, LLC. All rights reserved.
//
import UIKit
public enum AnchorPoint {
case `default`
case center
case top
case topLeft
case topRight
case bottom
case bottomLeft
case bottomRight
case left
case right
public func point() -> CGPoint {
switch self {
case .center:
return CGPoint(x: 0.5, y: 0.5)
case .top:
return CGPoint(x: 0.5, y: 0)
case .topLeft:
return CGPoint(x: 0, y: 0)
case .topRight:
return CGPoint(x: 1, y: 0)
case .bottom:
return CGPoint(x: 0.5, y: 1)
case .bottomLeft:
return CGPoint(x: 0, y: 1)
case .bottomRight:
return CGPoint(x: 1, y: 1)
case .left:
return CGPoint(x: 0, y: 0.5)
case .right:
return CGPoint(x: 1, y: 0.5)
default:
return CGPoint(x: 0.5, y: 0.5)
}
}
}
public enum TweenMode {
case to
case from
case fromTo
}
public class Tween: Animation {
private(set) public var target: Tweenable
public var antialiasing: Bool {
get {
if let view = target as? ViewType {
return view.antialiasing
}
return false
}
set(newValue) {
if var view = target as? ViewType {
view.antialiasing = newValue
}
}
}
override public var totalTime: TimeInterval {
return (elapsed - delay)
}
public weak var timeline: Timeline?
internal var properties: [FromToValue] {
return [FromToValue](propertiesByType.values)
}
fileprivate var propertiesByType: Dictionary<String, FromToValue> = [String: FromToValue]()
private(set) var animators = [String: Animator]()
fileprivate var needsPropertyPrep = false
fileprivate var anchorPoint: CGPoint = AnchorPoint.center.point()
public var additive = true;
// MARK: Lifecycle
required public init(target: Tweenable) {
self.target = target
super.init()
self.on(.started) { [unowned self] (animation) in
guard var view = self.target as? UIView else { return }
view.anchorPoint = self.anchorPoint
}
TweenCache.session.cache(self, target: target)
}
deinit {
propertiesByType.removeAll()
}
// MARK: Tween
@discardableResult
public func from(_ props: Property...) -> Tween {
return from(props)
}
@discardableResult
public func to(_ props: Property...) -> Tween {
return to(props)
}
@discardableResult
public func along(_ path: InterpolatablePath) -> Tween {
add(Path(path), mode: .to)
return self
}
// internal `from` and `to` methods that support a single array of Property types since we can't forward variadic arguments
@discardableResult
internal func from(_ props: [Property]) -> Tween {
props.forEach { (prop) in
add(prop, mode: .from)
}
return self
}
@discardableResult
internal func to(_ props: [Property]) -> Tween {
props.forEach { (prop) in
add(prop, mode: .to)
}
return self
}
@discardableResult
open func perspective(_ value: CGFloat) -> Tween {
if var view = target as? ViewType {
view.perspective = value
}
return self
}
@discardableResult
open func anchor(_ anchor: AnchorPoint) -> Tween {
return anchorPoint(anchor.point())
}
@discardableResult
open func anchorPoint(_ point: CGPoint) -> Tween {
anchorPoint = point
return self
}
// MARK: Animation
override public var timingFunction: TimingFunction {
didSet {
animators.forEach { (_, animator) in
animator.timingFunction = timingFunction
}
}
}
override public var spring: Spring? {
didSet {
animators.forEach { (_, animator) in
animator.spring = spring
}
}
}
@discardableResult
override public func delay(_ delay: CFTimeInterval) -> Tween {
super.delay(delay)
if timeline == nil {
startTime = delay
}
return self
}
override public func kill() {
super.kill()
let keys = propertiesByType.map { return $0.key }
TweenCache.session.removeActiveKeys(keys: keys, ofTarget: target)
TweenCache.session.removeFromCache(self, target: target)
}
override public func play() {
guard state != .running && state != .cancelled else { return }
TweenCache.session.cache(self, target: target)
animators.forEach { (_, animator) in
animator.reset()
}
super.play()
}
// public func updateTo(options: [Property], restart: Bool = false) {
//
// }
// MARK: Private Methods
fileprivate func add(_ prop: Property, mode: TweenMode) {
var value = propertiesByType[prop.key] ?? FromToValue()
if mode == .from {
value.from = prop
// immediately set initial state for this property
if var current = target.currentProperty(for: prop) {
if value.to == nil {
value.to = current
}
current.apply(prop)
target.apply(current)
}
} else {
value.to = prop
}
propertiesByType[prop.key] = value
}
// MARK: - Subscriber
override func advance(_ time: Double) {
guard shouldAdvance() else { return }
if propertiesByType.count == 0 {
return
}
// parent Animation class handles updating the elapsed and runningTimes accordingly
super.advance(time)
}
override internal func canSubscribe() -> Bool {
return timeline == nil
}
override internal func render(time: TimeInterval, advance: TimeInterval = 0) {
elapsed = time
setupAnimatorsIfNeeded()
animators.forEach { (_, animator) in
animator.render(time, advance: advance)
}
updated.trigger(self)
}
override internal func isAnimationComplete() -> Bool {
var done = true
// spring-based animators must determine if their animation has completed, not the animation duration
animators.forEach { (_, animator) in
if !animator.finished {
done = false
}
}
return done
}
fileprivate func setupAnimatorsIfNeeded() {
var transformFrom: Transform?
var transformTo: Transform?
var transformKeys: [String] = []
var tweenedProps = [String: Property]()
for (key, prop) in propertiesByType {
var animator = animators[key]
if animator == nil {
// print("--------- tween.id: \(id) - animator key: \(key) ------------")
var from: Property?
var to: Property?
let type = prop.to ?? prop.from
// let additive = (prop.from == nil && !prop.isAutoTo)
var isAdditive = self.additive
// if we have any currently running animations for this same property, animation needs to be additive
// but animation should not be additive if we have a `from` value
if isAdditive {
isAdditive = (prop.from != nil) ? false : TweenCache.session.hasActiveTween(forKey: key, ofTarget: target)
}
// there's no real presentation value when animating along a path, so disable additive
if prop.from is Path || prop.to is Path {
isAdditive = false
self.additive = false
}
if let type = type, let value = target.currentProperty(for: type) {
from = value
to = value
if let tweenFrom = prop.from {
from?.apply(tweenFrom)
} else if let previousTo = tweenedProps[key] {
from = previousTo
} else if prop.to != nil {
let activeTweens = Scheduler.shared.activeTweenPropsForKey(key, ofTarget: target, excludingTween: self)
if activeTweens.count > 0 {
from = activeTweens.last?.to
to = activeTweens.last?.to
}
}
if let tweenTo = prop.to {
to?.apply(tweenTo)
}
// need to update axes which are to be animated based on destination value
if type is Rotation {
if var _from = from as? Rotation, var _to = to as? Rotation, let tweenTo = prop.to as? Rotation {
_to.applyAxes(tweenTo)
_from.applyAxes(tweenTo)
from = _from
to = _to
}
}
tweenedProps[key] = to
}
if let from = from, let to = to {
// print("ANIMATION from: \(from), to: \(to)")
// update stored from/to property that other tweens may reference
propertiesByType[key] = FromToValue(from, to)
TweenCache.session.addActiveKeys(keys: [key], toTarget: target)
if let from = from as? TransformType, let to = to as? TransformType {
if transformKeys.contains(key) == false {
transformKeys.append(key)
}
if let view = target as? ViewType {
if transformFrom == nil && transformTo == nil {
transformFrom = Transform(view.transform3d)
transformTo = Transform(view.transform3d)
}
transformFrom?.apply(from)
transformTo?.apply(to)
}
} else {
let tweenAnimator = Animator(from: from, to: to, duration: duration, timingFunction: timingFunction)
tweenAnimator.additive = isAdditive
tweenAnimator.spring = spring
tweenAnimator.setPresentation({ (prop) -> Property? in
return self.target.currentProperty(for: prop)
})
tweenAnimator.onChange({ [unowned self] (animator, value) in
if self.additive {
// update running animator's `additive` property based on existance of other running animators for the same property
animator.additive = TweenCache.session.hasActiveTween(forKey: animator.key, ofTarget: self.target)
}
self.target.apply(value)
})
animator = tweenAnimator
animators[key] = tweenAnimator
}
} else {
print("Could not create animator for property \(prop)")
}
}
}
if let transformFrom = transformFrom, let transformTo = transformTo {
if animators["transform"] == nil {
let animator = Animator(from: transformFrom, to: transformTo, duration: duration, timingFunction: timingFunction)
animator.spring = spring
animator.additive = false
animator.anchorPoint = anchorPoint
animator.onChange({ [weak self] (animator, value) in
self?.target.apply(value)
})
animators["transform"] = animator
transformKeys.forEach { animators[$0] = animator }
}
}
}
}
| mit | f889fdc1a98137579f77af9512c6a2b3 | 24.231362 | 124 | 0.656342 | 3.520445 | false | false | false | false |
jam891/Luna | Luna/LunarHeaderView.swift | 1 | 2039 | //
// LunarHeaderView.swift
// Luna
//
// Created by Andrew Shepard on 3/1/15.
// Copyright (c) 2015 Andrew Shepard. All rights reserved.
//
import UIKit
class LunarHeaderView: UIView {
@IBOutlet var phaseView: LunarPhaseView!
@IBOutlet var phaseNameLabel: UILabel!
@IBOutlet var ageLabel: UILabel!
@IBOutlet var illuminationLabel: UILabel!
@IBOutlet var riseLabel: UILabel!
@IBOutlet var setLabel: UILabel!
class var nibName: String {
return "LunarHeaderView"
}
var viewModel: LunarViewModel? {
didSet {
self.riseLabel.text = viewModel?.rise
self.setLabel.text = viewModel?.set
self.ageLabel.text = viewModel?.age
self.illuminationLabel.text = viewModel?.illumination
if let phase = viewModel?.phase {
let font = UIFont(name: "EuphemiaUCAS", size: 38.0)!
let color = UIColor.whiteColor()
let attributes = [NSForegroundColorAttributeName: color, NSFontAttributeName: font]
self.phaseNameLabel.attributedText = NSAttributedString(string: phase, attributes: attributes)
}
UIView.animateWithDuration(0.5, animations: { () -> Void in
self.phaseView.alpha = 1.0
})
}
}
override func awakeFromNib() {
super.awakeFromNib()
self.phaseView.alpha = 0.0
self.phaseNameLabel.text = "Loading..."
self.ageLabel.text = ""
self.illuminationLabel.text = ""
self.riseLabel.text = ""
self.setLabel.text = ""
self.phaseNameLabel.textColor = UIColor.whiteColor()
self.ageLabel.textColor = UIColor.whiteColor()
self.illuminationLabel.textColor = UIColor.whiteColor()
self.riseLabel.textColor = UIColor.whiteColor()
self.setLabel.textColor = UIColor.whiteColor()
self.backgroundColor = UIColor.clearColor()
}
}
| mit | 9ada5f256301c6b24e76e43116474078 | 29.893939 | 110 | 0.600785 | 4.644647 | false | false | false | false |
luinily/hOme | hOme/Model/FlicButton.swift | 1 | 5635 | //
// FlicButton.swift
// hOme
//
// Created by Coldefy Yoann on 2016/03/08.
// Copyright © 2016年 YoannColdefy. All rights reserved.
//
import Foundation
import CloudKit
class FlicButton: NSObject, SCLFlicButtonDelegate, Nameable, Button, CloudKitObject {
private var _button: SCLFlicButton?
private let _actionTypes: Set<ButtonActionType> = [ButtonActionType.press, ButtonActionType.doublePress, ButtonActionType.longPress]
private var _actions = [ButtonActionType: CommandProtocol]()
private var _flicName: String = "flic"
private var _name: String = "flic"
private var _identifier: UUID?
private var _onPressedForUI: (() -> Void)?
private var _currentCKRecordName: String?
var button: SCLFlicButton? {return _button}
init(button: SCLFlicButton?) {
let newButton = button != nil
_button = button
_identifier = button?.buttonIdentifier
if let button = button {
_name = button.name
_flicName = button.name
_identifier = button.buttonIdentifier
}
super.init()
_button?.delegate = self
_button?.triggerBehavior = SCLFlicButtonTriggerBehavior.clickAndDoubleClickAndHold
_button?.connect()
if newButton {
updateCloudKit()
}
}
class func getButtonType() -> ButtonType {
return .flic
}
func printButtonState() {
var connectionState = "Unkown"
if let button = _button {
switch button.connectionState {
case .connected: connectionState = "Connected"
case .connecting: connectionState = "Connecting"
case .disconnected: connectionState = "Disconnected"
case .disconnecting: connectionState = "Disconnected"
}
}
print(name + " buttonConnectionState: " + connectionState)
}
func reconnectButton() {
print("reconnect flic " + name)
button?.connect()
}
func getAvailableActionTypes() -> Set<ButtonActionType> {
return _actionTypes
}
func flicButton(_ button: SCLFlicButton, didReceiveButtonClick queued: Bool, age: Int) {
print("button " + _name + " click")
_onPressedForUI?()
_actions[.press]?.execute()
}
func flicButton(_ button: SCLFlicButton, didReceiveButtonDoubleClick queued: Bool, age: Int) {
print("button " + _name + " double click")
_onPressedForUI?()
_actions[.doublePress]?.execute()
}
func flicButton(_ button: SCLFlicButton, didReceiveButtonHold queued: Bool, age: Int) {
print("button " + _name + " long click")
_onPressedForUI?()
_actions[.longPress]?.execute()
}
func flicButton(_ button: SCLFlicButton, didDisconnectWithError error: Error?) {
// var errorString = ""
// if let error = error?.description {
// errorString = error
// }
// print(name + " didDisconnectWithError: " + errorString)
reconnectButton()
}
//MARK: - Nameable
var name: String {
get {return _name}
set {
_name = newValue
updateCloudKit()
}
}
private func nameSetter(_ name: String) {
_name = name
}
var fullName: String {return _name}
var internalName: String {return _flicName}
//MARK: - Button
func getButtonAction(actionType: ButtonActionType) -> CommandProtocol? {
return _actions[actionType]
}
func setButtonAction(actionType: ButtonActionType, action: CommandProtocol?) {
_actions[actionType] = action
updateCloudKit()
}
func setOnPressForUI(onPress: (() -> Void)?) {
_onPressedForUI = onPress
}
//MARK: - CloudKitObject
convenience init (ckRecord: CKRecord, getCommandOfUniqueName: (_ uniqueName: String) -> CommandProtocol?, getButtonOfIdentifier: (_ identifier: UUID) -> SCLFlicButton?) throws {
guard let name = ckRecord["name"] as? String else {
throw CommandClassError.noDeviceNameInCKRecord
}
guard let flicName = ckRecord["flicName"] as? String else {
throw CommandClassError.noDeviceNameInCKRecord
}
self.init(button: nil)
_name = name
_flicName = flicName
if let pressAction = ckRecord["pressAction"] as? String {
_actions[ButtonActionType.press] = getCommandOfUniqueName(pressAction)
}
if let doublePressAction = ckRecord["doublePressAction"] as? String {
_actions[ButtonActionType.doublePress] = getCommandOfUniqueName(doublePressAction)
}
if let longPressAction = ckRecord["longPressAction"] as? String {
_actions[ButtonActionType.longPress] = getCommandOfUniqueName(longPressAction)
}
if let identifier = ckRecord["identifier"] as? String {
_identifier = UUID(uuidString: identifier)
}
_currentCKRecordName = ckRecord.recordID.recordName
if let identifier = _identifier {
_button = getButtonOfIdentifier(identifier)
_button?.delegate = self
_button?.triggerBehavior = SCLFlicButtonTriggerBehavior.clickAndDoubleClickAndHold
_button?.connect()
if _button != nil {
print("Restored button " + _name)
}
}
}
func getNewCKRecordName () -> String {
return "FlicButton:" + _flicName
}
func getCurrentCKRecordName() -> String? {
return _currentCKRecordName
}
func setUpCKRecord(_ record: CKRecord) {
record["type"] = FlicButton.getButtonType().rawValue as CKRecordValue?
record["identifier"] = _identifier?.uuidString as CKRecordValue?
var data = [String]()
_actions.forEach {
(actionType, command) in
data.append(command.internalName)
}
record["name"] = _name as CKRecordValue?
record["flicName"] = _flicName as CKRecordValue?
record["pressAction"] = data[0] as CKRecordValue?
record["doublePressAction"] = data[1] as CKRecordValue?
record["longPressAction"] = data[2] as CKRecordValue?
}
func getCKRecordType() -> String {
return "FlicButton"
}
func updateCloudKit() {
CloudKitHelper.sharedHelper.export(self)
_currentCKRecordName = getNewCKRecordName()
}
}
| mit | c388472d639d25c3ba85cbafc351436a | 25.691943 | 178 | 0.708274 | 3.555556 | false | false | false | false |
devxoul/URLNavigator | Tests/URLMatcherTests/URLConvertibleSpec.swift | 1 | 4395 | import Foundation
import Nimble
import Quick
import URLMatcher
final class URLConvertibleSpec: QuickSpec {
override func spec() {
describe("urlValue") {
it("returns an URL instance") {
let url = URL(string: "https://xoul.kr")!
expect(url.urlValue) == url
expect(url.absoluteString.urlValue) == url
}
it("returns an URL instance from unicode string") {
let urlString = "https://xoul.kr/한글"
expect(urlString.urlValue) == URL(string: "https://xoul.kr/%ED%95%9C%EA%B8%80")!
}
}
describe("urlStringValue") {
it("returns a URL string value") {
let url = URL(string: "https://xoul.kr")!
expect(url.urlStringValue) == url.absoluteString
expect(url.absoluteString.urlStringValue) == url.absoluteString
}
}
describe("queryParameters") {
context("when there is no query string") {
it("returns empty dictionary") {
let url = "https://xoul.kr"
expect(url.urlValue?.queryParameters) == [:]
expect(url.urlStringValue.queryParameters) == [:]
}
}
context("when there is an empty query string") {
it("returns empty dictionary") {
let url = "https://xoul.kr?"
expect(url.urlValue?.queryParameters) == [:]
expect(url.urlStringValue.queryParameters) == [:]
}
}
context("when there is a query string") {
let url = "https://xoul.kr?key=this%20is%20a%20value&greeting=hello+world!&int=12&int=34&url=https://foo/bar?hello=world"
it("has proper keys") {
expect(Set(url.urlValue!.queryParameters.keys)) == ["key", "greeting", "int", "url"]
expect(Set(url.urlStringValue.queryParameters.keys)) == ["key", "greeting", "int", "url"]
}
it("decodes a percent encoding") {
expect(url.urlValue?.queryParameters["key"]) == "this is a value"
expect(url.urlStringValue.queryParameters["key"]) == "this is a value"
}
it("doesn't convert + to whitespace") {
expect(url.urlValue?.queryParameters["greeting"]) == "hello+world!"
expect(url.urlStringValue.queryParameters["greeting"]) == "hello+world!"
}
it("takes last value from duplicated keys") {
expect(url.urlValue?.queryParameters["int"]) == "34"
expect(url.urlStringValue.queryParameters["int"]) == "34"
}
it("has an url") {
expect(url.urlValue?.queryParameters["url"]) == "https://foo/bar?hello=world"
}
}
}
describe("queryItems") {
context("when there is no query string") {
it("returns nil") {
let url = "https://xoul.kr"
expect(url.urlValue?.queryItems).to(beNil())
expect(url.urlStringValue.queryItems).to(beNil())
}
}
context("when there is an empty query string") {
it("returns an empty array") {
let url = "https://xoul.kr?"
expect(url.urlValue?.queryItems) == []
expect(url.urlStringValue.queryItems) == []
}
}
context("when there is a query string") {
let url = "https://xoul.kr?key=this%20is%20a%20value&greeting=hello+world!&int=12&int=34"
it("has exact number of items") {
expect(url.urlValue?.queryItems?.count) == 4
expect(url.urlStringValue.queryItems?.count) == 4
}
it("decodes a percent encoding") {
expect(url.urlValue?.queryItems?[0]) == URLQueryItem(name: "key", value: "this is a value")
expect(url.urlStringValue.queryItems?[0]) == URLQueryItem(name: "key", value: "this is a value")
}
it("doesn't convert + to whitespace") {
expect(url.urlValue?.queryItems?[1]) == URLQueryItem(name: "greeting", value: "hello+world!")
expect(url.urlStringValue.queryItems?[1]) == URLQueryItem(name: "greeting", value: "hello+world!")
}
it("takes all duplicated keys") {
expect(url.urlValue?.queryItems?[2]) == URLQueryItem(name: "int", value: "12")
expect(url.urlValue?.queryItems?[3]) == URLQueryItem(name: "int", value: "34")
expect(url.urlStringValue.queryItems?[2]) == URLQueryItem(name: "int", value: "12")
expect(url.urlStringValue.queryItems?[3]) == URLQueryItem(name: "int", value: "34")
}
}
}
}
}
| mit | a44ebce4f359cf84c7a14885a3c95136 | 35.289256 | 129 | 0.58506 | 4.010046 | false | false | false | false |
NordicSemiconductor/IOS-Pods-DFU-Library | Example/Pods/ZIPFoundation/Sources/ZIPFoundation/Archive+Writing.swift | 1 | 22257 | //
// Archive+Writing.swift
// ZIPFoundation
//
// Copyright © 2017-2020 Thomas Zoechling, https://www.peakstep.com and the ZIP Foundation project authors.
// Released under the MIT License.
//
// See https://github.com/weichsel/ZIPFoundation/blob/master/LICENSE for license information.
//
import Foundation
extension Archive {
private enum ModifyOperation: Int {
case remove = -1
case add = 1
}
/// Write files, directories or symlinks to the receiver.
///
/// - Parameters:
/// - path: The path that is used to identify an `Entry` within the `Archive` file.
/// - baseURL: The base URL of the `Entry` to add.
/// The `baseURL` combined with `path` must form a fully qualified file URL.
/// - compressionMethod: Indicates the `CompressionMethod` that should be applied to `Entry`.
/// By default, no compression will be applied.
/// - bufferSize: The maximum size of the write buffer and the compression buffer (if needed).
/// - progress: A progress object that can be used to track or cancel the add operation.
/// - Throws: An error if the source file cannot be read or the receiver is not writable.
public func addEntry(with path: String, relativeTo baseURL: URL, compressionMethod: CompressionMethod = .none,
bufferSize: UInt32 = defaultWriteChunkSize, progress: Progress? = nil) throws {
let fileManager = FileManager()
let entryURL = baseURL.appendingPathComponent(path)
guard fileManager.itemExists(at: entryURL) else {
throw CocoaError(.fileReadNoSuchFile, userInfo: [NSFilePathErrorKey: entryURL.path])
}
let type = try FileManager.typeForItem(at: entryURL)
// symlinks do not need to be readable
guard type == .symlink || fileManager.isReadableFile(atPath: entryURL.path) else {
throw CocoaError(.fileReadNoPermission, userInfo: [NSFilePathErrorKey: url.path])
}
let modDate = try FileManager.fileModificationDateTimeForItem(at: entryURL)
let uncompressedSize = type == .directory ? 0 : try FileManager.fileSizeForItem(at: entryURL)
let permissions = try FileManager.permissionsForItem(at: entryURL)
var provider: Provider
switch type {
case .file:
let entryFileSystemRepresentation = fileManager.fileSystemRepresentation(withPath: entryURL.path)
guard let entryFile: UnsafeMutablePointer<FILE> = fopen(entryFileSystemRepresentation, "rb") else {
throw CocoaError(.fileNoSuchFile)
}
defer { fclose(entryFile) }
provider = { _, _ in return try Data.readChunk(of: Int(bufferSize), from: entryFile) }
try self.addEntry(with: path, type: type, uncompressedSize: uncompressedSize,
modificationDate: modDate, permissions: permissions,
compressionMethod: compressionMethod, bufferSize: bufferSize,
progress: progress, provider: provider)
case .directory:
provider = { _, _ in return Data() }
try self.addEntry(with: path.hasSuffix("/") ? path : path + "/",
type: type, uncompressedSize: uncompressedSize,
modificationDate: modDate, permissions: permissions,
compressionMethod: compressionMethod, bufferSize: bufferSize,
progress: progress, provider: provider)
case .symlink:
provider = { _, _ -> Data in
let linkDestination = try fileManager.destinationOfSymbolicLink(atPath: entryURL.path)
let linkFileSystemRepresentation = fileManager.fileSystemRepresentation(withPath: linkDestination)
let linkLength = Int(strlen(linkFileSystemRepresentation))
let linkBuffer = UnsafeBufferPointer(start: linkFileSystemRepresentation, count: linkLength)
return Data(buffer: linkBuffer)
}
try self.addEntry(with: path, type: type, uncompressedSize: uncompressedSize,
modificationDate: modDate, permissions: permissions,
compressionMethod: compressionMethod, bufferSize: bufferSize,
progress: progress, provider: provider)
}
}
/// Write files, directories or symlinks to the receiver.
///
/// - Parameters:
/// - path: The path that is used to identify an `Entry` within the `Archive` file.
/// - type: Indicates the `Entry.EntryType` of the added content.
/// - uncompressedSize: The uncompressed size of the data that is going to be added with `provider`.
/// - modificationDate: A `Date` describing the file modification date of the `Entry`.
/// Default is the current `Date`.
/// - permissions: POSIX file permissions for the `Entry`.
/// Default is `0`o`644` for files and symlinks and `0`o`755` for directories.
/// - compressionMethod: Indicates the `CompressionMethod` that should be applied to `Entry`.
/// By default, no compression will be applied.
/// - bufferSize: The maximum size of the write buffer and the compression buffer (if needed).
/// - progress: A progress object that can be used to track or cancel the add operation.
/// - provider: A closure that accepts a position and a chunk size. Returns a `Data` chunk.
/// - Throws: An error if the source data is invalid or the receiver is not writable.
public func addEntry(with path: String, type: Entry.EntryType, uncompressedSize: UInt32,
modificationDate: Date = Date(), permissions: UInt16? = nil,
compressionMethod: CompressionMethod = .none, bufferSize: UInt32 = defaultWriteChunkSize,
progress: Progress? = nil, provider: Provider) throws {
guard self.accessMode != .read else { throw ArchiveError.unwritableArchive }
progress?.totalUnitCount = type == .directory ? defaultDirectoryUnitCount : Int64(uncompressedSize)
var endOfCentralDirRecord = self.endOfCentralDirectoryRecord
var startOfCD = Int(endOfCentralDirRecord.offsetToStartOfCentralDirectory)
var existingCentralDirData = Data()
fseek(self.archiveFile, startOfCD, SEEK_SET)
existingCentralDirData = try Data.readChunk(of: Int(endOfCentralDirRecord.sizeOfCentralDirectory),
from: self.archiveFile)
fseek(self.archiveFile, startOfCD, SEEK_SET)
let localFileHeaderStart = ftell(self.archiveFile)
let modDateTime = modificationDate.fileModificationDateTime
defer { fflush(self.archiveFile) }
do {
var localFileHeader = try self.writeLocalFileHeader(path: path, compressionMethod: compressionMethod,
size: (uncompressedSize, 0), checksum: 0,
modificationDateTime: modDateTime)
let (written, checksum) = try self.writeEntry(localFileHeader: localFileHeader, type: type,
compressionMethod: compressionMethod, bufferSize: bufferSize,
progress: progress, provider: provider)
startOfCD = ftell(self.archiveFile)
fseek(self.archiveFile, localFileHeaderStart, SEEK_SET)
// Write the local file header a second time. Now with compressedSize (if applicable) and a valid checksum.
localFileHeader = try self.writeLocalFileHeader(path: path, compressionMethod: compressionMethod,
size: (uncompressedSize, written),
checksum: checksum, modificationDateTime: modDateTime)
fseek(self.archiveFile, startOfCD, SEEK_SET)
_ = try Data.write(chunk: existingCentralDirData, to: self.archiveFile)
let permissions = permissions ?? (type == .directory ? defaultDirectoryPermissions :defaultFilePermissions)
let externalAttributes = FileManager.externalFileAttributesForEntry(of: type, permissions: permissions)
let offset = UInt32(localFileHeaderStart)
let centralDir = try self.writeCentralDirectoryStructure(localFileHeader: localFileHeader,
relativeOffset: offset,
externalFileAttributes: externalAttributes)
if startOfCD > UINT32_MAX { throw ArchiveError.invalidStartOfCentralDirectoryOffset }
endOfCentralDirRecord = try self.writeEndOfCentralDirectory(centralDirectoryStructure: centralDir,
startOfCentralDirectory: UInt32(startOfCD),
operation: .add)
self.endOfCentralDirectoryRecord = endOfCentralDirRecord
} catch ArchiveError.cancelledOperation {
try rollback(localFileHeaderStart, existingCentralDirData, endOfCentralDirRecord)
throw ArchiveError.cancelledOperation
}
}
/// Remove a ZIP `Entry` from the receiver.
///
/// - Parameters:
/// - entry: The `Entry` to remove.
/// - bufferSize: The maximum size for the read and write buffers used during removal.
/// - progress: A progress object that can be used to track or cancel the remove operation.
/// - Throws: An error if the `Entry` is malformed or the receiver is not writable.
public func remove(_ entry: Entry, bufferSize: UInt32 = defaultReadChunkSize, progress: Progress? = nil) throws {
let manager = FileManager()
let tempDir = self.uniqueTemporaryDirectoryURL()
defer { try? manager.removeItem(at: tempDir) }
let uniqueString = ProcessInfo.processInfo.globallyUniqueString
let tempArchiveURL = tempDir.appendingPathComponent(uniqueString)
do { try manager.createParentDirectoryStructure(for: tempArchiveURL) } catch {
throw ArchiveError.unwritableArchive }
guard let tempArchive = Archive(url: tempArchiveURL, accessMode: .create) else {
throw ArchiveError.unwritableArchive
}
progress?.totalUnitCount = self.totalUnitCountForRemoving(entry)
var centralDirectoryData = Data()
var offset = 0
for currentEntry in self {
let centralDirectoryStructure = currentEntry.centralDirectoryStructure
if currentEntry != entry {
let entryStart = Int(currentEntry.centralDirectoryStructure.relativeOffsetOfLocalHeader)
fseek(self.archiveFile, entryStart, SEEK_SET)
let provider: Provider = { (_, chunkSize) -> Data in
return try Data.readChunk(of: Int(chunkSize), from: self.archiveFile)
}
let consumer: Consumer = {
if progress?.isCancelled == true { throw ArchiveError.cancelledOperation }
_ = try Data.write(chunk: $0, to: tempArchive.archiveFile)
progress?.completedUnitCount += Int64($0.count)
}
_ = try Data.consumePart(of: Int(currentEntry.localSize), chunkSize: Int(bufferSize),
provider: provider, consumer: consumer)
let centralDir = CentralDirectoryStructure(centralDirectoryStructure: centralDirectoryStructure,
offset: UInt32(offset))
centralDirectoryData.append(centralDir.data)
} else { offset = currentEntry.localSize }
}
let startOfCentralDirectory = ftell(tempArchive.archiveFile)
_ = try Data.write(chunk: centralDirectoryData, to: tempArchive.archiveFile)
tempArchive.endOfCentralDirectoryRecord = self.endOfCentralDirectoryRecord
let endOfCentralDirectoryRecord = try
tempArchive.writeEndOfCentralDirectory(centralDirectoryStructure: entry.centralDirectoryStructure,
startOfCentralDirectory: UInt32(startOfCentralDirectory),
operation: .remove)
tempArchive.endOfCentralDirectoryRecord = endOfCentralDirectoryRecord
self.endOfCentralDirectoryRecord = endOfCentralDirectoryRecord
fflush(tempArchive.archiveFile)
try self.replaceCurrentArchiveWithArchive(at: tempArchive.url)
}
// MARK: - Helpers
func uniqueTemporaryDirectoryURL() -> URL {
#if swift(>=5.0) || os(macOS) || os(iOS) || os(watchOS) || os(tvOS)
if let tempDir = try? FileManager().url(for: .itemReplacementDirectory, in: .userDomainMask,
appropriateFor: self.url, create: true) {
return tempDir
}
#endif
return URL(fileURLWithPath: NSTemporaryDirectory()).appendingPathComponent(
ProcessInfo.processInfo.globallyUniqueString)
}
func replaceCurrentArchiveWithArchive(at URL: URL) throws {
fclose(self.archiveFile)
let fileManager = FileManager()
#if os(macOS) || os(iOS) || os(watchOS) || os(tvOS)
do {
_ = try fileManager.replaceItemAt(self.url, withItemAt: URL)
} catch {
_ = try fileManager.removeItem(at: self.url)
_ = try fileManager.moveItem(at: URL, to: self.url)
}
#else
_ = try fileManager.removeItem(at: self.url)
_ = try fileManager.moveItem(at: URL, to: self.url)
#endif
let fileSystemRepresentation = fileManager.fileSystemRepresentation(withPath: self.url.path)
self.archiveFile = fopen(fileSystemRepresentation, "rb+")
}
private func writeLocalFileHeader(path: String, compressionMethod: CompressionMethod,
size: (uncompressed: UInt32, compressed: UInt32),
checksum: CRC32,
modificationDateTime: (UInt16, UInt16)) throws -> LocalFileHeader {
// We always set Bit 11 in generalPurposeBitFlag, which indicates an UTF-8 encoded path.
guard let fileNameData = path.data(using: .utf8) else { throw ArchiveError.invalidEntryPath }
let localFileHeader = LocalFileHeader(versionNeededToExtract: UInt16(20), generalPurposeBitFlag: UInt16(2048),
compressionMethod: compressionMethod.rawValue,
lastModFileTime: modificationDateTime.1,
lastModFileDate: modificationDateTime.0, crc32: checksum,
compressedSize: size.compressed, uncompressedSize: size.uncompressed,
fileNameLength: UInt16(fileNameData.count), extraFieldLength: UInt16(0),
fileNameData: fileNameData, extraFieldData: Data())
_ = try Data.write(chunk: localFileHeader.data, to: self.archiveFile)
return localFileHeader
}
private func writeEntry(localFileHeader: LocalFileHeader, type: Entry.EntryType,
compressionMethod: CompressionMethod, bufferSize: UInt32, progress: Progress? = nil,
provider: Provider) throws -> (sizeWritten: UInt32, crc32: CRC32) {
var checksum = CRC32(0)
var sizeWritten = UInt32(0)
switch type {
case .file:
switch compressionMethod {
case .none:
(sizeWritten, checksum) = try self.writeUncompressed(size: localFileHeader.uncompressedSize,
bufferSize: bufferSize,
progress: progress, provider: provider)
case .deflate:
(sizeWritten, checksum) = try self.writeCompressed(size: localFileHeader.uncompressedSize,
bufferSize: bufferSize,
progress: progress, provider: provider)
}
case .directory:
_ = try provider(0, 0)
if let progress = progress { progress.completedUnitCount = progress.totalUnitCount }
case .symlink:
(sizeWritten, checksum) = try self.writeSymbolicLink(size: localFileHeader.uncompressedSize,
provider: provider)
if let progress = progress { progress.completedUnitCount = progress.totalUnitCount }
}
return (sizeWritten, checksum)
}
private func writeUncompressed(size: UInt32, bufferSize: UInt32, progress: Progress? = nil,
provider: Provider) throws -> (sizeWritten: UInt32, checksum: CRC32) {
var position = 0
var sizeWritten = 0
var checksum = CRC32(0)
while position < size {
if progress?.isCancelled == true { throw ArchiveError.cancelledOperation }
let readSize = (Int(size) - position) >= bufferSize ? Int(bufferSize) : (Int(size) - position)
let entryChunk = try provider(Int(position), Int(readSize))
checksum = entryChunk.crc32(checksum: checksum)
sizeWritten += try Data.write(chunk: entryChunk, to: self.archiveFile)
position += Int(bufferSize)
progress?.completedUnitCount = Int64(sizeWritten)
}
return (UInt32(sizeWritten), checksum)
}
private func writeCompressed(size: UInt32, bufferSize: UInt32, progress: Progress? = nil,
provider: Provider) throws -> (sizeWritten: UInt32, checksum: CRC32) {
var sizeWritten = 0
let consumer: Consumer = { data in sizeWritten += try Data.write(chunk: data, to: self.archiveFile) }
let checksum = try Data.compress(size: Int(size), bufferSize: Int(bufferSize),
provider: { (position, size) -> Data in
if progress?.isCancelled == true { throw ArchiveError.cancelledOperation }
let data = try provider(position, size)
progress?.completedUnitCount += Int64(data.count)
return data
}, consumer: consumer)
return(UInt32(sizeWritten), checksum)
}
private func writeSymbolicLink(size: UInt32, provider: Provider) throws -> (sizeWritten: UInt32, checksum: CRC32) {
let linkData = try provider(0, Int(size))
let checksum = linkData.crc32(checksum: 0)
let sizeWritten = try Data.write(chunk: linkData, to: self.archiveFile)
return (UInt32(sizeWritten), checksum)
}
private func writeCentralDirectoryStructure(localFileHeader: LocalFileHeader, relativeOffset: UInt32,
externalFileAttributes: UInt32) throws -> CentralDirectoryStructure {
let centralDirectory = CentralDirectoryStructure(localFileHeader: localFileHeader,
fileAttributes: externalFileAttributes,
relativeOffset: relativeOffset)
_ = try Data.write(chunk: centralDirectory.data, to: self.archiveFile)
return centralDirectory
}
private func writeEndOfCentralDirectory(centralDirectoryStructure: CentralDirectoryStructure,
startOfCentralDirectory: UInt32,
operation: ModifyOperation) throws -> EndOfCentralDirectoryRecord {
var record = self.endOfCentralDirectoryRecord
let countChange = operation.rawValue
var dataLength = centralDirectoryStructure.extraFieldLength
dataLength += centralDirectoryStructure.fileNameLength
dataLength += centralDirectoryStructure.fileCommentLength
let centralDirectoryDataLengthChange = operation.rawValue * (Int(dataLength) + CentralDirectoryStructure.size)
var updatedSizeOfCentralDirectory = Int(record.sizeOfCentralDirectory)
updatedSizeOfCentralDirectory += centralDirectoryDataLengthChange
let numberOfEntriesOnDisk = UInt16(Int(record.totalNumberOfEntriesOnDisk) + countChange)
let numberOfEntriesInCentralDirectory = UInt16(Int(record.totalNumberOfEntriesInCentralDirectory) + countChange)
record = EndOfCentralDirectoryRecord(record: record, numberOfEntriesOnDisk: numberOfEntriesOnDisk,
numberOfEntriesInCentralDirectory: numberOfEntriesInCentralDirectory,
updatedSizeOfCentralDirectory: UInt32(updatedSizeOfCentralDirectory),
startOfCentralDirectory: startOfCentralDirectory)
_ = try Data.write(chunk: record.data, to: self.archiveFile)
return record
}
private func rollback(_ localFileHeaderStart: Int,
_ existingCentralDirectoryData: Data,
_ endOfCentralDirRecord: EndOfCentralDirectoryRecord) throws {
fflush(self.archiveFile)
ftruncate(fileno(self.archiveFile), off_t(localFileHeaderStart))
fseek(self.archiveFile, localFileHeaderStart, SEEK_SET)
_ = try Data.write(chunk: existingCentralDirectoryData, to: self.archiveFile)
_ = try Data.write(chunk: endOfCentralDirRecord.data, to: self.archiveFile)
}
}
| bsd-3-clause | 09db37a2156669600aa7c9f8df994fc5 | 62.048159 | 120 | 0.610397 | 5.438905 | false | false | false | false |
wayfindrltd/wayfindr-demo-ios | Wayfindr Demo/Classes/Extensions/UIView+Borders.swift | 1 | 4863 | //
// UIView+Borders.swift
// Wayfindr Demo
//
// Created by Wayfindr on 12/11/2015.
// Copyright (c) 2016 Wayfindr (http://www.wayfindr.net)
//
// 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
extension UIView {
/**
Creates borders and adds them as subviews to the view.
- parameter edges: Edges on which to create a border.
- parameter colour: Color to tint the border. Default is white.
- parameter thickness: Thickness of the border. Default is 1.
- seealso: Taken from http://stackoverflow.com/questions/17355280/how-to-add-a-border-just-on-the-top-side-of-a-uiview
- returns: Border views that have been added as subviews.
*/
@discardableResult func addBorder(edges: UIRectEdge, colour: UIColor = UIColor.white, thickness: CGFloat = 1) -> [UIView] {
var borders = [UIView]()
func border() -> UIView {
let border = UIView(frame: CGRect.zero)
border.backgroundColor = colour
border.translatesAutoresizingMaskIntoConstraints = false
return border
}
if edges.contains(.top) || edges.contains(.all) {
let top = border()
addSubview(top)
addConstraints(
NSLayoutConstraint.constraints(withVisualFormat: "V:|-(0)-[top(==thickness)]",
options: [],
metrics: ["thickness": thickness],
views: ["top": top]))
addConstraints(
NSLayoutConstraint.constraints(withVisualFormat: "H:|-(0)-[top]-(0)-|",
options: [],
metrics: nil,
views: ["top": top]))
borders.append(top)
}
if edges.contains(.left) || edges.contains(.all) {
let left = border()
addSubview(left)
addConstraints(
NSLayoutConstraint.constraints(withVisualFormat: "H:|-(0)-[left(==thickness)]",
options: [],
metrics: ["thickness": thickness],
views: ["left": left]))
addConstraints(
NSLayoutConstraint.constraints(withVisualFormat: "V:|-(0)-[left]-(0)-|",
options: [],
metrics: nil,
views: ["left": left]))
borders.append(left)
}
if edges.contains(.right) || edges.contains(.all) {
let right = border()
addSubview(right)
addConstraints(
NSLayoutConstraint.constraints(withVisualFormat: "H:[right(==thickness)]-(0)-|",
options: [],
metrics: ["thickness": thickness],
views: ["right": right]))
addConstraints(
NSLayoutConstraint.constraints(withVisualFormat: "V:|-(0)-[right]-(0)-|",
options: [],
metrics: nil,
views: ["right": right]))
borders.append(right)
}
if edges.contains(.bottom) || edges.contains(.all) {
let bottom = border()
addSubview(bottom)
addConstraints(
NSLayoutConstraint.constraints(withVisualFormat: "V:[bottom(==thickness)]-(0)-|",
options: [],
metrics: ["thickness": thickness],
views: ["bottom": bottom]))
addConstraints(
NSLayoutConstraint.constraints(withVisualFormat: "H:|-(0)-[bottom]-(0)-|",
options: [],
metrics: nil,
views: ["bottom": bottom]))
borders.append(bottom)
}
return borders
}
}
| mit | 6fcf1f7550bbb96043027b4fc8e95efb | 39.865546 | 127 | 0.560148 | 5.118947 | false | false | false | false |
jens-maus/Frameless | Frameless/JSSAlertView.swift | 2 | 15508 | //
// JSSAlertView
// JSSAlertView
//
// Created by Jay Stakelon on 9/16/14.
// Copyright (c) 2014 Jay Stakelon / https://github.com/stakes - all rights reserved.
//
// Inspired by and modeled after https://github.com/vikmeup/SCLAlertView-Swift
// by Victor Radchenko: https://github.com/vikmeup
//
import Foundation
import UIKit
class JSSAlertView: UIViewController {
var containerView:UIView!
var alertBackgroundView:UIView!
var dismissButton:UIButton!
var cancelButton:UIButton!
var buttonLabel:UILabel!
var cancelButtonLabel:UILabel!
var titleLabel:UILabel!
var textView:UITextView!
var rootViewController:UIViewController!
var iconImage:UIImage!
var iconImageView:UIImageView!
var closeAction:(()->Void)!
var isAlertOpen:Bool = false
enum FontType {
case Title, Text, Button
}
var titleFont = "HelveticaNeue-Light"
var textFont = "HelveticaNeue"
var buttonFont = "HelveticaNeue-Bold"
var defaultColor = UIColorFromHex(0xF2F4F4, alpha: 1)
enum TextColorTheme {
case Dark, Light
}
var darkTextColor = UIColorFromHex(0x000000, alpha: 0.75)
var lightTextColor = UIColorFromHex(0xffffff, alpha: 0.9)
let baseHeight:CGFloat = 160.0
var alertWidth:CGFloat = 290.0
let buttonHeight:CGFloat = 70.0
let padding:CGFloat = 20.0
var viewWidth:CGFloat?
var viewHeight:CGFloat?
// Allow alerts to be closed/renamed in a chainable manner
class JSSAlertViewResponder {
let alertview: JSSAlertView
init(alertview: JSSAlertView) {
self.alertview = alertview
}
func addAction(action: ()->Void) {
self.alertview.addAction(action)
}
func setTitleFont(fontStr: String) {
self.alertview.setFont(fontStr, type: .Title)
}
func setTextFont(fontStr: String) {
self.alertview.setFont(fontStr, type: .Text)
}
func setButtonFont(fontStr: String) {
self.alertview.setFont(fontStr, type: .Button)
}
func setTextTheme(theme: TextColorTheme) {
self.alertview.setTextTheme(theme)
}
func close() {
self.alertview.closeView(false)
}
}
func setFont(fontStr: String, type: FontType) {
switch type {
case .Title:
self.titleFont = fontStr
if let font = UIFont(name: self.titleFont, size: 24) {
self.titleLabel.font = font
} else {
self.titleLabel.font = UIFont.systemFontOfSize(24)
}
case .Text:
if self.textView != nil {
self.textFont = fontStr
if let font = UIFont(name: self.textFont, size: 16) {
self.textView.font = font
} else {
self.textView.font = UIFont.systemFontOfSize(16)
}
}
case .Button:
self.buttonFont = fontStr
if let font = UIFont(name: self.buttonFont, size: 24) {
self.buttonLabel.font = font
} else {
self.buttonLabel.font = UIFont.systemFontOfSize(24)
}
}
// relayout to account for size changes
self.viewDidLayoutSubviews()
}
func setTextTheme(theme: TextColorTheme) {
switch theme {
case .Light:
recolorText(lightTextColor)
case .Dark:
recolorText(darkTextColor)
}
}
func recolorText(color: UIColor) {
titleLabel.textColor = color
if textView != nil {
textView.textColor = color
}
buttonLabel.textColor = color
if cancelButtonLabel != nil {
cancelButtonLabel.textColor = color
}
}
required init(coder aDecoder: NSCoder) {
fatalError("NSCoding not supported")
}
override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: NSBundle?) {
super.init(nibName:nibNameOrNil, bundle:nibBundleOrNil)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
override func viewDidLayoutSubviews() {
super.viewWillLayoutSubviews()
let size = UIScreen.mainScreen().bounds.size
self.viewWidth = size.width
self.viewHeight = size.height
var yPos:CGFloat = 0.0
var contentWidth:CGFloat = self.alertWidth - (self.padding*2)
// position the icon image view, if there is one
if self.iconImageView != nil {
yPos += iconImageView.frame.height
var centerX = (self.alertWidth-self.iconImageView.frame.width)/2
self.iconImageView.frame.origin = CGPoint(x: centerX, y: self.padding)
yPos += padding
}
// position the title
let titleString = titleLabel.text! as NSString
let titleAttr = [NSFontAttributeName:titleLabel.font]
let titleSize = CGSize(width: contentWidth, height: 90)
let titleRect = titleString.boundingRectWithSize(titleSize, options: NSStringDrawingOptions.UsesLineFragmentOrigin, attributes: titleAttr, context: nil)
yPos += padding
self.titleLabel.frame = CGRect(x: self.padding, y: yPos, width: self.alertWidth - (self.padding*2), height: ceil(titleRect.size.height))
yPos += ceil(titleRect.size.height)
// position text
if self.textView != nil {
let textString = textView.text! as NSString
let textAttr = [NSFontAttributeName:textView.font]
let textSize = CGSize(width: contentWidth, height: 90)
let textRect = textString.boundingRectWithSize(textSize, options: NSStringDrawingOptions.UsesLineFragmentOrigin, attributes: textAttr, context: nil)
self.textView.frame = CGRect(x: self.padding, y: yPos, width: self.alertWidth - (self.padding*2), height: ceil(textRect.size.height)*2)
yPos += ceil(textRect.size.height) + padding/2
}
// position the buttons
yPos += self.padding
var buttonWidth = self.alertWidth
if self.cancelButton != nil {
buttonWidth = self.alertWidth/2
self.cancelButton.frame = CGRect(x: 0, y: yPos, width: buttonWidth-0.5, height: self.buttonHeight)
if self.cancelButtonLabel != nil {
self.cancelButtonLabel.frame = CGRect(x: self.padding, y: (self.buttonHeight/2) - 15, width: buttonWidth - (self.padding*2), height: 30)
}
}
var buttonX = buttonWidth == self.alertWidth ? 0 : buttonWidth
self.dismissButton.frame = CGRect(x: buttonX, y: yPos, width: buttonWidth, height: self.buttonHeight)
if self.buttonLabel != nil {
self.buttonLabel.frame = CGRect(x: self.padding, y: (self.buttonHeight/2) - 15, width: buttonWidth - (self.padding*2), height: 30)
}
// set button fonts
if self.buttonLabel != nil {
buttonLabel.font = UIFont(name: self.buttonFont, size: 20)
}
if self.cancelButtonLabel != nil {
cancelButtonLabel.font = UIFont(name: self.buttonFont, size: 20)
}
yPos += self.buttonHeight
// size the background view
self.alertBackgroundView.frame = CGRect(x: 0, y: 0, width: self.alertWidth, height: yPos)
// size the container that holds everything together
self.containerView.frame = CGRect(x: (self.viewWidth!-self.alertWidth)/2, y: (self.viewHeight! - yPos)/2, width: self.alertWidth, height: yPos)
}
func info(viewController: UIViewController, title: String, text: String?=nil, buttonText: String?=nil, cancelButtonText: String?=nil) -> JSSAlertViewResponder {
var alertview = self.show(viewController, title: title, text: text, buttonText: buttonText, cancelButtonText: cancelButtonText, color: UIColorFromHex(0x3498db, alpha: 1))
alertview.setTextTheme(.Light)
return alertview
}
func success(viewController: UIViewController, title: String, text: String?=nil, buttonText: String?=nil, cancelButtonText: String?=nil) -> JSSAlertViewResponder {
return self.show(viewController, title: title, text: text, buttonText: buttonText, cancelButtonText: cancelButtonText, color: UIColorFromHex(0x2ecc71, alpha: 1))
}
func warning(viewController: UIViewController, title: String, text: String?=nil, buttonText: String?=nil, cancelButtonText: String?=nil) -> JSSAlertViewResponder {
return self.show(viewController, title: title, text: text, buttonText: buttonText, cancelButtonText: cancelButtonText, color: UIColorFromHex(0xf1c40f, alpha: 1))
}
func danger(viewController: UIViewController, title: String, text: String?=nil, buttonText: String?=nil, cancelButtonText: String?=nil) -> JSSAlertViewResponder {
var alertview = self.show(viewController, title: title, text: text, buttonText: buttonText, cancelButtonText: cancelButtonText, color: UIColorFromHex(0xe74c3c, alpha: 1))
alertview.setTextTheme(.Light)
return alertview
}
func show(viewController: UIViewController, title: String, text: String?=nil, buttonText: String?=nil, cancelButtonText: String?=nil, color: UIColor?=nil, iconImage: UIImage?=nil) -> JSSAlertViewResponder {
self.rootViewController = viewController
self.rootViewController.addChildViewController(self)
self.rootViewController.view.addSubview(view)
self.view.backgroundColor = UIColorFromHex(0x000000, alpha: 0.7)
var baseColor:UIColor?
if let customColor = color {
baseColor = customColor
} else {
baseColor = self.defaultColor
}
var textColor = self.darkTextColor
let sz = UIScreen.mainScreen().bounds.size
self.viewWidth = sz.width
self.viewHeight = sz.height
// Container for the entire alert modal contents
self.containerView = UIView()
self.view.addSubview(self.containerView!)
// Background view/main color
self.alertBackgroundView = UIView()
alertBackgroundView.backgroundColor = baseColor
alertBackgroundView.layer.cornerRadius = 4
alertBackgroundView.layer.masksToBounds = true
self.containerView.addSubview(alertBackgroundView!)
// Icon
self.iconImage = iconImage
if self.iconImage != nil {
self.iconImageView = UIImageView(image: self.iconImage)
self.containerView.addSubview(iconImageView)
}
// Title
self.titleLabel = UILabel()
titleLabel.textColor = textColor
titleLabel.numberOfLines = 0
titleLabel.textAlignment = .Center
titleLabel.font = UIFont(name: self.titleFont, size: 24)
titleLabel.text = title
self.containerView.addSubview(titleLabel)
// View text
if let str = text {
self.textView = UITextView()
self.textView.userInteractionEnabled = false
textView.editable = false
textView.textColor = textColor
textView.textAlignment = .Center
textView.font = UIFont(name: self.textFont, size: 16)
textView.backgroundColor = UIColor.clearColor()
textView.text = str
self.containerView.addSubview(textView)
}
// Button
self.dismissButton = UIButton()
let buttonColor = UIImage.withColor(adjustBrightness(baseColor!, 0.8))
let buttonHighlightColor = UIImage.withColor(adjustBrightness(baseColor!, 0.9))
dismissButton.setBackgroundImage(buttonColor, forState: .Normal)
dismissButton.setBackgroundImage(buttonHighlightColor, forState: .Highlighted)
dismissButton.addTarget(self, action: "buttonTap", forControlEvents: .TouchUpInside)
alertBackgroundView!.addSubview(dismissButton)
// Button text
self.buttonLabel = UILabel()
buttonLabel.textColor = textColor
buttonLabel.numberOfLines = 1
buttonLabel.textAlignment = .Center
if let text = buttonText {
buttonLabel.text = text
} else {
buttonLabel.text = "OK"
}
dismissButton.addSubview(buttonLabel)
// Second cancel button
if let btnText = cancelButtonText {
self.cancelButton = UIButton()
let buttonColor = UIImage.withColor(adjustBrightness(baseColor!, 0.8))
let buttonHighlightColor = UIImage.withColor(adjustBrightness(baseColor!, 0.9))
cancelButton.setBackgroundImage(buttonColor, forState: .Normal)
cancelButton.setBackgroundImage(buttonHighlightColor, forState: .Highlighted)
cancelButton.addTarget(self, action: "cancelButtonTap", forControlEvents: .TouchUpInside)
alertBackgroundView!.addSubview(cancelButton)
// Button text
self.cancelButtonLabel = UILabel()
cancelButtonLabel.alpha = 0.7
cancelButtonLabel.textColor = textColor
cancelButtonLabel.numberOfLines = 1
cancelButtonLabel.textAlignment = .Center
if let text = cancelButtonText {
cancelButtonLabel.text = text
}
cancelButton.addSubview(cancelButtonLabel)
}
// Animate it in
self.view.alpha = 0
UIView.animateWithDuration(0.2, animations: {
self.view.alpha = 1
})
self.containerView.frame.origin.x = self.rootViewController.view.center.x
self.containerView.center.y = -500
UIView.animateWithDuration(0.5, delay: 0.05, usingSpringWithDamping: 0.8, initialSpringVelocity: 0.5, options: nil, animations: {
self.containerView.center = self.rootViewController.view.center
}, completion: { finished in
})
isAlertOpen = true
return JSSAlertViewResponder(alertview: self)
}
func addAction(action: ()->Void) {
self.closeAction = action
}
func buttonTap() {
closeView(true);
}
func cancelButtonTap() {
closeView(false);
}
func closeView(withCallback:Bool) {
UIView.animateWithDuration(0.3, delay: 0, usingSpringWithDamping: 0.7, initialSpringVelocity: 0.5, options: nil, animations: {
self.containerView.center.y = self.rootViewController.view.center.y + self.viewHeight!
}, completion: { finished in
UIView.animateWithDuration(0.1, animations: {
self.view.alpha = 0
}, completion: { finished in
if withCallback == true {
if let action = self.closeAction {
action()
}
}
self.removeView()
})
})
}
func removeView() {
isAlertOpen = false
self.view.removeFromSuperview()
}
}
| mit | f385f0e2ab9179cf71278667d424ceb4 | 37.964824 | 210 | 0.616198 | 4.852315 | false | false | false | false |
Jakobeha/lAzR4t | lAzR4t Shared/Code/UI/ColorButtonElem.swift | 1 | 1184 | //
// ColorButtonElem.swift
// lAzR4t
//
// Created by Jakob Hain on 9/30/17.
// Copyright © 2017 Jakob Hain. All rights reserved.
//
import Foundation
///A button which represents color
final class ColorButtonElem: ButtonElem {
let color: AttackColor
init(color: AttackColor, isSelected: Bool, pos: CellPos) {
self.color = color
super.init(isSelected: isSelected, pos: pos, size: CellSize.unit)
}
override func set(pos newPos: CellPos) -> ColorButtonElem {
return ColorButtonElem(
color: self.color,
isSelected: self.isSelected,
pos: newPos
)
}
override func set(isSelected newIsSelected: Bool) -> ColorButtonElem {
return ColorButtonElem(
color: self.color,
isSelected: newIsSelected,
pos: self.pos
)
}
override func equals(_ other: Elem) -> Bool {
guard let other = other as? ColorButtonElem else {
return false
}
return
super.equals(other) &&
(other.color == self.color) &&
(other.isSelected == self.isSelected)
}
}
| mit | f625b02da30d465349bf6dad4290bac8 | 24.717391 | 74 | 0.579882 | 4.286232 | false | false | false | false |
kostickm/mobileStack | MobileStack/VolumeViewController.swift | 1 | 3088 | /**
* Copyright IBM Corporation 2016
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
**/
import UIKit
class VolumeViewController: UIViewController, UITextFieldDelegate {
var volumes = [Volume]()
var volumeId:String = ""
var volume: Volume?
@IBOutlet weak var volumeNameLabel: UILabel!
@IBOutlet weak var volumeSizeLabel: UILabel!
@IBOutlet weak var volumeNameTextField: UITextField!
@IBOutlet weak var volumeSizeTextField: UITextField!
@IBOutlet weak var saveVolumeButton: UIBarButtonItem!
@IBAction func cancelVolumeButton(_ sender: UIBarButtonItem) {
dismiss(animated: true, completion: nil)
}
/*override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}*/
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated) // No need for semicolon
getVolumes { volumes in
}
// Handle the text field’s user input through delegate callbacks.
volumeNameTextField.delegate = self
// Enable the Save button only if the text field has a valid Volume name.
checkValidVolumeName()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func textFieldDidBeginEditing(_ textField: UITextField) {
// Disable the Save button while editing.
saveVolumeButton.isEnabled = false
}
func checkValidVolumeName() {
// Disable the Save button if the text field is empty.
let text = volumeNameTextField.text ?? ""
saveVolumeButton.isEnabled = !text.isEmpty
}
func textFieldDidEndEditing(_ textField: UITextField) {
checkValidVolumeName()
navigationItem.title = textField.text
}
// 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.
if saveVolumeButton === sender as AnyObject? {
let name = volumeNameTextField.text ?? ""
let size = volumeSizeTextField.text ?? "0"
// Set the volume to be passed to VolumeTableViewController after the unwind segue.
createVolume(name: name, size: size)
}
}
}
| apache-2.0 | 918851b55f9813410bef66952f6aaf94 | 32.182796 | 106 | 0.673364 | 5.117745 | false | false | false | false |
alltheflow/copypasta | Carthage/Checkouts/VinceRP/vincerp/Common/Core/Node.swift | 1 | 1623 | //
// Created by Viktor Belenyesi on 19/04/15.
// Copyright (c) 2015 Viktor Belenyesi. All rights reserved.
//
public class Node: Hashable {
private static var hashCounter = AtomicLong(0)
private let childrenHolder = AtomicReference<WeakSet<Node>>(WeakSet())
public let hashValue = Int(Node.hashCounter.getAndIncrement()) // Hashable
public var children: Set<Node> {
return childrenHolder.value.filter {
$0.parents.contains(self)
}.set
}
public var descendants: Set<Node> {
return children ++ children.flatMap {
$0.descendants
}
}
public var parents: Set<Node> {
return Set()
}
public var ancestors: Set<Node> {
return parents ++ parents.flatMap {
$0.ancestors
}
}
func isSuccess() -> Bool {
return true
}
func error() -> NSError {
fatalError(ABSTRACT_METHOD)
}
func linkChild(child: Node) {
if (!childrenHolder.value.hasElementPassingTest {$0 == child}) {
childrenHolder.value.insert(child)
}
}
func unlinkChild(child: Node) {
childrenHolder.value = childrenHolder.value.filter {$0 != child}
}
func ping(incoming: Set<Node>) -> Set<Node> {
fatalError(ABSTRACT_METHOD)
}
private var alive = true
public func kill() {
alive = false
parents.forEach {
$0.unlinkChild(self)
}
}
var level: long {
return 0
}
}
public func ==(lhs: Node, rhs: Node) -> Bool {
return lhs.hashValue == rhs.hashValue
}
| mit | 133f941a3905a2b41fc54d1fdf8035f1 | 20.932432 | 79 | 0.579174 | 4.161538 | false | false | false | false |
R3dTeam/SwiftLint | Source/SwiftLintFramework/Rules/TypeNameRule.swift | 5 | 3192 | //
// TypeNameRule.swift
// SwiftLint
//
// Created by JP Simard on 2015-05-16.
// Copyright (c) 2015 Realm. All rights reserved.
//
import SourceKittenFramework
import SwiftXPC
public struct TypeNameRule: ASTRule {
public init() {}
public let identifier = "type_name"
public func validateFile(file: File) -> [StyleViolation] {
return validateFile(file, dictionary: file.structure.dictionary)
}
public func validateFile(file: File, dictionary: XPCDictionary) -> [StyleViolation] {
return (dictionary["key.substructure"] as? XPCArray ?? []).flatMap { subItem in
var violations = [StyleViolation]()
if let subDict = subItem as? XPCDictionary,
let kindString = subDict["key.kind"] as? String,
let kind = flatMap(kindString, { SwiftDeclarationKind(rawValue: $0) }) {
violations.extend(validateFile(file, dictionary: subDict))
violations.extend(validateFile(file, kind: kind, dictionary: subDict))
}
return violations
}
}
public func validateFile(file: File,
kind: SwiftDeclarationKind,
dictionary: XPCDictionary) -> [StyleViolation] {
let typeKinds: [SwiftDeclarationKind] = [
.Class,
.Struct,
.Typealias,
.Enum,
.Enumelement
]
if !contains(typeKinds, kind) {
return []
}
var violations = [StyleViolation]()
if let name = dictionary["key.name"] as? String,
let offset = flatMap(dictionary["key.offset"] as? Int64, { Int($0) }) {
let location = Location(file: file, offset: offset)
let nameCharacterSet = NSCharacterSet(charactersInString: name)
if !NSCharacterSet.alphanumericCharacterSet().isSupersetOfSet(nameCharacterSet) {
violations.append(StyleViolation(type: .NameFormat,
location: location,
severity: .High,
reason: "Type name should only contain alphanumeric characters: '\(name)'"))
} else if !name.substringToIndex(name.startIndex.successor()).isUppercase() {
violations.append(StyleViolation(type: .NameFormat,
location: location,
severity: .High,
reason: "Type name should start with an uppercase character: '\(name)'"))
} else if count(name) < 3 || count(name) > 40 {
violations.append(StyleViolation(type: .NameFormat,
location: location,
severity: .Medium,
reason: "Type name should be between 3 and 40 characters in length: " +
"'\(name)'"))
}
}
return violations
}
public let example = RuleExample(
ruleName: "Type Name Rule",
ruleDescription: "Type name should only contain alphanumeric characters, " +
"start with an uppercase character and between 3 and 40 characters in length.",
nonTriggeringExamples: [],
triggeringExamples: [],
showExamples: false
)
}
| mit | bcddeeb8a9ff8bea0d19511cc425ae28 | 38.407407 | 96 | 0.5849 | 5.050633 | false | false | false | false |
allbto/WayThere | ios/WayThere/Pods/Nimble/Nimble/Matchers/BeGreaterThanOrEqualTo.swift | 78 | 1700 | import Foundation
/// A Nimble matcher that succeeds when the actual value is greater than
/// or equal to the expected value.
public func beGreaterThanOrEqualTo<T: Comparable>(expectedValue: T?) -> NonNilMatcherFunc<T> {
return NonNilMatcherFunc { actualExpression, failureMessage in
failureMessage.postfixMessage = "be greater than or equal to <\(stringify(expectedValue))>"
let actualValue = actualExpression.evaluate()
return actualValue >= expectedValue
}
}
/// A Nimble matcher that succeeds when the actual value is greater than
/// or equal to the expected value.
public func beGreaterThanOrEqualTo<T: NMBComparable>(expectedValue: T?) -> NonNilMatcherFunc<T> {
return NonNilMatcherFunc { actualExpression, failureMessage in
failureMessage.postfixMessage = "be greater than or equal to <\(stringify(expectedValue))>"
let actualValue = actualExpression.evaluate()
let matches = actualValue != nil && actualValue!.NMB_compare(expectedValue) != NSComparisonResult.OrderedAscending
return matches
}
}
public func >=<T: Comparable>(lhs: Expectation<T>, rhs: T) {
lhs.to(beGreaterThanOrEqualTo(rhs))
}
public func >=<T: NMBComparable>(lhs: Expectation<T>, rhs: T) {
lhs.to(beGreaterThanOrEqualTo(rhs))
}
extension NMBObjCMatcher {
public class func beGreaterThanOrEqualToMatcher(expected: NMBComparable?) -> NMBObjCMatcher {
return NMBObjCMatcher(canMatchNil: false) { actualExpression, failureMessage, location in
let expr = actualExpression.cast { $0 as? NMBComparable }
return beGreaterThanOrEqualTo(expected).matches(expr, failureMessage: failureMessage)
}
}
}
| mit | f2a8f5da648b7208e09c441e55ad8867 | 42.589744 | 122 | 0.727647 | 5.29595 | false | false | false | false |
mahomealex/MASQLiteWrapper | Source/SQOperation.swift | 2 | 3319 | //
// SQOperation.swift
//
//
// Created by Alex on 25/04/2017.
// Copyright © 2017 Alex. All rights reserved.
//
import Foundation
import SQLite
class SQOperation : NSObject {
weak var db : Connection!
func save(model:SQObject) {
let schema = SQSchemaCache.objectSchema(model: model)
var ary:[Setter] = []
for pt in schema.properties {
ary.append(pt.generalSetter(model: model))
}
do {
let pt = schema.primaryKeyProperty()
let filterTable = schema.table.filter(pt.filter(model: model))
if let _ = try db.pluck(filterTable) {//exist
_ = try db.run(filterTable.update(ary))
} else {
try db.run(schema.table.insert(ary))
}
} catch {
print(error)
}
}
func saveAll(models:[SQObject]) {
guard models.count > 0 else {
return
}
for model in models {
save(model: model)
}
}
func delete(model:SQObject) {
let schema = SQSchemaCache.objectSchema(model: model)
do {
let pt = schema.primaryKeyProperty()
let filterTable = schema.table.filter(pt.filter(model: model))
try db.run(filterTable.delete())
} catch {
print(error)
}
}
func queryAll(_ m:SQObject) -> [SQObject] {
let schema = SQSchemaCache.objectSchema(model: m)
var items:[SQObject] = []
do {
let datas = try db.prepare(schema.table)
for data in datas {
let item = schema.objClass.init()
for pt in schema.properties {
pt.convertcolumnToModel(model: item, row: data)
}
items.append(item)
}
} catch {
print(error)
}
return items
}
func queryAll<T:SQObject>(_ m:T.Type) -> [T] {
let schema = SQSchemaCache.objectSchema(m)
var items:[T] = []
do {
let datas = try db.prepare(schema.table)
for data in datas {
let item = schema.objClass.init()
for pt in schema.properties {
pt.convertcolumnToModel(model: item, row: data)
}
items.append(item as! T)
}
} catch {
print(error)
}
return items
}
func createTable(model:SQObject) {
let schema = SQSchemaCache.objectSchema(model: model)
do {
try db.run(schema.table.create(ifNotExists: true, block: { (t) in
for pt in schema.properties {
pt.buildColumn(builder: t)
}
}))
} catch {
print(error)
}
}
func crateTable<T:SQObject>(_ m:T.Type) {
let schema = SQSchemaCache.objectSchema(m)
do {
// let state =
_ = try db.run(schema.table.create(ifNotExists: true, block: { (t) in
for pt in schema.properties {
pt.buildColumn(builder: t)
}
}))
// print(state)
} catch {
print(error)
}
}
}
| mit | e0626dc9bec16988f7eb4a27c510fb36 | 26.196721 | 81 | 0.486136 | 4.275773 | false | false | false | false |
acegreen/Bitcoin-Sample-iOS-App | Pods/Charts/Charts/Classes/Renderers/PieChartRenderer.swift | 6 | 32536 | //
// PieChartRenderer.swift
// Charts
//
// Created by Daniel Cohen Gindi on 4/3/15.
//
// Copyright 2015 Daniel Cohen Gindi & Philipp Jahoda
// A port of MPAndroidChart for iOS
// Licensed under Apache License 2.0
//
// https://github.com/danielgindi/Charts
//
import Foundation
import CoreGraphics
#if !os(OSX)
import UIKit
#endif
open class PieChartRenderer: ChartDataRendererBase
{
open weak var chart: PieChartView?
public init(chart: PieChartView, animator: ChartAnimator?, viewPortHandler: ChartViewPortHandler)
{
super.init(animator: animator, viewPortHandler: viewPortHandler)
self.chart = chart
}
open override func drawData(context: CGContext)
{
guard let chart = chart else { return }
let pieData = chart.data
if (pieData != nil)
{
for set in pieData!.dataSets as! [IPieChartDataSet]
{
if set.visible && set.entryCount > 0
{
drawDataSet(context: context, dataSet: set)
}
}
}
}
open func calculateMinimumRadiusForSpacedSlice(
center: CGPoint,
radius: CGFloat,
angle: CGFloat,
arcStartPointX: CGFloat,
arcStartPointY: CGFloat,
startAngle: CGFloat,
sweepAngle: CGFloat) -> CGFloat
{
let angleMiddle = startAngle + sweepAngle / 2.0
// Other point of the arc
let arcEndPointX = center.x + radius * cos((startAngle + sweepAngle) * ChartUtils.Math.FDEG2RAD)
let arcEndPointY = center.y + radius * sin((startAngle + sweepAngle) * ChartUtils.Math.FDEG2RAD)
// Middle point on the arc
let arcMidPointX = center.x + radius * cos(angleMiddle * ChartUtils.Math.FDEG2RAD)
let arcMidPointY = center.y + radius * sin(angleMiddle * ChartUtils.Math.FDEG2RAD)
// This is the base of the contained triangle
let basePointsDistance = sqrt(
pow(arcEndPointX - arcStartPointX, 2) +
pow(arcEndPointY - arcStartPointY, 2))
// After reducing space from both sides of the "slice",
// the angle of the contained triangle should stay the same.
// So let's find out the height of that triangle.
let containedTriangleHeight = (basePointsDistance / 2.0 *
tan((180.0 - angle) / 2.0 * ChartUtils.Math.FDEG2RAD))
// Now we subtract that from the radius
var spacedRadius = radius - containedTriangleHeight
// And now subtract the height of the arc that's between the triangle and the outer circle
spacedRadius -= sqrt(
pow(arcMidPointX - (arcEndPointX + arcStartPointX) / 2.0, 2) +
pow(arcMidPointY - (arcEndPointY + arcStartPointY) / 2.0, 2))
return spacedRadius
}
open func drawDataSet(context: CGContext, dataSet: IPieChartDataSet)
{
guard let chart = chart,
let data = chart.data,
let animator = animator
else {return }
var angle: CGFloat = 0.0
let rotationAngle = chart.rotationAngle
let phaseX = animator.phaseX
let phaseY = animator.phaseY
let entryCount = dataSet.entryCount
var drawAngles = chart.drawAngles
let center = chart.centerCircleBox
let radius = chart.radius
let drawInnerArc = chart.drawHoleEnabled && !chart.drawSlicesUnderHoleEnabled
let userInnerRadius = drawInnerArc ? radius * chart.holeRadiusPercent : 0.0
var visibleAngleCount = 0
for j in 0 ..< entryCount
{
guard let e = dataSet.entryForIndex(j) else { continue }
if ((abs(e.value) > 0.000001))
{
visibleAngleCount += 1
}
}
let sliceSpace = visibleAngleCount <= 1 ? 0.0 : dataSet.sliceSpace
context.saveGState()
for j in 0 ..< entryCount
{
let sliceAngle = drawAngles[j]
var innerRadius = userInnerRadius
guard let e = dataSet.entryForIndex(j) else { continue }
// draw only if the value is greater than zero
if ((abs(e.value) > 0.000001))
{
if (!chart.needsHighlight(xIndex: e.xIndex,
dataSetIndex: data.indexOfDataSet(dataSet)))
{
let accountForSliceSpacing = sliceSpace > 0.0 && sliceAngle <= 180.0
context.setFillColor(dataSet.colorAt(j).cgColor)
let sliceSpaceAngleOuter = visibleAngleCount == 1 ?
0.0 :
sliceSpace / (ChartUtils.Math.FDEG2RAD * radius)
let startAngleOuter = rotationAngle + (angle + sliceSpaceAngleOuter / 2.0) * phaseY
var sweepAngleOuter = (sliceAngle - sliceSpaceAngleOuter) * phaseY
if (sweepAngleOuter < 0.0)
{
sweepAngleOuter = 0.0
}
let arcStartPointX = center.x + radius * cos(startAngleOuter * ChartUtils.Math.FDEG2RAD)
let arcStartPointY = center.y + radius * sin(startAngleOuter * ChartUtils.Math.FDEG2RAD)
let path = CGMutablePath()
path.move(to: CGPoint(x: arcStartPointX, y: arcStartPointY))
path.addRelativeArc(center: CGPoint(x: center.x, y: center.y),
radius: radius,
startAngle: startAngleOuter * ChartUtils.Math.FDEG2RAD,
delta: sweepAngleOuter * ChartUtils.Math.FDEG2RAD)
if drawInnerArc &&
(innerRadius > 0.0 || accountForSliceSpacing)
{
if accountForSliceSpacing
{
var minSpacedRadius = calculateMinimumRadiusForSpacedSlice(
center: center,
radius: radius,
angle: sliceAngle * phaseY,
arcStartPointX: arcStartPointX,
arcStartPointY: arcStartPointY,
startAngle: startAngleOuter,
sweepAngle: sweepAngleOuter)
if minSpacedRadius < 0.0
{
minSpacedRadius = -minSpacedRadius
}
innerRadius = min(max(innerRadius, minSpacedRadius), radius)
}
let sliceSpaceAngleInner = visibleAngleCount == 1 || innerRadius == 0.0 ?
0.0 :
sliceSpace / (ChartUtils.Math.FDEG2RAD * innerRadius)
let startAngleInner = rotationAngle + (angle + sliceSpaceAngleInner / 2.0) * phaseY
var sweepAngleInner = (sliceAngle - sliceSpaceAngleInner) * phaseY
if (sweepAngleInner < 0.0)
{
sweepAngleInner = 0.0
}
let endAngleInner = startAngleInner + sweepAngleInner
path.addLine(to: CGPoint(x: center.x + innerRadius * cos(endAngleInner * ChartUtils.Math.FDEG2RAD),
y: center.y + innerRadius * sin(endAngleInner * ChartUtils.Math.FDEG2RAD)))
path.addRelativeArc(center: CGPoint(x: center.x, y: center.y),
radius: innerRadius,
startAngle: endAngleInner * ChartUtils.Math.FDEG2RAD,
delta: -sweepAngleInner * ChartUtils.Math.FDEG2RAD)
}
else
{
if accountForSliceSpacing
{
let angleMiddle = startAngleOuter + sweepAngleOuter / 2.0
let sliceSpaceOffset =
calculateMinimumRadiusForSpacedSlice(
center: center,
radius: radius,
angle: sliceAngle * phaseY,
arcStartPointX: arcStartPointX,
arcStartPointY: arcStartPointY,
startAngle: startAngleOuter,
sweepAngle: sweepAngleOuter)
let arcEndPointX = center.x + sliceSpaceOffset * cos(angleMiddle * ChartUtils.Math.FDEG2RAD)
let arcEndPointY = center.y + sliceSpaceOffset * sin(angleMiddle * ChartUtils.Math.FDEG2RAD)
path.addLine(to: CGPoint(x: arcEndPointX, y: arcEndPointY))
}
else
{
path.addLine(to: CGPoint(x: center.x, y: center.y))
}
}
path.closeSubpath()
context.beginPath()
context.addPath(path)
context.fillPath(using: .evenOdd)
}
}
angle += sliceAngle * phaseX
}
context.restoreGState()
}
open override func drawValues(context: CGContext)
{
guard let chart = chart,
let data = chart.data,
let animator = animator
else { return }
let center = chart.centerCircleBox
// get whole the radius
let radius = chart.radius
let rotationAngle = chart.rotationAngle
var drawAngles = chart.drawAngles
var absoluteAngles = chart.absoluteAngles
let phaseX = animator.phaseX
let phaseY = animator.phaseY
var labelRadiusOffset = radius / 10.0 * 3.0
if chart.drawHoleEnabled
{
labelRadiusOffset = (radius - (radius * chart.holeRadiusPercent)) / 2.0
}
let labelRadius = radius - labelRadiusOffset
var dataSets = data.dataSets
let yValueSum = (data as! PieChartData).yValueSum
let drawXVals = chart.drawSliceTextEnabled
let usePercentValuesEnabled = chart.usePercentValuesEnabled
var angle: CGFloat = 0.0
var xIndex = 0
context.saveGState()
defer { context.restoreGState() }
for i in 0 ..< dataSets.count
{
guard let dataSet = dataSets[i] as? IPieChartDataSet else { continue }
let drawYVals = dataSet.drawValuesEnabled
if (!drawYVals && !drawXVals)
{
continue
}
let xValuePosition = dataSet.xValuePosition
let yValuePosition = dataSet.yValuePosition
let valueFont = dataSet.valueFont
let lineHeight = valueFont.lineHeight
guard let formatter = dataSet.valueFormatter else { continue }
for j in 0 ..< dataSet.entryCount
{
if (drawXVals && !drawYVals && (j >= data.xValCount || data.xVals[j] == nil))
{
continue
}
guard let e = dataSet.entryForIndex(j) else { continue }
if (xIndex == 0)
{
angle = 0.0
}
else
{
angle = absoluteAngles[xIndex - 1] * phaseX
}
let sliceAngle = drawAngles[xIndex]
let sliceSpace = dataSet.sliceSpace
let sliceSpaceMiddleAngle = sliceSpace / (ChartUtils.Math.FDEG2RAD * labelRadius)
// offset needed to center the drawn text in the slice
let angleOffset = (sliceAngle - sliceSpaceMiddleAngle / 2.0) / 2.0
angle = angle + angleOffset
let transformedAngle = rotationAngle + angle * phaseY
let value = usePercentValuesEnabled ? e.value / yValueSum * 100.0 : e.value
let valueText = formatter.string(from: value as NSNumber)!
let sliceXBase = cos(transformedAngle * ChartUtils.Math.FDEG2RAD)
let sliceYBase = sin(transformedAngle * ChartUtils.Math.FDEG2RAD)
let drawXOutside = drawXVals && xValuePosition == .outsideSlice
let drawYOutside = drawYVals && yValuePosition == .outsideSlice
let drawXInside = drawXVals && xValuePosition == .insideSlice
let drawYInside = drawYVals && yValuePosition == .insideSlice
if drawXOutside || drawYOutside
{
let valueLineLength1 = dataSet.valueLinePart1Length
let valueLineLength2 = dataSet.valueLinePart2Length
let valueLinePart1OffsetPercentage = dataSet.valueLinePart1OffsetPercentage
var pt2: CGPoint
var labelPoint: CGPoint
var align: NSTextAlignment
var line1Radius: CGFloat
if chart.drawHoleEnabled
{
line1Radius = (radius - (radius * chart.holeRadiusPercent)) * valueLinePart1OffsetPercentage + (radius * chart.holeRadiusPercent)
}
else
{
line1Radius = radius * valueLinePart1OffsetPercentage
}
let polyline2Length = dataSet.valueLineVariableLength
? labelRadius * valueLineLength2 * abs(sin(transformedAngle * ChartUtils.Math.FDEG2RAD))
: labelRadius * valueLineLength2;
let pt0 = CGPoint(
x: line1Radius * sliceXBase + center.x,
y: line1Radius * sliceYBase + center.y)
let pt1 = CGPoint(
x: labelRadius * (1 + valueLineLength1) * sliceXBase + center.x,
y: labelRadius * (1 + valueLineLength1) * sliceYBase + center.y)
if transformedAngle.truncatingRemainder(dividingBy: 360.0) >= 90.0 && transformedAngle.truncatingRemainder(dividingBy: 360.0) <= 270.0
{
pt2 = CGPoint(x: pt1.x - polyline2Length, y: pt1.y)
align = .right
labelPoint = CGPoint(x: pt2.x - 5, y: pt2.y - lineHeight)
}
else
{
pt2 = CGPoint(x: pt1.x + polyline2Length, y: pt1.y)
align = .left
labelPoint = CGPoint(x: pt2.x + 5, y: pt2.y - lineHeight)
}
if dataSet.valueLineColor != nil
{
context.setStrokeColor(dataSet.valueLineColor!.cgColor)
context.setLineWidth(dataSet.valueLineWidth);
context.move(to: CGPoint(x: pt0.x, y: pt0.y))
context.addLine(to: CGPoint(x: pt1.x, y: pt1.y))
context.addLine(to: CGPoint(x: pt2.x, y: pt2.y))
context.drawPath(using: CGPathDrawingMode.stroke);
}
if drawXOutside && drawYOutside
{
ChartUtils.drawText(
context: context,
text: valueText,
point: labelPoint,
align: align,
attributes: [NSFontAttributeName: valueFont, NSForegroundColorAttributeName: dataSet.valueTextColorAt(j)]
)
if (j < data.xValCount && data.xVals[j] != nil)
{
ChartUtils.drawText(
context: context,
text: data.xVals[j]!,
point: CGPoint(x: labelPoint.x, y: labelPoint.y + lineHeight),
align: align,
attributes: [NSFontAttributeName: valueFont, NSForegroundColorAttributeName: dataSet.valueTextColorAt(j)]
)
}
}
else if drawXOutside
{
ChartUtils.drawText(
context: context,
text: data.xVals[j]!,
point: CGPoint(x: labelPoint.x, y: labelPoint.y + lineHeight / 2.0),
align: align,
attributes: [NSFontAttributeName: valueFont, NSForegroundColorAttributeName: dataSet.valueTextColorAt(j)]
)
}
else if drawYOutside
{
ChartUtils.drawText(
context: context,
text: valueText,
point: CGPoint(x: labelPoint.x, y: labelPoint.y + lineHeight / 2.0),
align: align,
attributes: [NSFontAttributeName: valueFont, NSForegroundColorAttributeName: dataSet.valueTextColorAt(j)]
)
}
}
if drawXInside || drawYInside
{
// calculate the text position
let x = labelRadius * sliceXBase + center.x
let y = labelRadius * sliceYBase + center.y - lineHeight
if drawXInside && drawYInside
{
ChartUtils.drawText(
context: context,
text: valueText,
point: CGPoint(x: x, y: y),
align: .center,
attributes: [NSFontAttributeName: valueFont, NSForegroundColorAttributeName: dataSet.valueTextColorAt(j)]
)
if j < data.xValCount && data.xVals[j] != nil
{
ChartUtils.drawText(
context: context,
text: data.xVals[j]!,
point: CGPoint(x: x, y: y + lineHeight),
align: .center,
attributes: [NSFontAttributeName: valueFont, NSForegroundColorAttributeName: dataSet.valueTextColorAt(j)]
)
}
}
else if drawXInside
{
ChartUtils.drawText(
context: context,
text: data.xVals[j]!,
point: CGPoint(x: x, y: y + lineHeight / 2.0),
align: .center,
attributes: [NSFontAttributeName: valueFont, NSForegroundColorAttributeName: dataSet.valueTextColorAt(j)]
)
}
else if drawYInside
{
ChartUtils.drawText(
context: context,
text: valueText,
point: CGPoint(x: x, y: y + lineHeight / 2.0),
align: .center,
attributes: [NSFontAttributeName: valueFont, NSForegroundColorAttributeName: dataSet.valueTextColorAt(j)]
)
}
}
xIndex += 1
}
}
}
open override func drawExtras(context: CGContext)
{
drawHole(context: context)
drawCenterText(context: context)
}
/// draws the hole in the center of the chart and the transparent circle / hole
private func drawHole(context: CGContext)
{
guard let chart = chart,
let animator = animator
else { return }
if (chart.drawHoleEnabled)
{
context.saveGState()
let radius = chart.radius
let holeRadius = radius * chart.holeRadiusPercent
let center = chart.centerCircleBox
if let holeColor = chart.holeColor
{
if holeColor != NSUIColor.clear
{
// draw the hole-circle
context.setFillColor(chart.holeColor!.cgColor)
context.fillEllipse(in: CGRect(x: center.x - holeRadius, y: center.y - holeRadius, width: holeRadius * 2.0, height: holeRadius * 2.0))
}
}
// only draw the circle if it can be seen (not covered by the hole)
if let transparentCircleColor = chart.transparentCircleColor
{
if transparentCircleColor != NSUIColor.clear &&
chart.transparentCircleRadiusPercent > chart.holeRadiusPercent
{
let alpha = animator.phaseX * animator.phaseY
let secondHoleRadius = radius * chart.transparentCircleRadiusPercent
// make transparent
context.setAlpha(alpha);
context.setFillColor(transparentCircleColor.cgColor)
// draw the transparent-circle
context.beginPath()
context.addEllipse(in: CGRect(
x: center.x - secondHoleRadius,
y: center.y - secondHoleRadius,
width: secondHoleRadius * 2.0,
height: secondHoleRadius * 2.0))
context.addEllipse(in: CGRect(
x: center.x - holeRadius,
y: center.y - holeRadius,
width: holeRadius * 2.0,
height: holeRadius * 2.0))
context.fillPath(using: .evenOdd)
}
}
context.restoreGState()
}
}
/// draws the description text in the center of the pie chart makes most sense when center-hole is enabled
private func drawCenterText(context: CGContext)
{
guard let chart = chart,
let centerAttributedText = chart.centerAttributedText
else { return }
if chart.drawCenterTextEnabled && centerAttributedText.length > 0
{
let center = chart.centerCircleBox
let innerRadius = chart.drawHoleEnabled && !chart.drawSlicesUnderHoleEnabled ? chart.radius * chart.holeRadiusPercent : chart.radius
let holeRect = CGRect(x: center.x - innerRadius, y: center.y - innerRadius, width: innerRadius * 2.0, height: innerRadius * 2.0)
var boundingRect = holeRect
if (chart.centerTextRadiusPercent > 0.0)
{
boundingRect = boundingRect.insetBy(dx: (boundingRect.width - boundingRect.width * chart.centerTextRadiusPercent) / 2.0, dy: (boundingRect.height - boundingRect.height * chart.centerTextRadiusPercent) / 2.0)
}
let textBounds = centerAttributedText.boundingRect(with: boundingRect.size, options: [.usesLineFragmentOrigin, .usesFontLeading, .truncatesLastVisibleLine], context: nil)
var drawingRect = boundingRect
drawingRect.origin.x += (boundingRect.size.width - textBounds.size.width) / 2.0
drawingRect.origin.y += (boundingRect.size.height - textBounds.size.height) / 2.0
drawingRect.size = textBounds.size
context.saveGState()
let clippingPath = CGPath(ellipseIn: holeRect, transform: nil)
context.beginPath()
context.addPath(clippingPath)
context.clip()
centerAttributedText.draw(with: drawingRect, options: [.usesLineFragmentOrigin, .usesFontLeading, .truncatesLastVisibleLine], context: nil)
context.restoreGState()
}
}
open override func drawHighlighted(context: CGContext, indices: [ChartHighlight])
{
guard let chart = chart,
let data = chart.data,
let animator = animator
else { return }
context.saveGState()
let phaseX = animator.phaseX
let phaseY = animator.phaseY
var angle: CGFloat = 0.0
let rotationAngle = chart.rotationAngle
var drawAngles = chart.drawAngles
var absoluteAngles = chart.absoluteAngles
let center = chart.centerCircleBox
let radius = chart.radius
let drawInnerArc = chart.drawHoleEnabled && !chart.drawSlicesUnderHoleEnabled
let userInnerRadius = drawInnerArc ? radius * chart.holeRadiusPercent : 0.0
for i in 0 ..< indices.count
{
// get the index to highlight
let xIndex = indices[i].xIndex
if (xIndex >= drawAngles.count)
{
continue
}
guard let set = data.getDataSetByIndex(indices[i].dataSetIndex) as? IPieChartDataSet else { continue }
if !set.highlightEnabled
{
continue
}
let entryCount = set.entryCount
var visibleAngleCount = 0
for j in 0 ..< entryCount
{
guard let e = set.entryForIndex(j) else { continue }
if ((abs(e.value) > 0.000001))
{
visibleAngleCount += 1
}
}
if (xIndex == 0)
{
angle = 0.0
}
else
{
angle = absoluteAngles[xIndex - 1] * phaseX
}
let sliceSpace = visibleAngleCount <= 1 ? 0.0 : set.sliceSpace
let sliceAngle = drawAngles[xIndex]
var innerRadius = userInnerRadius
let shift = set.selectionShift
let highlightedRadius = radius + shift
let accountForSliceSpacing = sliceSpace > 0.0 && sliceAngle <= 180.0
context.setFillColor(set.colorAt(xIndex).cgColor)
let sliceSpaceAngleOuter = visibleAngleCount == 1 ?
0.0 :
sliceSpace / (ChartUtils.Math.FDEG2RAD * radius)
let sliceSpaceAngleShifted = visibleAngleCount == 1 ?
0.0 :
sliceSpace / (ChartUtils.Math.FDEG2RAD * highlightedRadius)
let startAngleOuter = rotationAngle + (angle + sliceSpaceAngleOuter / 2.0) * phaseY
var sweepAngleOuter = (sliceAngle - sliceSpaceAngleOuter) * phaseY
if (sweepAngleOuter < 0.0)
{
sweepAngleOuter = 0.0
}
let startAngleShifted = rotationAngle + (angle + sliceSpaceAngleShifted / 2.0) * phaseY
var sweepAngleShifted = (sliceAngle - sliceSpaceAngleShifted) * phaseY
if (sweepAngleShifted < 0.0)
{
sweepAngleShifted = 0.0
}
let path = CGMutablePath()
path.move(to: CGPoint(x: center.x + highlightedRadius * cos(startAngleShifted * ChartUtils.Math.FDEG2RAD),
y: center.y + highlightedRadius * sin(startAngleShifted * ChartUtils.Math.FDEG2RAD)))
path.addRelativeArc(center: CGPoint(x: center.x, y: center.y),
radius: highlightedRadius,
startAngle: startAngleShifted * ChartUtils.Math.FDEG2RAD,
delta: sweepAngleShifted * ChartUtils.Math.FDEG2RAD)
var sliceSpaceRadius: CGFloat = 0.0
if accountForSliceSpacing
{
sliceSpaceRadius = calculateMinimumRadiusForSpacedSlice(
center: center,
radius: radius,
angle: sliceAngle * phaseY,
arcStartPointX: center.x + radius * cos(startAngleOuter * ChartUtils.Math.FDEG2RAD),
arcStartPointY: center.y + radius * sin(startAngleOuter * ChartUtils.Math.FDEG2RAD),
startAngle: startAngleOuter,
sweepAngle: sweepAngleOuter)
}
if drawInnerArc &&
(innerRadius > 0.0 || accountForSliceSpacing)
{
if accountForSliceSpacing
{
var minSpacedRadius = sliceSpaceRadius
if minSpacedRadius < 0.0
{
minSpacedRadius = -minSpacedRadius
}
innerRadius = min(max(innerRadius, minSpacedRadius), radius)
}
let sliceSpaceAngleInner = visibleAngleCount == 1 || innerRadius == 0.0 ?
0.0 :
sliceSpace / (ChartUtils.Math.FDEG2RAD * innerRadius)
let startAngleInner = rotationAngle + (angle + sliceSpaceAngleInner / 2.0) * phaseY
var sweepAngleInner = (sliceAngle - sliceSpaceAngleInner) * phaseY
if (sweepAngleInner < 0.0)
{
sweepAngleInner = 0.0
}
let endAngleInner = startAngleInner + sweepAngleInner
path.addLine(to: CGPoint(x: center.x + innerRadius * cos(endAngleInner * ChartUtils.Math.FDEG2RAD),
y: center.y + innerRadius * sin(endAngleInner * ChartUtils.Math.FDEG2RAD)))
path.addRelativeArc(center: CGPoint(x: center.x, y: center.y),
radius: innerRadius,
startAngle: endAngleInner * ChartUtils.Math.FDEG2RAD,
delta: -sweepAngleInner * ChartUtils.Math.FDEG2RAD)
}
else
{
if accountForSliceSpacing
{
let angleMiddle = startAngleOuter + sweepAngleOuter / 2.0
let arcEndPointX = center.x + sliceSpaceRadius * cos(angleMiddle * ChartUtils.Math.FDEG2RAD)
let arcEndPointY = center.y + sliceSpaceRadius * sin(angleMiddle * ChartUtils.Math.FDEG2RAD)
path.addLine(to: CGPoint(x: arcEndPointX, y: arcEndPointY))
}
else
{
path.addLine(to: CGPoint(x: center.x, y: center.y))
}
}
path.closeSubpath()
context.beginPath()
context.addPath(path)
context.fillPath(using: .evenOdd)
}
context.restoreGState()
}
}
| mit | ed9234567340b8d3b34a819642e4578e | 41.145078 | 223 | 0.486968 | 5.690101 | false | false | false | false |
rockwotj/shiloh-ranch | ios/shiloh_ranch/shiloh_ranch/Helpers.swift | 1 | 12584 | //
// Helpers.swift
// Shiloh Ranch
//
// Created by Tyler Rockwood on 6/11/15.
// Copyright (c) 2015 Shiloh Ranch Cowboy Church. All rights reserved.
//
import UIKit
func showErrorDialog(error : NSError) {
let dialog = UIAlertView(title: "Error!", message: error.localizedDescription, delegate: nil, cancelButtonTitle: "OK")
dialog.show()
}
func showErrorDialog(message : String) {
let dialog = UIAlertView(title: "Error!", message: message, delegate: nil, cancelButtonTitle: "OK")
dialog.show()
}
func getApiService() -> GTLServiceShilohranch {
let app = UIApplication.sharedApplication().delegate as! AppDelegate
return app.service
}
func getDatabase() -> Database {
let app = UIApplication.sharedApplication().delegate as! AppDelegate
return app.database
}
func convertDateToUnixTime(dateString : String) -> Int64 {
var timestamp = dateString.stringByReplacingOccurrencesOfString("T", withString: " ")
let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss.SS"
if let date = dateFormatter.dateFromString(timestamp) {
let lastSync = Int64(date.timeIntervalSince1970 * 1000)
return lastSync
} else {
println("Error converting datetime to unix time: \(timestamp)")
return -1
}
}
func parseDate(dateString : String) -> NSDate? {
var timestamp = dateString.stringByReplacingOccurrencesOfString("T", withString: " ")
let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss.SS"
if let date = dateFormatter.dateFromString(timestamp) {
return date
} else {
println("Error converting datetime to unix time: \(timestamp)")
return nil
}
}
func getTimeFromDate(dateString : String) -> String? {
var timestamp = dateString.stringByReplacingOccurrencesOfString("T", withString: " ")
let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss.SS"
if let date = dateFormatter.dateFromString(timestamp) {
dateFormatter.dateFormat = "hh:mm aa"
return dateFormatter.stringFromDate(date)
} else {
println("Error converting datetime to NSDate: \(timestamp)")
return nil
}
}
func prettyFormatDate(dateString : String) -> String? {
var timestamp = dateString.stringByReplacingOccurrencesOfString("T", withString: " ")
let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss.SS"
if let date = dateFormatter.dateFromString(timestamp) {
dateFormatter.dateFormat = "MM/dd/yyyy"
return dateFormatter.stringFromDate(date)
} else {
println("Error converting datetime to NSDate: \(timestamp)")
return nil
}
}
func parseDateComponents(dateString : String) -> NSDateComponents? {
if let date = parseDate(dateString) {
return dateComponents(date)
} else {
return nil
}
}
func dateComponents(date: NSDate) -> NSDateComponents {
return NSCalendar.currentCalendar().components(.DayCalendarUnit | .MonthCalendarUnit | .YearCalendarUnit, fromDate: date)
}
func getDayOfWeek(dateString: String) -> String? {
var timestamp = dateString.stringByReplacingOccurrencesOfString("T", withString: " ")
let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss.SS"
if let date = dateFormatter.dateFromString(timestamp) {
return getDayOfWeek(date)
} else {
println("Error converting datetime to NSDate: \(timestamp)")
return nil
}
}
func getDayOfWeek(date: NSDate) -> String? {
let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "EEEE"
return dateFormatter.stringFromDate(date)
}
extension NSDate
{
func isGreaterThanDate(dateToCompare : NSDate) -> Bool
{
//Declare Variables
var isGreater = false
//Compare Values
if self.compare(dateToCompare) == NSComparisonResult.OrderedDescending
{
isGreater = true
}
//Return Result
return isGreater
}
func isLessThanDate(dateToCompare : NSDate) -> Bool
{
//Declare Variables
var isLess = false
//Compare Values
if self.compare(dateToCompare) == NSComparisonResult.OrderedAscending
{
isLess = true
}
//Return Result
return isLess
}
func addDays(daysToAdd : Int) -> NSDate
{
var secondsInDays : NSTimeInterval = Double(daysToAdd) * 60 * 60 * 24
var dateWithDaysAdded : NSDate = self.dateByAddingTimeInterval(secondsInDays)
//Return Result
return dateWithDaysAdded
}
func addHours(hoursToAdd : Int) -> NSDate
{
var secondsInHours : NSTimeInterval = Double(hoursToAdd) * 60 * 60
var dateWithHoursAdded : NSDate = self.dateByAddingTimeInterval(secondsInHours)
//Return Result
return dateWithHoursAdded
}
}
infix operator ~> {}
/**
Executes the lefthand closure on a background thread and,
upon completion, the righthand closure on the main thread.
*/
func ~> (
backgroundClosure: () -> (),
mainClosure: () -> ())
{
dispatch_async(queue) {
backgroundClosure()
dispatch_async(dispatch_get_main_queue(), mainClosure)
}
}
/**
Executes the lefthand closure on a background thread and,
upon completion, the righthand closure on the main thread.
Passes the background closure's output to the main closure.
*/
func ~> <R> (
backgroundClosure: () -> R,
mainClosure: (result: R) -> ())
{
dispatch_async(queue) {
let result = backgroundClosure()
dispatch_async(dispatch_get_main_queue(), {
mainClosure(result: result)
})
}
}
/** Serial dispatch queue used by the ~> operator. */
private let queue = dispatch_queue_create("serial-worker", DISPATCH_QUEUE_SERIAL)
extension UIViewController {
func setViewWidth(view : UIView, width : CGFloat) {
let viewsDictionary = ["view":view]
let metricsDictionary = ["viewWidth":width - 16]
let constraint:Array = NSLayoutConstraint.constraintsWithVisualFormat("H:[view(viewWidth)]",
options: NSLayoutFormatOptions(0), metrics: metricsDictionary, views: viewsDictionary)
view.addConstraints(constraint)
}
}
//
// FMDB Extensions
//
// This extension inspired by http://stackoverflow.com/a/24187932/1271826
extension FMDatabase {
/// Private generic function used for the variadic renditions of the FMDatabaseAdditions methods
///
/// :param: sql The SQL statement to be used.
/// :param: values The NSArray of the arguments to be bound to the ? placeholders in the SQL.
/// :param: completionHandler The closure to be used to call the appropriate FMDatabase method to return the desired value.
///
/// :returns: This returns the T value if value is found. Returns nil if column is NULL or upon error.
private func valueForQuery<T>(sql: String, values: [AnyObject]?, completionHandler:(FMResultSet)->(T!)) -> T! {
var result: T!
if let rs = executeQuery(sql, withArgumentsInArray: values) {
if rs.next() {
let obj: AnyObject! = rs.objectForColumnIndex(0)
if !(obj is NSNull) {
result = completionHandler(rs)
}
}
rs.close()
}
return result
}
/// This is a rendition of stringForQuery that handles Swift variadic parameters
/// for the values to be bound to the ? placeholders in the SQL.
///
/// :param: sql The SQL statement to be used.
/// :param: values The values to be bound to the ? placeholders
///
/// :returns: This returns string value if value is found. Returns nil if column is NULL or upon error.
func stringForQuery(sql: String, _ values: AnyObject...) -> String! {
return valueForQuery(sql, values: values) { $0.stringForColumnIndex(0) }
}
/// This is a rendition of intForQuery that handles Swift variadic parameters
/// for the values to be bound to the ? placeholders in the SQL.
///
/// :param: sql The SQL statement to be used.
/// :param: values The values to be bound to the ? placeholders
///
/// :returns: This returns integer value if value is found. Returns nil if column is NULL or upon error.
func intForQuery(sql: String, _ values: AnyObject...) -> Int32! {
return valueForQuery(sql, values: values) { $0.intForColumnIndex(0) }
}
/// This is a rendition of longForQuery that handles Swift variadic parameters
/// for the values to be bound to the ? placeholders in the SQL.
///
/// :param: sql The SQL statement to be used.
/// :param: values The values to be bound to the ? placeholders
///
/// :returns: This returns long value if value is found. Returns nil if column is NULL or upon error.
func longForQuery(sql: String, _ values: AnyObject...) -> Int! {
return valueForQuery(sql, values: values) { $0.longForColumnIndex(0) }
}
/// This is a rendition of boolForQuery that handles Swift variadic parameters
/// for the values to be bound to the ? placeholders in the SQL.
///
/// :param: sql The SQL statement to be used.
/// :param: values The values to be bound to the ? placeholders
///
/// :returns: This returns Bool value if value is found. Returns nil if column is NULL or upon error.
func boolForQuery(sql: String, _ values: AnyObject...) -> Bool! {
return valueForQuery(sql, values: values) { $0.boolForColumnIndex(0) }
}
/// This is a rendition of doubleForQuery that handles Swift variadic parameters
/// for the values to be bound to the ? placeholders in the SQL.
///
/// :param: sql The SQL statement to be used.
/// :param: values The values to be bound to the ? placeholders
///
/// :returns: This returns Double value if value is found. Returns nil if column is NULL or upon error.
func doubleForQuery(sql: String, _ values: AnyObject...) -> Double! {
return valueForQuery(sql, values: values) { $0.doubleForColumnIndex(0) }
}
/// This is a rendition of dateForQuery that handles Swift variadic parameters
/// for the values to be bound to the ? placeholders in the SQL.
///
/// :param: sql The SQL statement to be used.
/// :param: values The values to be bound to the ? placeholders
///
/// :returns: This returns NSDate value if value is found. Returns nil if column is NULL or upon error.
func dateForQuery(sql: String, _ values: AnyObject...) -> NSDate! {
return valueForQuery(sql, values: values) { $0.dateForColumnIndex(0) }
}
/// This is a rendition of dataForQuery that handles Swift variadic parameters
/// for the values to be bound to the ? placeholders in the SQL.
///
/// :param: sql The SQL statement to be used.
/// :param: values The values to be bound to the ? placeholders
///
/// :returns: This returns NSData value if value is found. Returns nil if column is NULL or upon error.
func dataForQuery(sql: String, _ values: AnyObject...) -> NSData! {
return valueForQuery(sql, values: values) { $0.dataForColumnIndex(0) }
}
/// This is a rendition of executeQuery that handles Swift variadic parameters
/// for the values to be bound to the ? placeholders in the SQL.
///
/// :param: sql The SQL statement to be used.
/// :param: values The values to be bound to the ? placeholders
///
/// :returns: This returns FMResultSet if successful. Returns nil upon error.
func executeQuery(sql:String, _ values: AnyObject...) -> FMResultSet? {
return executeQuery(sql, withArgumentsInArray: values as [AnyObject]);
}
/// This is a rendition of executeUpdate that handles Swift variadic parameters
/// for the values to be bound to the ? placeholders in the SQL.
///
/// :param: sql The SQL statement to be used.
/// :param: values The values to be bound to the ? placeholders
///
/// :returns: This returns true if successful. Returns false upon error.
func executeUpdate(sql:String, _ values: AnyObject...) -> Bool {
return executeUpdate(sql, withArgumentsInArray: values as [AnyObject]);
}
} | mit | af3f0d21ce0707c0f43ae5308aab0377 | 34.651558 | 127 | 0.653528 | 4.572674 | false | false | false | false |
manavgabhawala/CocoaMultipeer | iOS/ViewController.swift | 1 | 2161 | //
// ViewController.swift
// iOS
//
// Created by Manav Gabhawala on 13/07/15.
//
//
import UIKit
import MultipeerCocoaiOS
class ViewController: UIViewController
{
var session : MGSession!
var browser: MGNearbyServiceBrowser!
@IBOutlet var textView : UITextView!
override func viewDidLoad()
{
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
let peer = MGPeerID(displayName: UIDevice.currentDevice().name)
session = MGSession(peer: peer)
session.delegate = self
browser = MGNearbyServiceBrowser(peer: peer, serviceType: "peer-demo")
textView.delegate = self
}
override func viewDidAppear(animated: Bool)
{
super.viewDidAppear(animated)
if session.connectedPeers.count == 0
{
displayPicker()
}
}
override func didReceiveMemoryWarning()
{
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
private func displayPicker()
{
let browserVC = MGBrowserViewController(browser: browser, session: session)
presentViewController(browserVC, animated: true, completion: nil)
}
}
extension ViewController : MGSessionDelegate
{
func session(session: MGSession, peer peerID: MGPeerID, didChangeState state: MGSessionState)
{
print("State of connection to \(peerID) is \(state)")
if session.connectedPeers.count == 0
{
displayPicker()
}
}
func session(session: MGSession, didReceiveData data: NSData, fromPeer peerID: MGPeerID)
{
guard let recievedText = NSString(data: data, encoding: NSUTF8StringEncoding)
else
{
print("Could not parse data \(data)")
return
}
textView.text = "\(textView.text)\n\(recievedText)"
}
}
extension ViewController : UITextViewDelegate
{
func textView(textView: UITextView, shouldChangeTextInRange range: NSRange, replacementText text: String) -> Bool
{
if text == "\n"
{
guard let stringToSend = textView.text?.componentsSeparatedByString("\n").last
else
{
return true
}
do
{
try session.sendData(stringToSend.dataUsingEncoding(NSUTF8StringEncoding)!, toPeers: session.connectedPeers)
}
catch
{
print(error)
}
}
return true
}
}
| apache-2.0 | e17b70ac430d355ac5a8f406b2800a4f | 22.747253 | 114 | 0.724202 | 3.777972 | false | false | false | false |
fgengine/quickly | Quickly/Views/Image/QImageCache.swift | 1 | 4824 | //
// Quickly
//
public class QImageCache {
public private(set) var name: String
public private(set) var memory: [String: UIImage]
public private(set) var url: URL
private var _fileManager: FileManager
private var _queue: DispatchQueue
public init(name: String) throws {
self.name = name
self.memory = [:]
self._fileManager = FileManager.default
self._queue = DispatchQueue(label: name)
if let cachePath = self._fileManager.urls(for: .cachesDirectory, in: .userDomainMask).first {
self.url = cachePath
} else {
self.url = URL(fileURLWithPath: NSHomeDirectory())
}
self.url.appendPathComponent(name)
if self._fileManager.fileExists(atPath: self.url.path) == false {
try self._fileManager.createDirectory(at: self.url, withIntermediateDirectories: true, attributes: nil)
}
NotificationCenter.default.addObserver(self, selector: #selector(self._didReceiveMemoryWarning(_:)), name: UIApplication.didReceiveMemoryWarningNotification, object: nil)
}
deinit {
NotificationCenter.default.removeObserver(self)
}
public func isExist(url: URL, filter: IQImageLoaderFilter? = nil) -> Bool {
guard let key = self._key(url: url, filter: filter) else {
return false
}
let memoryImage = self._queue.sync(execute: { return self.memory[key] })
if memoryImage != nil {
return true
}
let url = self.url.appendingPathComponent(key)
return self._fileManager.fileExists(atPath: url.path)
}
public func image(url: URL, filter: IQImageLoaderFilter? = nil) -> UIImage? {
guard let key = self._key(url: url, filter: filter) else {
return nil
}
let memoryImage = self._queue.sync(execute: { return self.memory[key] })
if let image = memoryImage {
return image
}
let url = self.url.appendingPathComponent(key)
if let image = UIImage(contentsOfFile: url.path) {
self._queue.sync(execute: {
self.memory[key] = image
})
return image
}
return nil
}
public func set(data: Data, image: UIImage, url: URL, filter: IQImageLoaderFilter? = nil) throws {
guard let key = self._key(url: url, filter: filter) else { return }
let url = self.url.appendingPathComponent(key)
do {
try data.write(to: url, options: .atomic)
self._queue.sync(execute: {
self.memory[key] = image
})
} catch let error {
throw error
}
}
public func remove(url: URL, filter: IQImageLoaderFilter? = nil) throws {
guard let key = self._key(url: url, filter: filter) else { return }
self._queue.sync(execute: {
_ = self.memory.removeValue(forKey: key)
})
let url = self.url.appendingPathComponent(key)
if self._fileManager.fileExists(atPath: url.path) == true {
do {
try self._fileManager.removeItem(at: url)
} catch let error {
throw error
}
}
}
public func cleanup(before: TimeInterval) {
self._queue.sync(execute: {
self.memory.removeAll()
})
let now = Date()
if let urls = try? self._fileManager.contentsOfDirectory(at: self.url, includingPropertiesForKeys: nil, options: [ .skipsHiddenFiles ]) {
for url in urls {
guard
let attributes = try? self._fileManager.attributesOfItem(atPath: url.path),
let modificationDate = attributes[FileAttributeKey.modificationDate] as? Date
else {
continue
}
let delta = now.timeIntervalSince1970 - modificationDate.timeIntervalSince1970
if delta > before {
try? self._fileManager.removeItem(at: url)
}
}
}
}
@objc
private func _didReceiveMemoryWarning(_ notification: NSNotification) {
self._queue.sync(execute: {
self.memory.removeAll()
})
}
}
private extension QImageCache {
func _key(url: URL, filter: IQImageLoaderFilter?) -> String? {
var unique: String
var path: String
if url.isFileURL == true {
path = url.lastPathComponent
} else {
path = url.absoluteString
}
if let filter = filter {
unique = "{\(filter.name)}{\(path)}"
} else {
unique = path
}
if let key = unique.sha256 {
return key
}
return nil
}
}
| mit | cf4835ba4bee0c20066f9b9c27b04607 | 32.5 | 178 | 0.567164 | 4.669894 | false | false | false | false |
ps2/rileylink_ios | MinimedKit/Messages/Models/GlucoseEventType.swift | 1 | 2092 | //
// GlucoseEventType.swift
// RileyLink
//
// Created by Timothy Mecklem on 10/16/16.
// Copyright © 2016 Pete Schwamb. All rights reserved.
//
import Foundation
public enum GlucoseEventType: UInt8 {
case dataEnd = 0x01
case sensorWeakSignal = 0x02
case sensorCal = 0x03
case sensorPacket = 0x04
case sensorError = 0x05
case sensorDataLow = 0x06
case sensorDataHigh = 0x07
case sensorTimestamp = 0x08
case batteryChange = 0x0a
case sensorStatus = 0x0b
case dateTimeChange = 0x0c
case sensorSync = 0x0d
case calBGForGH = 0x0e
case sensorCalFactor = 0x0f
case tenSomething = 0x10
case nineteenSomething = 0x13
public var eventType: GlucoseEvent.Type {
switch self {
case .dataEnd:
return DataEndGlucoseEvent.self
case .sensorWeakSignal:
return SensorWeakSignalGlucoseEvent.self
case .sensorCal:
return SensorCalGlucoseEvent.self
case .sensorPacket:
return SensorPacketGlucoseEvent.self
case .sensorError:
return SensorErrorGlucoseEvent.self
case .sensorDataLow:
return SensorDataLowGlucoseEvent.self
case .sensorDataHigh:
return SensorDataHighGlucoseEvent.self
case .sensorTimestamp:
return SensorTimestampGlucoseEvent.self
case .batteryChange:
return BatteryChangeGlucoseEvent.self
case .sensorStatus:
return SensorStatusGlucoseEvent.self
case .dateTimeChange:
return DateTimeChangeGlucoseEvent.self
case .sensorSync:
return SensorSyncGlucoseEvent.self
case .calBGForGH:
return CalBGForGHGlucoseEvent.self
case .sensorCalFactor:
return SensorCalFactorGlucoseEvent.self
case .tenSomething:
return TenSomethingGlucoseEvent.self
case .nineteenSomething:
return NineteenSomethingGlucoseEvent.self
}
}
}
| mit | c3bcc75967758ec50fe0a7c7b983ee86 | 31.169231 | 55 | 0.639407 | 4.595604 | false | false | false | false |
Subsets and Splits