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 |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
r4phab/ECAB
|
ECAB/PlayersTableViewController.swift
|
1
|
4511
|
//
// PlayersTableViewController.swift
// ECAB
//
// Created by Boris Yurkevich on 01/02/2015.
// Copyright (c) 2015 Oliver Braddick and Jan Atkinson. All rights reserved.
//
import UIKit
protocol SubjectPickerDelegate {
func pickSubject()
}
class PlayersTableViewController: UITableViewController {
var delegate: SubjectPickerDelegate!
private let model: Model = Model.sharedInstance
private let reuseIdentifier = "Subject picker cell"
@IBAction func addPlayerHandler(sender: UIBarButtonItem) {
let alert = UIAlertController(title: "New player",
message: "Add a name for a new player",
preferredStyle: .Alert)
let saveAction = UIAlertAction(title: "Save",
style: .Default) { (action: UIAlertAction) -> Void in
let textField = alert.textFields![0]
self.model.addPlayer(textField.text!)
self.tableView.reloadData()
}
let cancelAction = UIAlertAction(title: "Cancel",
style: .Cancel) { (action: UIAlertAction) -> Void in
}
alert.addTextFieldWithConfigurationHandler {
(textField: UITextField!) -> Void in
}
alert.addAction(saveAction)
alert.addAction(cancelAction)
presentViewController(alert,
animated: true,
completion: nil)
}
// MARK: - View Controller life
override func viewDidLoad() {
super.viewDidLoad()
tableView.registerClass(UITableViewCell.self,
forCellReuseIdentifier: reuseIdentifier)
self.clearsSelectionOnViewWillAppear = true;
// Make row selections not persist.
tableView.reloadData()
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
self.preferredContentSize = CGSizeMake(200, 200)
var index = 0
for case let player as Player in model.data.players{
if(player.name == model.data.selectedPlayer.name){
selectRow(index)
break
}
index += 1
}
}
func selectRow(index:Int) {
let rowToSelect:NSIndexPath = NSIndexPath(forRow: index, inSection: 0)
self.tableView.selectRowAtIndexPath(rowToSelect, animated: false, scrollPosition:UITableViewScrollPosition.None)
}
// MARK: - Table view data source
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier(reuseIdentifier) as UITableViewCell!
let data = model.data as Data
let players = data.players
let player = players[indexPath.row] as! Player
let label: UILabel! = cell.textLabel
label.text = player.name
return cell
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return model.data.players.count
}
override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
// Make selected player current player
let data = model.data as Data
let selectedPlayerEntity = data.players[indexPath.row] as! Player
model.data.selectedPlayer = selectedPlayerEntity
model.save()
delegate?.pickSubject()
}
override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool {
return indexPath.row != 0
}
override func tableView(tableView: UITableView, commitEditingStyle
editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
if editingStyle == UITableViewCellEditingStyle.Delete{
let player: Player = model.data.players[indexPath.row] as! Player
model.managedContext.deleteObject(player)
var error: NSError?
do {
try model.managedContext.save()
} catch let error1 as NSError {
error = error1
print("Could not save after delete: \(error)")
}
// Last step
tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: UITableViewRowAnimation.Automatic)
}
}
}
|
mit
|
ab11c8c5bbf9e7c995c2f09e0617806c
| 30.992908 | 120 | 0.616936 | 5.57602 | false | false | false | false |
johnlui/Swift-MMP
|
Frameworks/Reachability.swift
|
1
|
9864
|
/*
Copyright (c) 2014, Ashley Mills
All rights reserved.
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.
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 HOLDER 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.
*/
// Reachability.swift version 2.2beta2
import SystemConfiguration
import Foundation
public enum ReachabilityError: Error {
case failedToCreateWithAddress(sockaddr_in)
case failedToCreateWithHostname(String)
case unableToSetCallback
case unableToSetDispatchQueue
}
public let ReachabilityChangedNotification = Notification.Name("ReachabilityChangedNotification")
func callback(_ reachability:SCNetworkReachability, flags: SCNetworkReachabilityFlags, info: UnsafeMutableRawPointer?) {
guard let info = info else { return }
let reachability = Unmanaged<Reachability>.fromOpaque(info).takeUnretainedValue()
DispatchQueue.main.async {
reachability.reachabilityChanged()
}
}
open class Reachability {
public typealias NetworkReachable = (Reachability) -> ()
public typealias NetworkUnreachable = (Reachability) -> ()
public enum NetworkStatus: CustomStringConvertible {
case notReachable, reachableViaWiFi, reachableViaWWAN
public var description: String {
switch self {
case .reachableViaWWAN: return "Cellular"
case .reachableViaWiFi: return "WiFi"
case .notReachable: return "No Connection"
}
}
}
open var whenReachable: NetworkReachable?
open var whenUnreachable: NetworkUnreachable?
open var reachableOnWWAN: Bool
open var currentReachabilityString: String {
return "\(currentReachabilityStatus)"
}
open var currentReachabilityStatus: NetworkStatus {
guard isReachable else { return .notReachable }
if isReachableViaWiFi {
return .reachableViaWiFi
}
if isRunningOnDevice {
return .reachableViaWWAN
}
return .notReachable
}
fileprivate var previousFlags: SCNetworkReachabilityFlags?
fileprivate var isRunningOnDevice: Bool = {
#if (arch(i386) || arch(x86_64)) && os(iOS)
return false
#else
return true
#endif
}()
fileprivate var notifierRunning = false
fileprivate var reachabilityRef: SCNetworkReachability?
fileprivate let reachabilitySerialQueue = DispatchQueue(label: "uk.co.ashleymills.reachability")
required public init(reachabilityRef: SCNetworkReachability) {
reachableOnWWAN = true
self.reachabilityRef = reachabilityRef
}
public convenience init?(hostname: String) {
guard let ref = SCNetworkReachabilityCreateWithName(nil, hostname) else { return nil }
self.init(reachabilityRef: ref)
}
public convenience init?() {
var zeroAddress = sockaddr()
zeroAddress.sa_len = UInt8(MemoryLayout<sockaddr>.size)
zeroAddress.sa_family = sa_family_t(AF_INET)
guard let ref: SCNetworkReachability = withUnsafePointer(to: &zeroAddress, {
SCNetworkReachabilityCreateWithAddress(nil, UnsafePointer($0))
}) else { return nil }
self.init(reachabilityRef: ref)
}
deinit {
stopNotifier()
reachabilityRef = nil
whenReachable = nil
whenUnreachable = nil
}
}
public extension Reachability {
// MARK: - *** Notifier methods ***
func startNotifier() throws {
guard let reachabilityRef = reachabilityRef, !notifierRunning else { return }
var context = SCNetworkReachabilityContext(version: 0, info: nil, retain: nil, release: nil, copyDescription: nil)
context.info = UnsafeMutableRawPointer(Unmanaged<Reachability>.passUnretained(self).toOpaque())
if !SCNetworkReachabilitySetCallback(reachabilityRef, callback, &context) {
stopNotifier()
throw ReachabilityError.unableToSetCallback
}
if !SCNetworkReachabilitySetDispatchQueue(reachabilityRef, reachabilitySerialQueue) {
stopNotifier()
throw ReachabilityError.unableToSetDispatchQueue
}
// Perform an intial check
reachabilitySerialQueue.async {
self.reachabilityChanged()
}
notifierRunning = true
}
func stopNotifier() {
defer { notifierRunning = false }
guard let reachabilityRef = reachabilityRef else { return }
SCNetworkReachabilitySetCallback(reachabilityRef, nil, nil)
SCNetworkReachabilitySetDispatchQueue(reachabilityRef, nil)
}
// MARK: - *** Connection test methods ***
var isReachable: Bool {
guard isReachableFlagSet else { return false }
if isConnectionRequiredAndTransientFlagSet {
return false
}
if isRunningOnDevice {
if isOnWWANFlagSet && !reachableOnWWAN {
// We don't want to connect when on 3G.
return false
}
}
return true
}
var isReachableViaWWAN: Bool {
// Check we're not on the simulator, we're REACHABLE and check we're on WWAN
return isRunningOnDevice && isReachableFlagSet && isOnWWANFlagSet
}
var isReachableViaWiFi: Bool {
// Check we're reachable
guard isReachableFlagSet else { return false }
// If reachable we're reachable, but not on an iOS device (i.e. simulator), we must be on WiFi
guard isRunningOnDevice else { return true }
// Check we're NOT on WWAN
return !isOnWWANFlagSet
}
var description: String {
let W = isRunningOnDevice ? (isOnWWANFlagSet ? "W" : "-") : "X"
let R = isReachableFlagSet ? "R" : "-"
let c = isConnectionRequiredFlagSet ? "c" : "-"
let t = isTransientConnectionFlagSet ? "t" : "-"
let i = isInterventionRequiredFlagSet ? "i" : "-"
let C = isConnectionOnTrafficFlagSet ? "C" : "-"
let D = isConnectionOnDemandFlagSet ? "D" : "-"
let l = isLocalAddressFlagSet ? "l" : "-"
let d = isDirectFlagSet ? "d" : "-"
return "\(W)\(R) \(c)\(t)\(i)\(C)\(D)\(l)\(d)"
}
}
fileprivate extension Reachability {
func reachabilityChanged() {
let flags = reachabilityFlags
guard previousFlags != flags else { return }
let block = isReachable ? whenReachable : whenUnreachable
block?(self)
NotificationCenter.default.post(name: ReachabilityChangedNotification, object:self)
previousFlags = flags
}
var isOnWWANFlagSet: Bool {
#if os(iOS)
return reachabilityFlags.contains(.isWWAN)
#else
return false
#endif
}
var isReachableFlagSet: Bool {
return reachabilityFlags.contains(.reachable)
}
var isConnectionRequiredFlagSet: Bool {
return reachabilityFlags.contains(.connectionRequired)
}
var isInterventionRequiredFlagSet: Bool {
return reachabilityFlags.contains(.interventionRequired)
}
var isConnectionOnTrafficFlagSet: Bool {
return reachabilityFlags.contains(.connectionOnTraffic)
}
var isConnectionOnDemandFlagSet: Bool {
return reachabilityFlags.contains(.connectionOnDemand)
}
var isConnectionOnTrafficOrDemandFlagSet: Bool {
return !reachabilityFlags.intersection([.connectionOnTraffic, .connectionOnDemand]).isEmpty
}
var isTransientConnectionFlagSet: Bool {
return reachabilityFlags.contains(.transientConnection)
}
var isLocalAddressFlagSet: Bool {
return reachabilityFlags.contains(.isLocalAddress)
}
var isDirectFlagSet: Bool {
return reachabilityFlags.contains(.isDirect)
}
var isConnectionRequiredAndTransientFlagSet: Bool {
return reachabilityFlags.intersection([.connectionRequired, .transientConnection]) == [.connectionRequired, .transientConnection]
}
var reachabilityFlags: SCNetworkReachabilityFlags {
guard let reachabilityRef = reachabilityRef else { return SCNetworkReachabilityFlags() }
var flags = SCNetworkReachabilityFlags()
let gotFlags = withUnsafeMutablePointer(to: &flags) {
SCNetworkReachabilityGetFlags(reachabilityRef, UnsafeMutablePointer($0))
}
if gotFlags {
return flags
} else {
return SCNetworkReachabilityFlags()
}
}
}
|
mit
|
08e609e2916192b010eb2f8bfe7808a5
| 32.212121 | 137 | 0.660381 | 5.989071 | false | false | false | false |
haskellswift/swift-package-manager
|
Sources/Get/RawClone.swift
|
2
|
3842
|
/*
This source file is part of the Swift.org open source project
Copyright 2015 - 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 Swift project authors
*/
import Basic
import PackageModel
import Utility
/// A clone of a repository which is not yet fully loaded.
///
/// Initially we clone into a non-final form because we may need to adjust the
/// dependency graph due to further specifications as we clone more
/// repositories. This is the non-final form. Once `recursivelyFetch` completes
/// we finalize these clones into the `PackagesDirectory`.
class RawClone: Fetchable {
let path: AbsolutePath
let manifestParser: (_ path: AbsolutePath, _ url: String, _ version: Version?) throws -> Manifest
private func getRepositoryVersion() -> Version? {
var branch = repo.branch!
if branch.hasPrefix("heads/") {
branch = String(branch.characters.dropFirst(6))
}
if branch.hasPrefix("v") {
branch = String(branch.characters.dropFirst())
}
if branch.contains("@") {
branch = branch.components(separatedBy: "@").first!
}
return Version(branch)
}
// lazy because the tip of the default branch does not have to be a valid package
//FIXME we should error gracefully if a selected version does not however
var manifest: Manifest! {
if let manifest = _manifest {
return manifest
} else {
_manifest = try? manifestParser(path, repo.origin!, getRepositoryVersion())
return _manifest
}
}
private var _manifest: Manifest?
init(path: AbsolutePath, manifestParser: @escaping (_ path: AbsolutePath, _ url: String, _ version: Version?) throws -> Manifest) throws {
self.path = path
self.manifestParser = manifestParser
if !repo.hasVersion {
throw Error.unversioned(path.asString)
}
}
var repo: Git.Repo {
return Git.Repo(path: path)!
}
var currentVersion: Version {
return getRepositoryVersion()!
}
/// contract, you cannot call this before you have attempted to `constrain` this clone
func setCurrentVersion(_ ver: Version) throws {
let tag = repo.knownVersions[ver]!
try Git.runCommandQuietly([Git.tool, "-C", path.asString, "reset", "--hard", tag])
try Git.runCommandQuietly([Git.tool, "-C", path.asString, "branch", "-m", tag])
print("Resolved version:", ver)
// we must re-read the manifest
_manifest = nil
if manifest == nil {
throw Error.noManifest(path.asString, ver)
}
}
func constrain(to versionRange: Range<Version>) -> Version? {
return availableVersions.filter {
// not using `contains` as it uses successor() and for Range<Version>
// this involves iterating from 0 to Int.max!
versionRange ~= $0
}.last
}
var children: [(String, Range<Version>)] {
guard manifest != nil else {
// manifest may not exist, if so the package is BAD,
// still: we should not crash. Build failure will occur
// shortly after this because we cannot `setVersion`
return []
}
//COPY PASTA from Package.dependencies
return manifest.dependencies
}
var url: String {
return repo.origin ?? "BAD_ORIGIN"
}
var availableVersions: [Version] {
let versions = repo.versions
assert(versions == versions.sorted())
return versions
}
var finalName: String {
return "\(manifest.package.name)-\(currentVersion)"
}
}
|
apache-2.0
|
fecbde10b272efa5cc09ef15e2cee642
| 32.408696 | 142 | 0.628579 | 4.628916 | false | false | false | false |
velvetroom/columbus
|
Source/GenericExtensions/ExtensionData.swift
|
1
|
2547
|
import Foundation
extension Data
{
//MARK: internal
func writeToTemporal(withExtension:String?) -> URL?
{
var randomName:String = UUID().uuidString
if let withExtension:String = withExtension
{
randomName.append(".")
randomName.append(withExtension)
}
let directoryUrl:URL = URL(fileURLWithPath:NSTemporaryDirectory())
let fileUrl:URL = directoryUrl.appendingPathComponent(randomName)
do
{
try write(
to:fileUrl,
options:Data.WritingOptions.atomicWrite)
}
catch
{
return nil
}
return fileUrl
}
mutating func append<T>(value:T)
{
var value:T = value
let buffer:UnsafeBufferPointer = UnsafeBufferPointer(
start:&value,
count:1)
append(buffer)
}
func arrayFromBytes<T>(elements:Int) -> [T]?
{
let valueSize:Int = MemoryLayout<T>.size
let expectedSize:Int = elements * valueSize
guard
count >= expectedSize
else
{
return nil
}
let array:[T] = withUnsafeBytes
{ (pointer:UnsafePointer<T>) -> [T] in
let bufferPointer:UnsafeBufferPointer = UnsafeBufferPointer(
start:pointer,
count:elements)
let array:[T] = Array(bufferPointer)
return array
}
return array
}
func valueFromBytes<T>() -> T?
{
guard
let array:[T] = arrayFromBytes(elements:1),
let value:T = array.first
else
{
return nil
}
return value
}
func subdata(
start:Int,
endNotIncluding:Int) -> Data
{
let range:Range<Data.Index> = Range<Data.Index>(start ..< endNotIncluding)
let sliced:Data = subdata(in:range)
return sliced
}
func subdata(start:Int) -> Data
{
let sliced:Data = subdata(
start:start,
endNotIncluding:count)
return sliced
}
func subdata(endNotIncluding:Int) -> Data
{
let sliced:Data = subdata(
start:0,
endNotIncluding:endNotIncluding)
return sliced
}
}
|
mit
|
2e3e6dcf599728244c16e88e9eff2432
| 20.956897 | 82 | 0.485669 | 5.35084 | false | false | false | false |
GYLibrary/GPRS
|
OznerGPRS/MQTTHelper.swift
|
1
|
4046
|
//
// MQTTHelper.swift
// OznerGPRS
//
// Created by ZGY on 2017/9/18.
// Copyright © 2017年 macpro. All rights reserved.
//
// Author: Airfight
// My GitHub: https://github.com/airfight
// My Blog: http://airfight.github.io/
// My Jane book: http://www.jianshu.com/users/17d6a01e3361
// Current Time: 2017/9/18 上午9:51
// GiantForJade: Efforts to do my best
// Real developers ship.
import UIKit
import MQTTKit
typealias recievedDataBlock = (Data,String) -> Void
class MQTTHelper: NSObject {
private var mqttClient:MQTTClient!
static let `default`: MQTTHelper = MQTTHelper()
var block:recievedDataBlock?
override init() {
super.init()
mqttClient = MQTTClient(clientId: "1231zhu777777788")
mqttClient.port=1884
mqttClient.username="17621050877"//手机号
var token = "12345678" + "@\(mqttClient.username!)" + "@\(mqttClient.clientID!)"
token = Helper.base64EncodedString(from: Helper.md5(token))
print("BASE64:\(token)")
mqttClient.password=token//token
mqttClient.keepAlive=60
mqttClient.cleanSession=false
//http://iot.ozner.net:1884 (内网地址请使用192.168.173.21:1884)
mqttClient.connect(toHost: "iot.ozner.net") { (code) in
switch code {
case ConnectionAccepted:
print("连接成功!")
case ConnectionRefusedUnacceptableProtocolVersion:
print("ConnectionRefusedUnacceptableProtocolVersion")
case ConnectionRefusedIdentiferRejected:
print("ConnectionRefusedIdentiferRejected")
case ConnectionRefusedServerUnavailable:
print("ConnectionRefusedServerUnavailable")
case ConnectionRefusedBadUserNameOrPassword:
print("ConnectionRefusedBadUserNameOrPassword")
case ConnectionRefusedNotAuthorized:
print("ConnectionRefusedNotAuthorized")
default:
print("连接失败")
}
}
//校园空净 ID:类型名称/Mac
mqttClient.messageHandler = {(mess) in
self.block!((mess?.payload)!,mess?.payloadString() ?? "")
let arr = try! JSONSerialization.jsonObject(with: (mess?.payload)!, options: JSONSerialization.ReadingOptions.allowFragments) as! [[String:Any]]
for item in arr {
print(item)
}
// let string = String.init(data: (mess?.payload)!, encoding: String.Encoding.utf8)
// print(string)
//
// let dic = try! JSONSerialization.jsonObject(with: (mess?.payload)!, options: JSONSerialization.ReadingOptions.allowFragments)
// print(dic)
}
}
func subscribeAction(_ str:String) {
print(str)
mqttClient.subscribe(str, withQos: AtLeastOnce) { (result) in
print(result ?? "")
UserDefaults.standard.set(str, forKey: "OznerSubscribe")
UserDefaults.standard.synchronize()
}
}
func unsubscribAction(_ str:String) {
mqttClient.unsubscribe(str) {
print("已取消订阅")
UserDefaults.standard.setValue(nil, forKey: "OznerSubscribe")
UserDefaults.standard.synchronize()
}
}
func sendDataToDevice(_ data:Data,topic:String) {
mqttClient.publishData(data, toTopic: topic, withQos: AtMostOnce, retain: true) { (code) in
print(code)
}
}
func sendStringToDevice(_ sendStr:String,topic:String) {
mqttClient.publishString(sendStr, toTopic: topic, withQos: AtMostOnce, retain: true) { (code) in
print(code)
}
}
}
|
mit
|
e14bffe2d5b0cff5b2555cc4303c0448
| 29.113636 | 156 | 0.567547 | 4.511918 | false | false | false | false |
CallMeMrAlex/DYTV
|
DYTV-AlexanderZ-Swift/DYTV-AlexanderZ-Swift/Classes/Home(首页)/View/AmuseMenuView.swift
|
1
|
2548
|
//
// AmuseMenuView.swift
// DYTV-AlexanderZ-Swift
//
// Created by Alexander Zou on 2016/10/17.
// Copyright © 2016年 Alexander Zou. All rights reserved.
//
import UIKit
private let kMenuCellID = "kMenuCellID"
class AmuseMenuView: UIView {
var groups : [AnchorGroupModel]? {
didSet {
collectionView.reloadData()
}
}
@IBOutlet weak var collectionView: UICollectionView!
@IBOutlet weak var pageControl: UIPageControl!
override func awakeFromNib() {
super.awakeFromNib()
collectionView.register(UINib(nibName: "AmuseMenuViewCell", bundle: nil), forCellWithReuseIdentifier: kMenuCellID)
}
override func layoutSubviews() {
super.layoutSubviews()
let layout = collectionView.collectionViewLayout as! UICollectionViewFlowLayout
layout.itemSize = collectionView.bounds.size
}
}
extension AmuseMenuView {
class func amuseMenuView() -> AmuseMenuView {
return Bundle.main.loadNibNamed("AmuseMenuView", owner: nil, options: nil)?.first as! AmuseMenuView
}
}
extension AmuseMenuView : UICollectionViewDataSource {
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
if groups == nil { return 0 }
let pageNum = (groups!.count - 1) / 8 + 1
pageControl.numberOfPages = pageNum
return pageNum
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: kMenuCellID, for: indexPath) as! AmuseMenuViewCell
setupCellDataWithCell(cell, indexPath: indexPath)
return cell
}
fileprivate func setupCellDataWithCell(_ cell : AmuseMenuViewCell, indexPath : IndexPath) {
// 0页: 0 ~ 7
// 1页: 8 ~ 15
// 2页: 16 ~ 23
// 取出起始位置&终点位置
let startIndex = indexPath.item * 8
var endIndex = (indexPath.item + 1) * 8 - 1
// 判断越界问题
if endIndex > groups!.count - 1 {
endIndex = groups!.count - 1
}
cell.groups = Array(groups![startIndex...endIndex])
}
}
extension AmuseMenuView : UICollectionViewDelegate {
func scrollViewDidScroll(_ scrollView: UIScrollView) {
pageControl.currentPage = Int(scrollView.contentOffset.x / scrollView.bounds.width)
}
}
|
mit
|
9352400e26d63b53569e3c552d5020d0
| 25.670213 | 125 | 0.644994 | 5.085193 | false | false | false | false |
TrondKjeldas/KnxBasics2
|
Playgrounds/Temperature.playground/Contents.swift
|
1
|
1904
|
//
// The KnxBasics2 framework provides basic interworking with a KNX installation.
// Copyright © 2016 Trond Kjeldås ([email protected]).
//
// This library is free software; you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License Version 2.1
// as published by the Free Software Foundation.
//
// This library 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 Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public License
// along with this library; if not, write to the Free Software
// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
//
//: Playground - noun: a place where people can play
import PlaygroundSupport
PlaygroundPage.current.needsIndefiniteExecution = true
import Cocoa
import CocoaAsyncSocket
import SwiftyBeaver
import KnxBasics2
//: Set up logging with SwiftyBeaver
let console = ConsoleDestination()
console.asynchronously = false
SwiftyBeaver.addDestination(console)
class Handler: KnxTemperatureResponseHandlerDelegate {
func temperatureResponse(sender: KnxGroupAddress, level: Double) {
print("Temperature now: \(level)")
}
}
//KnxRouterInterface.routerIp = "zbox"
KnxRouterInterface.multicastGroup = "224.0.23.12"
KnxRouterInterface.knxSourceAddr = KnxDeviceAddress(fromString: "0.1.0")
KnxRouterInterface.connectionType = .udpMulticast
KnxGroupAddressRegistry.addTypeForGroupAddress(address: KnxGroupAddress(fromString:"3/2/0"),
type: KnxTelegramType.dpt9_001)
let sub = KnxTemperatureControl(subscriptionAddress: KnxGroupAddress(fromString: "3/2/0"),
responseHandler: Handler())
|
lgpl-2.1
|
5a1ff1c73c96a7c1c47722f07ff854df
| 37.04 | 92 | 0.745005 | 4.107991 | false | false | false | false |
ArnavChawla/InteliChat
|
Carthage/Checkouts/swift-sdk/Source/PersonalityInsightsV3/Models/Trait.swift
|
1
|
3531
|
/**
* Copyright IBM Corporation 2018
*
* 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
/** Trait. */
public struct Trait: Decodable {
/// The category of the characteristic: `personality` for Big Five personality characteristics, `needs` for Needs, and `values` for Values.
public enum Category: String {
case personality = "personality"
case needs = "needs"
case values = "values"
}
/// The unique, non-localized identifier of the characteristic to which the results pertain. IDs have the form * `big5_{characteristic}` for Big Five personality dimensions * `facet_{characteristic}` for Big Five personality facets * `need_{characteristic}` for Needs *`value_{characteristic}` for Values.
public var traitID: String
/// The user-visible, localized name of the characteristic.
public var name: String
/// The category of the characteristic: `personality` for Big Five personality characteristics, `needs` for Needs, and `values` for Values.
public var category: String
/// The normalized percentile score for the characteristic. The range is 0 to 1. For example, if the percentage for Openness is 0.60, the author scored in the 60th percentile; the author is more open than 59 percent of the population and less open than 39 percent of the population.
public var percentile: Double
/// The raw score for the characteristic. The range is 0 to 1. A higher score generally indicates a greater likelihood that the author has that characteristic, but raw scores must be considered in aggregate: The range of values in practice might be much smaller than 0 to 1, so an individual score must be considered in the context of the overall scores and their range. The raw score is computed based on the input and the service model; it is not normalized or compared with a sample population. The raw score enables comparison of the results against a different sampling population and with a custom normalization approach.
public var rawScore: Double?
/// **`2017-10-13`**: Indicates whether the characteristic is meaningful for the input language. The field is always `true` for all characteristics of English, Spanish, and Japanese input. The field is `false` for the subset of characteristics of Arabic and Korean input for which the service's models are unable to generate meaningful results. **`2016-10-19`**: Not returned.
public var significant: Bool?
/// For `personality` (Big Five) dimensions, more detailed results for the facets of each dimension as inferred from the input text.
public var children: [Trait]?
// Map each property name to the key that shall be used for encoding/decoding.
private enum CodingKeys: String, CodingKey {
case traitID = "trait_id"
case name = "name"
case category = "category"
case percentile = "percentile"
case rawScore = "raw_score"
case significant = "significant"
case children = "children"
}
}
|
mit
|
ba0b8d8d149d12f223b25e1321280082
| 56.885246 | 633 | 0.73322 | 4.567917 | false | false | false | false |
koutalou/Shoyu
|
Classes/Row.swift
|
1
|
2073
|
//
// Row.swift
// Shoyu
//
// Created by asai.yuki on 2015/12/12.
// Copyright © 2015年 yukiasai. All rights reserved.
//
import UIKit
public class Row<T: UITableViewCell>: RowType {
init() { }
init(@noescape clousure: (Row<T> -> Void)) {
clousure(self)
}
public var configureCell: ((T, NSIndexPath) -> Void)?
public var heightFor: (NSIndexPath -> CGFloat?)?
public var didSelect: (NSIndexPath -> Void)?
public var didDeselect: (NSIndexPath -> Void)?
public var willDisplayCell: ((T, NSIndexPath) -> Void)?
public var didEndDisplayCell: ((T, NSIndexPath) -> Void)?
private var _reuseIdentifier: String?
public var reuseIdentifier: String {
set {
_reuseIdentifier = newValue
}
get {
if let identifier = _reuseIdentifier {
return identifier
}
if let identifier = T() as? ReuseIdentifierType {
return identifier.identifier
}
fatalError()
}
}
public var height: CGFloat?
}
extension Row: RowDelegateType {
func configureCell(cell: UITableViewCell, indexPath: NSIndexPath) {
guard let genericCell = cell as? T else {
fatalError()
}
configureCell?(genericCell, indexPath)
}
func heightFor(indexPath: NSIndexPath) -> CGFloat? {
return heightFor?(indexPath) ?? height
}
func didSelect(indexPath: NSIndexPath) {
didSelect?(indexPath)
}
func didDeselect(indexPath: NSIndexPath) {
didDeselect?(indexPath)
}
func willDisplayCell(cell: UITableViewCell, indexPath: NSIndexPath) {
guard let genericCell = cell as? T else {
fatalError()
}
willDisplayCell?(genericCell, indexPath)
}
func didEndDisplayCell(cell: UITableViewCell, indexPath: NSIndexPath) {
guard let genericCell = cell as? T else {
fatalError()
}
didEndDisplayCell?(genericCell, indexPath)
}
}
|
mit
|
3912eaeb64b512aaf020f34722cc7108
| 25.883117 | 75 | 0.593237 | 4.836449 | false | false | false | false |
maxsokolov/Leeloo
|
Sources/NetworkMultipartDataRequest.swift
|
1
|
1890
|
//
// Copyright (c) 2017 Max Sokolov https://twitter.com/max_sokolov
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of
// this software and associated documentation files (the "Software"), to deal in
// the Software without restriction, including without limitation the rights to
// use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
// the Software, and to permit persons to whom the Software is furnished to do so,
// subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
// FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
// COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
// IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
// CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
import Foundation
public struct MultipartData {
public enum Source {
case data(Data)
case file(URL)
}
public let source: Source
public let fileName: String
public let mimeType: String
public init(filePath: URL, fileName: String, mimeType: String) {
self.source = .file(filePath)
self.fileName = fileName
self.mimeType = mimeType
}
public init(data: Data, fileName: String, mimeType: String) {
self.source = .data(data)
self.fileName = fileName
self.mimeType = mimeType
}
}
public protocol NetworkMultipartDataRequest: NetworkRequest {
var files: [MultipartData] { get }
}
|
mit
|
264cc740b0822c800d353189ce6cd07a
| 36.8 | 86 | 0.696296 | 4.489311 | false | false | false | false |
paperboy1109/Capstone
|
Pods/Charts/Charts/Classes/Charts/ChartViewBase.swift
|
12
|
36581
|
//
// ChartViewBase.swift
// Charts
//
// Created by Daniel Cohen Gindi on 23/2/15.
//
// Copyright 2015 Daniel Cohen Gindi & Philipp Jahoda
// A port of MPAndroidChart for iOS
// Licensed under Apache License 2.0
//
// https://github.com/danielgindi/Charts
//
// Based on https://github.com/PhilJay/MPAndroidChart/commit/c42b880
import Foundation
import CoreGraphics
#if !os(OSX)
import UIKit
#endif
@objc
public protocol ChartViewDelegate
{
/// Called when a value has been selected inside the chart.
/// - parameter entry: The selected Entry.
/// - parameter dataSetIndex: The index in the datasets array of the data object the Entrys DataSet is in.
optional func chartValueSelected(chartView: ChartViewBase, entry: ChartDataEntry, dataSetIndex: Int, highlight: ChartHighlight)
// Called when nothing has been selected or an "un-select" has been made.
optional func chartValueNothingSelected(chartView: ChartViewBase)
// Callbacks when the chart is scaled / zoomed via pinch zoom gesture.
optional func chartScaled(chartView: ChartViewBase, scaleX: CGFloat, scaleY: CGFloat)
// Callbacks when the chart is moved / translated via drag gesture.
optional func chartTranslated(chartView: ChartViewBase, dX: CGFloat, dY: CGFloat)
}
public class ChartViewBase: NSUIView, ChartDataProvider, ChartAnimatorDelegate
{
// MARK: - Properties
/// - returns: the object representing all x-labels, this method can be used to
/// acquire the XAxis object and modify it (e.g. change the position of the
/// labels)
public var xAxis: ChartXAxis
{
return _xAxis
}
/// the default value formatter
internal var _defaultValueFormatter: NSNumberFormatter = ChartUtils.defaultValueFormatter()
/// object that holds all data that was originally set for the chart, before it was modified or any filtering algorithms had been applied
internal var _data: ChartData?
/// Flag that indicates if highlighting per tap (touch) is enabled
private var _highlightPerTapEnabled = true
/// If set to true, chart continues to scroll after touch up
public var dragDecelerationEnabled = true
/// Deceleration friction coefficient in [0 ; 1] interval, higher values indicate that speed will decrease slowly, for example if it set to 0, it will stop immediately.
/// 1 is an invalid value, and will be converted to 0.999 automatically.
private var _dragDecelerationFrictionCoef: CGFloat = 0.9
/// Font object used for drawing the description text (by default in the bottom right corner of the chart)
public var descriptionFont: NSUIFont? = NSUIFont(name: "HelveticaNeue", size: 9.0)
/// Text color used for drawing the description text
public var descriptionTextColor: NSUIColor? = NSUIColor.blackColor()
/// Text align used for drawing the description text
public var descriptionTextAlign: NSTextAlignment = NSTextAlignment.Right
/// Custom position for the description text in pixels on the screen.
public var descriptionTextPosition: CGPoint? = nil
/// font object for drawing the information text when there are no values in the chart
public var infoFont: NSUIFont! = NSUIFont(name: "HelveticaNeue", size: 12.0)
public var infoTextColor: NSUIColor! = NSUIColor(red: 247.0/255.0, green: 189.0/255.0, blue: 51.0/255.0, alpha: 1.0) // orange
/// description text that appears in the bottom right corner of the chart
public var descriptionText = "Description"
/// if true, units are drawn next to the values in the chart
internal var _drawUnitInChart = false
/// the object representing the labels on the x-axis
internal var _xAxis: ChartXAxis!
/// the legend object containing all data associated with the legend
internal var _legend: ChartLegend!
/// delegate to receive chart events
public weak var delegate: ChartViewDelegate?
/// text that is displayed when the chart is empty
public var noDataText = "No chart data available."
/// text that is displayed when the chart is empty that describes why the chart is empty
public var noDataTextDescription: String?
internal var _legendRenderer: ChartLegendRenderer!
/// object responsible for rendering the data
public var renderer: ChartDataRendererBase?
public var highlighter: ChartHighlighter?
/// object that manages the bounds and drawing constraints of the chart
internal var _viewPortHandler: ChartViewPortHandler!
/// object responsible for animations
internal var _animator: ChartAnimator!
/// flag that indicates if offsets calculation has already been done or not
private var _offsetsCalculated = false
/// array of Highlight objects that reference the highlighted slices in the chart
internal var _indicesToHighlight = [ChartHighlight]()
/// if set to true, the marker is drawn when a value is clicked
public var drawMarkers = true
/// the view that represents the marker
public var marker: ChartMarker?
private var _interceptTouchEvents = false
/// An extra offset to be appended to the viewport's top
public var extraTopOffset: CGFloat = 0.0
/// An extra offset to be appended to the viewport's right
public var extraRightOffset: CGFloat = 0.0
/// An extra offset to be appended to the viewport's bottom
public var extraBottomOffset: CGFloat = 0.0
/// An extra offset to be appended to the viewport's left
public var extraLeftOffset: CGFloat = 0.0
public func setExtraOffsets(left left: CGFloat, top: CGFloat, right: CGFloat, bottom: CGFloat)
{
extraLeftOffset = left
extraTopOffset = top
extraRightOffset = right
extraBottomOffset = bottom
}
// MARK: - Initializers
public override init(frame: CGRect)
{
super.init(frame: frame)
#if os(iOS)
self.backgroundColor = NSUIColor.clearColor()
#endif
initialize()
}
public required init?(coder aDecoder: NSCoder)
{
super.init(coder: aDecoder)
initialize()
}
deinit
{
self.removeObserver(self, forKeyPath: "bounds")
self.removeObserver(self, forKeyPath: "frame")
}
internal func initialize()
{
_animator = ChartAnimator()
_animator.delegate = self
_viewPortHandler = ChartViewPortHandler()
_viewPortHandler.setChartDimens(width: bounds.size.width, height: bounds.size.height)
_legend = ChartLegend()
_legendRenderer = ChartLegendRenderer(viewPortHandler: _viewPortHandler, legend: _legend)
_xAxis = ChartXAxis()
self.addObserver(self, forKeyPath: "bounds", options: .New, context: nil)
self.addObserver(self, forKeyPath: "frame", options: .New, context: nil)
}
// MARK: - ChartViewBase
/// The data for the chart
public var data: ChartData?
{
get
{
return _data
}
set
{
_offsetsCalculated = false
_data = newValue
// calculate how many digits are needed
if let data = _data
{
calculateFormatter(min: data.getYMin(), max: data.getYMax())
}
notifyDataSetChanged()
}
}
/// Clears the chart from all data (sets it to null) and refreshes it (by calling setNeedsDisplay()).
public func clear()
{
_data = nil
_indicesToHighlight.removeAll()
setNeedsDisplay()
}
/// Removes all DataSets (and thereby Entries) from the chart. Does not remove the x-values. Also refreshes the chart by calling setNeedsDisplay().
public func clearValues()
{
_data?.clearValues()
setNeedsDisplay()
}
/// - returns: true if the chart is empty (meaning it's data object is either null or contains no entries).
public func isEmpty() -> Bool
{
guard let data = _data else { return true }
if (data.yValCount <= 0)
{
return true
}
else
{
return false
}
}
/// Lets the chart know its underlying data has changed and should perform all necessary recalculations.
/// It is crucial that this method is called everytime data is changed dynamically. Not calling this method can lead to crashes or unexpected behaviour.
public func notifyDataSetChanged()
{
fatalError("notifyDataSetChanged() cannot be called on ChartViewBase")
}
/// calculates the offsets of the chart to the border depending on the position of an eventual legend or depending on the length of the y-axis and x-axis labels and their position
internal func calculateOffsets()
{
fatalError("calculateOffsets() cannot be called on ChartViewBase")
}
/// calcualtes the y-min and y-max value and the y-delta and x-delta value
internal func calcMinMax()
{
fatalError("calcMinMax() cannot be called on ChartViewBase")
}
/// calculates the required number of digits for the values that might be drawn in the chart (if enabled), and creates the default value formatter
internal func calculateFormatter(min min: Double, max: Double)
{
// check if a custom formatter is set or not
var reference = Double(0.0)
if let data = _data where data.xValCount >= 2
{
reference = fabs(max - min)
}
else
{
let absMin = fabs(min)
let absMax = fabs(max)
reference = absMin > absMax ? absMin : absMax
}
let digits = ChartUtils.decimals(reference)
_defaultValueFormatter.maximumFractionDigits = digits
_defaultValueFormatter.minimumFractionDigits = digits
}
public override func drawRect(rect: CGRect)
{
let optionalContext = NSUIGraphicsGetCurrentContext()
guard let context = optionalContext else { return }
let frame = self.bounds
if _data === nil
{
CGContextSaveGState(context)
defer { CGContextRestoreGState(context) }
let hasText = noDataText.characters.count > 0
let hasDescription = noDataTextDescription?.characters.count > 0
var textHeight = hasText ? infoFont.lineHeight : 0.0
if hasDescription
{
textHeight += infoFont.lineHeight
}
// if no data, inform the user
var y = (frame.height - textHeight) / 2.0
if hasText
{
ChartUtils.drawText(
context: context,
text: noDataText,
point: CGPoint(x: frame.width / 2.0, y: y),
align: .Center,
attributes: [NSFontAttributeName: infoFont, NSForegroundColorAttributeName: infoTextColor]
)
y = y + infoFont.lineHeight
}
if (noDataTextDescription != nil && (noDataTextDescription!).characters.count > 0)
{
ChartUtils.drawText(context: context, text: noDataTextDescription!, point: CGPoint(x: frame.width / 2.0, y: y), align: .Center, attributes: [NSFontAttributeName: infoFont, NSForegroundColorAttributeName: infoTextColor])
}
return
}
if (!_offsetsCalculated)
{
calculateOffsets()
_offsetsCalculated = true
}
}
/// draws the description text in the bottom right corner of the chart
internal func drawDescription(context context: CGContext)
{
if (descriptionText.lengthOfBytesUsingEncoding(NSUTF16StringEncoding) == 0)
{
return
}
let frame = self.bounds
var attrs = [String : AnyObject]()
var font = descriptionFont
if (font == nil)
{
#if os(tvOS)
// 23 is the smallest recommended font size on the TV
font = NSUIFont.systemFontOfSize(23, weight: UIFontWeightMedium)
#else
font = NSUIFont.systemFontOfSize(NSUIFont.systemFontSize())
#endif
}
attrs[NSFontAttributeName] = font
attrs[NSForegroundColorAttributeName] = descriptionTextColor
if descriptionTextPosition == nil
{
ChartUtils.drawText(
context: context,
text: descriptionText,
point: CGPoint(
x: frame.width - _viewPortHandler.offsetRight - 10.0,
y: frame.height - _viewPortHandler.offsetBottom - 10.0 - (font?.lineHeight ?? 0.0)),
align: descriptionTextAlign,
attributes: attrs)
}
else
{
ChartUtils.drawText(
context: context,
text: descriptionText,
point: descriptionTextPosition!,
align: descriptionTextAlign,
attributes: attrs)
}
}
// MARK: - Highlighting
/// - returns: the array of currently highlighted values. This might an empty if nothing is highlighted.
public var highlighted: [ChartHighlight]
{
return _indicesToHighlight
}
/// Set this to false to prevent values from being highlighted by tap gesture.
/// Values can still be highlighted via drag or programmatically.
/// **default**: true
public var highlightPerTapEnabled: Bool
{
get { return _highlightPerTapEnabled }
set { _highlightPerTapEnabled = newValue }
}
/// Returns true if values can be highlighted via tap gesture, false if not.
public var isHighLightPerTapEnabled: Bool
{
return highlightPerTapEnabled
}
/// Checks if the highlight array is null, has a length of zero or if the first object is null.
/// - returns: true if there are values to highlight, false if there are no values to highlight.
public func valuesToHighlight() -> Bool
{
return _indicesToHighlight.count > 0
}
/// Highlights the values at the given indices in the given DataSets. Provide
/// null or an empty array to undo all highlighting.
/// This should be used to programmatically highlight values.
/// This DOES NOT generate a callback to the delegate.
public func highlightValues(highs: [ChartHighlight]?)
{
// set the indices to highlight
_indicesToHighlight = highs ?? [ChartHighlight]()
if (_indicesToHighlight.isEmpty)
{
self.lastHighlighted = nil
}
else
{
self.lastHighlighted = _indicesToHighlight[0];
}
// redraw the chart
setNeedsDisplay()
}
/// Highlights the values represented by the provided Highlight object
/// This DOES NOT generate a callback to the delegate.
/// - parameter highlight: contains information about which entry should be highlighted
public func highlightValue(highlight: ChartHighlight?)
{
highlightValue(highlight: highlight, callDelegate: false)
}
/// Highlights the value at the given x-index in the given DataSet.
/// Provide -1 as the x-index to undo all highlighting.
public func highlightValue(xIndex xIndex: Int, dataSetIndex: Int)
{
highlightValue(xIndex: xIndex, dataSetIndex: dataSetIndex, callDelegate: true)
}
/// Highlights the value at the given x-index in the given DataSet.
/// Provide -1 as the x-index to undo all highlighting.
public func highlightValue(xIndex xIndex: Int, dataSetIndex: Int, callDelegate: Bool)
{
guard let data = _data else
{
Swift.print("Value not highlighted because data is nil")
return
}
if (xIndex < 0 || dataSetIndex < 0 || xIndex >= data.xValCount || dataSetIndex >= data.dataSetCount)
{
highlightValue(highlight: nil, callDelegate: callDelegate)
}
else
{
highlightValue(highlight: ChartHighlight(xIndex: xIndex, dataSetIndex: dataSetIndex), callDelegate: callDelegate)
}
}
/// Highlights the value selected by touch gesture.
public func highlightValue(highlight highlight: ChartHighlight?, callDelegate: Bool)
{
var entry: ChartDataEntry?
var h = highlight
if (h == nil)
{
_indicesToHighlight.removeAll(keepCapacity: false)
}
else
{
// set the indices to highlight
entry = _data?.getEntryForHighlight(h!)
if (entry == nil)
{
h = nil
_indicesToHighlight.removeAll(keepCapacity: false)
}
else
{
if self is BarLineChartViewBase
&& (self as! BarLineChartViewBase).isHighlightFullBarEnabled
{
h = ChartHighlight(xIndex: h!.xIndex, value: Double.NaN, dataIndex: -1, dataSetIndex: -1, stackIndex: -1)
}
_indicesToHighlight = [h!]
}
}
if (callDelegate && delegate != nil)
{
if (h == nil)
{
delegate!.chartValueNothingSelected?(self)
}
else
{
// notify the listener
delegate!.chartValueSelected?(self, entry: entry!, dataSetIndex: h!.dataSetIndex, highlight: h!)
}
}
// redraw the chart
setNeedsDisplay()
}
/// The last value that was highlighted via touch.
public var lastHighlighted: ChartHighlight?
// MARK: - Markers
/// draws all MarkerViews on the highlighted positions
internal func drawMarkers(context context: CGContext)
{
// if there is no marker view or drawing marker is disabled
if (marker === nil || !drawMarkers || !valuesToHighlight())
{
return
}
for i in 0 ..< _indicesToHighlight.count
{
let highlight = _indicesToHighlight[i]
let xIndex = highlight.xIndex
let deltaX = _xAxis?.axisRange ?? (Double(_data?.xValCount ?? 0) - 1)
if xIndex <= Int(deltaX) && xIndex <= Int(CGFloat(deltaX) * _animator.phaseX)
{
let e = _data?.getEntryForHighlight(highlight)
if (e === nil || e!.xIndex != highlight.xIndex)
{
continue
}
let pos = getMarkerPosition(entry: e!, highlight: highlight)
// check bounds
if (!_viewPortHandler.isInBounds(x: pos.x, y: pos.y))
{
continue
}
// callbacks to update the content
marker!.refreshContent(entry: e!, highlight: highlight)
let markerSize = marker!.size
if (pos.y - markerSize.height <= 0.0)
{
let y = markerSize.height - pos.y
marker!.draw(context: context, point: CGPoint(x: pos.x, y: pos.y + y))
}
else
{
marker!.draw(context: context, point: pos)
}
}
}
}
/// - returns: the actual position in pixels of the MarkerView for the given Entry in the given DataSet.
public func getMarkerPosition(entry entry: ChartDataEntry, highlight: ChartHighlight) -> CGPoint
{
fatalError("getMarkerPosition() cannot be called on ChartViewBase")
}
// MARK: - Animation
/// - returns: the animator responsible for animating chart values.
public var chartAnimator: ChartAnimator!
{
return _animator
}
/// Animates the drawing / rendering of the chart on both x- and y-axis with the specified animation time.
/// If `animate(...)` is called, no further calling of `invalidate()` is necessary to refresh the chart.
/// - parameter xAxisDuration: duration for animating the x axis
/// - parameter yAxisDuration: duration for animating the y axis
/// - parameter easingX: an easing function for the animation on the x axis
/// - parameter easingY: an easing function for the animation on the y axis
public func animate(xAxisDuration xAxisDuration: NSTimeInterval, yAxisDuration: NSTimeInterval, easingX: ChartEasingFunctionBlock?, easingY: ChartEasingFunctionBlock?)
{
_animator.animate(xAxisDuration: xAxisDuration, yAxisDuration: yAxisDuration, easingX: easingX, easingY: easingY)
}
/// Animates the drawing / rendering of the chart on both x- and y-axis with the specified animation time.
/// If `animate(...)` is called, no further calling of `invalidate()` is necessary to refresh the chart.
/// - parameter xAxisDuration: duration for animating the x axis
/// - parameter yAxisDuration: duration for animating the y axis
/// - parameter easingOptionX: the easing function for the animation on the x axis
/// - parameter easingOptionY: the easing function for the animation on the y axis
public func animate(xAxisDuration xAxisDuration: NSTimeInterval, yAxisDuration: NSTimeInterval, easingOptionX: ChartEasingOption, easingOptionY: ChartEasingOption)
{
_animator.animate(xAxisDuration: xAxisDuration, yAxisDuration: yAxisDuration, easingOptionX: easingOptionX, easingOptionY: easingOptionY)
}
/// Animates the drawing / rendering of the chart on both x- and y-axis with the specified animation time.
/// If `animate(...)` is called, no further calling of `invalidate()` is necessary to refresh the chart.
/// - parameter xAxisDuration: duration for animating the x axis
/// - parameter yAxisDuration: duration for animating the y axis
/// - parameter easing: an easing function for the animation
public func animate(xAxisDuration xAxisDuration: NSTimeInterval, yAxisDuration: NSTimeInterval, easing: ChartEasingFunctionBlock?)
{
_animator.animate(xAxisDuration: xAxisDuration, yAxisDuration: yAxisDuration, easing: easing)
}
/// Animates the drawing / rendering of the chart on both x- and y-axis with the specified animation time.
/// If `animate(...)` is called, no further calling of `invalidate()` is necessary to refresh the chart.
/// - parameter xAxisDuration: duration for animating the x axis
/// - parameter yAxisDuration: duration for animating the y axis
/// - parameter easingOption: the easing function for the animation
public func animate(xAxisDuration xAxisDuration: NSTimeInterval, yAxisDuration: NSTimeInterval, easingOption: ChartEasingOption)
{
_animator.animate(xAxisDuration: xAxisDuration, yAxisDuration: yAxisDuration, easingOption: easingOption)
}
/// Animates the drawing / rendering of the chart on both x- and y-axis with the specified animation time.
/// If `animate(...)` is called, no further calling of `invalidate()` is necessary to refresh the chart.
/// - parameter xAxisDuration: duration for animating the x axis
/// - parameter yAxisDuration: duration for animating the y axis
public func animate(xAxisDuration xAxisDuration: NSTimeInterval, yAxisDuration: NSTimeInterval)
{
_animator.animate(xAxisDuration: xAxisDuration, yAxisDuration: yAxisDuration)
}
/// Animates the drawing / rendering of the chart the x-axis with the specified animation time.
/// If `animate(...)` is called, no further calling of `invalidate()` is necessary to refresh the chart.
/// - parameter xAxisDuration: duration for animating the x axis
/// - parameter easing: an easing function for the animation
public func animate(xAxisDuration xAxisDuration: NSTimeInterval, easing: ChartEasingFunctionBlock?)
{
_animator.animate(xAxisDuration: xAxisDuration, easing: easing)
}
/// Animates the drawing / rendering of the chart the x-axis with the specified animation time.
/// If `animate(...)` is called, no further calling of `invalidate()` is necessary to refresh the chart.
/// - parameter xAxisDuration: duration for animating the x axis
/// - parameter easingOption: the easing function for the animation
public func animate(xAxisDuration xAxisDuration: NSTimeInterval, easingOption: ChartEasingOption)
{
_animator.animate(xAxisDuration: xAxisDuration, easingOption: easingOption)
}
/// Animates the drawing / rendering of the chart the x-axis with the specified animation time.
/// If `animate(...)` is called, no further calling of `invalidate()` is necessary to refresh the chart.
/// - parameter xAxisDuration: duration for animating the x axis
public func animate(xAxisDuration xAxisDuration: NSTimeInterval)
{
_animator.animate(xAxisDuration: xAxisDuration)
}
/// Animates the drawing / rendering of the chart the y-axis with the specified animation time.
/// If `animate(...)` is called, no further calling of `invalidate()` is necessary to refresh the chart.
/// - parameter yAxisDuration: duration for animating the y axis
/// - parameter easing: an easing function for the animation
public func animate(yAxisDuration yAxisDuration: NSTimeInterval, easing: ChartEasingFunctionBlock?)
{
_animator.animate(yAxisDuration: yAxisDuration, easing: easing)
}
/// Animates the drawing / rendering of the chart the y-axis with the specified animation time.
/// If `animate(...)` is called, no further calling of `invalidate()` is necessary to refresh the chart.
/// - parameter yAxisDuration: duration for animating the y axis
/// - parameter easingOption: the easing function for the animation
public func animate(yAxisDuration yAxisDuration: NSTimeInterval, easingOption: ChartEasingOption)
{
_animator.animate(yAxisDuration: yAxisDuration, easingOption: easingOption)
}
/// Animates the drawing / rendering of the chart the y-axis with the specified animation time.
/// If `animate(...)` is called, no further calling of `invalidate()` is necessary to refresh the chart.
/// - parameter yAxisDuration: duration for animating the y axis
public func animate(yAxisDuration yAxisDuration: NSTimeInterval)
{
_animator.animate(yAxisDuration: yAxisDuration)
}
// MARK: - Accessors
/// - returns: the current y-max value across all DataSets
public var chartYMax: Double
{
return _data?.yMax ?? 0.0
}
/// - returns: the current y-min value across all DataSets
public var chartYMin: Double
{
return _data?.yMin ?? 0.0
}
public var chartXMax: Double
{
return _xAxis._axisMaximum
}
public var chartXMin: Double
{
return _xAxis._axisMinimum
}
public var xValCount: Int
{
return _data?.xValCount ?? 0
}
/// - returns: the total number of (y) values the chart holds (across all DataSets)
public var valueCount: Int
{
return _data?.yValCount ?? 0
}
/// *Note: (Equivalent of getCenter() in MPAndroidChart, as center is already a standard in iOS that returns the center point relative to superview, and MPAndroidChart returns relative to self)*
/// - returns: the center point of the chart (the whole View) in pixels.
public var midPoint: CGPoint
{
let bounds = self.bounds
return CGPoint(x: bounds.origin.x + bounds.size.width / 2.0, y: bounds.origin.y + bounds.size.height / 2.0)
}
public func setDescriptionTextPosition(x x: CGFloat, y: CGFloat)
{
descriptionTextPosition = CGPoint(x: x, y: y)
}
/// - returns: the center of the chart taking offsets under consideration. (returns the center of the content rectangle)
public var centerOffsets: CGPoint
{
return _viewPortHandler.contentCenter
}
/// - returns: the Legend object of the chart. This method can be used to get an instance of the legend in order to customize the automatically generated Legend.
public var legend: ChartLegend
{
return _legend
}
/// - returns: the renderer object responsible for rendering / drawing the Legend.
public var legendRenderer: ChartLegendRenderer!
{
return _legendRenderer
}
/// - returns: the rectangle that defines the borders of the chart-value surface (into which the actual values are drawn).
public var contentRect: CGRect
{
return _viewPortHandler.contentRect
}
/// - returns: the x-value at the given index
public func getXValue(index: Int) -> String!
{
guard let data = _data where data.xValCount > index else
{
return nil
}
return data.xVals[index]
}
/// Get all Entry objects at the given index across all DataSets.
public func getEntriesAtIndex(xIndex: Int) -> [ChartDataEntry]
{
var vals = [ChartDataEntry]()
guard let data = _data else { return vals }
for i in 0 ..< data.dataSetCount
{
let set = data.getDataSetByIndex(i)
let e = set.entryForXIndex(xIndex)
if (e !== nil)
{
vals.append(e!)
}
}
return vals
}
/// - returns: the ViewPortHandler of the chart that is responsible for the
/// content area of the chart and its offsets and dimensions.
public var viewPortHandler: ChartViewPortHandler!
{
return _viewPortHandler
}
/// - returns: the bitmap that represents the chart.
public func getChartImage(transparent transparent: Bool) -> NSUIImage?
{
NSUIGraphicsBeginImageContextWithOptions(bounds.size, opaque || !transparent, NSUIMainScreen()?.nsuiScale ?? 1.0)
let context = NSUIGraphicsGetCurrentContext()
let rect = CGRect(origin: CGPoint(x: 0, y: 0), size: bounds.size)
if (opaque || !transparent)
{
// Background color may be partially transparent, we must fill with white if we want to output an opaque image
CGContextSetFillColorWithColor(context, NSUIColor.whiteColor().CGColor)
CGContextFillRect(context, rect)
if (self.backgroundColor !== nil)
{
CGContextSetFillColorWithColor(context, self.backgroundColor?.CGColor)
CGContextFillRect(context, rect)
}
}
if let context = context
{
nsuiLayer?.renderInContext(context)
}
let image = NSUIGraphicsGetImageFromCurrentImageContext()
NSUIGraphicsEndImageContext()
return image
}
public enum ImageFormat
{
case JPEG
case PNG
}
/// Saves the current chart state with the given name to the given path on
/// the sdcard leaving the path empty "" will put the saved file directly on
/// the SD card chart is saved as a PNG image, example:
/// saveToPath("myfilename", "foldername1/foldername2")
///
/// - parameter filePath: path to the image to save
/// - parameter format: the format to save
/// - parameter compressionQuality: compression quality for lossless formats (JPEG)
///
/// - returns: true if the image was saved successfully
public func saveToPath(path: String, format: ImageFormat, compressionQuality: Double) -> Bool
{
if let image = getChartImage(transparent: format != .JPEG) {
var imageData: NSData!
switch (format)
{
case .PNG:
imageData = NSUIImagePNGRepresentation(image)
break
case .JPEG:
imageData = NSUIImageJPEGRepresentation(image, CGFloat(compressionQuality))
break
}
return imageData.writeToFile(path, atomically: true)
}
return false
}
#if !os(tvOS) && !os(OSX)
/// Saves the current state of the chart to the camera roll
public func saveToCameraRoll()
{
if let img = getChartImage(transparent: false) {
UIImageWriteToSavedPhotosAlbum(img, nil, nil, nil)
}
}
#endif
internal var _viewportJobs = [ChartViewPortJob]()
public override func observeValueForKeyPath(keyPath: String?, ofObject object: AnyObject?, change: [String : AnyObject]?, context: UnsafeMutablePointer<Void>)
{
if (keyPath == "bounds" || keyPath == "frame")
{
let bounds = self.bounds
if (_viewPortHandler !== nil &&
(bounds.size.width != _viewPortHandler.chartWidth ||
bounds.size.height != _viewPortHandler.chartHeight))
{
_viewPortHandler.setChartDimens(width: bounds.size.width, height: bounds.size.height)
// Finish any pending viewport changes
while (!_viewportJobs.isEmpty)
{
let job = _viewportJobs.removeAtIndex(0)
job.doJob()
}
notifyDataSetChanged()
}
}
}
public func removeViewportJob(job: ChartViewPortJob)
{
if let index = _viewportJobs.indexOf({ $0 === job })
{
_viewportJobs.removeAtIndex(index)
}
}
public func clearAllViewportJobs()
{
_viewportJobs.removeAll(keepCapacity: false)
}
public func addViewportJob(job: ChartViewPortJob)
{
if (_viewPortHandler.hasChartDimens)
{
job.doJob()
}
else
{
_viewportJobs.append(job)
}
}
/// **default**: true
/// - returns: true if chart continues to scroll after touch up, false if not.
public var isDragDecelerationEnabled: Bool
{
return dragDecelerationEnabled
}
/// Deceleration friction coefficient in [0 ; 1] interval, higher values indicate that speed will decrease slowly, for example if it set to 0, it will stop immediately.
/// 1 is an invalid value, and will be converted to 0.999 automatically.
///
/// **default**: true
public var dragDecelerationFrictionCoef: CGFloat
{
get
{
return _dragDecelerationFrictionCoef
}
set
{
var val = newValue
if (val < 0.0)
{
val = 0.0
}
if (val >= 1.0)
{
val = 0.999
}
_dragDecelerationFrictionCoef = val
}
}
// MARK: - ChartAnimatorDelegate
public func chartAnimatorUpdated(chartAnimator: ChartAnimator)
{
setNeedsDisplay()
}
public func chartAnimatorStopped(chartAnimator: ChartAnimator)
{
}
// MARK: - Touches
public override func nsuiTouchesBegan(touches: Set<NSUITouch>, withEvent event: NSUIEvent?)
{
if (!_interceptTouchEvents)
{
super.nsuiTouchesBegan(touches, withEvent: event)
}
}
public override func nsuiTouchesMoved(touches: Set<NSUITouch>, withEvent event: NSUIEvent?)
{
if (!_interceptTouchEvents)
{
super.nsuiTouchesMoved(touches, withEvent: event)
}
}
public override func nsuiTouchesEnded(touches: Set<NSUITouch>, withEvent event: NSUIEvent?)
{
if (!_interceptTouchEvents)
{
super.nsuiTouchesEnded(touches, withEvent: event)
}
}
public override func nsuiTouchesCancelled(touches: Set<NSUITouch>?, withEvent event: NSUIEvent?)
{
if (!_interceptTouchEvents)
{
super.nsuiTouchesCancelled(touches, withEvent: event)
}
}
}
|
mit
|
5b437dda510c39d7f489e34edf2284f6
| 35.075937 | 235 | 0.623247 | 5.341072 | false | false | false | false |
TsvetanMilanov/BG-Tourist-Guide
|
Pods/QRCodeReader.swift/QRCodeReader/QRCodeViewController.swift
|
1
|
12476
|
/*
* QRCodeReader.swift
*
* Copyright 2014-present Yannick Loriot.
* http://yannickloriot.com
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*
*/
import UIKit
import AVFoundation
/// Convenient controller to display a view to scan/read 1D or 2D bar codes like the QRCodes. It is based on the `AVFoundation` framework from Apple. It aims to replace ZXing or ZBar for iOS 7 and over.
public class QRCodeReaderViewController: UIViewController {
private var cameraView = ReaderOverlayView()
private var cancelButton = UIButton()
private var switchCameraButton: SwitchCameraButton?
private var toggleTorchButton: ToggleTorchButton?
let codeReader: QRCodeReader
let startScanningAtLoad: Bool
let showSwitchCameraButton: Bool
let showTorchButton: Bool
// MARK: - Managing the Callback Responders
/// The receiver's delegate that will be called when a result is found.
public weak var delegate: QRCodeReaderViewControllerDelegate?
/// The completion blocak that will be called when a result is found.
public var completionBlock: (QRCodeReaderResult? -> Void)?
deinit {
codeReader.stopScanning()
NSNotificationCenter.defaultCenter().removeObserver(self)
}
// MARK: - Creating the View Controller
/**
Initializes a view controller to read QRCodes from a displayed video preview and a cancel button to be go back.
- parameter cancelButtonTitle: The title to use for the cancel button.
- parameter startScanningAtLoad: Flag to know whether the view controller start scanning the codes when the view will appear.
:see: init(cancelButtonTitle:, metadataObjectTypes:)
*/
convenience public init(cancelButtonTitle: String, startScanningAtLoad: Bool = true) {
self.init(cancelButtonTitle: cancelButtonTitle, metadataObjectTypes: [AVMetadataObjectTypeQRCode], startScanningAtLoad: startScanningAtLoad)
}
/**
Initializes a reader view controller with a list of metadata object types.
- parameter metadataObjectTypes: An array of strings identifying the types of metadata objects to process.
- parameter startScanningAtLoad: Flag to know whether the view controller start scanning the codes when the view will appear.
:see: init(cancelButtonTitle:, metadataObjectTypes:)
*/
convenience public init(metadataObjectTypes: [String], startScanningAtLoad: Bool = true) {
self.init(cancelButtonTitle: "Cancel", metadataObjectTypes: metadataObjectTypes, startScanningAtLoad: startScanningAtLoad)
}
/**
Initializes a view controller to read wanted metadata object types from a displayed video preview and a cancel button to be go back.
- parameter cancelButtonTitle: The title to use for the cancel button.
- parameter metadataObjectTypes: An array of strings identifying the types of metadata objects to process.
- parameter startScanningAtLoad: Flag to know whether the view controller start scanning the codes when the view will appear.
:see: init(cancelButtonTitle:, coderReader:, startScanningAtLoad:)
*/
convenience public init(cancelButtonTitle: String, metadataObjectTypes: [String], startScanningAtLoad: Bool = true) {
let reader = QRCodeReader(metadataObjectTypes: metadataObjectTypes)
self.init(cancelButtonTitle: cancelButtonTitle, codeReader: reader, startScanningAtLoad: startScanningAtLoad)
}
/**
Initializes a view controller using a cancel button title and a code reader.
- parameter cancelButtonTitle: The title to use for the cancel button.
- parameter codeReader: The code reader object used to scan the bar code.
- parameter startScanningAtLoad: Flag to know whether the view controller start scanning the codes when the view will appear.
- parameter showSwitchCameraButton: Flag to display the switch camera button.
- parameter showTorchButton: Flag to display the toggle torch button. If the value is true and there is no torch the button will not be displayed.
*/
public convenience init(cancelButtonTitle: String, codeReader reader: QRCodeReader, startScanningAtLoad startScan: Bool = true, showSwitchCameraButton showSwitch: Bool = true, showTorchButton showTorch: Bool = false) {
self.init(builder: QRCodeViewControllerBuilder { builder in
builder.cancelButtonTitle = cancelButtonTitle
builder.reader = reader
builder.startScanningAtLoad = startScan
builder.showSwitchCameraButton = showSwitch
builder.showTorchButton = showTorch
})
}
/**
Initializes a view controller using a builder.
- parameter builder: A QRCodeViewController builder object.
*/
required public init(builder: QRCodeViewControllerBuilder) {
startScanningAtLoad = builder.startScanningAtLoad
codeReader = builder.reader
showSwitchCameraButton = builder.showSwitchCameraButton
showTorchButton = builder.showTorchButton
super.init(nibName: nil, bundle: nil)
view.backgroundColor = .blackColor()
codeReader.completionBlock = { [weak self] resultAsObject in
if let weakSelf = self {
weakSelf.completionBlock?(resultAsObject)
weakSelf.delegate?.reader(weakSelf, didScanResult: resultAsObject)
}
}
setupUIComponentsWithCancelButtonTitle(builder.cancelButtonTitle)
setupAutoLayoutConstraints()
cameraView.layer.insertSublayer(codeReader.previewLayer, atIndex: 0)
NSNotificationCenter.defaultCenter().addObserver(self, selector: "orientationDidChanged:", name: UIDeviceOrientationDidChangeNotification, object: nil)
}
required public init?(coder aDecoder: NSCoder) {
codeReader = QRCodeReader(metadataObjectTypes: [])
startScanningAtLoad = false
showTorchButton = false
showSwitchCameraButton = false
super.init(coder: aDecoder)
}
// MARK: - Responding to View Events
override public func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
if startScanningAtLoad {
startScanning()
}
}
override public func viewWillDisappear(animated: Bool) {
stopScanning()
super.viewWillDisappear(animated)
}
override public func viewWillLayoutSubviews() {
super.viewWillLayoutSubviews()
codeReader.previewLayer.frame = view.bounds
}
// MARK: - Managing the Orientation
func orientationDidChanged(notification: NSNotification) {
cameraView.setNeedsDisplay()
if codeReader.previewLayer.connection != nil {
let orientation = UIApplication.sharedApplication().statusBarOrientation
codeReader.previewLayer.connection.videoOrientation = QRCodeReader.videoOrientationFromInterfaceOrientation(orientation)
}
}
// MARK: - Initializing the AV Components
private func setupUIComponentsWithCancelButtonTitle(cancelButtonTitle: String) {
cameraView.clipsToBounds = true
cameraView.translatesAutoresizingMaskIntoConstraints = false
view.addSubview(cameraView)
codeReader.previewLayer.frame = CGRectMake(0, 0, view.frame.size.width, view.frame.size.height)
if codeReader.previewLayer.connection.supportsVideoOrientation {
let orientation = UIApplication.sharedApplication().statusBarOrientation
codeReader.previewLayer.connection.videoOrientation = QRCodeReader.videoOrientationFromInterfaceOrientation(orientation)
}
if showSwitchCameraButton && codeReader.hasFrontDevice() {
let newSwitchCameraButton = SwitchCameraButton()
newSwitchCameraButton.translatesAutoresizingMaskIntoConstraints = false
newSwitchCameraButton.addTarget(self, action: "switchCameraAction:", forControlEvents: .TouchUpInside)
view.addSubview(newSwitchCameraButton)
switchCameraButton = newSwitchCameraButton
}
if showTorchButton && codeReader.isTorchAvailable() {
let newToggleTorchButton = ToggleTorchButton()
newToggleTorchButton.translatesAutoresizingMaskIntoConstraints = false
newToggleTorchButton.addTarget(self, action: "toggleTorchAction:", forControlEvents: .TouchUpInside)
view.addSubview(newToggleTorchButton)
toggleTorchButton = newToggleTorchButton
}
cancelButton.translatesAutoresizingMaskIntoConstraints = false
cancelButton.setTitle(cancelButtonTitle, forState: .Normal)
cancelButton.setTitleColor(.grayColor(), forState: .Highlighted)
cancelButton.addTarget(self, action: "cancelAction:", forControlEvents: .TouchUpInside)
view.addSubview(cancelButton)
}
private func setupAutoLayoutConstraints() {
let views = ["cameraView": cameraView, "cancelButton": cancelButton]
view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|[cameraView][cancelButton(40)]|", options: [], metrics: nil, views: views))
view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|[cameraView]|", options: [], metrics: nil, views: views))
view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|-[cancelButton]-|", options: [], metrics: nil, views: views))
if let _switchCameraButton = switchCameraButton {
let switchViews: [String: AnyObject] = ["switchCameraButton": _switchCameraButton, "topGuide": topLayoutGuide]
view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:[topGuide]-[switchCameraButton(50)]", options: [], metrics: nil, views: switchViews))
view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:[switchCameraButton(70)]|", options: [], metrics: nil, views: switchViews))
}
if let _toggleTorchButton = toggleTorchButton {
let toggleViews: [String: AnyObject] = ["toggleTorchButton": _toggleTorchButton, "topGuide": topLayoutGuide]
view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:[topGuide]-[toggleTorchButton(50)]", options: [], metrics: nil, views: toggleViews))
view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|[toggleTorchButton(70)]", options: [], metrics: nil, views: toggleViews))
}
}
// MARK: - Controlling the Reader
/// Starts scanning the codes.
public func startScanning() {
codeReader.startScanning()
}
/// Stops scanning the codes.
public func stopScanning() {
codeReader.stopScanning()
}
// MARK: - Catching Button Events
func cancelAction(button: UIButton) {
codeReader.stopScanning()
if let _completionBlock = completionBlock {
_completionBlock(nil)
}
delegate?.readerDidCancel(self)
}
func switchCameraAction(button: SwitchCameraButton) {
codeReader.switchDeviceInput()
}
func toggleTorchAction(button: ToggleTorchButton) {
codeReader.toggleTorch()
}
}
/**
This protocol defines delegate methods for objects that implements the `QRCodeReaderDelegate`. The methods of the protocol allow the delegate to be notified when the reader did scan result and or when the user wants to stop to read some QRCodes.
*/
public protocol QRCodeReaderViewControllerDelegate: class {
/**
Tells the delegate that the reader did scan a code.
- parameter reader: A code reader object informing the delegate about the scan result.
- parameter result: The result of the scan
*/
func reader(reader: QRCodeReaderViewController, didScanResult result: QRCodeReaderResult)
/**
Tells the delegate that the user wants to stop scanning codes.
- parameter reader: A code reader object informing the delegate about the cancellation.
*/
func readerDidCancel(reader: QRCodeReaderViewController)
}
|
mit
|
a59fca85bbac1fdba3f8a7bc8409366e
| 40.451827 | 245 | 0.76018 | 5.433798 | false | false | false | false |
cuzv/TinyCoordinator
|
Sources/ResuableView+Extension.swift
|
1
|
6093
|
//
// ResuableView+Extension.swift
// Copyright (c) 2016 Red Rain (https://github.com/cuzv).
//
// 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
// MARK: - ResuableView
internal func isSupportedConstraintsProperty() -> Bool {
if let version = UIDevice.current.systemVersion.components(separatedBy: ".").first, let systemVersion = Int(version) {
return systemVersion > 7
}
return false
}
/// Stolen from Apple's Demo `AdvancedCollectionView`
internal extension UICollectionReusableView {
/// This is kind of a hack because cells don't have an intrinsic content size or any other way to constrain them to a size. As a result,
/// labels that _should_ wrap at the bounds of a cell, don't.
/// So by adding width and height constraints to the cell temporarily, we can make the labels wrap and the layout compute correctly.
internal func preferredLayoutSize(fitting fittingSize: CGSize, takeFittingWidth: Bool = true) -> CGSize {
var frame = self.frame
frame.size = fittingSize
self.frame = frame
var size: CGSize!
if isSupportedConstraintsProperty() {
layoutSubviews()
size = systemLayoutSizeFitting(UILayoutFittingCompressedSize)
} else {
let constraints = [
NSLayoutConstraint(item: self, attribute: .width, relatedBy: .lessThanOrEqual, toItem: nil, attribute: .notAnAttribute, multiplier: 1, constant: fittingSize.width),
NSLayoutConstraint(item: self, attribute: .height, relatedBy: .lessThanOrEqual, toItem: nil, attribute: .notAnAttribute, multiplier: 1, constant: UILayoutFittingExpandedSize.height),
]
addConstraints(constraints)
updateConstraints()
size = systemLayoutSizeFitting(fittingSize)
removeConstraints(constraints)
}
frame.size = size
if takeFittingWidth {
size.width = fittingSize.width
}
self.frame = frame
return size
}
}
internal extension UITableViewCell {
/// **Note**: You should indicate the `preferredMaxLayoutWidth` by this way:
/// **Note**: You should indicate the `preferredMaxLayoutWidth` by this way:
/// ```Swift
/// override func layoutSubviews() {
/// super.layoutSubviews()
/// contentView.setNeedsLayout()
/// contentView.layoutIfNeeded()
/// nameLabel.preferredMaxLayoutWidth = CGRectGetWidth(nameLabel.bounds)
/// }
/// ```
internal func preferredLayoutSize(fitting fittingSize: CGSize) -> CGSize {
var frame = self.frame
frame.size = fittingSize
self.frame = frame
var size: CGSize!
if isSupportedConstraintsProperty() {
layoutSubviews()
size = contentView.systemLayoutSizeFitting(UILayoutFittingCompressedSize)
} else {
let constraints = [
NSLayoutConstraint(item: self, attribute: .width, relatedBy: .lessThanOrEqual, toItem: nil, attribute: .notAnAttribute, multiplier: 1, constant: fittingSize.width),
NSLayoutConstraint(item: self, attribute: .height, relatedBy: .lessThanOrEqual, toItem: nil, attribute: .notAnAttribute, multiplier: 1, constant: UILayoutFittingExpandedSize.height),
]
addConstraints(constraints)
updateConstraints()
size = systemLayoutSizeFitting(fittingSize)
removeConstraints(constraints)
}
// Only consider the height for cells, because the contentView isn't anchored correctly sometimes.
size.width = fittingSize.width
frame.size = size
self.frame = frame
return size
}
}
internal extension UITableViewHeaderFooterView {
internal func preferredLayoutSize(fitting fittingSize: CGSize) -> CGSize {
var frame = self.frame
frame.size = fittingSize
self.frame = frame
var size: CGSize!
if isSupportedConstraintsProperty() {
layoutSubviews()
size = contentView.systemLayoutSizeFitting(UILayoutFittingCompressedSize)
} else {
let constraints = [
NSLayoutConstraint(item: self, attribute: .width, relatedBy: .lessThanOrEqual, toItem: nil, attribute: .notAnAttribute, multiplier: 1, constant: fittingSize.width),
NSLayoutConstraint(item: self, attribute: .height, relatedBy: .lessThanOrEqual, toItem: nil, attribute: .notAnAttribute, multiplier: 1, constant: UILayoutFittingExpandedSize.height),
]
addConstraints(constraints)
updateConstraints()
size = systemLayoutSizeFitting(fittingSize)
removeConstraints(constraints)
}
// Only consider the height for cells, because the contentView isn't anchored correctly sometimes.
size.width = fittingSize.width
frame.size = size
self.frame = frame
return size
}
}
|
mit
|
56c0e918bb521c55556bb96f805788c1
| 43.152174 | 198 | 0.669293 | 5.248062 | false | false | false | false |
eelcokoelewijn/StepUp
|
StepUp/Entities/Treatment.swift
|
1
|
355
|
import Foundation
struct Treatment {
let title: String
let description: String
let number: Int
}
extension Treatment: Equatable {
static func == (lhs: Treatment, rhs: Treatment) -> Bool {
return lhs.title == rhs.title &&
lhs.description == rhs.description &&
lhs.number == rhs.number
}
}
|
mit
|
3421003fab1e239d5e1d7db9195eea8d
| 22.666667 | 61 | 0.591549 | 4.277108 | false | false | false | false |
mattwelborn/HSTracker
|
HSTracker/UIs/DeckManager/CardCell.swift
|
1
|
1447
|
//
// CardCell.swift
// HSTracker
//
// Created by Benjamin Michotte on 3/03/16.
// Copyright © 2016 Benjamin Michotte. All rights reserved.
//
import Foundation
class CardCell: JNWCollectionViewCell {
private var _card: Card?
var showCard = true
var isArena = false
var cellView: CardBar?
func setCard(card: Card) {
_card = card
if showCard {
if let cellView = cellView {
cellView.removeFromSuperview()
self.cellView = nil
}
self.backgroundImage = ImageUtils.cardImage(card)
} else {
if let cellView = cellView {
cellView.card = card
} else {
cellView = CardBar.factory()
cellView?.frame = NSRect(x: 0, y: 0,
width: CGFloat(kFrameWidth),
height: CGFloat(kRowHeight))
cellView?.card = card
cellView?.playerType = .CardList
self.addSubview(cellView!)
}
}
}
var card: Card? {
return _card
}
func setCount(count: Int) {
var alpha: Float = 1.0
if !isArena {
if count == 2 || (count == 1 && _card!.rarity == .Legendary) {
alpha = 0.5
}
}
self.layer!.opacity = alpha
self.layer!.setNeedsDisplay()
}
}
|
mit
|
47b28b3d8e01505439381cceb85cc8a4
| 25.777778 | 74 | 0.489627 | 4.679612 | false | false | false | false |
jefflinwood/volunteer-recognition-ios
|
APASlapApp/APASlapApp/Profile/ProfileViewController.swift
|
1
|
4536
|
//
// ProfileViewController.swift
// APASlapApp
//
// Created by Jeffrey Linwood on 6/4/17.
// Copyright © 2017 Jeff Linwood. All rights reserved.
//
import UIKit
import Firebase
class ProfileViewController: BaseViewController, UIImagePickerControllerDelegate, UINavigationControllerDelegate {
let userImagesStorageRef = FIRStorage.storage().reference().child("user-images")
@IBOutlet weak var updateDisplayNameButton: UIButton!
@IBOutlet weak var displayNameTextField: UITextField!
@IBOutlet weak var chooseProfilePhotoButton: UIButton!
@IBOutlet weak var profileImageView: UIImageView!
@IBAction func updateDisplayName(_ sender: Any) {
if let auth = FIRAuth.auth() {
let changeRequest = auth.currentUser?.profileChangeRequest()
changeRequest?.displayName = displayNameTextField.text
changeRequest?.commitChanges { (error) in
if let error = error {
self.showErrorMessage(errorMessage:error.localizedDescription)
return
} else {
self.dismiss(animated: true, completion: nil)
}
}
}
}
@IBAction func chooseProfilePhoto(_ sender: Any) {
let imagePicker = UIImagePickerController()
imagePicker.delegate = self
imagePicker.sourceType = .photoLibrary
present(imagePicker, animated: true)
}
@IBAction func done(_ sender: Any) {
dismiss(animated: true, completion: nil)
}
@IBAction func tapView(_ sender: Any) {
displayNameTextField.resignFirstResponder()
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
styleButton(button: updateDisplayNameButton)
styleButton(button: chooseProfilePhotoButton)
if let auth = FIRAuth.auth() {
if let photoURL = auth.currentUser?.photoURL {
profileImageView.sd_setImage(with: photoURL)
} else {
profileImageView.image = UIImage(named: "logo_apa")
}
if let displayName = auth.currentUser?.displayName {
displayNameTextField.text = displayName
}
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
//TODO: Refactor this monster!
if let image = info[UIImagePickerControllerOriginalImage] as? UIImage {
self.profileImageView.image = image
if let imageData = UIImageJPEGRepresentation(image,0.3) {
let imageMetadata = FIRStorageMetadata()
imageMetadata.contentType = "image/jpeg"
if let auth = FIRAuth.auth() {
let uid = auth.currentUser!.uid
let uploadTask = userImagesStorageRef.child(uid).put(imageData, metadata: imageMetadata)
uploadTask.observe(.success) { snapshot in
self.userImagesStorageRef.child(uid).downloadURL(completion: { (downloadURL, urlError) in
let changeRequest = auth.currentUser?.profileChangeRequest()
changeRequest?.photoURL = downloadURL
changeRequest?.commitChanges { (error) in
if let error = error {
self.showErrorMessage(errorMessage:error.localizedDescription)
return
} else {
//self.showMessage(title: "Thanks", message: "Your profile photo has been updated")
self.dismiss(animated: true, completion: nil)
}
}
})
}
}
}
}
picker.dismiss(animated: true, completion: nil)
}
func imagePickerControllerDidCancel(_ picker: UIImagePickerController) {
picker.dismiss(animated: true, completion: nil)
}
}
|
mit
|
e846c884458015f2ffae6f0df880835e
| 35.28 | 123 | 0.558986 | 6.087248 | false | false | false | false |
wordpress-mobile/WordPress-iOS
|
WordPress/WordPressTest/ClicksStatsRecordValueTests.swift
|
1
|
2906
|
import XCTest
@testable import WordPress
class ClicksStatsRecordValueTests: StatsTestCase {
func testCreation() {
let parent = createStatsRecord(in: mainContext, type: .clicks, period: .month, date: Date())
let clicks = ClicksStatsRecordValue(parent: parent)
clicks.label = "test"
clicks.clicksCount = 9001
XCTAssertNoThrow(try mainContext.save())
let fr = StatsRecord.fetchRequest(for: .clicks, on: Date(), periodType: .month)
let results = try! mainContext.fetch(fr)
XCTAssertEqual(results.count, 1)
XCTAssertEqual(results.first!.values?.count, 1)
let fetchedClicks = results.first?.values?.firstObject! as! ClicksStatsRecordValue
XCTAssertEqual(fetchedClicks.label, clicks.label)
XCTAssertEqual(fetchedClicks.clicksCount, clicks.clicksCount)
}
func testChildrenRelationships() {
let parent = createStatsRecord(in: mainContext, type: .clicks, period: .month, date: Date())
let clicks = ClicksStatsRecordValue(parent: parent)
clicks.label = "parent"
clicks.clicksCount = 5000
let child = ClicksStatsRecordValue(context: mainContext)
child.label = "child"
child.clicksCount = 4000
let child2 = ClicksStatsRecordValue(context: mainContext)
child2.label = "child2"
child2.clicksCount = 1
clicks.addToChildren([child, child2])
XCTAssertNoThrow(try mainContext.save())
let fr = StatsRecord.fetchRequest(for: .clicks, on: Date(), periodType: .month)
let results = try! mainContext.fetch(fr)
XCTAssertEqual(results.count, 1)
XCTAssertEqual(results.first!.values?.count, 1)
let fetchedClicks = results.first?.values?.firstObject! as! ClicksStatsRecordValue
XCTAssertEqual(fetchedClicks.label, clicks.label)
let children = fetchedClicks.children?.array as? [ClicksStatsRecordValue]
XCTAssertNotNil(children)
XCTAssertEqual(children!.count, 2)
XCTAssertEqual(children!.first!.label, child.label)
XCTAssertEqual(children![1].label, child2.label)
XCTAssertEqual(9001, fetchedClicks.clicksCount + children!.first!.clicksCount + children![1].clicksCount)
}
func testURLConversionWorks() {
let parent = createStatsRecord(in: mainContext, type: .clicks, period: .month, date: Date())
let tag = ClicksStatsRecordValue(parent: parent)
tag.urlString = "www.wordpress.com"
tag.clicksCount = 90001
tag.label = "test"
XCTAssertNoThrow(try mainContext.save())
let fr = StatsRecord.fetchRequest(for: .clicks, on: Date(), periodType: .month)
let result = try! mainContext.fetch(fr)
let fetchedValue = result.first!.values!.firstObject as! ClicksStatsRecordValue
XCTAssertNotNil(fetchedValue.clickedURL)
}
}
|
gpl-2.0
|
7430ac7aad50d8295e86e14d56258f6a
| 32.402299 | 113 | 0.677908 | 4.612698 | false | true | false | false |
wordpress-mobile/WordPress-iOS
|
WordPress/Classes/ViewRelated/NUX/LoginEpilogueDividerView.swift
|
1
|
2543
|
import UIKit
import WordPressAuthenticator
final class LoginEpilogueDividerView: UIView {
private let leadingDividerLine = UIView()
private let trailingDividerLine = UIView()
private let dividerLabel = UILabel()
override init(frame: CGRect) {
super.init(frame: frame)
setupViews()
}
@available(*, unavailable)
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
// MARK: - Private Methods
private extension LoginEpilogueDividerView {
func setupViews() {
setupTitleLabel()
setupLeadingDividerLine()
setupTrailingDividerLine()
}
func setupTitleLabel() {
dividerLabel.textColor = .divider
dividerLabel.font = .preferredFont(forTextStyle: .footnote)
dividerLabel.text = NSLocalizedString("Or", comment: "Divider on initial auth view separating auth options.").localizedUppercase
dividerLabel.translatesAutoresizingMaskIntoConstraints = false
addSubview(dividerLabel)
NSLayoutConstraint.activate([
dividerLabel.centerXAnchor.constraint(equalTo: centerXAnchor),
dividerLabel.centerYAnchor.constraint(equalTo: centerYAnchor)
])
}
func setupLeadingDividerLine() {
leadingDividerLine.backgroundColor = .divider
leadingDividerLine.translatesAutoresizingMaskIntoConstraints = false
addSubview(leadingDividerLine)
NSLayoutConstraint.activate([
leadingDividerLine.centerYAnchor.constraint(equalTo: dividerLabel.centerYAnchor),
leadingDividerLine.leadingAnchor.constraint(equalTo: leadingAnchor),
leadingDividerLine.trailingAnchor.constraint(equalTo: dividerLabel.leadingAnchor, constant: -4),
leadingDividerLine.heightAnchor.constraint(equalToConstant: .hairlineBorderWidth)
])
}
func setupTrailingDividerLine() {
trailingDividerLine.backgroundColor = .divider
trailingDividerLine.translatesAutoresizingMaskIntoConstraints = false
addSubview(trailingDividerLine)
NSLayoutConstraint.activate([
trailingDividerLine.centerYAnchor.constraint(equalTo: dividerLabel.centerYAnchor),
trailingDividerLine.leadingAnchor.constraint(equalTo: dividerLabel.trailingAnchor, constant: 4),
trailingDividerLine.trailingAnchor.constraint(equalTo: trailingAnchor),
trailingDividerLine.heightAnchor.constraint(equalToConstant: .hairlineBorderWidth)
])
}
}
|
gpl-2.0
|
43263c000a736b77d7af4326a2a9bd39
| 39.365079 | 136 | 0.721195 | 5.714607 | false | false | false | false |
Spreetail/SpreeBoard
|
SpreeBoard/Classes/SpreeBoard.swift
|
1
|
9263
|
//
// SpreeBoard.swift
// SpreeBoard
//
// Created by Trevor Poppen on 8/19/16.
// Copyright © 2016 Spreetail. All rights reserved.
//
import UIKit
import UIColor_Hex_Swift
public struct Colors {
static let SpreeRed = UIColor(rgba: "#F45B5F")
static let SpreeBlue1 = UIColor(rgba: "#1D4849")
static let SpreeBlue2 = UIColor(rgba: "#2D6B70")
static let SpreeBlue3 = UIColor(rgba: "#67D5C9")
static let SpreeBlue4 = UIColor(rgba: "#8EF4D0")
}
public protocol SpreeBoardDelegate {
func inputUpdated(input: String)
func enter()
func dismissKeyboard()
}
public enum SpreeBoardInputState {
case Normal, NumPad
}
public class SpreeBoard: UIView {
let delegate: SpreeBoardDelegate
let numPad: [String] = ["1", "2", "3", "4", "5", "6", "7", "8", "9", "0"]
let characters: [String] = ["1", "2", "3", "4", "5", "6", "7", "8", "9", "0",
"Q", "W", "E", "R", "T", "Y", "U", "I", "O", "P",
"A", "S", "D", "F", "G", "H", "J", "K", "L",
"Z", "X", "C", "V", "B", "N", "M"]
var inputString: String
var inputState: SpreeBoardInputState
public init(frame: CGRect, state: SpreeBoardInputState, delegate: SpreeBoardDelegate) {
self.delegate = delegate
self.inputString = ""
self.inputState = state
// setup the view
super.init(frame: frame)
self.backgroundColor = Colors.SpreeBlue1
if self.inputState == .Normal {
self.drawNormalKeyboard()
} else if self.inputState == .NumPad {
self.drawNumPad()
}
}
required public init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func drawNormalKeyboard() {
self.subviews.forEach({ $0.removeFromSuperview() })
// configure buttons
let buttonWidth: CGFloat = self.frame.width * 0.09
let bigButtonWidth: CGFloat = buttonWidth * 3
let buttonHeight: CGFloat = self.frame.height * 0.165
let edgeBuffer = self.frame.width * 0.009
// text buttons
var index = 0
for row in 0...3 {
for column in 0...9 {
if index < characters.count {
if row == 2 && column > 8 {
continue
}
if row == 3 && column > 7 {
continue
}
var xOffset: CGFloat = edgeBuffer
let xCoefficient: CGFloat = edgeBuffer
if row == 2 {
xOffset = buttonWidth * 0.5 + edgeBuffer
} else if row == 3 {
xOffset = buttonWidth * 0.5 + buttonWidth + (edgeBuffer * 2)
}
let x = CGFloat(column) * buttonWidth + xOffset + (CGFloat(column) * xCoefficient)
let y = CGFloat(row) * buttonHeight + edgeBuffer + (CGFloat(row) * 7.5)
let button = SpreeBoardButton(frame: CGRect(x: x, y: y, width: buttonWidth, height: buttonHeight), text: characters[index])
button.addTarget(self, action: #selector(buttonPressed), forControlEvents: .TouchUpInside)
button.tag = index
self.addSubview(button)
index = index + 1
}
}
}
// function buttons
let bottomUpOne: CGFloat = 3
let bottomRow: CGFloat = 4
let modeRect = CGRect(x: edgeBuffer, y: (buttonHeight * bottomUpOne) + edgeBuffer + (bottomUpOne * 7.5), width: (buttonWidth * 1.50), height: buttonHeight)
let buttonMode = SpreeBoardButton(frame: modeRect, text: "#")
buttonMode.addTarget(self, action: #selector(buttonPressed), forControlEvents: .TouchUpInside)
buttonMode.tag = 103
self.addSubview(buttonMode)
let deleteRect = CGRect(x: self.frame.width - (buttonWidth * 1.50) - edgeBuffer, y: (buttonHeight * bottomUpOne) + edgeBuffer + (bottomUpOne * 7.5), width: (buttonWidth * 1.50), height: buttonHeight)
let buttonDelete = SpreeBoardButton(frame: deleteRect, text: "DEL")
buttonDelete.addTarget(self, action: #selector(buttonPressed), forControlEvents: .TouchUpInside)
buttonDelete.tag = 99
self.addSubview(buttonDelete)
let exitRect = CGRect(x: edgeBuffer, y: (buttonHeight * bottomRow) + edgeBuffer + (bottomRow * (edgeBuffer * bottomUpOne)), width: bigButtonWidth, height: buttonHeight)
let buttonExit = SpreeBoardButton(frame: exitRect, text: "exit")
buttonExit.addTarget(self, action: #selector(buttonPressed), forControlEvents: .TouchUpInside)
buttonExit.tag = 100
self.addSubview(buttonExit)
let spaceRect = CGRect(x: (self.frame.width * 0.5) - (bigButtonWidth * 0.5) + (1.5 * edgeBuffer), y: (buttonHeight * bottomRow) + edgeBuffer + (bottomRow * (edgeBuffer * bottomUpOne)), width: bigButtonWidth, height: buttonHeight)
let buttonSpace = SpreeBoardButton(frame: spaceRect, text: "space")
buttonSpace.addTarget(self, action: #selector(buttonPressed), forControlEvents: .TouchUpInside)
buttonSpace.tag = 101
self.addSubview(buttonSpace)
let returnRect = CGRect(x: self.frame.width - bigButtonWidth - edgeBuffer, y: (buttonHeight * bottomRow) + edgeBuffer + (bottomRow * (edgeBuffer * bottomUpOne)), width: bigButtonWidth, height: buttonHeight)
let buttonReturn = SpreeBoardButton(frame: returnRect, text: "return")
buttonReturn.addTarget(self, action: #selector(buttonPressed), forControlEvents: .TouchUpInside)
buttonReturn.tag = 102
self.addSubview(buttonReturn)
}
func drawNumPad() {
self.subviews.forEach({ $0.removeFromSuperview() })
// configure buttons
let buttonWidth: CGFloat = self.frame.width * 0.32
let buttonHeight: CGFloat = self.frame.height * 0.22
let edgeBuffer = self.frame.width * 0.009
// text buttons
var index = 0
for row in 0...3 {
for column in 0...2 {
if index < numPad.count {
var x = CGFloat(column) * buttonWidth + edgeBuffer + (CGFloat(column) * edgeBuffer)
let y = CGFloat(row) * buttonHeight + edgeBuffer + (CGFloat(row) * 7.5)
if index == numPad.endIndex - 1 {
x = CGFloat(column + 1) * buttonWidth + edgeBuffer + (CGFloat(column + 1) * edgeBuffer)
}
let button = SpreeBoardButton(frame: CGRect(x: x, y: y, width: buttonWidth, height: buttonHeight), text: numPad[index])
button.addTarget(self, action: #selector(buttonPressed), forControlEvents: .TouchUpInside)
button.tag = index
self.addSubview(button)
index = index + 1
}
}
}
// function buttons
let bottomRow: CGFloat = 3
let modeRect = CGRect(x: edgeBuffer, y: (buttonHeight * bottomRow) + edgeBuffer + (bottomRow * 7.5), width: buttonWidth, height: buttonHeight)
let buttonMode = SpreeBoardButton(frame: modeRect, text: "ABC")
buttonMode.addTarget(self, action: #selector(buttonPressed), forControlEvents: .TouchUpInside)
buttonMode.tag = 103
self.addSubview(buttonMode)
let deleteRect = CGRect(x: self.frame.width - buttonWidth - edgeBuffer, y: (buttonHeight * bottomRow) + edgeBuffer + (bottomRow * 7.5), width: buttonWidth, height: buttonHeight)
let buttonDelete = SpreeBoardButton(frame: deleteRect, text: "DEL")
buttonDelete.addTarget(self, action: #selector(buttonPressed), forControlEvents: .TouchUpInside)
buttonDelete.tag = 99
self.addSubview(buttonDelete)
}
func buttonPressed(sender: UIButton) {
if sender.tag == 99 {
if self.inputString.characters.count > 0 {
self.inputString.removeAtIndex(self.inputString.endIndex.predecessor())
}
} else if sender.tag == 100 {
self.delegate.dismissKeyboard()
} else if sender.tag == 101 {
self.inputString = self.inputString.stringByAppendingString(" ")
} else if sender.tag == 102 {
self.delegate.enter()
} else if sender.tag == 103 {
if inputState == .NumPad {
self.drawNormalKeyboard()
self.inputState = .Normal
} else {
self.drawNumPad()
self.inputState = .NumPad
}
} else if let char = sender.currentTitle {
self.inputString = self.inputString.stringByAppendingString(char)
}
self.delegate.inputUpdated(self.inputString)
}
}
|
mit
|
16159efb09ecb00584cc8d6f6738f347
| 41.884259 | 237 | 0.56219 | 4.414681 | false | false | false | false |
mentalfaculty/impeller
|
Sources/Metadata.swift
|
1
|
1092
|
//
// Metadata.swift
// Impeller
//
// Created by Drew McCormack on 08/12/2016.
// Copyright © 2016 Drew McCormack. All rights reserved.
//
import Foundation
public typealias UniqueIdentifier = String
typealias RepositedVersion = UInt64
public struct Metadata: Equatable {
public enum Key: String {
case version, timestamp, uniqueIdentifier, isDeleted
}
public let uniqueIdentifier: UniqueIdentifier
public internal(set) var timestamp: TimeInterval // When stored
public internal(set) var isDeleted: Bool
internal var version: RepositedVersion = 0
public init(uniqueIdentifier: UniqueIdentifier = UUID().uuidString) {
self.uniqueIdentifier = uniqueIdentifier
self.timestamp = Date.timeIntervalSinceReferenceDate
self.isDeleted = false
}
public static func == (left: Metadata, right: Metadata) -> Bool {
return left.version == right.version && left.timestamp == right.timestamp && left.uniqueIdentifier == right.uniqueIdentifier && left.isDeleted == right.isDeleted
}
}
|
mit
|
415c5e952994073a672a0d0d0fe5d0a6
| 28.486486 | 169 | 0.695692 | 4.785088 | false | false | false | false |
apple/swift-nio
|
Sources/NIOPosix/SelectorUring.swift
|
1
|
17669
|
//===----------------------------------------------------------------------===//
//
// This source file is part of the SwiftNIO open source project
//
// Copyright (c) 2021 Apple Inc. and the SwiftNIO project authors
// Licensed under Apache License v2.0
//
// See LICENSE.txt for license information
// See CONTRIBUTORS.txt for the list of SwiftNIO project authors
//
// SPDX-License-Identifier: Apache-2.0
//
//===----------------------------------------------------------------------===//
import NIOCore
#if SWIFTNIO_USE_IO_URING
#if os(Linux) || os(Android)
/// Represents the `poll` filters/events we might use from io_uring:
///
/// - `hangup` corresponds to `POLLHUP`
/// - `readHangup` corresponds to `POLLRDHUP`
/// - `input` corresponds to `POLLIN`
/// - `output` corresponds to `POLLOUT`
/// - `error` corresponds to `POLLERR`
private struct URingFilterSet: OptionSet, Equatable {
typealias RawValue = UInt8
let rawValue: RawValue
static let _none = URingFilterSet([])
static let hangup = URingFilterSet(rawValue: 1 << 0)
static let readHangup = URingFilterSet(rawValue: 1 << 1)
static let input = URingFilterSet(rawValue: 1 << 2)
static let output = URingFilterSet(rawValue: 1 << 3)
static let error = URingFilterSet(rawValue: 1 << 4)
init(rawValue: RawValue) {
self.rawValue = rawValue
}
}
extension URingFilterSet {
/// Convert NIO's `SelectorEventSet` set to a `URingFilterSet`
init(selectorEventSet: SelectorEventSet) {
var thing: URingFilterSet = [.error, .hangup]
if selectorEventSet.contains(.read) {
thing.formUnion(.input)
}
if selectorEventSet.contains(.write) {
thing.formUnion(.output)
}
if selectorEventSet.contains(.readEOF) {
thing.formUnion(.readHangup)
}
self = thing
}
}
extension SelectorEventSet {
var uringEventSet: UInt32 {
assert(self != ._none)
// POLLERR | POLLHUP is always set unconditionally anyway but it's easier to understand if we explicitly ask.
var filter: UInt32 = URing.POLLERR | URing.POLLHUP
let uringFilters = URingFilterSet(selectorEventSet: self)
if uringFilters.contains(.input) {
filter |= URing.POLLIN
}
if uringFilters.contains(.output) {
filter |= URing.POLLOUT
}
if uringFilters.contains(.readHangup) {
filter |= URing.POLLRDHUP
}
assert(filter & URing.POLLHUP != 0) // both of these are reported
assert(filter & URing.POLLERR != 0) // always and can't be masked.
return filter
}
fileprivate init(uringEvent: UInt32) {
var selectorEventSet: SelectorEventSet = ._none
if uringEvent & URing.POLLIN != 0 {
selectorEventSet.formUnion(.read)
}
if uringEvent & URing.POLLOUT != 0 {
selectorEventSet.formUnion(.write)
}
if uringEvent & URing.POLLRDHUP != 0 {
selectorEventSet.formUnion(.readEOF)
}
if uringEvent & URing.POLLHUP != 0 || uringEvent & URing.POLLERR != 0 {
selectorEventSet.formUnion(.reset)
}
self = selectorEventSet
}
}
extension Selector: _SelectorBackendProtocol {
internal func _debugPrint(_ s: @autoclosure () -> String) {
#if SWIFTNIO_IO_URING_DEBUG_SELECTOR
print("S [\(NIOThread.current)] " + s())
#endif
}
func initialiseState0() throws {
try ring.io_uring_queue_init()
self.selectorFD = ring.fd
// eventfd are always singleshot and re-register each time around
// as certain use cases of nio seems to generate superfluous wakeups.
// (at least its tested for that in some of the performance tests
// e.g. future_whenallsucceed_100k_deferred_off_loop, future_whenallcomplete_100k_deferred_off_loop
// ) - if using normal ET multishots, we would get 100k events to handle basically.
// so using single shot for wakeups makes those tests run 30-35% faster approx.
self.eventFD = try EventFd.eventfd(initval: 0, flags: Int32(EventFd.EFD_CLOEXEC | EventFd.EFD_NONBLOCK))
ring.io_uring_prep_poll_add(fileDescriptor: self.eventFD,
pollMask: URing.POLLIN,
registrationID:SelectorRegistrationID(rawValue: 0),
multishot:false) // wakeups
self.lifecycleState = .open
_debugPrint("URingSelector up and running fd [\(self.selectorFD)] wakeups on event_fd [\(self.eventFD)]")
}
func deinitAssertions0() {
assert(self.eventFD == -1, "self.eventFD == \(self.eventFD) on deinitAssertions0 deinit, forgot close?")
}
func register0<S: Selectable>(selectable: S,
fileDescriptor: CInt,
interested: SelectorEventSet,
registrationID: SelectorRegistrationID) throws {
_debugPrint("register interested \(interested) uringEventSet [\(interested.uringEventSet)] registrationID[\(registrationID)]")
self.deferredReregistrationsPending = true
ring.io_uring_prep_poll_add(fileDescriptor: fileDescriptor,
pollMask: interested.uringEventSet,
registrationID: registrationID,
submitNow: !deferReregistrations,
multishot: multishot)
}
func reregister0<S: Selectable>(selectable: S,
fileDescriptor: CInt,
oldInterested: SelectorEventSet,
newInterested: SelectorEventSet,
registrationID: SelectorRegistrationID) throws {
_debugPrint("Re-register old \(oldInterested) new \(newInterested) uringEventSet [\(oldInterested.uringEventSet)] reg.uringEventSet [\(newInterested.uringEventSet)]")
self.deferredReregistrationsPending = true
if multishot {
ring.io_uring_poll_update(fileDescriptor: fileDescriptor,
newPollmask: newInterested.uringEventSet,
oldPollmask: oldInterested.uringEventSet,
registrationID: registrationID,
submitNow: !deferReregistrations,
multishot: true)
} else {
ring.io_uring_prep_poll_remove(fileDescriptor: fileDescriptor,
pollMask: oldInterested.uringEventSet,
registrationID: registrationID,
submitNow:!deferReregistrations,
link: true) // next event linked will cancel if this event fails
ring.io_uring_prep_poll_add(fileDescriptor: fileDescriptor,
pollMask: newInterested.uringEventSet,
registrationID: registrationID,
submitNow: !deferReregistrations,
multishot: false)
}
}
func deregister0<S: Selectable>(selectable: S, fileDescriptor: CInt, oldInterested: SelectorEventSet, registrationID: SelectorRegistrationID) throws {
_debugPrint("deregister interested \(selectable) reg.interested.uringEventSet [\(oldInterested.uringEventSet)]")
self.deferredReregistrationsPending = true
ring.io_uring_prep_poll_remove(fileDescriptor: fileDescriptor,
pollMask: oldInterested.uringEventSet,
registrationID: registrationID,
submitNow:!deferReregistrations)
}
private func shouldRefreshPollForEvent(selectorEvent:SelectorEventSet) -> Bool {
if selectorEvent.contains(.read) {
// as we don't do exhaustive reads, we need to prod the kernel for
// new events, would be even better if we knew if we had read all there is
return true
}
// If the event is fully handled, we can return false to avoid reregistration for multishot polls.
return false
}
/// Apply the given `SelectorStrategy` and execute `body` once it's complete (which may produce `SelectorEvent`s to handle).
///
/// - parameters:
/// - strategy: The `SelectorStrategy` to apply
/// - body: The function to execute for each `SelectorEvent` that was produced.
func whenReady0(strategy: SelectorStrategy, onLoopBegin loopStart: () -> Void, _ body: (SelectorEvent<R>) throws -> Void) throws -> Void {
assert(self.myThread == NIOThread.current)
guard self.lifecycleState == .open else {
throw IOError(errnoCode: EBADF, reason: "can't call whenReady for selector as it's \(self.lifecycleState).")
}
var ready: Int = 0
// flush reregistration of pending modifications if needed (nop in SQPOLL mode)
// basically this elides all reregistrations and deregistrations into a single
// syscall instead of one for each. Future improvement would be to also merge
// the pending pollmasks (now each change will be queued, but we could also
// merge the masks for reregistrations) - but the most important thing is to
// only trap into the kernel once for the set of changes, so needs to be measured.
if deferReregistrations && self.deferredReregistrationsPending {
self.deferredReregistrationsPending = false
ring.io_uring_flush()
}
switch strategy {
case .now:
_debugPrint("whenReady.now")
ready = Int(ring.io_uring_peek_batch_cqe(events: events, maxevents: UInt32(eventsCapacity), multishot:multishot))
case .blockUntilTimeout(let timeAmount):
_debugPrint("whenReady.blockUntilTimeout")
ready = try Int(ring.io_uring_wait_cqe_timeout(events: events, maxevents: UInt32(eventsCapacity), timeout:timeAmount, multishot:multishot))
case .block:
_debugPrint("whenReady.block")
ready = Int(ring.io_uring_peek_batch_cqe(events: events, maxevents: UInt32(eventsCapacity), multishot:multishot)) // first try to consume any existing
if (ready <= 0) // otherwise block (only single supported, but we will use batch peek cqe next run around...
{
ready = try ring.io_uring_wait_cqe(events: events, maxevents: UInt32(eventsCapacity), multishot:multishot)
}
}
loopStart()
for i in 0..<ready {
let event = events[i]
switch event.fd {
case self.eventFD: // we don't run these as multishots to avoid tons of events when many wakeups are done
_debugPrint("wakeup successful for event.fd [\(event.fd)]")
var val = EventFd.eventfd_t()
ring.io_uring_prep_poll_add(fileDescriptor: self.eventFD,
pollMask: URing.POLLIN,
registrationID: SelectorRegistrationID(rawValue: 0),
submitNow: false,
multishot: false)
do {
_ = try EventFd.eventfd_read(fd: self.eventFD, value: &val) // consume wakeup event
_debugPrint("read val [\(val)] from event.fd [\(event.fd)]")
} catch {
}
default:
if let registration = registrations[Int(event.fd)] {
_debugPrint("We found a registration for event.fd [\(event.fd)]") // \(registration)
// The io_uring backend only has 16 bits available for the registration id
guard event.registrationID == UInt16(truncatingIfNeeded:registration.registrationID.rawValue) else {
_debugPrint("The event.registrationID [\(event.registrationID)] != registration.selectableregistrationID [\(registration.registrationID)], skipping to next event")
continue
}
var selectorEvent = SelectorEventSet(uringEvent: event.pollMask)
_debugPrint("selectorEvent [\(selectorEvent)] registration.interested [\(registration.interested)]")
// we only want what the user is currently registered for & what we got
selectorEvent = selectorEvent.intersection(registration.interested)
_debugPrint("intersection [\(selectorEvent)]")
if selectorEvent.contains(.readEOF) {
_debugPrint("selectorEvent.contains(.readEOF) [\(selectorEvent.contains(.readEOF))]")
}
if multishot == false { // must be before guard, otherwise lost wake
ring.io_uring_prep_poll_add(fileDescriptor: event.fd,
pollMask: registration.interested.uringEventSet,
registrationID: registration.registrationID,
submitNow: false,
multishot: false)
if event.pollCancelled {
_debugPrint("Received event.pollCancelled")
}
}
guard selectorEvent != ._none else {
_debugPrint("selectorEvent != ._none / [\(selectorEvent)] [\(registration.interested)] [\(SelectorEventSet(uringEvent: event.pollMask))] [\(event.pollMask)] [\(event.fd)]")
continue
}
// This is only needed due to the edge triggered nature of liburing, possibly
// we can get away with only updating (force triggering an event if available) for
// partial reads (where we currently give up after N iterations)
if multishot && self.shouldRefreshPollForEvent(selectorEvent:selectorEvent) { // can be after guard as it is multishot
ring.io_uring_poll_update(fileDescriptor: event.fd,
newPollmask: registration.interested.uringEventSet,
oldPollmask: registration.interested.uringEventSet,
registrationID: registration.registrationID,
submitNow: false)
}
_debugPrint("running body [\(NIOThread.current)] \(selectorEvent) \(SelectorEventSet(uringEvent: event.pollMask))")
try body((SelectorEvent(io: selectorEvent, registration: registration)))
} else { // remove any polling if we don't have a registration for it
_debugPrint("We had no registration for event.fd [\(event.fd)] event.pollMask [\(event.pollMask)] event.registrationID [\(event.registrationID)], it should be deregistered already")
if multishot == false {
ring.io_uring_prep_poll_remove(fileDescriptor: event.fd,
pollMask: event.pollMask,
registrationID: SelectorRegistrationID(rawValue: UInt32(event.registrationID)),
submitNow: false)
}
}
}
}
self.deferredReregistrationsPending = false // none pending as we will flush here
ring.io_uring_flush() // flush reregisteration of the polls if needed (nop in SQPOLL mode)
growEventArrayIfNeeded(ready: ready)
}
/// Close the `Selector`.
///
/// After closing the `Selector` it's no longer possible to use it.
public func close0() throws {
self.externalSelectorFDLock.withLock {
// We try! all of the closes because close can only fail in the following ways:
// - EINTR, which we eat in Posix.close
// - EIO, which can only happen for on-disk files
// - EBADF, which can't happen here because we would crash as EBADF is marked unacceptable
// Therefore, we assert here that close will always succeed and if not, that's a NIO bug we need to know
// about.
ring.io_uring_queue_exit() // This closes the ring selector fd for us
self.selectorFD = -1
try! Posix.close(descriptor: self.eventFD)
self.eventFD = -1
}
return
}
/* attention, this may (will!) be called from outside the event loop, ie. can't access mutable shared state (such as `self.open`) */
func wakeup0() throws {
assert(NIOThread.current != self.myThread)
try self.externalSelectorFDLock.withLock {
guard self.eventFD >= 0 else {
throw EventLoopError.shutdown
}
_ = try EventFd.eventfd_write(fd: self.eventFD, value: 1)
}
}
}
#endif
#endif
|
apache-2.0
|
ad154c2a98afd429913cd830d8062a8e
| 47.674931 | 201 | 0.568793 | 4.807891 | false | false | false | false |
wireapp/wire-ios-data-model
|
Tests/Source/ManagedObjectContext/NSManagedObjectContextTests+EncryptionAtRest.swift
|
1
|
11181
|
//
// Wire
// Copyright (C) 2017 Wire Swiss GmbH
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see http://www.gnu.org/licenses/.
//
import Foundation
import XCTest
@testable import WireDataModel
class NSManagedObjectContextTests_EncryptionAtRest: ZMBaseManagedObjectTest {
private typealias MigrationError = NSManagedObjectContext.MigrationError
override func setUp() {
super.setUp()
createSelfClient(onMOC: uiMOC)
}
private func fetchObjects<T: ZMManagedObject>() throws -> [T] {
let request = NSFetchRequest<T>(entityName: T.entityName())
request.returnsObjectsAsFaults = false
return try request.execute()
}
// MARK: - Positive Tests
// MARK: - Message Content
// @SF.Storage @TSFI.FS-IOS @TSFI.Enclave-IOS @S0.1 @S0.2
// Make sure that message content is encrypted when EAR is enabled
func testExistingMessageContentIsEncrypted_WhenEarIsEnabled() throws {
// Given
let conversation = createConversation(in: uiMOC)
try conversation.appendText(content: "Beep bloop")
try uiMOC.performGroupedAndWait { moc in
let results: [ZMGenericMessageData] = try self.fetchObjects()
guard let messageData = results.first else {
XCTFail("Could not find message data.")
return
}
// Then
XCTAssertFalse(messageData.isEncrypted)
XCTAssertEqual(messageData.unencryptedContent, "Beep bloop")
XCTAssertFalse(moc.encryptMessagesAtRest)
// When
XCTAssertNoThrow(try moc.enableEncryptionAtRest(encryptionKeys: self.validEncryptionKeys))
// Then
XCTAssertTrue(messageData.isEncrypted)
XCTAssertEqual(messageData.unencryptedContent, "Beep bloop")
XCTAssertTrue(moc.encryptMessagesAtRest)
}
}
func testExistingMessageContentIsDecrypted_WhenEarIsDisabled() throws {
// Given
let validEncryptionKeys = self.validEncryptionKeys
try uiMOC.enableEncryptionAtRest(encryptionKeys: validEncryptionKeys, skipMigration: true)
let conversation = createConversation(in: uiMOC)
try conversation.appendText(content: "Beep bloop")
try uiMOC.performGroupedAndWait { moc in
let results: [ZMGenericMessageData] = try self.fetchObjects()
guard let messageData = results.first else {
XCTFail("Could not find message data.")
return
}
// Then
XCTAssertTrue(messageData.isEncrypted)
XCTAssertEqual(messageData.unencryptedContent, "Beep bloop")
XCTAssertTrue(moc.encryptMessagesAtRest)
// When
XCTAssertNoThrow(try moc.disableEncryptionAtRest(encryptionKeys: validEncryptionKeys))
// Then
XCTAssertFalse(messageData.isEncrypted)
XCTAssertEqual(messageData.unencryptedContent, "Beep bloop")
XCTAssertFalse(moc.encryptMessagesAtRest)
}
}
// MARK: - Normalized Text
// @SF.Storage @TSFI.FS-IOS @TSFI.Enclave-IOS @S0.1 @S0.2
// Make sure that message content normalized for text search is also encrypted when EAR is enabled
func testNormalizedMessageContentIsCleared_WhenEarIsEnabled() throws {
// Given
let conversation = createConversation(in: uiMOC)
let message = try conversation.appendText(content: "Beep bloop") as! ZMMessage
try uiMOC.performGroupedAndWait { moc in
// Then
XCTAssertNotNil(message.normalizedText)
XCTAssertEqual(message.normalizedText?.isEmpty, false)
XCTAssertFalse(moc.encryptMessagesAtRest)
// When
XCTAssertNoThrow(try moc.enableEncryptionAtRest(encryptionKeys: self.validEncryptionKeys))
// Then
XCTAssertNotNil(message.normalizedText)
XCTAssertEqual(message.normalizedText?.isEmpty, true)
XCTAssertTrue(moc.encryptMessagesAtRest)
}
}
func testNormalizedMessageContentIsUpdated_WhenEarIsDisabled() throws {
// Given
let validEncryptionKeys = self.validEncryptionKeys
try uiMOC.enableEncryptionAtRest(encryptionKeys: validEncryptionKeys, skipMigration: true)
let conversation = createConversation(in: uiMOC)
let message = try conversation.appendText(content: "Beep bloop") as! ZMMessage
try uiMOC.performGroupedAndWait { moc in
// Then
XCTAssertNotNil(message.normalizedText)
XCTAssertEqual(message.normalizedText?.isEmpty, true)
XCTAssertTrue(moc.encryptMessagesAtRest)
// When
XCTAssertNoThrow(try moc.disableEncryptionAtRest(encryptionKeys: validEncryptionKeys))
// Then
XCTAssertNotNil(message.normalizedText)
XCTAssertEqual(message.normalizedText?.isEmpty, false)
XCTAssertFalse(moc.encryptMessagesAtRest)
}
}
// MARK: - Draft messages
// @SF.Storage @TSFI.FS-IOS @TSFI.Enclave-IOS @S0.1 @S0.2
// Make sure that message content that is drafted but not send by the user yet is also encrypted
// when EAR is enabled
func testDraftMessageContentIsEncrypted_WhenEarIsEnabled() throws {
// Given
let conversation = createConversation(in: uiMOC)
conversation.draftMessage = DraftMessage(text: "Beep bloop", mentions: [], quote: nil)
try uiMOC.performGroupedAndWait { moc in
// Then
XCTAssertTrue(conversation.hasDraftMessage)
XCTAssertFalse(conversation.hasEncryptedDraftMessageData)
XCTAssertEqual(conversation.unencryptedDraftMessageContent, "Beep bloop")
XCTAssertFalse(moc.encryptMessagesAtRest)
// When
XCTAssertNoThrow(try moc.enableEncryptionAtRest(encryptionKeys: self.validEncryptionKeys))
// Then
XCTAssertTrue(conversation.hasEncryptedDraftMessageData)
XCTAssertEqual(conversation.unencryptedDraftMessageContent, "Beep bloop")
XCTAssertTrue(moc.encryptMessagesAtRest)
}
}
func testDraftMessageContentIsDecrypted_WhenEarIsDisabled() throws {
// Given
let validEncryptionKeys = self.validEncryptionKeys
try uiMOC.enableEncryptionAtRest(encryptionKeys: validEncryptionKeys, skipMigration: true)
let conversation = createConversation(in: uiMOC)
conversation.draftMessage = DraftMessage(text: "Beep bloop", mentions: [], quote: nil)
try uiMOC.performGroupedAndWait { moc in
// Then
XCTAssertTrue(conversation.hasDraftMessage)
XCTAssertTrue(conversation.hasEncryptedDraftMessageData)
XCTAssertEqual(conversation.unencryptedDraftMessageContent, "Beep bloop")
XCTAssertTrue(moc.encryptMessagesAtRest)
// When
XCTAssertNoThrow(try moc.disableEncryptionAtRest(encryptionKeys: validEncryptionKeys))
// Then
XCTAssertTrue(conversation.hasDraftMessage)
XCTAssertFalse(conversation.hasEncryptedDraftMessageData)
XCTAssertEqual(conversation.unencryptedDraftMessageContent, "Beep bloop")
XCTAssertFalse(moc.encryptMessagesAtRest)
}
}
// MARK: - Negative Tests
// @SF.Storage @TSFI.FS-IOS @TSFI.Enclave-IOS @S0.1 @S0.2
func testItThrowsAnError_WhenDatabaseKeyIsMissing_WhenEarIsEnabled() throws {
// Given
uiMOC.encryptionKeys = nil
try uiMOC.performGroupedAndWait { moc in
// When
XCTAssertThrowsError(try moc.enableEncryptionAtRest(encryptionKeys: try moc.getEncryptionKeys())) { error in
// Then
guard case MigrationError.missingDatabaseKey = error else {
return XCTFail("Unexpected error thrown: \(error.localizedDescription)")
}
}
XCTAssertFalse(moc.encryptMessagesAtRest)
}
}
func testItThrowsAnError_WhenDatabaseKeyIsMissing_WhenEarIsDisabled() throws {
// Given
let validEncryptionKeys = self.validEncryptionKeys
try uiMOC.enableEncryptionAtRest(encryptionKeys: validEncryptionKeys, skipMigration: true)
uiMOC.encryptionKeys = nil
try uiMOC.performGroupedAndWait { moc in
// When
XCTAssertThrowsError(try moc.disableEncryptionAtRest(encryptionKeys: try self.uiMOC.getEncryptionKeys())) { error in
// Then
guard case MigrationError.missingDatabaseKey = error else {
return XCTFail("Unexpected error thrown: \(error.localizedDescription)")
}
}
XCTAssertTrue(moc.encryptMessagesAtRest)
}
}
func testMigrationIsCanceled_WhenASingleInstanceFailsToMigrate() throws {
// Given
let encryptionKeys1 = validEncryptionKeys
let encryptionKeys2 = validEncryptionKeys
uiMOC.encryptMessagesAtRest = true
let conversation = createConversation(in: uiMOC)
uiMOC.encryptionKeys = encryptionKeys1
try conversation.appendText(content: "Beep bloop")
uiMOC.encryptionKeys = encryptionKeys2
try conversation.appendText(content: "buzz buzzz")
try uiMOC.performGroupedAndWait { moc in
let results: [ZMGenericMessageData] = try self.fetchObjects()
XCTAssertEqual(results.count, 2)
XCTAssertTrue(moc.encryptMessagesAtRest)
// When
XCTAssertThrowsError(try moc.disableEncryptionAtRest(encryptionKeys: encryptionKeys1)) { error in
// Then
switch error {
case let MigrationError.failedToMigrateInstances(type, _):
XCTAssertEqual(type.entityName(), ZMGenericMessageData.entityName())
default:
XCTFail("Unexpected error thrown: \(error.localizedDescription)")
}
}
// Then
XCTAssertTrue(moc.encryptMessagesAtRest)
}
}
}
// MARK: - Helper Extensions
private extension ZMGenericMessageData {
var unencryptedContent: String? {
return underlyingMessage?.text.content
}
}
private extension ZMConversation {
var hasEncryptedDraftMessageData: Bool {
return draftMessageData != nil && draftMessageNonce != nil
}
var unencryptedDraftMessageContent: String? {
return draftMessage?.text
}
}
|
gpl-3.0
|
51d9666331a4fbe234643681659388d1
| 35.90099 | 128 | 0.665951 | 5.157288 | false | false | false | false |
shengzhc/Demo
|
DemoApp/DemoApp/Demo_SCModalDialog.swift
|
1
|
2680
|
//
// Demo_SCModalDialog.swift
// DemoApp
//
// Created by Shengzhe Chen on 11/30/14.
// Copyright (c) 2014 Shengzhe Chen. All rights reserved.
//
import Foundation
import UIKit
import SCModalDialog
class Demo_ModalDialogViewController: UIViewController, SCModalDialogPresentationControllerDelegate
{
lazy var customTransitioningDelegate: Demo_SCModalDialogTransitioningDelegate = {
var delegation = Demo_SCModalDialogTransitioningDelegate()
return delegation
}()
override func viewWillAppear(animated: Bool)
{
super.viewWillAppear(animated)
self.title = "Demo SCModalDialogViewController"
}
@IBAction func hitButtonClicked(sender: AnyObject)
{
var controller = UIViewController()
controller.view.backgroundColor = UIColor.whiteColor()
controller.view.layer.cornerRadius = 5.0
controller.view.layer.masksToBounds = true
controller.transitioningDelegate = self.customTransitioningDelegate
controller.modalPresentationStyle = .Custom
self.presentViewController(controller, animated: true, completion: nil)
}
func didDismissEnd(sender: AnyObject?)
{
println(__FUNCTION__)
}
func didPresentationEnd(sender: AnyObject?)
{
println(__FUNCTION__)
}
}
class Demo_SCModalDialogPresentationController: SCModalDialogPresentationController
{
override func setupCloseButton()
{
self.closeButton.setTitle(nil, forState: .Normal)
self.closeButton.setBackgroundImage(DemoIcons.closeIcon, forState: .Normal)
self.closeButton.sizeToFit()
}
override func didCloseButtonClicked(sender: AnyObject?)
{
self.presentingViewController.dismissViewControllerAnimated(true, completion: nil)
}
}
class Demo_SCModalDialogTransitioningDelegate: SCModalDialogTransitioningDelegate
{
override func presentationControllerForPresentedViewController(presented: UIViewController, presentingViewController presenting: UIViewController!, sourceViewController source: UIViewController) -> UIPresentationController?
{
var presentationController = Demo_SCModalDialogPresentationController(presentedViewController: presented, presentingViewController: presenting)
if let delegation = presenting as? SCModalDialogPresentationControllerDelegate {
presentationController.presentationControllerDelegate = delegation
} else if let delegation = source as? SCModalDialogPresentationControllerDelegate {
presentationController.presentationControllerDelegate = delegation
}
return presentationController
}
}
|
mit
|
f7c03aceb7a8e218108f9b81987e7a1d
| 34.733333 | 227 | 0.741791 | 5.690021 | false | false | false | false |
yoichitgy/swipe
|
browser/SwipeExporter.swift
|
2
|
7804
|
//
// SwipeExporter.swift
// sample
//
// Created by satoshi on 8/19/16.
// Copyright © 2016 Satoshi Nakajima. All rights reserved.
//
import UIKit
import ImageIO
import MobileCoreServices
import AVFoundation
class SwipeExporter: NSObject {
enum Error: Swift.Error {
case FailedToCreate
case FailedToFinalize
}
let swipeViewController:SwipeViewController
let fps:Int
let resolution:CGFloat
var progress = 0.0 as CGFloat // Output: Proress from 0.0 to 1.0
var outputSize = CGSize.zero // Output: Size of generated GIF/video
private var iFrame = 0
init(swipeViewController:SwipeViewController, fps:Int, resolution:CGFloat = 720.0) {
self.swipeViewController = swipeViewController
self.fps = fps
self.resolution = resolution
}
func exportAsGifAnimation(_ fileURL:URL, startPage:Int, pageCount:Int, progress:@escaping (_ complete:Bool, _ error:Swift.Error?)->Void) {
guard let idst = CGImageDestinationCreateWithURL(fileURL as CFURL, kUTTypeGIF, pageCount * fps + 1, nil) else {
return progress(false, Error.FailedToCreate)
}
CGImageDestinationSetProperties(idst, [String(kCGImagePropertyGIFDictionary):
[String(kCGImagePropertyGIFLoopCount):0]] as CFDictionary)
iFrame = 0
outputSize = swipeViewController.view.frame.size
self.processFrame(idst, startPage:startPage, pageCount: pageCount, progress:progress)
}
func processFrame(_ idst:CGImageDestination, startPage:Int, pageCount:Int, progress:@escaping (_ complete:Bool, _ error:Swift.Error?)->Void) {
self.progress = CGFloat(iFrame) / CGFloat(fps) / CGFloat(pageCount)
swipeViewController.scrollTo(CGFloat(startPage) + CGFloat(iFrame) / CGFloat(fps))
// HACK: This delay is not 100% reliable, but is sufficient practically.
DispatchQueue.main.asyncAfter(deadline: .now() + .milliseconds(100)) {
progress(false, nil)
let presentationLayer = self.swipeViewController.view.layer.presentation()!
UIGraphicsBeginImageContext(self.swipeViewController.view.frame.size); defer {
UIGraphicsEndImageContext()
}
presentationLayer.render(in: UIGraphicsGetCurrentContext()!)
let image = UIGraphicsGetImageFromCurrentImageContext()!
CGImageDestinationAddImage(idst, image.cgImage!, [String(kCGImagePropertyGIFDictionary):
[String(kCGImagePropertyGIFDelayTime):0.2]] as CFDictionary)
self.iFrame += 1
if self.iFrame < pageCount * self.fps + 1 {
self.processFrame(idst, startPage:startPage, pageCount: pageCount, progress:progress)
} else {
if CGImageDestinationFinalize(idst) {
progress(true, nil)
} else {
progress(false, Error.FailedToFinalize)
}
}
}
}
func exportAsMovie(_ fileURL:URL, startPage:Int, pageCount:Int?, progress:@escaping (_ complete:Bool, _ error:Swift.Error?)->Void) {
// AVAssetWrite will fail if the file already exists
let manager = FileManager.default
if manager.fileExists(atPath: fileURL.path) {
try! manager.removeItem(at: fileURL)
}
let limit:Int
if let pageCount = pageCount, startPage + pageCount < swipeViewController.book.pages.count {
limit = pageCount * self.fps + 1
} else {
limit = (swipeViewController.book.pages.count - startPage - 1) * self.fps + 1
}
let viewSize = swipeViewController.view.frame.size
let scale = min(resolution / min(viewSize.width, viewSize.height), swipeViewController.view.contentScaleFactor)
outputSize = CGSize(width: viewSize.width * scale, height: viewSize.height * scale)
do {
let writer = try AVAssetWriter(url: fileURL, fileType: AVFileTypeQuickTimeMovie)
let input = AVAssetWriterInput(mediaType: AVMediaTypeVideo, outputSettings: [
AVVideoCodecKey : AVVideoCodecH264,
AVVideoWidthKey : outputSize.width,
AVVideoHeightKey : outputSize.height
])
let adaptor = AVAssetWriterInputPixelBufferAdaptor(assetWriterInput: input, sourcePixelBufferAttributes: [
kCVPixelBufferPixelFormatTypeKey as String: NSNumber(value: kCVPixelFormatType_32ARGB),
kCVPixelBufferWidthKey as String: outputSize.width,
kCVPixelBufferHeightKey as String: outputSize.height,
])
writer.add(input)
iFrame = 0
guard writer.startWriting() else {
return progress(false, Error.FailedToFinalize)
}
writer.startSession(atSourceTime: kCMTimeZero)
self.swipeViewController.scrollTo(CGFloat(startPage))
input.requestMediaDataWhenReady(on: DispatchQueue.main) {
guard input.isReadyForMoreMediaData else {
return // Not ready. Just wait.
}
self.progress = 0.5 * CGFloat(self.iFrame) / CGFloat(limit)
progress(false, nil)
var pixelBufferX: CVPixelBuffer? = nil
let status: CVReturn = CVPixelBufferPoolCreatePixelBuffer(kCFAllocatorDefault, adaptor.pixelBufferPool!, &pixelBufferX)
guard let managedPixelBuffer = pixelBufferX, status == 0 else {
print("failed to allocate pixel buffer")
writer.cancelWriting()
return progress(false, Error.FailedToCreate)
}
CVPixelBufferLockBaseAddress(managedPixelBuffer, CVPixelBufferLockFlags(rawValue: CVOptionFlags(0)))
let data = CVPixelBufferGetBaseAddress(managedPixelBuffer)
let rgbColorSpace = CGColorSpaceCreateDeviceRGB()
if let context = CGContext(data: data, width: Int(self.outputSize.width), height: Int(self.outputSize.height), bitsPerComponent: 8, bytesPerRow: CVPixelBufferGetBytesPerRow(managedPixelBuffer), space: rgbColorSpace, bitmapInfo: CGImageAlphaInfo.premultipliedFirst.rawValue) {
let xf = CGAffineTransform(scaleX: scale, y: -scale)
context.concatenate(xf.translatedBy(x: 0, y: -viewSize.height))
let presentationLayer = self.swipeViewController.view.layer.presentation()!
presentationLayer.render(in: context)
}
CVPixelBufferUnlockBaseAddress(managedPixelBuffer, CVPixelBufferLockFlags(rawValue: CVOptionFlags(0)))
let presentationTime = CMTimeMake(Int64(self.iFrame), Int32(self.fps))
if !adaptor.append(managedPixelBuffer, withPresentationTime: presentationTime) {
writer.cancelWriting()
return progress(false, Error.FailedToCreate)
}
self.iFrame += 1
if self.iFrame < limit {
self.swipeViewController.scrollTo(CGFloat(startPage) + CGFloat(self.iFrame) / CGFloat(self.fps))
} else {
input.markAsFinished()
print("SwipeExporter: finishWritingWithCompletionHandler")
writer.finishWriting(completionHandler: {
DispatchQueue.main.async {
progress(true, nil)
}
})
}
}
} catch let error {
progress(false, error)
}
}
}
|
mit
|
4f837ad79eb46aa74c06589c1310f241
| 46.290909 | 291 | 0.61989 | 5.319018 | false | false | false | false |
RoRoche/iOSSwiftStarter
|
iOSSwiftStarter/Pods/CoreStore/CoreStore/Fetching and Querying/Concrete Clauses/OrderBy.swift
|
2
|
4330
|
//
// OrderBy.swift
// CoreStore
//
// Copyright © 2015 John Rommel Estropia
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
//
import Foundation
import CoreData
public func +(left: OrderBy, right: OrderBy) -> OrderBy {
return OrderBy(left.sortDescriptors + right.sortDescriptors)
}
public func +=(inout left: OrderBy, right: OrderBy) {
left = left + right
}
// MARK: - KeyPath
public typealias KeyPath = String
// MARK: - SortKey
/**
The `SortKey` is passed to the `OrderBy` clause to indicate the sort keys and their sort direction.
*/
public enum SortKey {
/**
Indicates that the `KeyPath` should be sorted in ascending order
*/
case Ascending(KeyPath)
/**
Indicates that the `KeyPath` should be sorted in descending order
*/
case Descending(KeyPath)
}
// MARK: - OrderBy
/**
The `OrderBy` clause specifies the sort order for results for a fetch or a query.
*/
public struct OrderBy: FetchClause, QueryClause, DeleteClause {
/**
Initializes a `OrderBy` clause with a list of sort descriptors
- parameter sortDescriptors: a series of `NSSortDescriptor`s
*/
public init(_ sortDescriptors: [NSSortDescriptor]) {
self.sortDescriptors = sortDescriptors
}
/**
Initializes a `OrderBy` clause with an empty list of sort descriptors
*/
public init() {
self.init([NSSortDescriptor]())
}
/**
Initializes a `OrderBy` clause with a single sort descriptor
- parameter sortDescriptor: a `NSSortDescriptor`
*/
public init(_ sortDescriptor: NSSortDescriptor) {
self.init([sortDescriptor])
}
/**
Initializes a `OrderBy` clause with a series of `SortKey`s
- parameter sortKey: a series of `SortKey`s
*/
public init(_ sortKey: [SortKey]) {
self.init(
sortKey.map { sortKey -> NSSortDescriptor in
switch sortKey {
case .Ascending(let keyPath):
return NSSortDescriptor(key: keyPath, ascending: true)
case .Descending(let keyPath):
return NSSortDescriptor(key: keyPath, ascending: false)
}
}
)
}
/**
Initializes a `OrderBy` clause with a series of `SortKey`s
- parameter sortKey: a single `SortKey`
- parameter sortKeys: a series of `SortKey`s
*/
public init(_ sortKey: SortKey, _ sortKeys: SortKey...) {
self.init([sortKey] + sortKeys)
}
public let sortDescriptors: [NSSortDescriptor]
// MARK: FetchClause, QueryClause, DeleteClause
public func applyToFetchRequest(fetchRequest: NSFetchRequest) {
if let sortDescriptors = fetchRequest.sortDescriptors where sortDescriptors != self.sortDescriptors {
CoreStore.log(
.Warning,
message: "Existing sortDescriptors for the \(typeName(NSFetchRequest)) was overwritten by \(typeName(self)) query clause."
)
}
fetchRequest.sortDescriptors = self.sortDescriptors
}
}
|
apache-2.0
|
291ef888718221bdfbe3d439dfa8b487
| 27.86 | 138 | 0.633172 | 4.930524 | false | false | false | false |
tiusender/JVToolkit
|
JVToolkit/Classes/JVSimpleCollectionViewController.swift
|
1
|
2548
|
//
// JVSimpleCollectionViewController.swift
// Pods
//
// Created by Jorge Villalobos Beato on 12/21/16.
//
//
import Foundation
open class JVSimpleCollectionViewController: UICollectionViewController, JVSimplifiedCVCProtocol, JVRemotableViewController {
open func fetchRemoteData(_ completion: @escaping (JVResult<Any>) -> Void) {
completion(JVResult.Failure(RemoteError.unimplemented))
}
public typealias T = Any
public var useRefreshControl: Bool = true
public var items:[T] = []
open var cellIdentifier:String = ""
public func itemForIndexPath(_ indexPath:IndexPath) -> T? {
if items.count > indexPath.row {
return items[indexPath.row] as T
} else {
return nil
}
}
open func configureCell<T>(_ cell:UICollectionViewCell, item:T?, indexPath:IndexPath) {
}
open func cellDidDisappear(_ cell:UICollectionViewCell, indexPath:IndexPath) {
}
override open func viewDidLoad() {
self.collectionView?.delegate = self
self.collectionView?.dataSource = self
self.cellIdentifier = "cell"
if let collectionView = collectionView {
self.customViewDidLoad(collectionView)
}
super.viewDidLoad()
}
override open func viewWillDisappear(_ animated: Bool) {
self.customViewWillDisappear(animated)
super.viewWillDisappear(animated)
}
public func reloadData() {
self.collectionView?.reloadData()
}
// MARK: - Collection View Controller cell management
override open func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell
{
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: self.cellIdentifier, for: indexPath)
let item = self.itemForIndexPath(indexPath)
self.configureCell(cell, item:item, indexPath: indexPath)
return cell
}
override open func collectionView(_ collectionView: UICollectionView, didEndDisplaying cell: UICollectionViewCell, forItemAt indexPath: IndexPath) {
if collectionView.indexPathsForVisibleItems.index(of: indexPath) == nil {
self.cellDidDisappear(cell, indexPath: indexPath)
}
}
override open func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int
{
return items.count
}
}
|
mit
|
c8d2d56212d76352dd97968fd1f19227
| 29.333333 | 152 | 0.659341 | 5.421277 | false | false | false | false |
shoheiyokoyama/Koyomi
|
Koyomi/UIColorExtension.swift
|
1
|
1781
|
//
// UIColorExtension.swift
// Pods
//
// Created by Shohei Yokoyama on 2016/10/11.
//
//
import UIKit
extension UIColor {
convenience init(hex: Int, alpha: CGFloat = 1.0) {
let red = CGFloat((hex & 0xFF0000) >> 16) / 255.0
let green = CGFloat((hex & 0xFF00) >> 8) / 255.0
let blue = CGFloat((hex & 0xFF)) / 255.0
self.init(red: red, green: green, blue: blue, alpha: alpha)
}
struct KoyomiColor {
// Using [iOS 7 colors] as reference.
// http://ios7colors.com/
static let lightBlack: UIColor = .init(hex: 0x4A4A4A)
static let black: UIColor = .init(hex: 0x2B2B2B)
static let darkBlack: UIColor = .init(hex: 0x1F1F21)
static let lightGray: UIColor = .init(hex: 0xDBDDDE)
static let darkGray: UIColor = .init(hex: 0x8E8E93)
static let lightYellow: UIColor = .init(hex: 0xFFDB4C)
static let lightPurple: UIColor = .init(hex: 0xC86EDF)
static let lightGreen: UIColor = .init(hex: 0xA4E786)
static let lightPink: UIColor = .init(hex: 0xFFD3E0)
// Using [iOS Human Interface Guidelines] as reference.
// https://developer.apple.com/ios/human-interface-guidelines/visual-design/color/
static let red: UIColor = .init(hex: 0xff3b30)
static let orange: UIColor = .init(hex: 0xff9500)
static let green: UIColor = .init(hex: 0x4cd964)
static let blue: UIColor = .init(hex: 0x007aff)
static let purple: UIColor = .init(hex: 0x5856d6)
static let yellow: UIColor = .init(hex: 0xffcc00)
static let tealBlue: UIColor = .init(hex: 0x5ac8fa)
static let pink: UIColor = .init(hex: 0xff2d55)
}
}
|
mit
|
5061ad48fdd054a0d95f2000d4aa4331
| 37.717391 | 90 | 0.59854 | 3.292052 | false | false | false | false |
ucotta/BrilliantTemplate
|
Sources/BrilliantTemplate/filters/FilterString.swift
|
1
|
2846
|
//
// Created by Ubaldo Cotta on 4/1/17.
//
import Foundation
func filterString(value _val: String, filters _filters: [String]) -> (value: String, result: FilterAction, extra: String?) {
var filters = _filters
var value: String = _val
var result: FilterAction = .replace
var variable: String? = nil
var escapeMethod = "htmlencode"
filters.remove(at: 0)
while filters.count > 0 {
var filter: String = filters.remove(at: 0)
if filter.isEmpty {
continue
}
switch filter {
case "date":
// reset and send it to filterDate
filters.insert("date", at: 0)
return filterDate(value: getDate(from: value), filters: filters)
case "+":
if result == .replace {
result = .plus
}
case "raw":
escapeMethod = "raw"
case "urlencode":
escapeMethod = "urlencode"
case "htmlencode":
escapeMethod = "htmlencode"
case "notempty", "true":
result = value.isEmpty ? .removeNode : .remainNodes
case "empty", "false":
result = value.isEmpty ? .remainNodes : .removeNode
case "isnil":
result = .removeNode
case "notnil":
result = .remainNodes
case "cap":
value = value.capitalized
case "upper":
value = value.uppercased()
case "lower":
value = value.lowercased()
case "size":
// Return the strings's size
value = String(value.characters.count)
default:
// Comparable filter has two parts, first character is operator, the rest are value to by compared.
let c: Character = filter.characters.popFirst()!
switch c {
case "=":
result = value == filter ? .remainNodes : .removeNode
case "<":
result = value < filter ? .remainNodes : .removeNode
case ">":
result = value > filter ? .remainNodes : .removeNode
case "!":
result = value < filter ? .remainNodes : .removeNode
case "~":
variable = filter
result = .replaceVariable
case "?" where !value.isEmpty:
value = filter
case "?":
continue
default:
return (value: "filter: \(c)\(filter) not supported", result: .replace, extra: variable)
}
}
}
if escapeMethod == "htmlencode" {
value = value.htmlEscape()
} else if escapeMethod == "urlencode" {
//value = value.stringByEncodingURL
}
return (value: value, result: result, extra: variable)
}
|
apache-2.0
|
ff46a33d46bbdff65679e881582f2afe
| 25.849057 | 124 | 0.513352 | 4.657938 | false | false | false | false |
i-schuetz/SwiftCharts
|
Examples/Examples/HelloWorld.swift
|
1
|
3674
|
//
// HelloWorld.swift
// SwiftCharts
//
// Created by ischuetz on 05/05/15.
// Copyright (c) 2015 ivanschuetz. All rights reserved.
//
import UIKit
import SwiftCharts
class HelloWorld: UIViewController {
fileprivate var chart: Chart? // arc
override func viewDidLoad() {
super.viewDidLoad()
// map model data to chart points
let chartPoints: [ChartPoint] = [(2, 2), (4, 4), (6, 6), (8, 8), (8, 10), (15, 15)].map{ChartPoint(x: ChartAxisValueInt($0.0), y: ChartAxisValueInt($0.1))}
let labelSettings = ChartLabelSettings(font: ExamplesDefaults.labelFont)
let generator = ChartAxisGeneratorMultiplier(2)
let labelsGenerator = ChartAxisLabelsGeneratorFunc {scalar in
return ChartAxisLabel(text: "\(scalar)", settings: labelSettings)
}
let xGenerator = ChartAxisGeneratorMultiplier(2)
let xModel = ChartAxisModel(firstModelValue: 0, lastModelValue: 16, axisTitleLabels: [ChartAxisLabel(text: "Axis title", settings: labelSettings)], axisValuesGenerator: xGenerator, labelsGenerator: labelsGenerator)
let yModel = ChartAxisModel(firstModelValue: 0, lastModelValue: 16, axisTitleLabels: [ChartAxisLabel(text: "Axis title", settings: labelSettings.defaultVertical())], axisValuesGenerator: generator, labelsGenerator: labelsGenerator)
let chartFrame = ExamplesDefaults.chartFrame(view.bounds)
let chartSettings = ExamplesDefaults.chartSettingsWithPanZoom
// generate axes layers and calculate chart inner frame, based on the axis models
let coordsSpace = ChartCoordsSpaceLeftBottomSingleAxis(chartSettings: chartSettings, chartFrame: chartFrame, xModel: xModel, yModel: yModel)
let (xAxisLayer, yAxisLayer, innerFrame) = (coordsSpace.xAxisLayer, coordsSpace.yAxisLayer, coordsSpace.chartInnerFrame)
// create layer with guidelines
let guidelinesLayerSettings = ChartGuideLinesDottedLayerSettings(linesColor: UIColor.black, linesWidth: ExamplesDefaults.guidelinesWidth)
let guidelinesLayer = ChartGuideLinesDottedLayer(xAxisLayer: xAxisLayer, yAxisLayer: yAxisLayer, settings: guidelinesLayerSettings)
// view generator - this is a function that creates a view for each chartpoint
let viewGenerator = {(chartPointModel: ChartPointLayerModel, layer: ChartPointsViewsLayer, chart: Chart) -> UIView? in
let viewSize: CGFloat = Env.iPad ? 30 : 20
let center = chartPointModel.screenLoc
let label = UILabel(frame: CGRect(x: center.x - viewSize / 2, y: center.y - viewSize / 2, width: viewSize, height: viewSize))
label.backgroundColor = UIColor.green
label.textAlignment = NSTextAlignment.center
label.text = chartPointModel.chartPoint.y.description
label.font = ExamplesDefaults.labelFont
return label
}
// create layer that uses viewGenerator to display chartpoints
let chartPointsLayer = ChartPointsViewsLayer(xAxis: xAxisLayer.axis, yAxis: yAxisLayer.axis, chartPoints: chartPoints, viewGenerator: viewGenerator, mode: .translate)
// create chart instance with frame and layers
let chart = Chart(
frame: chartFrame,
innerFrame: innerFrame,
settings: chartSettings,
layers: [
xAxisLayer,
yAxisLayer,
guidelinesLayer,
chartPointsLayer
]
)
view.addSubview(chart.view)
self.chart = chart
}
}
|
apache-2.0
|
899795c076c4c7afbd49736a9ae91681
| 46.102564 | 239 | 0.671203 | 5.583587 | false | false | false | false |
EricHein/Swift3.0Practice2016
|
01.Applicatons/LoginDemo/LoginDemo/ViewController.swift
|
1
|
3926
|
//
// ViewController.swift
// LoginDemo
//
// Created by Eric H on 28/10/2016.
// Copyright © 2016 FabledRealm. All rights reserved.
//
import UIKit
import CoreData
class ViewController: UIViewController {
@IBOutlet var tf: UITextField!
@IBOutlet var label: UILabel!
@IBOutlet var button: UIButton!
@IBOutlet var logoutButton: UIButton!
var isLoggedIn = false
let appDelegate = UIApplication.shared.delegate as! AppDelegate
override func viewDidLoad() {
super.viewDidLoad()
let context = appDelegate.persistentContainer.viewContext
let request = NSFetchRequest<NSFetchRequestResult>(entityName: "Users")
logoutButton.alpha = 0
request.returnsObjectsAsFaults = false
do{
let results = try context.fetch(request)
for result in results as! [NSManagedObject]{
if let username = result.value(forKey: "name") as? String{
tf.alpha = 0
button.setTitle("Update name", for: [])
label.alpha = 1
label.text = "Hi there " + username + "!"
isLoggedIn = true
}
}
}catch{
print("Failed to Save")
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func loginButtonTapped(_ sender: AnyObject) {
let context = appDelegate.persistentContainer.viewContext
if isLoggedIn {
let request = NSFetchRequest<NSFetchRequestResult>(entityName: "Users")
do{
let results = try context.fetch(request)
if results.count > 0{
for result in results as! [NSManagedObject]{
result.setValue(tf.text, forKey: "name")
do{
try context.save()
}catch{
print("username change save failed")
}
}
label.text = "Hi there " + tf.text! + "!"
}
}catch{
print("Update user name failed")
}
}else{
let newValue = NSEntityDescription.insertNewObject(forEntityName: "Users", into: context)
newValue.setValue(tf.text, forKey: "name")
do{
try context.save()
button.setTitle("Update username", for: [])
tf.alpha = 0
button.alpha = 0
label.alpha = 1
label.text = "Hi there " + tf.text! + "!"
}catch{
print("Failed to Save")
}
}
}
@IBAction func logoutButtonTapped(_ sender: AnyObject) {
let context = appDelegate.persistentContainer.viewContext
let request = NSFetchRequest<NSFetchRequestResult>(entityName: "Users")
do{
let results = try context.fetch(request)
if results.count > 0 {
for result in results as! [NSManagedObject]{
context.delete(result)
do{
try context.save()
}catch{
print("")
}
}
isLoggedIn = false
label.alpha = 0
logoutButton.alpha = 0
tf.alpha = 0
button.alpha = 0
}
}catch{
print("Delete Failed")
}
}
}
|
gpl-3.0
|
630d65ff6b0210d0777524603f783045
| 29.426357 | 101 | 0.466752 | 5.92006 | false | false | false | false |
levantAJ/ResearchKit
|
TestVoiceActions/PromptCollectionViewController.swift
|
1
|
2807
|
//
// PromptCollectionViewController.swift
// TestVoiceActions
//
// Created by Le Tai on 8/25/16.
// Copyright © 2016 Snowball. All rights reserved.
//
import UIKit
final class PromptCollectionViewController: UICollectionViewController {
var shakeManager: ShakeManager!
var currentIndex = 0
override func viewDidLoad() {
super.viewDidLoad()
collectionView?.scrollEnabled = false
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
navigationController?.setNavigationBarHidden(true, animated: true)
shakeManager = ShakeManager()
currentIndex = 0
shakeManager.shakeLeft = {
guard self.currentIndex > 0 else {
ShakeManager.vibrate()
return
}
self.currentIndex = self.currentIndex - 1
self.collectionView?.scrollToItemAtIndexPath(NSIndexPath(forItem: self.currentIndex, inSection: 0), atScrollPosition: .None, animated: true)
}
shakeManager.shakeRight = {
guard self.currentIndex < 4 else {
ShakeManager.vibrate()
return
}
self.currentIndex = self.currentIndex + 1
self.collectionView?.scrollToItemAtIndexPath(NSIndexPath(forItem: self.currentIndex, inSection: 0), atScrollPosition: .None, animated: true)
}
}
override func viewWillDisappear(animated: Bool) {
super.viewWillDisappear(animated)
navigationController?.setNavigationBarHidden(false, animated: true)
shakeManager = nil
}
override func prefersStatusBarHidden() -> Bool {
return true
}
override func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int {
return 1
}
override func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return 5
}
override func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCellWithReuseIdentifier("PromptCellectuonViewCell", forIndexPath: indexPath) as! PromptCellectuonViewCell
cell.promptImageView.image = UIImage(named: "p\(indexPath.row+1).png")
return cell
}
func collectionView(collectionView: UICollectionView,
layout collectionViewLayout: UICollectionViewLayout,
sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize {
return view.frame.size
}
}
final class PromptCellectuonViewCell: UICollectionViewCell {
@IBOutlet weak var promptImageView: UIImageView!
}
|
mit
|
9654c299bac4e3f3bdc400e01da186c1
| 32.807229 | 154 | 0.659301 | 5.773663 | false | false | false | false |
CatchChat/Yep
|
Yep/ViewControllers/Chat/CellNodes/ChatLoadingCellNode.swift
|
1
|
1014
|
//
// ChatLoadingCellNode.swift
// Yep
//
// Created by NIX on 16/7/7.
// Copyright © 2016年 Catch Inc. All rights reserved.
//
import UIKit
import AsyncDisplayKit
class ChatLoadingCellNode: ASCellNode {
var isLoading: Bool = false {
didSet {
if isLoading {
indicator.startAnimating()
} else {
indicator.stopAnimating()
}
}
}
private lazy var indicator: UIActivityIndicatorView = {
let view = UIActivityIndicatorView(activityIndicatorStyle: .Gray)
view.hidesWhenStopped = true
return view
}()
override init() {
super.init()
selectionStyle = .None
self.view.addSubview(indicator)
}
override func calculateSizeThatFits(constrainedSize: CGSize) -> CGSize {
return CGSize(width: constrainedSize.width, height: 30)
}
override func layout() {
super.layout()
indicator.center = self.view.center
}
}
|
mit
|
6e4513469ecab6d8bca557b29977e6c8
| 19.632653 | 76 | 0.59545 | 4.884058 | false | false | false | false |
byu-oit-appdev/ios-byuSuite
|
byuSuite/Apps/JobOpenings/controller/JobOpeningsPostingsViewController.swift
|
1
|
898
|
//
// JobOpeningsPostingsViewController.swift
// byuSuite
//
// Created by Alex Boswell on 2/16/18.
// Copyright © 2018 Brigham Young University. All rights reserved.
//
import UIKit
class JobOpeningsPostingsViewController: ByuTableDataViewController {
//MARK: Public Variables
var family: JobOpeningsFamily!
//MARK: View controller lifecycle
override func viewDidLoad() {
super.viewDidLoad()
title = family.jobTitle
tableData = TableData(rows: family.jobPostings.map { Row(text: $0.title, object: $0) })
tableView.reloadData()
}
//MARK: Navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "showPosting",
let posting: JobOpeningsPosting = objectForSender(tableView: tableView, cellSender: sender),
let vc = segue.destination as? JobOpeningsDetailViewController {
vc.posting = posting
}
}
}
|
apache-2.0
|
eebce6777c71118a8bb95cf1e879c911
| 25.382353 | 95 | 0.727982 | 3.817021 | false | false | false | false |
cocos543/LetCode-in-Swift
|
LetCodeInSwift/LetCodeInSwift/Solution_Hamming_Distance.swift
|
1
|
518
|
//
// Solution_Hamming_Distance.swift
// LetCodeInSwift
//
// Created by Cocos on 2017/7/17.
// Copyright © 2017年 Cocos. All rights reserved.
//
import Foundation
class Solution_Hamming_Distance {
func hammingDistance(_ x: Int, _ y: Int) -> Int {
var num = x ^ y
var count = 0
for _ in 0 ... UInt32.max {
if num != 0 {
count += 1
}else {
break
}
num &= (num - 1)
}
return count
}
}
|
mit
|
5adadb936bd179306e7708c3811b1532
| 20.458333 | 53 | 0.47767 | 3.678571 | false | false | false | false |
kylef/RxHyperdrive
|
Pods/RxSwift/RxSwift/Subjects/ReplaySubject.swift
|
1
|
5920
|
//
// ReplaySubject.swift
// RxSwift
//
// Created by Krunoslav Zaher on 4/14/15.
// Copyright (c) 2015 Krunoslav Zaher. All rights reserved.
//
import Foundation
/**
Represents an object that is both an observable sequence as well as an observer.
Each notification is broadcasted to all subscribed and future observers, subject to buffer trimming policies.
*/
public class ReplaySubject<Element>
: Observable<Element>
, SubjectType
, ObserverType
, Disposable {
public typealias SubjectObserverType = ReplaySubject<Element>
typealias DisposeKey = Bag<AnyObserver<Element>>.KeyType
func unsubscribe(key: DisposeKey) {
abstractMethod()
}
/**
Notifies all subscribed observers about next event.
- parameter event: Event to send to the observers.
*/
public func on(event: Event<E>) {
abstractMethod()
}
/**
Returns observer interface for subject.
*/
public func asObserver() -> SubjectObserverType {
return self
}
/**
Unsubscribe all observers and release resources.
*/
public func dispose() {
}
/**
Creates new instance of `ReplaySubject` that replays at most `bufferSize` last elements of sequence.
- parameter bufferSize: Maximal number of elements to replay to observer after subscription.
- returns: New instance of replay subject.
*/
public static func create(bufferSize bufferSize: Int) -> ReplaySubject<Element> {
if bufferSize == 1 {
return ReplayOne()
}
else {
return ReplayMany(bufferSize: bufferSize)
}
}
}
class ReplayBufferBase<Element>
: ReplaySubject<Element>
, SynchronizedUnsubscribeType {
private var _lock = NSRecursiveLock()
// state
private var _disposed = false
private var _stoppedEvent = nil as Event<Element>?
private var _observers = Bag<AnyObserver<Element>>()
func trim() {
abstractMethod()
}
func addValueToBuffer(value: Element) {
abstractMethod()
}
func replayBuffer(observer: AnyObserver<Element>) {
abstractMethod()
}
override func on(event: Event<Element>) {
_lock.lock(); defer { _lock.unlock() }
_synchronized_on(event)
}
func _synchronized_on(event: Event<E>) {
if _disposed {
return
}
if _stoppedEvent != nil {
return
}
switch event {
case .Next(let value):
addValueToBuffer(value)
trim()
_observers.on(event)
case .Error, .Completed:
_stoppedEvent = event
trim()
_observers.on(event)
_observers.removeAll()
}
}
override func subscribe<O : ObserverType where O.E == Element>(observer: O) -> Disposable {
_lock.lock(); defer { _lock.unlock() }
return _synchronized_subscribe(observer)
}
func _synchronized_subscribe<O : ObserverType where O.E == E>(observer: O) -> Disposable {
if _disposed {
observer.on(.Error(RxError.Disposed(object: self)))
return NopDisposable.instance
}
let AnyObserver = observer.asObserver()
replayBuffer(AnyObserver)
if let stoppedEvent = _stoppedEvent {
observer.on(stoppedEvent)
return NopDisposable.instance
}
else {
let key = _observers.insert(AnyObserver)
return SubscriptionDisposable(owner: self, key: key)
}
}
func synchronizedUnsubscribe(disposeKey: DisposeKey) {
_lock.lock(); defer { _lock.unlock() }
_synchronized_unsubscribe(disposeKey)
}
func _synchronized_unsubscribe(disposeKey: DisposeKey) {
if _disposed {
return
}
_ = _observers.removeKey(disposeKey)
}
override func dispose() {
super.dispose()
synchronizedDispose()
}
func synchronizedDispose() {
_lock.lock(); defer { _lock.unlock() }
_synchronized_dispose()
}
func _synchronized_dispose() {
_disposed = true
_stoppedEvent = nil
_observers.removeAll()
}
}
final class ReplayOne<Element> : ReplayBufferBase<Element> {
private var _value: Element?
override init() {
super.init()
}
override func trim() {
}
override func addValueToBuffer(value: Element) {
_value = value
}
override func replayBuffer(observer: AnyObserver<Element>) {
if let value = _value {
observer.on(.Next(value))
}
}
override func _synchronized_dispose() {
super._synchronized_dispose()
_value = nil
}
}
class ReplayManyBase<Element> : ReplayBufferBase<Element> {
private var _queue: Queue<Element>
init(queueSize: Int) {
_queue = Queue(capacity: queueSize + 1)
}
override func addValueToBuffer(value: Element) {
_queue.enqueue(value)
}
override func replayBuffer(observer: AnyObserver<E>) {
for item in _queue {
observer.on(.Next(item))
}
}
override func _synchronized_dispose() {
super._synchronized_dispose()
_queue = Queue(capacity: 0)
}
}
final class ReplayMany<Element> : ReplayManyBase<Element> {
private let _bufferSize: Int
init(bufferSize: Int) {
_bufferSize = bufferSize
super.init(queueSize: bufferSize)
}
override func trim() {
while _queue.count > _bufferSize {
_queue.dequeue()
}
}
}
final class ReplayAll<Element> : ReplayManyBase<Element> {
init() {
super.init(queueSize: 0)
}
override func trim() {
}
}
|
mit
|
2e202fd2d9860204b7dd7ce20fe68f1c
| 23.069106 | 109 | 0.585473 | 4.828711 | false | false | false | false |
Senspark/ee-x
|
src/ios/ee/facebook_ads/FacebookBannerAd.swift
|
1
|
4392
|
//
// FacebookBannerAd.swift
// ee-x-6914a733
//
// Created by eps on 6/24/20.
//
import FBAudienceNetwork
private let kTag = "\(FacebookBannerAd.self)"
internal class FacebookBannerAd:
NSObject, IBannerAd, FBAdViewDelegate {
private let _bridge: IMessageBridge
private let _logger: ILogger
private let _adId: String
private let _adSize: FBAdSize
private let _messageHelper: MessageHelper
private var _helper: BannerAdHelper?
private let _viewHelper: ViewHelper
private var _isLoaded = false
private var _ad: FBAdView?
init(_ bridge: IMessageBridge,
_ logger: ILogger,
_ adId: String,
_ adSize: FBAdSize,
_ bannerHelper: FacebookBannerHelper) {
_bridge = bridge
_logger = logger
_adId = adId
_adSize = adSize
_messageHelper = MessageHelper("FacebookBannerAd", _adId)
_viewHelper = ViewHelper(CGPoint.zero, bannerHelper.getSize(adSize: adSize), false)
super.init()
_helper = BannerAdHelper(_bridge, self, _messageHelper)
registerHandlers()
createInternalAd()
}
func destroy() {
deregisterHandlers()
destroyInternalAd()
}
func registerHandlers() {
_helper?.registerHandlers()
}
func deregisterHandlers() {
_helper?.deregisterHandlers()
}
func createInternalAd() {
Thread.runOnMainThread {
if self._ad != nil {
return
}
self._isLoaded = false
let rootView = Utils.getCurrentRootViewController()
let ad = FBAdView(placementID: self._adId,
adSize: self._adSize,
rootViewController: rootView)
ad.delegate = self
self._ad = ad
self._viewHelper.view = ad
rootView?.view.addSubview(ad)
}
}
func destroyInternalAd() {
Thread.runOnMainThread {
guard let ad = self._ad else {
return
}
self._isLoaded = false
ad.delegate = nil
ad.removeFromSuperview()
self._ad = nil
self._viewHelper.view = nil
}
}
var isLoaded: Bool {
return _isLoaded
}
func load() {
Thread.runOnMainThread {
self._logger.debug("\(kTag): \(#function): id = \(self._adId)")
guard let ad = self._ad else {
assert(false, "Ad is not initialized")
return
}
ad.loadAd()
}
}
var isVisible: Bool {
get { return _viewHelper.isVisible }
set(value) { _viewHelper.isVisible = value }
}
var position: CGPoint {
get { return _viewHelper.position }
set(value) { _viewHelper.position = value }
}
var size: CGSize {
get { return _viewHelper.size }
set(value) { _viewHelper.size = value }
}
func adViewDidLoad(_ adView: FBAdView) {
Thread.runOnMainThread {
self._logger.debug("\(kTag): \(#function): id = \(self._adId)")
self._isLoaded = true
self._bridge.callCpp(self._messageHelper.onLoaded)
}
}
func adView(_ adView: FBAdView, didFailWithError error: Error) {
Thread.runOnMainThread {
self._logger.debug("\(kTag): \(#function): id = \(self._adId) message = \(error.localizedDescription)")
self._bridge.callCpp(self._messageHelper.onFailedToLoad, EEJsonUtils.convertDictionary(toString: [
"code": (error as NSError).code,
"message": error.localizedDescription
]))
}
}
func adViewDidClick(_ adView: FBAdView) {
Thread.runOnMainThread {
self._logger.debug("\(kTag): \(#function): id = \(self._adId)")
self._bridge.callCpp(self._messageHelper.onClicked)
}
}
func adViewDidFinishHandlingClick(_ adView: FBAdView) {
Thread.runOnMainThread {
self._logger.debug("\(kTag): \(#function): id = \(self._adId)")
}
}
func adViewWillLogImpression(_ adView: FBAdView) {
Thread.runOnMainThread {
self._logger.debug("\(kTag): \(#function): id = \(self._adId)")
}
}
}
|
mit
|
e30972e78d3e14135260ce228d5109f5
| 28.28 | 115 | 0.550091 | 4.67234 | false | false | false | false |
durbrow/LCS.playground
|
LCS.playground/Contents.swift
|
1
|
4800
|
import UIKit
/*:
# LCS - Longest Common Subsequence
http://en.wikipedia.org/wiki/Longest_common_subsequence_problem
*/
func LCS(X: String, _ Y: String) -> [String]
{
/*:
We turn the strings into arrays because it's easier in Swift to
work with them as arrays. We'll turn the results back into strings
when we are done.
*/
let x = [Character](X.characters)
let y = [Character](Y.characters)
/*:
# Using the recursion formula from the above wiki page
(using python string slicing syntax for brevity)
LCS(X,Y) = "" if X == "" or Y == ""
LCS(X,Y) = LCS(X[:-1],Y[:-1]) + X[-1] if X[-1] == Y[-1]
LCS(X,Y) = longest(LCS(X[:-1],Y),LCS(X,Y[:-1]))
The advantage here is mainly simplicity.
*/
func LCS_recursive(a: Int, _ b: Int) -> [[Character]]
{
//: Rule #1
if a == 0 || b == 0 { return [[]] }
let (i, j) = (a - 1, b - 1)
//: Rule #2
if x[i] == y[j] { return LCS_recursive(i, j).map { $0 + [x[i]] } }
//: Rule #3
let (u, l) = (LCS_recursive(i, b), LCS_recursive(a, j))
var rslt = [[Character]]()
if u[0].count >= l[0].count { rslt += u }
if l[0].count >= u[0].count { rslt += l }
return rslt
}
/*:
# Using "dynamic programming" - it's just so dynamic!
This is the "full" version where the cells of the workspace array hold the
intermediate results. It has the advantage of having the answer in one go.
It has the disadvantage of using lots of memory. However, it can be reduced
dramatically, but I won't do so here for simplicity.
*/
func LCS_dynamic() -> [[Character]]
{
//: a two dimensional array [0...y.count][0...x.count] of arrays of arrays of Character, Yikes!
var score = (0...y.count).map { _ in (0...x.count).map { _ in [[Character]]() } }
for i in 1...y.count {
for j in 1...x.count {
//: Rule #2
if x[j-1] == y[i-1] {
score[i][j] = score[i-1][j-1].map { $0 + [x[j-1]] }
}
else {
let (u, l) = (score[i-1][j], score[i][j-1])
//: Rule #3
if u[0].count >= l[0].count { score[i][j] += u }
if l[0].count >= u[0].count { score[i][j] += l }
}
}
}
return score[y.count][x.count]
}
/*:
This is the traceback version where the workspace array contains only the length.
In the full version, the cells of the workspace array held the intermediate results
(a vector of subsequences), while in this version, the cells of the workspace array
only each hold a single integer. It's advantage is in using much less memory.
It's disadvantage is that it requires an addition step, the traceback, to compute
the final result.
However, it has an additional advantage that is not so readily apparent. The values
that are held in the workspace array, here the lengths of the subsequences, are
actually scores. This can be generalized to situations where the length is not the
measure of merit. In other words, with the appropriate scoring matrix, it can be
transformed into Smith-Waterman.
*/
func LCS_traceback() -> [[Character]]
{
//: a two dimensional array [0...y.count][0...x.count] of Int
var score = (0...y.count).map { _ in (0...x.count).map { _ in 0 } }
for i in 1...y.count {
for j in 1...x.count {
if x[j-1] == y[i-1] {
score[i][j] = score[i-1][j-1] + 1
}
else {
let u = score[i-1][j]
let l = score[i][j-1]
if u > l {
score[i][j] = u
}
else {
score[i][j] = l
}
}
}
}
func traceback(a: Int, _ b: Int) -> [[Character]]
{
if a == 0 || b == 0 { return [[]] }
let i = a - 1
let j = b - 1
if x[i] == y[j] { return traceback(i, j).map { $0 + [x[i]] } }
var rslt = [[Character]]()
if score[b][i] >= score[j][a] { rslt += traceback(i, b) }
if score[j][a] >= score[b][i] { rslt += traceback(a, j) }
return rslt
}
return traceback(x.count, y.count)
}
let lcs = LCS_traceback()
//let lcs = LCS_dynamic()
//let lcs = LCS_recursive(x.count, y.count)
//: Turn the arrays back into strings and unique them
var rslt = [String]()
for s in lcs.map({ String($0) }).sort() {
if rslt.count == 0 || rslt.last != s {
rslt.append(s)
}
}
return rslt
}
//print(LCS("BANANA", "BATANA"))
print(LCS("AGCAT", "GAC"))
|
mit
|
3264dd70c0e5d36c115bd6e3d7b3e695
| 32.566434 | 95 | 0.513125 | 3.397028 | false | false | false | false |
son11592/STKeyboard
|
STKeyboard/Classes/Model.swift
|
2
|
718
|
//
// Model.swift
// STKeyboard
//
// Created by Son on 1/19/17.
// Copyright © 2017 Sonracle. All rights reserved.
//
import UIKit
import Photos
open class Model: NSObject {
override init() {
super.init()
self.commonInit()
}
func commonInit() {
}
}
open class AssetModel: Model {
open var index: Int = -1
open var phAsset: PHAsset!
open var cropImage: UIImage?
open var blurImage: UIImage?
open var isSelected: Bool = false
override func commonInit() {
super.commonInit()
self.phAsset = PHAsset()
}
}
open class ImagesGroup: Model {
open var assets: [AssetModel] = []
open var phAssets: [AssetModel] = []
open var assetsCollection: PHAssetCollection?
}
|
mit
|
fb4837adc935ae81c536d89606fc1db9
| 13.9375 | 51 | 0.658298 | 3.658163 | false | false | false | false |
Railsreactor/json-data-sync-swift
|
Pods/When/Sources/When/State.swift
|
1
|
1117
|
public enum State<T>: Equatable {
case pending
case resolved(value: T)
case rejected(error: Error)
public var isPending: Bool {
return result == nil
}
public var isResolved: Bool {
if case .resolved = self {
return true
} else {
return false
}
}
public var isRejected: Bool {
if case .rejected = self {
return true
} else {
return false
}
}
public func map<U>(_ closure: (T) -> U) -> State<U> {
switch self {
case let .resolved(value):
return .resolved(value: closure(value))
case let .rejected(error):
return State<U>.rejected(error: error)
case .pending:
return State<U>.pending
}
}
public var result: Result<T>? {
switch self {
case let .resolved(value):
return .success(value: value)
case let .rejected(error):
return .failure(error: error)
case .pending:
return nil
}
}
}
public func ==<T>(lhs: State<T>, rhs: State<T>) -> Bool {
return lhs.isPending == rhs.isPending
|| lhs.isResolved == rhs.isResolved
|| lhs.isRejected == rhs.isRejected
}
|
mit
|
4618754c61671c73117b62b98252839a
| 20.075472 | 57 | 0.59803 | 3.786441 | false | false | false | false |
kaltura/playkit-ios
|
Example/Tests/Analytics/AnalyticsPluginConfig.swift
|
1
|
1576
|
// ===================================================================================================
// Copyright (C) 2017 Kaltura Inc.
//
// Licensed under the AGPLv3 license,
// unless a different license for a particular library is specified in the applicable library path.
//
// You may obtain a copy of the License at
// https://www.gnu.org/licenses/agpl-3.0.html
// ===================================================================================================
import Foundation
enum AnalyticsPluginConfig {
case TVPAPI
case Phoenix
mutating func next() {
switch self {
case .TVPAPI: self = .Phoenix
case .Phoenix: self = .TVPAPI
}
}
var pluginName: String {
switch self {
case .TVPAPI: return PhoenixAnalyticsPluginMock.pluginName
case .Phoenix: return TVPAPIAnalyticsPluginMock.pluginName
}
}
var paramsDict: [String : Any] {
switch self {
case .TVPAPI: return [
"fileId": "464302",
"baseUrl": "http://tvpapi-preprod.ott.kaltura.com/v3_9/gateways/jsonpostgw.aspx?",
"timerInterval":30000,
"initObj": ""
]
case .Phoenix: return [
"fileId": "464302",
"baseUrl": "http://api-preprod.ott.kaltura.com/v4_1/api_v3/",
"ks": "djJ8MTk4fL1W9Rs4udDqNt_CpUT9dJKk1laPk9_XnBtUaq7PXVcVPYrXz2shTbKSW1G5Lhn_Hvbbnh0snheANOmSodl7Puowxhk2WYkpmNugi9vNAg5C",
"partnerId": 198,
"timerInterval": 30
]
}
}
}
|
agpl-3.0
|
30952cfe35e0a24f6f2c40fa962785a5
| 31.163265 | 137 | 0.520305 | 3.788462 | false | false | false | false |
gbuela/kanjiryokucha
|
KanjiRyokucha/DebugLogsManager.swift
|
1
|
1228
|
//
// DebugLogsManager.swift
// KanjiRyokucha
//
// Created by German Buela on 8/22/17.
// Copyright © 2017 German Buela. All rights reserved.
//
import Foundation
struct DebugLogsManager {
private let fileName = "krlogs.txt"
func readLogs() -> String {
if let path = logUrl() {
return (try? String(contentsOf: path)) ?? ""
}
return ""
}
func write(log: String) {
let dump = readLogs()
let df = DateFormatter()
df.dateFormat = "y-MM-dd H:m:ss.SSSS"
let date = df.string(from: Date())
if let path = logUrl() {
do {
try "\(dump)\n\(date): \(log)".write(to: path, atomically: true, encoding: .utf8)
} catch {
print("Failed writing log: \(error.localizedDescription)")
}
}
}
func clear() {
if let path = logUrl() {
try? FileManager.default.removeItem(at: path)
}
}
private func logUrl() -> URL? {
let dir = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first
return dir?.appendingPathComponent(fileName)
}
}
|
mit
|
bf6ece7d022682bfb68ce85115e447ec
| 23.54 | 97 | 0.524042 | 4.076412 | false | false | false | false |
mamouneyya/TheSkillsProof
|
Pods/p2.OAuth2/Sources/Base/extensions.swift
|
5
|
3019
|
//
// extensions.swift
// OAuth2
//
// Created by Pascal Pfiffner on 6/6/14.
// Copyright 2014 Pascal Pfiffner
//
// 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
extension NSHTTPURLResponse
{
/// A localized string explaining the current `statusCode`.
public var statusString: String {
get {
return NSHTTPURLResponse.localizedStringForStatusCode(self.statusCode)
}
}
}
extension String
{
private static var wwwFormURLPlusSpaceCharacterSet: NSCharacterSet = NSMutableCharacterSet.wwwFormURLPlusSpaceCharacterSet()
/// Encodes a string to become x-www-form-urlencoded; the space is encoded as plus sign (+).
var wwwFormURLEncodedString: String {
let characterSet = String.wwwFormURLPlusSpaceCharacterSet
return (stringByAddingPercentEncodingWithAllowedCharacters(characterSet) ?? "").stringByReplacingOccurrencesOfString(" ", withString: "+")
}
/// Decodes a percent-encoded string and converts the plus sign into a space.
var wwwFormURLDecodedString: String {
let rep = stringByReplacingOccurrencesOfString("+", withString: " ")
return rep.stringByRemovingPercentEncoding ?? rep
}
}
extension NSMutableCharacterSet
{
/**
Return the character set that does NOT need percent-encoding for x-www-form-urlencoded requests INCLUDING SPACE.
YOU are responsible for replacing spaces " " with the plus sign "+".
RFC3986 and the W3C spec are not entirely consistent, we're using W3C's spec which says:
http://www.w3.org/TR/html5/forms.html#application/x-www-form-urlencoded-encoding-algorithm
> If the byte is 0x20 (U+0020 SPACE if interpreted as ASCII):
> - Replace the byte with a single 0x2B byte ("+" (U+002B) character if interpreted as ASCII).
> If the byte is in the range 0x2A (*), 0x2D (-), 0x2E (.), 0x30 to 0x39 (0-9), 0x41 to 0x5A (A-Z), 0x5F (_),
> 0x61 to 0x7A (a-z)
> - Leave byte as-is
*/
class func wwwFormURLPlusSpaceCharacterSet() -> NSMutableCharacterSet {
let set = NSMutableCharacterSet.alphanumericCharacterSet()
set.addCharactersInString("-._* ")
return set
}
}
extension NSURLRequest {
/** Print the requests's headers and body to stdout. */
public func oauth2_print() {
print("---")
print("HTTP/1.1 \(HTTPMethod) \(URL?.description ?? "/")")
allHTTPHeaderFields?.forEach() { print("\($0): \($1)") }
print("")
if let data = HTTPBody, let body = NSString(data: data, encoding: NSUTF8StringEncoding) {
print(body as String)
}
print("---")
}
}
|
mit
|
acf38be8b76febc011f2e46c4d0852b8
| 32.544444 | 140 | 0.717456 | 3.920779 | false | false | false | false |
mityung/XERUNG
|
IOS/Xerung/Xerung/SideMenuViewController.swift
|
1
|
9729
|
//
// SideMenuViewController.swift
// Xerung
//
// Created by Mac on 07/04/17.
// Copyright © 2017 mityung. All rights reserved.
//
import UIKit
class SideMenuViewController: UIViewController {
@IBOutlet var userImage: UIImageView!
@IBOutlet var syncButton: UIButton!
@IBOutlet var createDirectoryButton: UIButton!
@IBOutlet var searchButton: UIButton!
@IBOutlet var dashBoardButton: UIButton!
@IBOutlet var LogoutButton: UIButton!
@IBOutlet var profileButton: UIButton!
@IBOutlet var emailAddress: UILabel!
@IBOutlet var NameLabel: UILabel!
var dataDict = [String:String]()
override func viewDidLoad() {
super.viewDidLoad()
self.dashBoardButton.tag = 1
self.searchButton.tag = 2
self.createDirectoryButton.tag = 3
self.syncButton.tag = 4
self.LogoutButton.tag = 5
self.profileButton.tag = 6
NameLabel.text = profileJson["NAME"].stringValue
emailAddress.text = mobileNo
self.dashBoardButton.addTarget(self, action: #selector(self.performAction(sender:)), for: UIControlEvents.touchUpInside)
self.searchButton.addTarget(self, action: #selector(self.performAction(sender:)), for: UIControlEvents.touchUpInside)
self.createDirectoryButton.addTarget(self, action: #selector(self.performAction(sender:)), for: UIControlEvents.touchUpInside)
self.syncButton.addTarget(self, action: #selector(self.performAction(sender:)), for: UIControlEvents.touchUpInside)
self.LogoutButton.addTarget(self, action: #selector(self.performAction(sender:)), for: UIControlEvents.touchUpInside)
self.profileButton.addTarget(self, action: #selector(self.performAction(sender:)), for: UIControlEvents.touchUpInside)
userImage.layer.shadowRadius = userImage.frame.height/2
userImage.layer.masksToBounds = true
userImage.layer.masksToBounds = true
userImage.layer.borderWidth = 2
userImage.layer.borderColor = UIColor.white.cgColor
userImage.layer.shadowRadius = 10
userImage.layer.shadowOffset = CGSize(width: 0, height: 0)
userImage.layer.shadowColor = UIColor.black.cgColor
userImage.layer.shadowOpacity = 0.3;
if profileJson["PHOTO"].stringValue != "" && profileJson["PHOTO"].stringValue != "0" {
if let imageData = Data(base64Encoded: profileJson["PHOTO"].stringValue , options: NSData.Base64DecodingOptions.ignoreUnknownCharacters) {
let DecodedImage = UIImage(data: imageData)
userImage.image = DecodedImage
}
}else{
userImage.image = UIImage(named: "user.png")
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func performAction(sender:UIButton) {
if sender.tag == 1 {
let storyBoard = UIStoryboard(name: "Main", bundle: nil) as UIStoryboard
let mfSideMenuContainer = storyBoard.instantiateViewController(withIdentifier: "MFSideMenuContainerViewController") as! MFSideMenuContainerViewController
let dashboard = storyBoard.instantiateViewController(withIdentifier: "Directory_ViewController") as! UITabBarController
let leftSideMenuController = storyBoard.instantiateViewController(withIdentifier: "SideMenuViewController") as! SideMenuViewController
mfSideMenuContainer.leftMenuViewController = leftSideMenuController
mfSideMenuContainer.centerViewController = dashboard
let appDelegate = UIApplication.shared.delegate as! AppDelegate
appDelegate.window?.rootViewController = mfSideMenuContainer
}else if sender.tag == 2 {
let center = storyboard?.instantiateViewController(withIdentifier: "SearchDirectoryViewController") as! SearchDirectoryViewController
let nav = UINavigationController(rootViewController: center)
self.menuContainerViewController.centerViewController = nav
}else if sender.tag == 3 {
let center = storyboard?.instantiateViewController(withIdentifier: "CreateDirectoryViewController") as! CreateDirectoryViewController
let nav = UINavigationController(rootViewController: center)
self.menuContainerViewController.centerViewController = nav
}else if sender.tag == 4 {
getContactDetails { (response) in
DispatchQueue.main.async(execute: {
for i in 0 ..< phoneBook.count {
self.dataDict.updateValue(phoneBook[i].phone, forKey: phoneBook[i].name)
}
self.syncContacts()
})
}
}else if sender.tag == 5 {
let title = "Are you sure you want to logout?"
let refreshAlert = UIAlertController(title: "Alert", message: title, preferredStyle: UIAlertControllerStyle.alert)
refreshAlert.addAction(UIAlertAction(title: "Yes", style: .default, handler: { (action: UIAlertAction!) in
self.deleteOffLineData()
UserDefaults.standard.removeObject(forKey: "profileJson")
UserDefaults.standard.removeObject(forKey: "name")
UserDefaults.standard.removeObject(forKey: "mobileNo")
UserDefaults.standard.removeObject(forKey: "uid")
UserDefaults.standard.setValue("No", forKey: "Login")
UserDefaults.standard.synchronize()
let storyBoard : UIStoryboard = UIStoryboard(name: "Main", bundle:nil)
let nextViewController = storyBoard.instantiateViewController(withIdentifier: "ViewController") as! ViewController
self.present(nextViewController, animated:true, completion:nil)
}))
refreshAlert.addAction(UIAlertAction(title: "No", style: .default, handler: { (action: UIAlertAction!) in
}))
present(refreshAlert, animated: true, completion: nil)
}else if sender.tag == 6 {
let center = storyboard?.instantiateViewController(withIdentifier: "UserProfileViewController") as! UserProfileViewController
let nav = UINavigationController(rootViewController: center)
self.menuContainerViewController.centerViewController = nav
}
self.menuContainerViewController.toggleLeftSideMenuCompletion(nil)
}
func deleteOffLineData(){
let databasePath = UserDefaults.standard.url(forKey: "DataBasePath")!
let contactDB = FMDatabase(path: String(describing: databasePath))
if (contactDB?.open())! {
let querySQL = "DELETE FROM Directory "
_ = contactDB!.executeUpdate(querySQL, withArgumentsIn: nil)
let querySQL1 = "DELETE FROM DirectoryMember "
_ = contactDB!.executeUpdate(querySQL1, withArgumentsIn: nil)
} else {
print("Error: \(contactDB?.lastErrorMessage())")
}
}
@IBAction func syncContacts() {
if phoneBook.count == 0 {
return
}else {
self.sync()
}
}
func sync(){
do {
let jsonData = try JSONSerialization.data(withJSONObject: dataDict, options: JSONSerialization.WritingOptions.prettyPrinted)
let decoded = try JSONSerialization.jsonObject(with: jsonData, options: [])
if let dictFromJSON = decoded as? [String:String] {
let sendJson: [String: String] = [
"PFLAG": "1",
"PUID":userID,
"PBACKUPLIST" : String(describing: dictFromJSON)
]
if Reachability.isConnectedToNetwork() {
startLoader(view: self.view)
DataProvider.sharedInstance.getServerData2(sendJson, path: "Mibackupsend", successBlock: { (response) in
stopLoader()
print(response)
}) { (error) in
print(error)
stopLoader()
}
}else{
self.showAlert("Alert", message: "No internet connectivity.")
}
}
} catch let error as NSError {
print(error)
}
}
func showAlert(_ title:String,message:String){
let refreshAlert = UIAlertController(title: title, message: message, preferredStyle: UIAlertControllerStyle.alert)
refreshAlert.addAction(UIAlertAction(title: "OK", style: .default, handler: { (action: UIAlertAction!) in
}))
present(refreshAlert, animated: true, completion: nil)
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
|
apache-2.0
|
7585477fdf8aadadd27bb16017545e7a
| 40.931034 | 165 | 0.607936 | 5.698887 | false | false | false | false |
mozilla-mobile/firefox-ios
|
Shared/AppInfo.swift
|
2
|
5063
|
// 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
public let debugPrefIsChinaEdition = "debugPrefIsChinaEdition"
open class AppInfo {
/// Return the main application bundle. If this is called from an extension, the containing app bundle is returned.
public static var applicationBundle: Bundle {
let bundle = Bundle.main
switch bundle.bundleURL.pathExtension {
case "app":
return bundle
case "appex":
// .../Client.app/PlugIns/SendTo.appex
return Bundle(url: bundle.bundleURL.deletingLastPathComponent().deletingLastPathComponent())!
default:
fatalError("Unable to get application Bundle (Bundle.main.bundlePath=\(bundle.bundlePath))")
}
}
public static var bundleIdentifier: String {
return applicationBundle.object(forInfoDictionaryKey: "CFBundleIdentifier") as! String
}
public static var displayName: String {
return applicationBundle.object(forInfoDictionaryKey: "CFBundleDisplayName") as! String
}
public static var appVersion: String {
return applicationBundle.object(forInfoDictionaryKey: "CFBundleShortVersionString") as! String
}
public static var buildNumber: String {
return applicationBundle.object(forInfoDictionaryKey: String(kCFBundleVersionKey)) as! String
}
public static var majorAppVersion: String {
return appVersion.components(separatedBy: ".").first!
}
/// Return the shared container identifier (also known as the app group) to be used with for example background
/// http requests. It is the base bundle identifier with a "group." prefix.
public static var sharedContainerIdentifier: String {
var bundleIdentifier = baseBundleIdentifier
if bundleIdentifier == "org.mozilla.ios.FennecEnterprise" {
// Bug 1373726 - Base bundle identifier incorrectly generated for Nightly builds
// This can be removed when we are able to fix the app group in the developer portal
bundleIdentifier = "org.mozilla.ios.Fennec.enterprise"
}
return "group." + bundleIdentifier
}
/// Return the keychain access group.
public static func keychainAccessGroupWithPrefix(_ prefix: String) -> String {
var bundleIdentifier = baseBundleIdentifier
if bundleIdentifier == "org.mozilla.ios.FennecEnterprise" {
// Bug 1373726 - Base bundle identifier incorrectly generated for Nightly builds
// This can be removed when we are able to fix the app group in the developer portal
bundleIdentifier = "org.mozilla.ios.Fennec.enterprise"
}
return prefix + "." + bundleIdentifier
}
/// Return the base bundle identifier.
///
/// This function is smart enough to find out if it is being called from an extension or the main application. In
/// case of the former, it will chop off the extension identifier from the bundle since that is a suffix not part
/// of the *base* bundle identifier.
public static var baseBundleIdentifier: String {
let bundle = Bundle.main
let packageType = bundle.object(forInfoDictionaryKey: "CFBundlePackageType") as! String
let baseBundleIdentifier = bundle.bundleIdentifier!
if packageType == "XPC!" {
let components = baseBundleIdentifier.components(separatedBy: ".")
return components[0..<components.count-1].joined(separator: ".")
}
return baseBundleIdentifier
}
// Return the MozWhatsNewTopic key from the Info.plist
public static var whatsNewTopic: String? {
// By default we don't want to add dot version to what's new section. Set this to true if you'd like to add dot version for whats new article.
let shouldAddDotVersion = false
let appVersionSplit = AppInfo.appVersion.components(separatedBy: ".")
let majorAppVersion = appVersionSplit[0]
var dotVersion = ""
if appVersionSplit.count > 1, appVersionSplit[0] != "0" { dotVersion = appVersionSplit[1] }
let topic = "whats-new-ios-\(majorAppVersion)\(shouldAddDotVersion ? dotVersion : "")"
return topic
}
// Return whether the currently executing code is running in an Application
public static var isApplication: Bool {
return Bundle.main.object(forInfoDictionaryKey: "CFBundlePackageType") as! String == "APPL"
}
// The port for the internal webserver, tests can change this
public static var webserverPort = 6571
public static var isChinaEdition: Bool = {
if UserDefaults.standard.bool(forKey: debugPrefIsChinaEdition) {
return true
}
return Locale.current.identifier == "zh_CN"
}()
// The App Store page identifier for the Firefox iOS application
public static var appStoreId = "id989804926"
}
|
mpl-2.0
|
07cfd3369fb4e233fb7818e039bf7dc9
| 44.205357 | 150 | 0.68892 | 5.098691 | false | false | false | false |
KoCMoHaBTa/MHAppKit
|
MHAppKit/Extensions/CoreGraphics/CGSize+Scale.swift
|
1
|
1129
|
//
// CGSize+Scale.swift
// MHAppKit
//
// Created by Milen Halachev on 15.02.18.
// Copyright © 2018 Milen Halachev. All rights reserved.
//
import Foundation
import CoreGraphics
//based on https://gist.github.com/tomasbasham/10533743
extension CGSize {
public enum ScaleMode {
case fill
case fit
}
public func scaling(to mode: ScaleMode, into size: CGSize) -> CGSize {
let aspectWidth = size.width / self.width
let aspectHeight = size.height / self.height
let aspectRatio: CGFloat
switch mode {
case .fill:
aspectRatio = max(aspectWidth, aspectHeight)
case .fit:
aspectRatio = min(aspectWidth, aspectHeight)
}
var result = CGSize.zero
result.width = self.width * aspectRatio;
result.height = self.height * aspectRatio;
return result
}
public mutating func scale(to mode: ScaleMode, into size: CGSize) {
self = self.scaling(to: mode, into: size)
}
}
|
mit
|
a98627b4dce328ad38c888a2d9519236
| 23 | 74 | 0.566489 | 4.604082 | false | false | false | false |
bfortunato/aj-framework
|
platforms/ios/Libs/AJ/AJ/AJJavaScriptCoreRuntime.swift
|
1
|
7307
|
//
// AJJavaScriptCoreRuntime.swift
// AJ
//
// Created by Bruno Fortunato on 18/02/16.
// Copyright © 2016 Bruno Fortunato. All rights reserved.
//
import UIKit
import JavaScriptCore
import ApplicaFramework
open class AJJavaScriptCoreRuntime: AJRuntime {
let jsContext: JSContext
let timers: AJTimers
var jsRuntime: JSValue?
public override init() {
jsContext = JSContext()
timers = AJTimers()
super.init()
jsContext.exceptionHandler = { context, exception in
// type of String
if let exception = exception {
let stacktrace: String = (exception.objectForKeyedSubscript("stack").toString()) ?? "NA"
// type of Number
let lineNumber: JSValue = exception.objectForKeyedSubscript("line") ?? JSValue(object: "", in: context)
// type of Number
let column: JSValue = exception.objectForKeyedSubscript("column") ?? JSValue(object: "", in: context)
let moreInfo = "\n - in method \(stacktrace)\n - line number in file: \(lineNumber)\n - column: \(column)"
NSLog("JS ERROR \n\(exception) \(moreInfo)")
} else {
NSLog("JS ERROR")
}
}
let aj_async: @convention(block) (JSValue) -> Void = { action in
AJThread.async {
action.call(withArguments: [])
}
}
let aj_setTimeout: @convention(block) (JSValue, Int) -> Int = { action, time in
return self.timers.setTimeout(action, time)
}
let aj_setInterval: @convention(block) (JSValue, Int) -> Int = { action, time in
return self.timers.setInterval(action, time)
}
let aj_clearTimeout: @convention(block) (Int) -> Void = { timerId in
return self.timers.clearTimeout(timerId)
}
let aj_clearInterval: @convention(block) (Int) -> Void = { timerId in
return self.timers.clearInterval(timerId)
}
let aj_trigger: @convention(block) (String, JSValue) -> Void = { (store, data) in
let dict = data.toDictionary() as? [String: AnyObject]
let state: AJObject = dict != nil ? AJObject(dict: dict!) : AJObject.empty()
self.tigger(store: store, data: state)
}
let aj_exec: @convention(block) (String, String, JSValue, JSValue) -> Void = { (plugin, fn, data, callback) in
let dict = data.toDictionary() as? [String: Any]
let arguments: AJObject = dict != nil ? AJObject(dict: dict!) : AJObject.empty()
self.exec(plugin: plugin, fn: fn, data: arguments) { (error, result) in
callback.call(withArguments: [error, result?.toDict() ?? [String: AnyObject]()])
}
}
jsContext.globalObject.setObject(jsContext.globalObject, forKeyedSubscript: "global" as (NSCopying & NSObjectProtocol)?)
let platform = ["engine": "native", "device": "iOS"]
jsContext.globalObject.setObject(platform, forKeyedSubscript: "platform" as (NSCopying & NSObjectProtocol)?)
//used by js components to notify the native parts
jsContext.globalObject.setObject(unsafeBitCast(aj_trigger, to: AnyObject.self), forKeyedSubscript: "__trigger" as (NSCopying & NSObjectProtocol))
jsContext.globalObject.setObject(unsafeBitCast(aj_exec, to: AnyObject.self), forKeyedSubscript: "__exec" as (NSCopying & NSObjectProtocol))
jsContext.globalObject.setObject(unsafeBitCast(aj_async, to: AnyObject.self), forKeyedSubscript: "async" as (NSCopying & NSObjectProtocol))
jsContext.globalObject.setObject(unsafeBitCast(aj_setTimeout, to: AnyObject.self), forKeyedSubscript: "setTimeout" as (NSCopying & NSObjectProtocol))
jsContext.globalObject.setObject(unsafeBitCast(aj_setInterval, to: AnyObject.self), forKeyedSubscript: "setInterval" as (NSCopying & NSObjectProtocol))
jsContext.globalObject.setObject(unsafeBitCast(aj_clearTimeout, to: AnyObject.self), forKeyedSubscript: "clearTimeout" as (NSCopying & NSObjectProtocol))
jsContext.globalObject.setObject(unsafeBitCast(aj_clearInterval, to: AnyObject.self), forKeyedSubscript: "clearInterval" as (NSCopying & NSObjectProtocol))
jsContext.globalObject.setObject(AJLogger(), forKeyedSubscript: "logger" as (NSCopying & NSObjectProtocol))
jsContext.evaluateScript("logger.i = function() { logger.__i(Array.prototype.join.call(arguments, ' ')); }")
jsContext.evaluateScript("logger.w = function() { logger.__w(Array.prototype.join.call(arguments, ' ')); }")
jsContext.evaluateScript("logger.e = function() { logger.__e(Array.prototype.join.call(arguments, ' ')); }")
jsContext.globalObject.setObject(AJHttpClient(runtime: self), forKeyedSubscript: "__httpClient" as (NSCopying & NSObjectProtocol))
jsContext.globalObject.setObject(AJAssetsManager(runtime: self), forKeyedSubscript: "__assetsManager" as (NSCopying & NSObjectProtocol))
jsContext.globalObject.setObject(AJStorageManager(runtime: self), forKeyedSubscript: "__storageManager" as (NSCopying & NSObjectProtocol))
jsContext.globalObject.setObject(AJBuffersManager(), forKeyedSubscript: "__buffersManager" as (NSCopying & NSObjectProtocol))
jsContext.globalObject.setObject(AJDevice(), forKeyedSubscript: "device" as (NSCopying & NSObjectProtocol))
jsContext.evaluateScript("var DEBUG = true;")
jsContext.evaluateScript("var LOG_LEVEL_INFO = 3;")
jsContext.evaluateScript("var LOG_LEVEL_WARNING = 2;")
jsContext.evaluateScript("var LOG_LEVEL_ERROR = 1;")
jsContext.evaluateScript("var LOG_LEVEL_DISABLED = 0;")
jsContext.evaluateScript("var LOG_LEVEL = LOG_LEVEL_INFO;")
let appDir = "/assets/js/"
if let url = Bundle.main.path(forResource: "app", ofType: "js", inDirectory: appDir) {
let source = try? String(contentsOfFile: url)
if let source = source {
jsContext.evaluateScript(source)
let main = jsContext.globalObject.objectForKeyedSubscript("main")
if let main = main {
self.jsRuntime = main.call(withArguments: [])
} else {
fatalError("Main function not found in app.js")
}
if self.jsRuntime == nil {
fatalError("Cannot initialize aj runtime")
}
NSLog("Runtime initialized: \(String(describing: jsRuntime?.toDictionary()))")
}
} else {
fatalError("app.js not found")
}
}
open override func run(action: String, data: AJObject = AJObject.empty()) -> AJSemaphore {
if let jr = self.jsRuntime {
let semaphore = AJFakeSemaphore(action: { () -> Void in
let dict = data.toDict()
jr.invokeMethod("run", withArguments: [action, dict])
})
return semaphore
}
fatalError("jsRuntime not initialized")
}
}
|
apache-2.0
|
90f2678f47fa78dd608fbcb2bcae7e50
| 49.041096 | 163 | 0.617301 | 4.704443 | false | false | false | false |
kdawgwilk/vapor
|
Tests/Vapor/SessionTests.swift
|
1
|
3633
|
@testable import Vapor
import XCTest
class SessionTests: XCTestCase {
static let allTests = [
("testDestroy_asksDriverToDestroy", testDestroy_asksDriverToDestroy),
("testSubscriptGet_asksDriverForValue", testSubscriptGet_asksDriverForValue),
("testSubscriptSet_asksDriverToSetValue", testSubscriptSet_asksDriverToSetValue),
("testIdentifierCreation", testIdentifierCreation)
]
func testDestroy_asksDriverToDestroy() {
let driver = TestDriver()
let subject = Session(identifier: "baz", sessions: driver)
subject.destroy()
guard let action = driver.actions.first, case .Destroy = action else {
XCTFail("No actions recorded or recorded action was not a destroy action")
return
}
}
func testSubscriptGet_asksDriverForValue() {
let driver = TestDriver()
let subject = Session(identifier: "baz", sessions: driver)
_ = subject["test"]
guard let action = driver.actions.first, case .ValueFor(let key) = action else {
XCTFail("No actions recorded or recorded action was not a value for action")
return
}
XCTAssertEqual(key.key, "test")
}
func testSubscriptSet_asksDriverToSetValue() {
let driver = TestDriver()
let subject = Session(identifier: "baz", sessions: driver)
subject["foo"] = "bar"
guard let action = driver.actions.first, case .SetValue(let key) = action else {
XCTFail("No actions recorded or recorded action was not a set value action")
return
}
XCTAssertEqual(key.value, "bar")
XCTAssertEqual(key.key, "foo")
}
func testIdentifierCreation() throws {
let drop = Droplet()
drop.get("cookie") { request in
request.session?["hi"] = "test"
return "hi"
}
let request = try Request(method: .get, path: "cookie")
request.headers["Cookie"] = "vapor-session=123"
let response = try drop.respond(to: request)
var sessionMiddleware: SessionMiddleware?
for middleware in drop.globalMiddleware {
if let middleware = middleware as? SessionMiddleware {
sessionMiddleware = middleware
}
}
XCTAssert(sessionMiddleware != nil, "Could not find session middleware")
XCTAssert(sessionMiddleware?.sessions.contains(identifier: "123") == false, "Session should not contain 123")
XCTAssert(response.cookies["vapor-session"] != nil, "No cookie was added")
let id = response.cookies["vapor-session"] ?? ""
XCTAssert(sessionMiddleware?.sessions.contains(identifier: id) == true, "Session did not contain cookie")
}
}
private class TestDriver: Sessions {
var drop = Droplet()
enum Action {
case ValueFor(key: String, identifier: String)
case SetValue(value: String?, key: String, identifier: String)
case Destroy(identifier: String)
}
var actions = [Action]()
func makeIdentifier() -> String {
return "Foo"
}
func value(for key: String, identifier: String) -> String? {
actions.append(.ValueFor(key: key, identifier: identifier))
return nil
}
private func contains(identifier: String) -> Bool {
return false
}
func set(_ value: String?, for key: String, identifier: String) {
actions.append(.SetValue(value: value, key: key, identifier: identifier))
}
func destroy(_ identifier: String) {
actions.append(.Destroy(identifier: identifier))
}
}
|
mit
|
0b27873a30a75385769c80196bf36797
| 31.4375 | 117 | 0.63281 | 4.633929 | false | true | false | false |
DemocracyClass-HWs/VotingBooth-CastVote-iOS
|
VotingBooth/VotingBooth/ThankYouPage.swift
|
1
|
6263
|
//
// ThankYouPage.swift
// VotingBooth
//
// Created by Peyman Mortazavi on 11/13/15.
// Copyright © 2015 Peyman. All rights reserved.
//
import UIKit
class ThankYouPage: PageViewController {
private var button = UIButton()
private var timer : NSTimer?
override func viewDidLoad() {
super.viewDidLoad()
// Send the vote
if let candidate = selectedCandidate, let policy = selectedPolicy {
let voteSubmissionDictionary = ["candidate_id" : candidate.id, "policy_id" : policy.id]
socket?.emit("votesubmission", args: [voteSubmissionDictionary])
}
// Picture
let imageView = UIImageView()
imageView.image = UIImage(named: "thankyou")
self.container.addSubview(imageView)
imageView.contentMode = .ScaleAspectFit
imageView.snp_makeConstraints { (make) -> Void in
make.top.left.right.equalTo(self.container).inset(10)
make.height.equalTo(self.container).dividedBy(3.5)
}
// Results
let policyLabel = UILabel()
policyLabel.font = largeTitleFont?.fontWithSize(30)
policyLabel.textAlignment = .Center
policyLabel.lineBreakMode = .ByWordWrapping
policyLabel.numberOfLines = 0
self.container.addSubview(policyLabel)
policyLabel.snp_makeConstraints { (make) -> Void in
make.left.equalTo(self.container).offset(50)
make.top.equalTo(imageView.snp_bottom).offset(15)
make.width.equalTo(self.container).dividedBy(2.5)
make.height.equalTo(self.container).dividedBy(3.5)
}
let candidateLabel = UILabel()
candidateLabel.font = largeTitleFont?.fontWithSize(30)
candidateLabel.textAlignment = .Center
candidateLabel.lineBreakMode = .ByWordWrapping
candidateLabel.numberOfLines = 0
self.container.addSubview(candidateLabel)
candidateLabel.snp_makeConstraints { (make) -> Void in
make.left.equalTo(policyLabel.snp_left)
make.top.equalTo(policyLabel.snp_bottom).offset(20)
make.width.height.equalTo(policyLabel)
}
// Pictures
let policyImageView = UIImageView()
policyImageView.contentMode = .ScaleAspectFit
policyImageView.layer.shadowRadius = 10
policyImageView.layer.shadowOpacity = 1
if let policy = selectedPolicy, let candidate = data?.candidates.filter({ (candidate) -> Bool in
candidate.id == policy.corrospondingCandidateId
})[0] {
policyImageView.sd_setImageWithURL(NSURL(string: candidate.imageUrl))
policyLabel.text = "Position \(selectedPolicyName!)\nwas\n\(candidate.name)"
switch(candidate.party) {
case .Democratic:
policyImageView.layer.shadowColor = textColor.CGColor
case.Republican:
policyImageView.layer.shadowColor = UIColor.redColor().CGColor
case _:
policyImageView.layer.shadowColor = UIColor.grayColor().CGColor
}
}
self.container.addSubview(policyImageView)
policyImageView.snp_makeConstraints { (make) -> Void in
make.left.equalTo(policyLabel.snp_right)
make.right.equalTo(self.container)
make.height.equalTo(policyLabel.snp_height)
make.top.equalTo(policyLabel.snp_top)
}
let candidateImageView = UIImageView()
candidateImageView.contentMode = .ScaleAspectFit
candidateImageView.layer.shadowRadius = 10
candidateImageView.layer.shadowOpacity = 1
if let candidate = selectedCandidate {
candidateImageView.sd_setImageWithURL(NSURL(string: candidate.imageUrl))
candidateLabel.text = "Image Vote\nwas\n\(candidate.name)"
switch(candidate.party) {
case .Democratic:
candidateImageView.layer.shadowColor = textColor.CGColor
case.Republican:
candidateImageView.layer.shadowColor = UIColor.redColor().CGColor
case _:
candidateImageView.layer.shadowColor = UIColor.grayColor().CGColor
}
}
self.container.addSubview(candidateImageView)
candidateImageView.snp_makeConstraints { (make) -> Void in
make.left.equalTo(candidateLabel.snp_right)
make.right.equalTo(self.container)
make.height.equalTo(candidateLabel.snp_height)
make.top.equalTo(candidateLabel.snp_top)
}
// Button
button.backgroundColor = UIColor.orangeColor()
self.container.addSubview(button)
button.snp_makeConstraints { (make) -> Void in
make.left.right.bottom.equalTo(self.container)
make.height.equalTo(60)
}
button.backgroundColor = UIColor(white: 200/255, alpha: 1)
tick()
self.timer = NSTimer.scheduledTimerWithTimeInterval(1, target: self, selector: "tick", userInfo: nil, repeats: true)
}
var counter = 11
func tick() {
dispatch_async(dispatch_get_main_queue()) { () -> Void in
self.counter--
self.button.setAttributedTitle(NSAttributedString(string: "Starting over in \(self.counter) seconds...", attributes: [NSFontAttributeName:titleFont!.fontWithSize(28), NSForegroundColorAttributeName:UIColor.whiteColor()]), forState: .Normal)
if(self.counter == 0) {
self.timer?.invalidate()
self.timer = nil
self.finish_tapped()
}
}
}
override func prefersStatusBarHidden() -> Bool {
return true
}
func finish_tapped() {
let secondNavigationController = self.navigationController?.viewControllers[1]
UIView.animateWithDuration(0.75) { () -> Void in
UIView.setAnimationCurve(.EaseInOut)
UIView.setAnimationTransition(.FlipFromLeft, forView: (self.navigationController?.view)!, cache: false)
}
self.navigationController?.popToViewController(secondNavigationController!, animated: false)
}
}
|
gpl-2.0
|
fed764f9d49886c90cb5f4be2d9057fd
| 39.4 | 252 | 0.629032 | 4.846749 | false | false | false | false |
erikmartens/NearbyWeather
|
NearbyWeather/Routing/Main Flow/MainFlow.swift
|
1
|
2145
|
//
// MainFlow.swift
// NearbyWeather
//
// Created by Erik Maximilian Martens on 19.04.20.
// Copyright © 2020 Erik Maximilian Martens. All rights reserved.
//
import RxFlow
import Swinject
// MARK: - Dependencies
extension MainFlow {
struct Dependencies {
let dependencyContainer: Container
}
}
// MARK: - Class Definition
final class MainFlow: Flow {
// MARK: - Assets
var root: Presentable {
rootViewController
}
private lazy var rootViewController = Factory.TabBarController.make(fromType: .standard)
// MARK: - Properties
let dependencies: Dependencies
// MARK: - Initialization
init(dependencies: Dependencies) {
self.dependencies = dependencies
}
deinit {
printDebugMessage(
domain: String(describing: self),
message: "was deinitialized",
type: .info
)
}
// MARK: - Functions
func navigate(to step: Step) -> FlowContributors {
guard let step = step as? MainStep else {
return .none
}
switch step {
case .main:
return summonRootTabBar()
}
}
}
// MARK: - Summoning Functions
private extension MainFlow {
func summonRootTabBar() -> FlowContributors {
let listFlow = WeatherListFlow(dependencies: WeatherListFlow.Dependencies(dependencyContainer: dependencies.dependencyContainer))
let mapFlow = WeatherMapFlow(dependencies: WeatherMapFlow.Dependencies(dependencyContainer: dependencies.dependencyContainer))
let settingsFlow = SettingsFlow(dependencies: SettingsFlow.Dependencies(dependencyContainer: dependencies.dependencyContainer))
Flows.use([listFlow, mapFlow, settingsFlow], when: .ready) { [unowned rootViewController] rootViewControllers in
rootViewController.viewControllers = rootViewControllers
}
return .multiple(flowContributors: [
.contribute(withNextPresentable: listFlow, withNextStepper: WeatherListStepper(dependencyContainer: dependencies.dependencyContainer)),
.contribute(withNextPresentable: mapFlow, withNextStepper: WeatherMapStepper()),
.contribute(withNextPresentable: settingsFlow, withNextStepper: SettingsStepper())
])
}
}
|
mit
|
5366a0e3602fc267bdb9f68a3d621155
| 24.831325 | 141 | 0.729478 | 4.53277 | false | false | false | false |
Tinker-S/SpriteKitDemoBySwift
|
SpriteKitDemoBySwift/GameOverScene.swift
|
1
|
1089
|
//
// GameScene.swift
// SpriteKitDemoBySwift
//
// Created by Ting Sun on 7/29/14.
// Copyright (c) 2014 Tinker S. All rights reserved.
//
import SpriteKit
class GameOverScene: SKScene, SKPhysicsContactDelegate {
var won: Bool = false
init(size: CGSize, won: Bool) {
super.init(size: size)
self.won = won
}
override func didMoveToView(view: SKView) {
let myLabel = SKLabelNode(fontNamed:"Chalkduster")
if self.won {
myLabel.text = "You Win!!!"
} else {
myLabel.text = "You Lose!!!"
}
myLabel.fontSize = 80
myLabel.position = CGPoint(x:CGRectGetMidX(self.frame), y:CGRectGetMidY(self.frame))
self.addChild(myLabel)
}
override func touchesBegan(touches: NSSet, withEvent event: UIEvent) {
let reveal = SKTransition.flipHorizontalWithDuration(0.5)
let gameScene = GameScene(size: self.size)
self.view.presentScene(gameScene, transition: reveal)
}
override func update(currentTime: CFTimeInterval) {
}
}
|
apache-2.0
|
6200817c69a511a7fe4860de89e49b3f
| 25.560976 | 92 | 0.621671 | 4.22093 | false | false | false | false |
practicalswift/swift
|
test/IRGen/Inputs/ObjectiveC.swift
|
15
|
1193
|
// This is an overlay Swift module.
@_exported import ObjectiveC
public struct ObjCBool : CustomStringConvertible {
#if os(macOS) || (os(iOS) && (arch(i386) || arch(arm)))
// On macOS and 32-bit iOS, Objective-C's BOOL type is a "signed char".
private var value: Int8
public init(_ value: Bool) {
self.value = value ? 1 : 0
}
/// Allow use in a Boolean context.
public var boolValue: Bool {
return value != 0
}
#else
// Everywhere else it is C/C++'s "Bool"
private var value: Bool
public init(_ value: Bool) {
self.value = value
}
public var boolValue: Bool {
return value
}
#endif
public var description: String {
// Dispatch to Bool.
return self.boolValue.description
}
}
public struct Selector {
private var ptr : OpaquePointer
}
// Functions used to implicitly bridge ObjCBool types to Swift's Bool type.
public func _convertBoolToObjCBool(_ x: Bool) -> ObjCBool {
return ObjCBool(x)
}
public func _convertObjCBoolToBool(_ x: ObjCBool) -> Bool {
return x.boolValue
}
extension NSObject : Hashable {
public func hash(into hasher: inout Hasher) {}
}
public func ==(x: NSObject, y: NSObject) -> Bool { return x === y }
|
apache-2.0
|
2b816ae804b360cefddc08abc31819bc
| 21.509434 | 75 | 0.66974 | 3.787302 | false | false | false | false |
turingcorp/gattaca
|
UnitTests/Model/Session/TMSessionFirebase.swift
|
1
|
7220
|
import XCTest
@testable import gattaca
class TMSessionFirebase:XCTestCase
{
private var firebase:FDatabase?
private var coreData:Database?
private var session:DSession?
private var modelSession:MSession?
private let kUnknownId:String = "unknown_id"
private let kWaitExpectation:TimeInterval = 2
override func setUp()
{
super.setUp()
let currentBundle:Bundle = Bundle(for:TMSessionFirebase.self)
modelSession = MSession()
firebase = FDatabase()
coreData = Database(bundle:currentBundle)
coreData?.create
{ [weak self] (session:DSession) in
session.initialValues()
self?.session = session
}
}
//MARK: internal
func testSync()
{
guard
let coreData:Database = self.coreData,
let session:DSession = self.session,
let modelSession:MSession = self.modelSession
else
{
return
}
let syncExpectation:XCTestExpectation = expectation(
description:"sync firebase")
modelSession.syncFirebase(
coreData:coreData,
session:session)
{
syncExpectation.fulfill()
}
waitForExpectations(timeout:kWaitExpectation)
{ (error:Error?) in
XCTAssertNotNil(
session.userId,
"user id not loaded")
}
}
func testCreateInFirebase()
{
guard
let firebase:FDatabase = self.firebase,
let modelSession:MSession = self.modelSession
else
{
return
}
let users:FDatabaseUsers = FDatabaseUsers()
let createExpectation:XCTestExpectation = expectation(
description:"create in firebase")
var firebaseUser:FDatabaseUsersItem?
modelSession.createInFirebase(
firebase:firebase,
users:users)
{ (user:FDatabaseUsersItem) in
firebaseUser = user
createExpectation.fulfill()
}
waitForExpectations(timeout:kWaitExpectation)
{ (error:Error?) in
XCTAssertNotNil(
firebaseUser,
"failed loading user")
XCTAssertNotNil(
firebaseUser?.identifier,
"user has no identifier")
}
}
func testLoadFromFirebase()
{
var firebaseUser:FDatabaseUsersItem?
let users:FDatabaseUsers = FDatabaseUsers()
let user:FDatabaseUsersItem = FDatabaseUsersItem(
users:users)
guard
let firebase:FDatabase = self.firebase,
let modelSession:MSession = self.modelSession,
let userJson:Any = user.json
else
{
return
}
let loadExpectation:XCTestExpectation = expectation(
description:"load from firebase")
let userId:String = firebase.create(
parent:users,
data:userJson)
modelSession.loadFromFirebase(
userId:userId,
firebase:firebase,
users:users)
{ (userLoaded:FDatabaseUsersItem) in
firebase.load(
parent:users,
identifier:userId)
{ (retrieved:FDatabaseUsersItem?) in
firebaseUser = retrieved
loadExpectation.fulfill()
}
}
waitForExpectations(timeout:kWaitExpectation)
{ (error:Error?) in
XCTAssertNotNil(
firebaseUser,
"failed loading user")
XCTAssertNotNil(
firebaseUser?.identifier,
"user has no identifier")
guard
let firebaseUser:FDatabaseUsersItem = firebaseUser
else
{
return
}
XCTAssertGreaterThan(
firebaseUser.syncstamp,
user.syncstamp,
"user syncstamp not updated")
}
}
func testLoadUnknownId()
{
var firebaseUser:FDatabaseUsersItem?
let users:FDatabaseUsers = FDatabaseUsers()
guard
let firebase:FDatabase = self.firebase,
let modelSession:MSession = self.modelSession
else
{
return
}
let loadExpectation:XCTestExpectation = expectation(
description:"load from firebase")
modelSession.loadFromFirebase(
userId:kUnknownId,
firebase:firebase,
users:users)
{ (userLoaded:FDatabaseUsersItem) in
firebaseUser = userLoaded
loadExpectation.fulfill()
}
waitForExpectations(timeout:kWaitExpectation)
{ (error:Error?) in
XCTAssertNotNil(
firebaseUser,
"failed loading unknown id")
XCTAssertNotNil(
firebaseUser?.identifier,
"user has no identifier")
}
}
func testStatusUpdates()
{
let users:FDatabaseUsers = FDatabaseUsers()
let user:FDatabaseUsersItem = FDatabaseUsersItem(
users:users)
guard
let firebase:FDatabase = self.firebase,
let coreData:Database = self.coreData,
let session:DSession = self.session,
let modelSession:MSession = self.modelSession,
let userJson:Any = user.json
else
{
return
}
let userId:String = firebase.create(
parent:users,
data:userJson)
user.identifier = userId
session.userId = userId
let status:DSession.Status = DSession.Status.banned
guard
let userStatus:FDatabaseUsersItemStatus = FDatabaseUsersItemStatus(
user:user)
else
{
return
}
userStatus.status = status
firebase.update(model:userStatus)
let syncExpectation:XCTestExpectation = expectation(
description:"sync firebase")
modelSession.syncFirebase(
coreData:coreData,
session:session)
{
syncExpectation.fulfill()
}
waitForExpectations(timeout:kWaitExpectation)
{ (error:Error?) in
let sessionStatus:DSession.Status = session.status
XCTAssertEqual(
sessionStatus,
status,
"sync not updating stauts")
}
}
}
|
mit
|
ebded8324230f3330138fe2c380fc05a
| 25.15942 | 79 | 0.505956 | 5.947282 | false | false | false | false |
Narcis11/PitchPerfect
|
PlaySoundsViewController.swift
|
1
|
3434
|
//
// PlaySoundsViewController.swift
// PitchPerfect
//
// Created by Narcis Mihai on 01/02/2016.
// Copyright © 2016 Narcis Mihai. All rights reserved.
//
import UIKit
import AVFoundation
class PlaySoundsViewController: UIViewController {
@IBOutlet weak var fastButton: UIButton!
@IBOutlet weak var slowButton: UIButton!
var audioPlayer : AVAudioPlayer!
var receivedAudio:RecordedAudio!
var audioEngine:AVAudioEngine!
var audioTimePitch:AVAudioUnitTimePitch!
var audioFile:AVAudioFile!
@IBOutlet weak var stopButton: UIButton!
@IBOutlet weak var vaderButton: UIButton!
@IBOutlet weak var chipmunkButton: UIButton!
override func viewDidLoad() {
super.viewDidLoad()
//receivedAudio = RecordedAudio()
//print("File path url: " + String(receivedAudio.filePathUrl))
//let urlPath:NSURL = receivedAudio.da//NSBundle.mainBundle().URLForResource("movie_quote", withExtension: "mp3")!
do { audioPlayer = try AVAudioPlayer(contentsOfURL: receivedAudio.filePathUrl, fileTypeHint: nil)}
catch let error as NSError { print(error.description) }
audioEngine = AVAudioEngine()
audioFile = try! AVAudioFile(forReading: receivedAudio.filePathUrl)
// Do any additional setup after loading the view.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func playSlowAudio(sender: AnyObject) {
print("in playSlowAudio")
audioPlayer.enableRate = true;
audioPlayer.rate = 0.6;
audioPlayer.currentTime = 0.0;
audioPlayer.play()
}
@IBAction func playFastAudio(sender: AnyObject) {
audioPlayer.enableRate = true;
audioPlayer.rate = 2;
audioPlayer.currentTime = 0.0;
audioPlayer.play()
}
@IBAction func stopAudioPlay(sender: AnyObject) {
if audioPlayer.playing {
audioPlayer.stop()
}
}
@IBAction func playChipmunkAudioEffect(sender: UIButton) {
playAudioWithVariablePitch(1000)
}
@IBAction func playVaderAudioEffect(sender: UIButton) {
playAudioWithVariablePitch(-1000)
}
func playAudioWithVariablePitch(pitch: Float) {
audioPlayer.stop()
audioEngine.stop()
audioEngine.reset()
let audioPlayerNode = AVAudioPlayerNode()
audioEngine.attachNode(audioPlayerNode)
let changePitchEffect = AVAudioUnitTimePitch()
changePitchEffect.pitch = pitch
audioEngine.attachNode(changePitchEffect)
audioEngine.connect(audioPlayerNode, to: changePitchEffect, format: nil)
audioEngine.connect(changePitchEffect, to: audioEngine.outputNode, format: nil)
audioPlayerNode.scheduleFile(audioFile, atTime: nil, completionHandler: nil)
try! audioEngine.start()
audioPlayerNode.play()
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
|
gpl-3.0
|
a02e581709d6f1209aca93baf585898d
| 31.386792 | 122 | 0.667055 | 5.048529 | false | false | false | false |
IntrepidPursuits/swift-wisdom
|
SwiftWisdom/Core/StandardLibrary/Array/Array+Utilities.swift
|
1
|
6321
|
//
// Array+Utilities.swift
// SwiftWisdom
//
import Foundation
extension Array {
/// Creates an array containing the elements at the indices passed in. If an index is out of the array's bounds it will be ignored.
///
/// - parameter indices: An array of integers representing the indices to grab
///
/// - returns: An array of elements at the specified indices
public func ip_subArray(fromIndices indices: [Int]) -> [Element] {
var subArray: [Element] = []
for (idx, element) in enumerated() {
if indices.contains(idx) {
subArray.append(element)
}
}
return subArray
}
@available (*, unavailable, message: "use allSatisfy(_:) instead")
public func ip_passes(test: (Element) -> Bool) -> Bool {
for ob in self {
if test(ob) {
return true
}
}
return false
}
}
extension Array {
/// Separates this array's elements into chunks with a given length. Elements in these chunks and the chunks themselves
/// are ordered the same way they are ordered in this array.
///
/// If this array is empty, we always return an empty array.
///
/// If `length` is not a positive number or if it's greater than or equal to this array's length, we return a new array
/// with no chunks at all, plus the "remainder" which is this array itself iff `includeRemainder` is `true`.
///
/// - parameter length: Number of elements in each chunk.
/// - parameter includeRemainder: If set to `true`, include the remainder in returned array even if its length is less than
/// `length`. If set to `false`, discard the remainder. Defaults to `true`.
///
/// - returns: New array of chunks of elements in this array.
public func ip_chunks(of length: Int, includeRemainder: Bool = true) -> [[Element]] {
guard !isEmpty else { return [] }
guard length > 0 else { return includeRemainder ? [self] : [] }
var chunks = [[Element]]()
var nextChunkLeftIndex = 0
let nextChunkRightIndex = { nextChunkLeftIndex + length - 1 }
while nextChunkRightIndex() < count {
let nextChunk = Array(self[nextChunkLeftIndex...nextChunkRightIndex()])
chunks.append(nextChunk)
nextChunkLeftIndex += length
}
if includeRemainder && nextChunkLeftIndex < count {
let remainder = Array(self[nextChunkLeftIndex..<count])
chunks.append(remainder)
}
return chunks
}
}
extension Array where Element: Equatable {
/// Removes a single element from the array.
///
/// - parameter object: Element to remove
///
/// - returns: Boolean value indicating the success/failure of removing the element.
@discardableResult public mutating func ip_remove(object: Element) -> Bool {
for (idx, objectToCompare) in enumerated() where object == objectToCompare {
remove(at: idx)
return true
}
return false
}
/// Removes multiple elements from an array.
///
/// - parameter elements: Array of elements to remove
public mutating func ip_remove(elements: [Element]) {
self = self.filter { element in
return !elements.contains(element)
}
}
/// Returns NSNotFound for any element in elements that does not exist.
///
/// - parameter elements: Array of Equatable elements
///
/// - returns: Array of indexes or NSNotFound if element does not exist in self; count is equal to the count of `elements`
public func ip_indices(ofElements elements: [Element]) -> [Int] {
return elements.map { element in
return firstIndex(of: element) ?? NSNotFound
}
}
}
extension Array where Element: Hashable {
/// Converts an Array into a Set of the same type.
///
/// - returns: Set of the array's elements
public func ip_toSet() -> Set<Element> {
return Set(self)
}
}
extension Array {
/// Provides a way to safely index into an array. If the index is beyond the array's
/// bounds this method will return `nil`.
///
/// - parameter index: Index of the element to return
///
/// - returns: An `Element` if the index is valid, or `nil` if the index is outside the bounds of the array.
public subscript(ip_safely index: Int) -> Element? {
guard 0 <= index && index < count else { return nil }
return self[index]
}
}
extension Array {
/// Removes the first instance of an element within an array.
///
/// - parameter matcher: The element that should be removed
public mutating func ip_removeFirst(matcher: (Iterator.Element) -> Bool) {
guard let idx = firstIndex(where: matcher) else { return }
remove(at: idx)
}
}
extension Array {
//TODO: Add documentation
public var ip_iterator: AnyIterator<Element> {
var idx = 0
let count = self.count
return AnyIterator {
guard idx < count else { return nil }
defer { idx += 1 }
return self[idx]
}
}
@available (*, unavailable, message: "ip_generator has been renamed to ip_iterator")
public var ip_generator: AnyIterator<Element> {
var idx = 0
let count = self.count
return AnyIterator {
guard idx < count else { return nil }
let this = idx
idx += 1
return self[this]
}
}
}
extension Collection {
/// This grabs the element(s) in the middle of the array without doing any sorting.
/// If there's an odd number the return array is just one element.
/// If there are an even number it will return the two middle elements.
/// The two middle elements will be flipped if the array has an even number.
public var ip_middleElements: [Element] {
guard count > 0 else { return [] }
let needsAverageOfTwo = Int(count).ip_isEven
let middle = index(startIndex, offsetBy: count / 2)
if needsAverageOfTwo {
let leftOfMiddle = index(middle, offsetBy: -1)
return [self[middle], self[leftOfMiddle]]
} else {
return [self[middle]]
}
}
}
|
mit
|
c58e6541477a35a8638ba28fbd5f6f7e
| 33.922652 | 135 | 0.612403 | 4.489347 | false | false | false | false |
jjatie/Charts
|
ChartsDemo-macOS/PlaygroundChart.playground/Pages/BubbleChart.xcplaygroundpage/Contents.swift
|
1
|
2056
|
//
// PlayGround
//
// Copyright 2015 Daniel Cohen Gindi & Philipp Jahoda
// Copyright © 2017 thierry Hentic.
// A port of MPAndroidChart for iOS
// Licensed under Apache License 2.0
//
// https://github.com/danielgindi/ios-charts
/*:
****
[Menu](Menu)
[Previous](@previous)
****
*/
import Charts
//: # Bubble Chart
import Cocoa
import PlaygroundSupport
let ITEM_COUNT = 20
let r = CGRect(x: 0, y: 0, width: 600, height: 600)
var chartView = BubbleChartView(frame: r)
//: ### General
chartView.drawGridBackgroundEnabled = true
//: ### xAxis
let xAxis = chartView.xAxis
xAxis.labelPosition = .bothSided
xAxis.axisMinimum = 0.0
xAxis.granularity = 1.0
//: ### LeftAxis
let leftAxis = chartView.leftAxis
leftAxis.drawGridLinesEnabled = true
leftAxis.axisMinimum = 40.0
//: ### RightAxis
let rightAxis = chartView.rightAxis
rightAxis.drawGridLinesEnabled = true
rightAxis.axisMinimum = 40.0
//: ### Legend
let legend = chartView.legend
legend.wordWrapEnabled = true
legend.horizontalAlignment = .center
legend.verticalAlignment = .bottom
legend.orientation = .horizontal
legend.drawInside = false
//: ### Description
chartView.chartDescription?.enabled = false
//: ### BubbleChartDataEntry
var entries = [BubbleChartDataEntry]()
for index in 0 ..< ITEM_COUNT {
let y = Double(arc4random_uniform(100)) + 50.0
let size = (y - 50) / 25.0
entries.append(BubbleChartDataEntry(x: Double(index) + 0.5, y: y, size: CGFloat(size)))
}
//: ### BubbleChartDataSet
let set = BubbleChartDataSet(values: entries, label: "Bubble DataSet")
set.colors = ChartColorTemplates.vordiplom()
set.valueTextColor = NSUIColor.labelOrBlack
set.valueFont = NSUIFont.systemFont(ofSize: CGFloat(10.0))
set.drawValuesEnabled = true
set.normalizeSizeEnabled = false
//: ### BubbleChartData
let data = BubbleChartData()
data.addDataSet(set)
chartView.data = data
chartView.animate(xAxisDuration: 1.0, yAxisDuration: 1.0)
/*:---*/
//: ### Setup for the live view
PlaygroundPage.current.liveView = chartView
/*:
****
[Menu](Menu)
[Previous](@previous)
****
*/
|
apache-2.0
|
fc2befe07893a0f78c06ff15a7cfc1e0
| 24.37037 | 91 | 0.720681 | 3.819703 | false | false | false | false |
domenicosolazzo/practice-swift
|
Camera/Photo Extension/PhotoEditExtension/PhotoEditingViewController.swift
|
1
|
4937
|
//
// PhotoEditingViewController.swift
// PhotoEditExtension
//
// Created by Domenico Solazzo on 06/05/15.
// License MIT
//
import UIKit
import Photos
import PhotosUI
import OpenGLES
class PhotoEditingViewController: UIViewController, PHContentEditingController {
/*
An image view on the screen that first shows the original
image to the user; after we are done applying our edits
it will show the edited image
*/
@IBOutlet weak var imageView: UIImageView!
/* The input that the system will give us */
var input: PHContentEditingInput?
/* We give our edits to the user in this way */
var output: PHContentEditingOutput!
/* We give our edits to the user in this way */
let filterName = "CIColorPosterize"
/* How we are telling to the Photos framework who is editing the photo */
let editFormatIdentifier = Bundle.main.bundleIdentifier
let editFormatVersion = "0.1"
/* A queue that will execute our edits in the background */
let operationQueue = OperationQueue()
let shouldShowCancelConfirmation: Bool = true
/* This turns an image into its NSData representation */
func dataFromCiImage(_ image: CIImage) -> Data{
let glContext = EAGLContext(api: .openGLES2)
let context = CIContext(eaglContext: glContext!)
let imageRef = context.createCGImage(image, from: image.extent)
let image = UIImage(cgImage: imageRef!, scale: 1.0, orientation: .up)
return UIImageJPEGRepresentation(image, 1.0)!
}
/* This takes the input and converts it to the output. The output
has our posterized content saved inside it */
func posterizedImageForInput(_ input: PHContentEditingInput) ->
PHContentEditingOutput{
/* Get the required information from the asset */
let url = input.fullSizeImageURL
let orientation = input.fullSizeImageOrientation
/* Retrieve an instance of CIImage to apply our filter to */
let inputImage =
CIImage(contentsOf: url!,
options: nil)?.applyingOrientation(orientation)
/* Apply the filter to our image */
let filter = CIFilter(name: filterName)
filter?.setDefaults()
filter?.setValue(inputImage, forKey: kCIInputImageKey)
let outputImage = filter?.outputImage
/* Get the data of our edited image */
let editedImageData = dataFromCiImage(outputImage!)
/* The results of editing our image are encapsulated here */
let output = PHContentEditingOutput(contentEditingInput: input)
/* Here we are saving our edited image to the URL that is dictated
by the content editing output class */
do{
try editedImageData.write(to:output.renderedContentURL,
options: NSData.WritingOptions.atomicWrite)
}catch{
print("Error!")
}
output.adjustmentData =
PHAdjustmentData(formatIdentifier: editFormatIdentifier!,
formatVersion: editFormatVersion,
data: filterName.data(using: String.Encoding.utf8,
allowLossyConversion: false)!)
return output
}
/* We just want to work with the original image */
func canHandle(_ adjustmentData: PHAdjustmentData) -> Bool {
return false
}
/* This is a closure that we will submit to our operation queue */
func editingOperation(){
output = posterizedImageForInput(input!)
DispatchQueue.main.async(execute: {[weak self] in
let strongSelf = self!
let data = try? Data(contentsOf: strongSelf.output.renderedContentURL,
options: .mappedIfSafe)
let image = UIImage(data: data!)
strongSelf.imageView.image = image
})
}
func startContentEditing(
with contentEditingInput: PHContentEditingInput,
placeholderImage: UIImage) {
imageView.image = placeholderImage
input = contentEditingInput
/* Start the editing in the background */
let block = BlockOperation(block: editingOperation)
operationQueue.addOperation(block)
}
func finishContentEditing(
completionHandler: @escaping (PHContentEditingOutput?) -> Void) {
/* Report our output */
completionHandler(output)
}
/* The user cancelled the editing process */
func cancelContentEditing() {
/* Make sure we stop our operation here */
operationQueue.cancelAllOperations()
}
}
|
mit
|
25cbaa2489682b3c228be68288381a10
| 34.264286 | 82 | 0.610492 | 5.61661 | false | false | false | false |
HabitRPG/habitrpg-ios
|
Habitica Database/Habitica Database/Models/User/RealmAuthentication.swift
|
1
|
1810
|
//
// RealmAuthentication.swift
// Habitica Database
//
// Created by Phillip Thelen on 09.04.18.
// Copyright © 2018 HabitRPG Inc. All rights reserved.
//
import Foundation
import RealmSwift
import Habitica_Models
class RealmAuthentication: Object, AuthenticationProtocol {
var timestamps: AuthenticationTimestampsProtocol? {
get {
return realmTimestamps
}
set {
if let value = newValue as? RealmAuthenticationTimestamps {
realmTimestamps = value
}
if let value = newValue {
realmTimestamps = RealmAuthenticationTimestamps(userID: id, protocolObject: value)
}
}
}
@objc dynamic var realmTimestamps: RealmAuthenticationTimestamps?
var local: LocalAuthenticationProtocol? {
get {
return realmLocal
}
set {
if let value = newValue as? RealmLocalAuthentication {
realmLocal = value
}
if let value = newValue {
realmLocal = RealmLocalAuthentication(userID: id, protocolObject: value)
}
}
}
@objc dynamic var realmLocal: RealmLocalAuthentication?
@objc dynamic var id: String?
@objc dynamic var facebookID: String?
@objc dynamic var googleID: String?
@objc dynamic var appleID: String?
override static func primaryKey() -> String {
return "id"
}
convenience init(userID: String?, protocolObject: AuthenticationProtocol) {
self.init()
self.id = userID
timestamps = protocolObject.timestamps
local = protocolObject.local
facebookID = protocolObject.facebookID
googleID = protocolObject.googleID
appleID = protocolObject.appleID
}
}
|
gpl-3.0
|
85206af869902ffa77fa8f67391f5f84
| 29.15 | 98 | 0.623549 | 5.183381 | false | false | false | false |
rivetlogic/liferay-mobile-directory-ios
|
Liferay-Screens/Source/Auth/LoginScreenlet/LoginScreenlet.swift
|
1
|
2817
|
/**
* Copyright (c) 2000-present Liferay, Inc. All rights reserved.
*
* This library is free software; you can redistribute it and/or modify it under
* the terms of the GNU Lesser General Public License as published by the Free
* Software Foundation; either version 2.1 of the License, or (at your option)
* any later version.
*
* This library 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 Lesser General Public License for more
* details.
*/
import UIKit
@objc public protocol LoginScreenletDelegate {
optional func onLoginResponse(attributes: [String:AnyObject])
optional func onLoginError(error: NSError)
optional func onCredentialsSaved()
optional func onCredentialsLoaded()
}
public class LoginScreenlet: BaseScreenlet, AuthBasedData {
//MARK: Inspectables
@IBInspectable public var authMethod: String? = AuthMethod.Email.rawValue {
didSet {
copyAuth(source: self, target: screenletView)
}
}
@IBInspectable public var saveCredentials: Bool = false {
didSet {
(screenletView as? AuthBasedData)?.saveCredentials = self.saveCredentials
}
}
@IBInspectable public var companyId: Int64 = 0 {
didSet {
(screenletView as? LoginData)?.companyId = self.companyId
}
}
@IBOutlet public var delegate: LoginScreenletDelegate?
internal var loginData: LoginData {
return screenletView as! LoginData
}
//MARK: BaseScreenlet
override internal func onCreated() {
super.onCreated()
copyAuth(source: self, target: screenletView)
loginData.companyId = companyId
if SessionContext.loadSessionFromStore() {
loginData.userName = SessionContext.currentUserName!
loginData.password = SessionContext.currentPassword!
delegate?.onCredentialsLoaded?()
}
}
override internal func onUserAction(actionName: String?, sender: AnyObject?) {
let loginOperation = createLoginOperation(authMethod: AuthMethod.create(authMethod))
loginOperation.validateAndEnqueue() {
if let error = $0.lastError {
self.delegate?.onLoginError?(error)
}
else {
self.onLoginSuccess(loginOperation.resultUserAttributes!)
}
}
}
//MARK: Private methods
private func onLoginSuccess(userAttributes: [String:AnyObject]) {
delegate?.onLoginResponse?(userAttributes)
if saveCredentials {
if SessionContext.storeSession() {
delegate?.onCredentialsSaved?()
}
}
}
private func createLoginOperation(#authMethod: AuthMethod) -> LiferayLoginBaseOperation {
switch authMethod {
case .ScreenName:
return LiferayLoginScreenNameOperation(screenlet: self)
case .UserId:
return LiferayLoginUserIdOperation(screenlet: self)
default:
return LiferayLoginEmailOperation(screenlet: self)
}
}
}
|
gpl-3.0
|
b1c60d01e97225c21352da31a84d3f11
| 23.929204 | 90 | 0.752574 | 3.843111 | false | false | false | false |
Argas/10923748
|
SOADemo/1. PresentationLayer/Modules/ApplicationsViewContrller/DemoModel.swift
|
1
|
1676
|
//
// DemoModel.swift
// SOADemo
//
// Created by a.y.zverev on 12.04.17.
// Copyright © 2017 a.y.zverev. All rights reserved.
//
import UIKit
import Foundation
struct CellDisplayModel {
let title: String
let imageUrl: String
}
protocol IDemoModel: class {
weak var delegate: IDemoModelDelegate? { get set }
func fetchNewApps()
func fetchTopTracks()
}
protocol IDemoModelDelegate: class {
func setup(dataSource: [CellDisplayModel])
func show(error message: String)
}
class DemoModel: IDemoModel {
weak var delegate: IDemoModelDelegate?
let appsService: IAppsService
let tracksService: ITracksService
init(appsService: IAppsService, tracksService: ITracksService) {
self.appsService = appsService
self.tracksService = tracksService
}
func fetchNewApps() {
appsService.loadNewApps { (apps: [AppApiModel]?, error) in
if let apps = apps {
let cells = apps.map({ CellDisplayModel(title: $0.name, imageUrl: $0.iconUrl) })
self.delegate?.setup(dataSource: cells)
} else {
self.delegate?.show(error: error ?? "Error")
}
}
}
func fetchTopTracks() {
tracksService.loadTopTracks { (tracks: [TrackApiModel]?, errorMessage) in
if let tracks = tracks {
let cells = tracks.map({ CellDisplayModel(title: $0.name, imageUrl: $0.coverUrl) })
self.delegate?.setup(dataSource: cells)
} else {
self.delegate?.show(error: errorMessage ?? "Error")
}
}
}
}
|
mit
|
279cf23202f18b441d57580a7defc250
| 25.171875 | 99 | 0.597015 | 4.05569 | false | false | false | false |
ulidev/Zilean
|
SampleCode/SampleCode/Zilean.swift
|
1
|
3317
|
//
// Created by Joan Molinas Ramon on 9/12/15.
// Copyright © 2015 Joan Molinas. All rights reserved.
//
import Foundation
class Zilean {
//MARK: Main functions
class func time <T> (
@autoclosure f f: () -> T,
times : Int) -> Double {
/*
* Return :
* Seconds to execute the function n times.
*/
let start = NSDate()
for _ in 0..<times {
f()
}
let end = NSDate()
return end.timeIntervalSinceDate(start)
}
class func time <T> (
@autoclosure f f:() -> T,
@autoclosure f2:() -> T,
times : Int) -> Double {
/*
* Return :
* 0 if function1 time was equal function2 time
* 1 if function2 time was faster than function1 time
* -1 if function1 time was faster than function2 time
*/
let fTime = time(f: f, times: times)
let f2Time = time(f: f2, times : times)
if fTime == f2Time { return 0 }
else if fTime < f2Time { return -1 }
else { return 1 }
}
}
extension Zilean {
//MARK: Most simple functions
class func time <T> (
@autoclosure f f:() -> T) -> Double {
return time(f: f, times: 1)
}
class func time <T> (
@autoclosure f f:() -> T,
@autoclosure f2:() -> T) -> Double {
return time(f: f, f2: f2, times: 1)
}
}
extension Zilean {
//MARK: Functions with Log
class func timeLog <T> (
@autoclosure f f:() -> T) {
print("Seconds: \(time(f: f, times: 1))")
}
class func timeLog <T> (
@autoclosure f f:() -> T,
times : Int) {
print("Seconds: \(time(f: f, times: times))")
}
class func timeLog <T> (
@autoclosure f f:() -> T,
@autoclosure f2:() -> T) {
print(time(f: f, f2: f2, times: 1))
}
class func timeLog <T> (
@autoclosure f f:() -> T,
@autoclosure f2:() -> T,
times : Int) {
print(time(f: f, f2: f2, times: times))
}
class func timesLog <T> (
@autoclosure f f: () -> T,
@autoclosure f2 : () -> T,
times : Int) {
let fTime = time(f: f, times: times)
let f2Time = time(f: f2, times : times)
print("Seconds: f1 = \(fTime), f2 = \(f2Time)")
}
class func timesLog <T> (
@autoclosure f f: () -> T,
@autoclosure f2 : () -> T) {
print(times(f: f, f2: f2, times: 1))
}
}
extension Zilean {
//MARK: Functions return 2 value times
class func times <T> (
@autoclosure f f: () -> T,
@autoclosure f2 : () -> T,
times : Int) -> (Double, Double) {
let fTime = time(f: f, times: times)
let f2Time = time(f: f2, times : times)
return (fTime, f2Time)
}
class func times <T> (
@autoclosure f f: () -> T,
@autoclosure f2 : () -> T) -> (Double, Double) {
return times(f: f, f2: f2, times: 1)
}
}
|
mit
|
b434b495ad7f4302b439f74dbefd6c41
| 24.515385 | 65 | 0.443908 | 3.798396 | false | false | false | false |
Kawoou/FlexibleImage
|
Examples/Example-playground-iOS.playground/Contents.swift
|
1
|
1370
|
import UIKit
import FlexibleImageIOS
let image1 = UIImage
.circle(
color: UIColor.blue,
size: CGSize(width: 100, height: 100)
)?
.adjust()
.offset(CGPoint(x: 25, y: 0))
.margin(EdgeInsets(top: 5, left: 5, bottom: 5, right: 5))
.padding(EdgeInsets(top: 15, left: 15, bottom: 15, right: 15))
.normal(color: UIColor.white)
.border(color: UIColor.red, lineWidth: 5, radius: 50)
.image()?
.adjust()
.background(color: UIColor.darkGray)
.image()
let image2 = UIImage(named: "macaron.jpg")
let image3 = image2?.adjust()
.outputSize(CGSize(width: 250, height: 250))
.exclusion(color: UIColor(red: 0, green: 0, blue: 0.352941176, alpha: 1.0))
.linearDodge(color: UIColor(red: 0.125490196, green: 0.058823529, blue: 0.192156863, alpha: 1.0))
.corner(CornerType(60))
.image()
let image4 = image3?.adjust()
.hardMix(color: UIColor(red: 0.3, green: 0.3, blue: 0.3, alpha: 1.0))
.image()
let image5 = image4?.adjust()
.append(
image1!.adjust()
.outputSize(CGSize(width: 250, height: 250))
.opacity(0.5)
)
.image()
let image6 = image4 + image1
let image7 = image3?.adjust()
.rotate(15 * CGFloat.pi / 180)
.image()
let image8 = image2?.adjust()
.solarize()
.image()
let image9 = image5?.adjust()
.blur(8)
.image()
|
mit
|
1abfb232ba4b6029b9b5bfc323422305
| 23.464286 | 101 | 0.606569 | 3.010989 | false | false | false | false |
fred76/FR76Tranisition
|
LogoReveal/RWLogoLayer.swift
|
1
|
37482
|
import UIKit
import QuartzCore
@IBDesignable class RWLogoLayer : UIView{
let b1 = UIView()
let b2 = UIView()
let b3 = UIView()
let b4 = UIView()
let b5 = UIView()
let b6 = UIView()
let b7 = UIView()
let b8 = UIView()
let b9 = UIView()
let b10 = UIView()
let b11 = UIView()
let b12 = UIView()
let t1 = UIView()
let t2 = UIView()
let t3 = UIView()
let t4 = UIView()
let t5 = UIView()
let t6 = UIView()
let t7 = UIView()
let t8 = UIView()
let t9 = UIView()
let t10 = UIView()
let t11 = UIView()
let t12 = UIView()
var pb1X = UIView()
var pb2X = UIView()
var pb3X = UIView()
var pb4X = UIView()
var pb5X = UIView()
var pb6X = UIView()
var pb7X = UIView()
var pb8X = UIView()
var pb9X = UIView()
var pb10X = UIView()
var pb11X = UIView()
var pb12X = UIView()
var pb13X = UIView()
var pb14X = UIView()
var pb15X = UIView()
var pb16X = UIView()
var pb17X = UIView()
var pb18X = UIView()
var pb19X = UIView()
var pb20X = UIView()
var pb21X = UIView()
var pb22X = UIView()
var pt1X = UIView()
var pt2X = UIView()
var pt3X = UIView()
var pt4X = UIView()
var pt5X = UIView()
var pt6X = UIView()
var pt7X = UIView()
var pt8X = UIView()
var pt9X = UIView()
var pt10X = UIView()
var pt11X = UIView()
var pt12X = UIView()
var pt13X = UIView()
var pt14X = UIView()
var pt15X = UIView()
var pt16X = UIView()
var pt17X = UIView()
var pt18X = UIView()
var pt19X = UIView()
var pt20X = UIView()
var pt21X = UIView()
var pt22X = UIView()
var width : CGFloat!
var height : CGFloat!
let elasticShape = CAShapeLayer()
var displayLink: CADisplayLink!
var animating = false {
didSet {self.isUserInteractionEnabled = !animating
displayLink.isPaused = !animating
} }
var centerViewBottom : [UIView] = []
var centerViewTop : [UIView] = []
var controlPointTop1 : [UIView] = []
var controlPointTop2 : [UIView] = []
var controlPointBottom1 : [UIView] = []
var controlPointBottom2 : [UIView] = []
func setup(frame: CGRect){
b1.center = CGPoint(x: frame.minX + 0.00000 * frame.width, y: frame.minY + 0.00000 * frame.height)
b2.center = CGPoint(x: frame.minX + 0.01777 * frame.width, y: frame.minY + 0.98258 * frame.height)
b3.center = CGPoint(x: frame.minX + 0.02567 * frame.width, y: frame.minY + 0.66777 * frame.height)
b4.center = CGPoint(x: frame.minX + 0.04067 * frame.width, y: frame.minY + 0.79656 * frame.height)
b5.center = CGPoint(x: frame.minX + 0.04067 * frame.width, y: frame.minY + 0.62484 * frame.height)
b6.center = CGPoint(x: frame.minX + 0.05456 * frame.width, y: frame.minY + 0.62484 * frame.height)
b7.center = CGPoint(x: frame.minX + 0.08884 * frame.width, y: frame.minY + 0.58192 * frame.height)
b8.center = CGPoint(x: frame.minX + 0.12401 * frame.width, y: frame.minY + 0.62484 * frame.height)
b9.center = CGPoint(x: frame.minX + 0.14385 * frame.width, y: frame.minY + 0.73932 * frame.height)
b10.center = CGPoint(x: frame.minX + 0.17768 * frame.width, y: frame.minY + 0.66777 * frame.height)
b11.center = CGPoint(x: frame.minX + 0.19348 * frame.width, y: frame.minY + 0.66777 * frame.height)
b12.center = CGPoint(x: frame.minX + 0.19841 * frame.width, y: frame.minY + 0.00000 * frame.height)
t12.center = CGPoint(x: frame.minX + 0.00000 * frame.width, y: frame.minY + 0.00000 * frame.height)
t11.center = CGPoint(x: frame.minX + 0.01777 * frame.width, y: frame.minY + 0.98258 * frame.height)
t10.center = CGPoint(x: frame.minX + 0.02567 * frame.width, y: frame.minY + 0.66777 * frame.height)
t9.center = CGPoint(x: frame.minX + 0.04067 * frame.width, y: frame.minY + 0.79656 * frame.height)
t8.center = CGPoint(x: frame.minX + 0.04067 * frame.width, y: frame.minY + 0.62484 * frame.height)
t7.center = CGPoint(x: frame.minX + 0.05456 * frame.width, y: frame.minY + 0.62484 * frame.height)
t6.center = CGPoint(x: frame.minX + 0.08884 * frame.width, y: frame.minY + 0.58192 * frame.height)
t5.center = CGPoint(x: frame.minX + 0.12401 * frame.width, y: frame.minY + 0.62484 * frame.height)
t4.center = CGPoint(x: frame.minX + 0.14385 * frame.width, y: frame.minY + 0.73932 * frame.height)
t3.center = CGPoint(x: frame.minX + 0.17768 * frame.width, y: frame.minY + 0.66777 * frame.height)
t2.center = CGPoint(x: frame.minX + 0.19348 * frame.width, y: frame.minY + 0.66777 * frame.height)
t1.center = CGPoint(x: frame.minX + 0.19841 * frame.width, y: frame.minY + 0.00000 * frame.height)
pb1X.center = CGPoint(x: frame.minX + 0.00000 * frame.width, y: frame.minY + 0.00000 * frame.height)
pb2X.center = CGPoint(x: frame.minX + 0.01185 * frame.width, y: frame.minY + 1.15429 * frame.height)
pb3X.center = CGPoint(x: frame.minX + 0.02369 * frame.width, y: frame.minY + 0.81087 * frame.height)
pb4X.center = CGPoint(x: frame.minX + 0.02480 * frame.width, y: frame.minY + 0.76794 * frame.height)
pb5X.center = CGPoint(x: frame.minX + 0.02653 * frame.width, y: frame.minY + 0.56761 * frame.height)
pb6X.center = CGPoint(x: frame.minX + 0.03870 * frame.width, y: frame.minY + 0.79656 * frame.height)
pb7X.center = CGPoint(x: frame.minX + 0.04265 * frame.width, y: frame.minY + 0.79656 * frame.height)
pb8X.center = CGPoint(x: frame.minX + 0.03475 * frame.width, y: frame.minY + 0.62484 * frame.height)
pb9X.center = CGPoint(x: frame.minX + 0.04660 * frame.width, y: frame.minY + 0.62484 * frame.height)
pb10X.center = CGPoint(x: frame.minX + 0.05456 * frame.width, y: frame.minY + 0.62484 * frame.height)
pb11X.center = CGPoint(x: frame.minX + 0.05456 * frame.width, y: frame.minY + 0.62484 * frame.height)
pb12X.center = CGPoint(x: frame.minX + 0.06712 * frame.width, y: frame.minY + 0.25757 * frame.height)
pb13X.center = CGPoint(x: frame.minX + 0.11056 * frame.width, y: frame.minY + 0.90626 * frame.height)
pb14X.center = CGPoint(x: frame.minX + 0.11409 * frame.width, y: frame.minY + 0.80610 * frame.height)
pb15X.center = CGPoint(x: frame.minX + 0.13393 * frame.width, y: frame.minY + 0.44359 * frame.height)
pb16X.center = CGPoint(x: frame.minX + 0.13003 * frame.width, y: frame.minY + 0.73932 * frame.height)
pb17X.center = CGPoint(x: frame.minX + 0.15767 * frame.width, y: frame.minY + 0.73932 * frame.height)
pb18X.center = CGPoint(x: frame.minX + 0.17176 * frame.width, y: frame.minY + 0.58192 * frame.height)
pb19X.center = CGPoint(x: frame.minX + 0.18361 * frame.width, y: frame.minY + 0.75363 * frame.height)
pb20X.center = CGPoint(x: frame.minX + 0.19348 * frame.width, y: frame.minY + 0.86810 * frame.height)
pb21X.center = CGPoint(x: frame.minX + 0.19348 * frame.width, y: frame.minY + 0.46744 * frame.height)
pb22X.center = CGPoint(x: frame.minX + 0.19841 * frame.width, y: frame.minY + 0.00000 * frame.height)
pt1X.center = CGPoint(x: frame.minX + 0.19841 * frame.width, y: frame.minY + 0.00000 * frame.height)
pt2X.center = CGPoint(x: frame.minX + 0.19348 * frame.width, y: frame.minY + 0.46744 * frame.height)
pt3X.center = CGPoint(x: frame.minX + 0.19348 * frame.width, y: frame.minY + 0.86810 * frame.height)
pt4X.center = CGPoint(x: frame.minX + 0.18361 * frame.width, y: frame.minY + 0.75363 * frame.height)
pt5X.center = CGPoint(x: frame.minX + 0.17176 * frame.width, y: frame.minY + 0.58192 * frame.height)
pt6X.center = CGPoint(x: frame.minX + 0.15767 * frame.width, y: frame.minY + 0.73932 * frame.height)
pt7X.center = CGPoint(x: frame.minX + 0.13003 * frame.width, y: frame.minY + 0.73932 * frame.height)
pt8X.center = CGPoint(x: frame.minX + 0.13393 * frame.width, y: frame.minY + 0.44359 * frame.height)
pt9X.center = CGPoint(x: frame.minX + 0.11409 * frame.width, y: frame.minY + 0.80610 * frame.height)
pt10X.center = CGPoint(x: frame.minX + 0.11056 * frame.width, y: frame.minY + 0.90626 * frame.height)
pt11X.center = CGPoint(x: frame.minX + 0.06712 * frame.width, y: frame.minY + 0.25757 * frame.height)
pt12X.center = CGPoint(x: frame.minX + 0.05456 * frame.width, y: frame.minY + 0.62484 * frame.height)
pt13X.center = CGPoint(x: frame.minX + 0.05456 * frame.width, y: frame.minY + 0.62484 * frame.height)
pt14X.center = CGPoint(x: frame.minX + 0.04660 * frame.width, y: frame.minY + 0.62484 * frame.height)
pt15X.center = CGPoint(x: frame.minX + 0.03475 * frame.width, y: frame.minY + 0.62484 * frame.height)
pt16X.center = CGPoint(x: frame.minX + 0.04265 * frame.width, y: frame.minY + 0.79656 * frame.height)
pt17X.center = CGPoint(x: frame.minX + 0.03870 * frame.width, y: frame.minY + 0.79656 * frame.height)
pt18X.center = CGPoint(x: frame.minX + 0.02653 * frame.width, y: frame.minY + 0.56761 * frame.height)
pt19X.center = CGPoint(x: frame.minX + 0.02480 * frame.width, y: frame.minY + 0.76794 * frame.height)
pt20X.center = CGPoint(x: frame.minX + 0.02369 * frame.width, y: frame.minY + 0.81087 * frame.height)
pt21X.center = CGPoint(x: frame.minX + 0.01185 * frame.width, y: frame.minY + 1.15429 * frame.height)
pt22X.center = CGPoint(x: frame.minX + 0.00000 * frame.width, y: frame.minY + 0.00000 * frame.height)
centerViewBottom=[b2,b3,b4, b5,b6,b7, b8,b9, b10,b11, b12]
controlPointBottom1 = [pb1X, pb3X, pb5X, pb7X, pb9X, pb11X, pb13X, pb15X, pb17X, pb19X, pb21X]
controlPointBottom2 = [pb2X, pb4X, pb6X, pb8X, pb10X, pb12X, pb14X, pb16X, pb18X, pb20X, pb22X]
centerViewTop=[t2,t3, t4,t5,t6, t7,t8, t9,t10, t11, t12]
controlPointTop1 = [pt1X, pt3X, pt5X, pt7X, pt9X, pt11X, pt13X, pt15X, pt17X, pt19X, pt21X]
controlPointTop2 = [pt2X, pt4X, pt6X, pt8X, pt10X, pt12X, pt14X, pt16X, pt18X, pt20X, pt22X]
elasticShape.path = bezierPathForControlPoints()
elasticShape.strokeColor = UIColor.white.cgColor
elasticShape.lineWidth = 2
layer.insertSublayer(elasticShape, at: 0)
layer.bounds = (bezierPathForControlPoints().boundingBox)
elasticShape.actions = ["position" : NSNull(), "bounds" : NSNull(), "path" : NSNull()]
self.addSubview(b1)
self.addSubview(b2)
self.addSubview(b3)
self.addSubview(b4)
self.addSubview(b5)
self.addSubview(b6)
self.addSubview(b7)
self.addSubview(b8)
self.addSubview(b9)
self.addSubview(b10)
self.addSubview(b11)
self.addSubview(b12)
self.addSubview(t1)
self.addSubview(t2)
self.addSubview(t3)
self.addSubview(t4)
self.addSubview(t5)
self.addSubview(t6)
self.addSubview(t7)
self.addSubview(t8)
self.addSubview(t9)
self.addSubview(t10)
self.addSubview(t11)
self.addSubview(t12)
self.addSubview(pb1X)
self.addSubview(pb2X)
self.addSubview(pb3X)
self.addSubview(pb4X)
self.addSubview(pb5X)
self.addSubview(pb6X)
self.addSubview(pb7X)
self.addSubview(pb8X)
self.addSubview(pb9X)
self.addSubview(pb10X)
self.addSubview(pb11X)
self.addSubview(pb12X)
self.addSubview(pb13X)
self.addSubview(pb14X)
self.addSubview(pb15X)
self.addSubview(pb16X)
self.addSubview(pb17X)
self.addSubview(pb18X)
self.addSubview(pb19X)
self.addSubview(pb20X)
self.addSubview(pb21X)
self.addSubview(pb22X)
self.addSubview(pt1X)
self.addSubview(pt2X)
self.addSubview(pt3X)
self.addSubview(pt4X)
self.addSubview(pt5X)
self.addSubview(pt6X)
self.addSubview(pt7X)
self.addSubview(pt8X)
self.addSubview(pt9X)
self.addSubview(pt10X)
self.addSubview(pt11X)
self.addSubview(pt12X)
self.addSubview(pt13X)
self.addSubview(pt14X)
self.addSubview(pt15X)
self.addSubview(pt16X)
self.addSubview(pt17X)
self.addSubview(pt18X)
self.addSubview(pt19X)
self.addSubview(pt20X)
self.addSubview(pt21X)
self.addSubview(pt22X)
displayLink = CADisplayLink(target: self, selector: #selector(RWLogoLayer.updateShapeLayer))
displayLink.add(to: RunLoop.main, forMode: RunLoopMode.defaultRunLoopMode)
displayLink.isPaused = true
}
func updateShapeLayer() {
elasticShape.path = bezierPathForControlPoints()
}
func centerPoint (view : UIView, mult : CGFloat) -> CGPoint{
let t = CGPoint(x: view.dg_center(animating).x + mult, y: view.dg_center(animating).y)
return t
}
func controlPoint1 (view : UIView, mult : CGFloat) -> CGPoint{
let t = CGPoint(x: view.dg_center(animating).x + mult, y: view.dg_center(animating).y)
return t
}
func controlPoint2 (view : UIView, mult : CGFloat) -> CGPoint{
let t = CGPoint(x: view.dg_center(animating).x + mult, y: view.dg_center(animating).y)
return t
}
func bezierPathForControlPoints()->CGPath {
let digb1 = CGPoint(x: b1.dg_center(animating).x, y: b1.dg_center(animating).y)
let digt1 = CGPoint(x: t12.dg_center(animating).x, y: t12.dg_center(animating).y)
let bezierPath = UIBezierPath()
let delta = self.bounds.width/5
bezierPath.move(to: digb1)
for s in 0...4{
for (i,g) in centerViewBottom.enumerated() {
// bezierPath.addLine(to: centerPoint(view: g, mult: CGFloat(s) * delta))
bezierPath.addCurve(to: centerPoint(view: g, mult: CGFloat(s) * delta),controlPoint1: controlPoint1(view: controlPointBottom1[i], mult: CGFloat(s) * delta), controlPoint2: controlPoint2(view: controlPointBottom2[i], mult: CGFloat(s) * delta))
}
}
for s in (0...4).reversed(){
for (i,g) in centerViewTop.enumerated() {
// bezierPath.addLine(to: centerPoint(view: g, mult: CGFloat(s) * delta))
bezierPath.addCurve(to: centerPoint(view: g, mult: CGFloat(s) * delta),controlPoint1: controlPoint1(view: controlPointTop1[i], mult: CGFloat(s) * delta), controlPoint2: controlPoint2(view: controlPointTop2[i], mult: CGFloat(s) * delta))
}
}
return bezierPath.cgPath
}
func updateLoop() {
elasticShape.path = bezierPathForControlPoints()
}
fileprivate func startUpdateLoop() {
displayLink.isPaused = false
}
fileprivate func stopUpdateLoop() {
displayLink.isPaused = true
}
@IBInspectable var overshootAmount : CGFloat = 10
override var backgroundColor: UIColor? {
willSet {
if let newValue = newValue {
elasticShape.fillColor = newValue.cgColor
super.backgroundColor = UIColor.blue
}
}
}
}
extension UIView {
func dg_center(_ usePresentationLayerIfPossible: Bool) -> CGPoint {
if usePresentationLayerIfPossible, let presentationLayer = layer.presentation()
{
return presentationLayer.position
}
return center
}
}
/*
import UIKit
import QuartzCore
@IBDesignable class RWLogoLayer : UIView{
let b1 = UIView()
let b2 = UIView()
let b3 = UIView()
let b4 = UIView()
let b5 = UIView()
let b6 = UIView()
let b7 = UIView()
let b8 = UIView()
let b9 = UIView()
let b10 = UIView()
let b11 = UIView()
let b12 = UIView()
let b13 = UIView()
let b14 = UIView()
let b15 = UIView()
let b16 = UIView()
let b17 = UIView()
let b18 = UIView()
let b19 = UIView()
let b20 = UIView()
let b21 = UIView()
let b22 = UIView()
let b23 = UIView()
let b24 = UIView()
let b25 = UIView()
let b26 = UIView()
let b27 = UIView()
let b28 = UIView()
let b29 = UIView()
let b30 = UIView()
let b31 = UIView()
let b32 = UIView()
let b33 = UIView()
let b34 = UIView()
let b35 = UIView()
let t1 = UIView()
let t2 = UIView()
let t3 = UIView()
let t4 = UIView()
let t5 = UIView()
let t6 = UIView()
let t7 = UIView()
let t8 = UIView()
let t9 = UIView()
let t10 = UIView()
let t11 = UIView()
let t12 = UIView()
let t13 = UIView()
let t14 = UIView()
let t15 = UIView()
let t16 = UIView()
let t17 = UIView()
let t18 = UIView()
let t19 = UIView()
let t20 = UIView()
let t21 = UIView()
let t22 = UIView()
let t23 = UIView()
let t24 = UIView()
let t25 = UIView()
let t26 = UIView()
let t27 = UIView()
let t28 = UIView()
let t29 = UIView()
let t30 = UIView()
let t31 = UIView()
let t32 = UIView()
let t33 = UIView()
let t34 = UIView()
let t35 = UIView()
var width : CGFloat!
var height : CGFloat!
var vies : [UIView] = []
var viesB : [UIView] = []
var viesT : [UIView] = []
let elasticShape = CAShapeLayer()
var displayLink: CADisplayLink!
var animating = false {
didSet {self.isUserInteractionEnabled = !animating
displayLink.isPaused = !animating
} }
func setup(frame: CGRect){
vies=[b1, b2,b3,b4, b5,b6,b7, b8,b9, b10,b11, b12,b13,b14,b15,b16,b17,b18,b19,b20,b21, b22, b23, b24, b25, b26, b27, b28, b29, b30,b31, b32, b33, b34, b35,t1, t2, t3, t4, t5, t6, t7, t8, t9, t10, t11, t12, t13, t14, t15, t16, t17, t18, t19, t20, t21, t22, t23, t24, t25, t26, t27, t28, t29, t30, t31,t32, t33, t34, t35]
viesB=[b2,b3,b4, b5,b6,b7, b8,b9, b10,b11, b12,b13,b14,b15,b16,b17,b18,b19,b20,b21, b22, b23, b24, b25, b26, b27, b28, b29, b30,b31, b32, b33, b34, b35]
viesT=[t1, t2, t3, t4, t5, t6, t7, t8, t9, t10, t11, t12, t13, t14, t15, t16, t17, t18, t19, t20, t21, t22, t23, t24, t25, t26, t27, t28, t29, t30, t31,t32, t33, t34, t35]
b1.center = CGPoint(x: frame.minX + 0.00000 * frame.width, y: frame.minY + 0.46816 * frame.height)
b2.center = CGPoint(x: frame.minX + 0.10695 * frame.width, y: frame.minY + 0.46816 * frame.height)
b3.center = CGPoint(x: frame.minX + 0.11586 * frame.width, y: frame.minY + 0.44943 * frame.height)
b4.center = CGPoint(x: frame.minX + 0.12121 * frame.width, y: frame.minY + 0.47939 * frame.height)
b5.center = CGPoint(x: frame.minX + 0.13012 * frame.width, y: frame.minY + 0.43445 * frame.height)
b6.center = CGPoint(x: frame.minX + 0.13547 * frame.width, y: frame.minY + 0.49812 * frame.height)
b7.center = CGPoint(x: frame.minX + 0.14973 * frame.width, y: frame.minY + 0.31086 * frame.height)
b8.center = CGPoint(x: frame.minX + 0.16221 * frame.width, y: frame.minY + 0.61048 * frame.height)
b9.center = CGPoint(x: frame.minX + 0.17291 * frame.width, y: frame.minY + 0.43445 * frame.height)
b10.center = CGPoint(x: frame.minX + 0.18004 * frame.width, y: frame.minY + 0.50187 * frame.height)
b11.center = CGPoint(x: frame.minX + 0.18717 * frame.width, y: frame.minY + 0.44569 * frame.height)
b12.center = CGPoint(x: frame.minX + 0.19251 * frame.width, y: frame.minY + 0.46816 * frame.height)
b13.center = CGPoint(x: frame.minX + 0.29768 * frame.width, y: frame.minY + 0.46816 * frame.height)
b14.center = CGPoint(x: frame.minX + 0.31551 * frame.width, y: frame.minY + 0.41198 * frame.height)
b15.center = CGPoint(x: frame.minX + 0.33333 * frame.width, y: frame.minY + 0.51310 * frame.height)
b16.center = CGPoint(x: frame.minX + 0.36185 * frame.width, y: frame.minY + 0.35205 * frame.height)
b17.center = CGPoint(x: frame.minX + 0.37968 * frame.width, y: frame.minY + 0.59175 * frame.height)
b18.center = CGPoint(x: frame.minX + 0.42068 * frame.width, y: frame.minY + 0.00000 * frame.height)
b19.center = CGPoint(x: frame.minX + 0.45633 * frame.width, y: frame.minY + 0.99624 * frame.height)
b20.center = CGPoint(x: frame.minX + 0.49198 * frame.width, y: frame.minY + 0.35580 * frame.height)
b21.center = CGPoint(x: frame.minX + 0.50980 * frame.width, y: frame.minY + 0.54306 * frame.height)
b22.center = CGPoint(x: frame.minX + 0.52763 * frame.width, y: frame.minY + 0.41198 * frame.height)
b23.center = CGPoint(x: frame.minX + 0.54724 * frame.width, y: frame.minY + 0.46816 * frame.height)
b24.center = CGPoint(x: frame.minX + 0.74688 * frame.width, y: frame.minY + 0.46816 * frame.height)
b25.center = CGPoint(x: frame.minX + 0.75401 * frame.width, y: frame.minY + 0.44943 * frame.height)
b26.center = CGPoint(x: frame.minX + 0.75936 * frame.width, y: frame.minY + 0.46816 * frame.height)
b27.center = CGPoint(x: frame.minX + 0.77005 * frame.width, y: frame.minY + 0.42696 * frame.height)
b28.center = CGPoint(x: frame.minX + 0.77540 * frame.width, y: frame.minY + 0.47939 * frame.height)
b29.center = CGPoint(x: frame.minX + 0.78788 * frame.width, y: frame.minY + 0.32584 * frame.height)
b30.center = CGPoint(x: frame.minX + 0.80036 * frame.width, y: frame.minY + 0.58801 * frame.height)
b31.center = CGPoint(x: frame.minX + 0.81283 * frame.width, y: frame.minY + 0.43445 * frame.height)
b32.center = CGPoint(x: frame.minX + 0.81818 * frame.width, y: frame.minY + 0.46816 * frame.height)
b33.center = CGPoint(x: frame.minX + 0.82353 * frame.width, y: frame.minY + 0.44943 * frame.height)
b34.center = CGPoint(x: frame.minX + 0.83244 * frame.width, y: frame.minY + 0.46816 * frame.height)
b35.center = CGPoint(x: frame.minX + 1.00000 * frame.width, y: frame.minY + 0.46816 * frame.height)
t1.center = CGPoint(x: frame.minX + 0.00000 * frame.width, y: frame.minY + 0.46816 * frame.height)
t2.center = CGPoint(x: frame.minX + 0.10695 * frame.width, y: frame.minY + 0.46816 * frame.height)
t3.center = CGPoint(x: frame.minX + 0.11586 * frame.width, y: frame.minY + 0.44943 * frame.height)
t4.center = CGPoint(x: frame.minX + 0.12121 * frame.width, y: frame.minY + 0.47939 * frame.height)
t5.center = CGPoint(x: frame.minX + 0.13012 * frame.width, y: frame.minY + 0.43445 * frame.height)
t6.center = CGPoint(x: frame.minX + 0.13547 * frame.width, y: frame.minY + 0.49812 * frame.height)
t7.center = CGPoint(x: frame.minX + 0.14973 * frame.width, y: frame.minY + 0.31086 * frame.height)
t8.center = CGPoint(x: frame.minX + 0.16221 * frame.width, y: frame.minY + 0.61048 * frame.height)
t9.center = CGPoint(x: frame.minX + 0.17291 * frame.width, y: frame.minY + 0.43445 * frame.height)
t10.center = CGPoint(x: frame.minX + 0.18004 * frame.width, y: frame.minY + 0.50187 * frame.height)
t11.center = CGPoint(x: frame.minX + 0.18717 * frame.width, y: frame.minY + 0.44569 * frame.height)
t12.center = CGPoint(x: frame.minX + 0.19251 * frame.width, y: frame.minY + 0.46816 * frame.height)
t13.center = CGPoint(x: frame.minX + 0.29768 * frame.width, y: frame.minY + 0.46816 * frame.height)
t14.center = CGPoint(x: frame.minX + 0.31551 * frame.width, y: frame.minY + 0.41198 * frame.height)
t15.center = CGPoint(x: frame.minX + 0.33333 * frame.width, y: frame.minY + 0.51310 * frame.height)
t16.center = CGPoint(x: frame.minX + 0.36185 * frame.width, y: frame.minY + 0.35205 * frame.height)
t17.center = CGPoint(x: frame.minX + 0.37968 * frame.width, y: frame.minY + 0.59175 * frame.height)
t18.center = CGPoint(x: frame.minX + 0.42068 * frame.width, y: frame.minY + 0.00000 * frame.height)
t19.center = CGPoint(x: frame.minX + 0.45633 * frame.width, y: frame.minY + 0.99624 * frame.height)
t20.center = CGPoint(x: frame.minX + 0.49198 * frame.width, y: frame.minY + 0.35580 * frame.height)
t21.center = CGPoint(x: frame.minX + 0.50980 * frame.width, y: frame.minY + 0.54306 * frame.height)
t22.center = CGPoint(x: frame.minX + 0.52763 * frame.width, y: frame.minY + 0.41198 * frame.height)
t23.center = CGPoint(x: frame.minX + 0.54724 * frame.width, y: frame.minY + 0.46816 * frame.height)
t24.center = CGPoint(x: frame.minX + 0.74688 * frame.width, y: frame.minY + 0.46816 * frame.height)
t25.center = CGPoint(x: frame.minX + 0.75401 * frame.width, y: frame.minY + 0.44943 * frame.height)
t26.center = CGPoint(x: frame.minX + 0.75936 * frame.width, y: frame.minY + 0.46816 * frame.height)
t27.center = CGPoint(x: frame.minX + 0.77005 * frame.width, y: frame.minY + 0.42696 * frame.height)
t28.center = CGPoint(x: frame.minX + 0.77540 * frame.width, y: frame.minY + 0.47939 * frame.height)
t29.center = CGPoint(x: frame.minX + 0.78788 * frame.width, y: frame.minY + 0.32584 * frame.height)
t30.center = CGPoint(x: frame.minX + 0.80036 * frame.width, y: frame.minY + 0.58801 * frame.height)
t31.center = CGPoint(x: frame.minX + 0.81283 * frame.width, y: frame.minY + 0.43445 * frame.height)
t32.center = CGPoint(x: frame.minX + 0.81818 * frame.width, y: frame.minY + 0.46816 * frame.height)
t33.center = CGPoint(x: frame.minX + 0.82353 * frame.width, y: frame.minY + 0.44943 * frame.height)
t34.center = CGPoint(x: frame.minX + 0.83244 * frame.width, y: frame.minY + 0.46816 * frame.height)
t35.center = CGPoint(x: frame.minX + 1.00000 * frame.width, y: frame.minY + 0.46816 * frame.height)
for v in vies {
v.bounds = CGRect(x: 0, y: 0, width: 6, height: 6)
v.backgroundColor = .black
}
elasticShape.path = bezierPathForControlPoints()
elasticShape.fillColor = UIColor.white.cgColor
elasticShape.strokeColor = UIColor.white.cgColor
elasticShape.lineWidth = 2
layer.insertSublayer(elasticShape, at: 0)
layer.bounds = (bezierPathForControlPoints().boundingBox)
elasticShape.actions = ["position" : NSNull(), "bounds" : NSNull(), "path" : NSNull()]
self.addSubview(b1)
self.addSubview(b2)
self.addSubview(b3)
self.addSubview(b4)
self.addSubview(b5)
self.addSubview(b6)
self.addSubview(b7)
self.addSubview(b8)
self.addSubview(b9)
self.addSubview(b10)
self.addSubview(b11)
self.addSubview(b12)
self.addSubview(b13)
self.addSubview(b14)
self.addSubview(b15)
self.addSubview(b16)
self.addSubview(b17)
self.addSubview(b18)
self.addSubview(b19)
self.addSubview(b20)
self.addSubview(b21)
self.addSubview(b22)
self.addSubview(b23)
self.addSubview(b24)
self.addSubview(b25)
self.addSubview(b26)
self.addSubview(b27)
self.addSubview(b28)
self.addSubview(b29)
self.addSubview(b30)
self.addSubview(b31)
self.addSubview(b32)
self.addSubview(b33)
self.addSubview(b34)
self.addSubview(b35)
self.addSubview(t1)
self.addSubview(t2)
self.addSubview(t3)
self.addSubview(t4)
self.addSubview(t5)
self.addSubview(t6)
self.addSubview(t7)
self.addSubview(t8)
self.addSubview(t9)
self.addSubview(t10)
self.addSubview(t11)
self.addSubview(t12)
self.addSubview(t13)
self.addSubview(t14)
self.addSubview(t15)
self.addSubview(t16)
self.addSubview(t17)
self.addSubview(t18)
self.addSubview(t19)
self.addSubview(t20)
self.addSubview(t21)
self.addSubview(t22)
self.addSubview(t23)
self.addSubview(t24)
self.addSubview(t25)
self.addSubview(t26)
self.addSubview(t27)
self.addSubview(t28)
self.addSubview(t29)
self.addSubview(t30)
self.addSubview(t31)
self.addSubview(t32)
self.addSubview(t33)
self.addSubview(t34)
self.addSubview(t35)
displayLink = CADisplayLink(target: self, selector: #selector(RWLogoLayer.updateShapeLayer))
displayLink.add(to: RunLoop.main, forMode: RunLoopMode.defaultRunLoopMode)
displayLink.isPaused = true
}
override func didMoveToSuperview() {
super.didMoveToSuperview()
print("kkk")
}
func updateShapeLayer() {
elasticShape.path = bezierPathForControlPoints()
}
func curve (view : UIView) -> CGPoint{
let t = CGPoint(x: view.dg_center(animating).x, y: view.dg_center(animating).y)
return t
}
func bezierPathForControlPoints()->CGPath {
let digb1 = CGPoint(x: b1.dg_center(animating).x, y: b1.dg_center(animating).y)
let digb2 = CGPoint(x: b2.dg_center(animating).x, y: b2.dg_center(animating).y)
let digb3 = CGPoint(x: b3.dg_center(animating).x, y: b3.dg_center(animating).y)
let digb4 = CGPoint(x: b4.dg_center(animating).x, y: b4.dg_center(animating).y)
let digb5 = CGPoint(x: b5.dg_center(animating).x, y: b5.dg_center(animating).y)
let digb6 = CGPoint(x: b6.dg_center(animating).x, y: b6.dg_center(animating).y)
let digb7 = CGPoint(x: b7.dg_center(animating).x, y: b7.dg_center(animating).y)
let digb8 = CGPoint(x: b8.dg_center(animating).x, y: b8.dg_center(animating).y)
let digb9 = CGPoint(x: b9.dg_center(animating).x, y: b9.dg_center(animating).y)
let digb10 = CGPoint(x: b10.dg_center(animating).x, y: b10.dg_center(animating).y)
let digb11 = CGPoint(x: b11.dg_center(animating).x, y: b11.dg_center(animating).y)
let digb12 = CGPoint(x: b12.dg_center(animating).x, y: b12.dg_center(animating).y)
let digb13 = CGPoint(x: b13.dg_center(animating).x, y: b13.dg_center(animating).y)
let digb14 = CGPoint(x: b14.dg_center(animating).x, y: b14.dg_center(animating).y)
let digb15 = CGPoint(x: b15.dg_center(animating).x, y: b15.dg_center(animating).y)
let digb16 = CGPoint(x: b16.dg_center(animating).x, y: b16.dg_center(animating).y)
let digb17 = CGPoint(x: b17.dg_center(animating).x, y: b17.dg_center(animating).y)
let digb18 = CGPoint(x: b18.dg_center(animating).x, y: b18.dg_center(animating).y)
let digb19 = CGPoint(x: b19.dg_center(animating).x, y: b19.dg_center(animating).y)
let digb20 = CGPoint(x: b20.dg_center(animating).x, y: b20.dg_center(animating).y)
let digb21 = CGPoint(x: b21.dg_center(animating).x, y: b21.dg_center(animating).y)
let digb22 = CGPoint(x: b22.dg_center(animating).x, y: b22.dg_center(animating).y)
let digb23 = CGPoint(x: b23.dg_center(animating).x, y: b23.dg_center(animating).y)
let digb24 = CGPoint(x: b24.dg_center(animating).x, y: b24.dg_center(animating).y)
let digb25 = CGPoint(x: b25.dg_center(animating).x, y: b25.dg_center(animating).y)
let digb26 = CGPoint(x: b26.dg_center(animating).x, y: b26.dg_center(animating).y)
let digb27 = CGPoint(x: b27.dg_center(animating).x, y: b27.dg_center(animating).y)
let digb28 = CGPoint(x: b28.dg_center(animating).x, y: b28.dg_center(animating).y)
let digb29 = CGPoint(x: b29.dg_center(animating).x, y: b29.dg_center(animating).y)
let digb30 = CGPoint(x: b30.dg_center(animating).x, y: b30.dg_center(animating).y)
let digb31 = CGPoint(x: b31.dg_center(animating).x, y: b31.dg_center(animating).y)
let digb32 = CGPoint(x: b32.dg_center(animating).x, y: b32.dg_center(animating).y)
let digb33 = CGPoint(x: b33.dg_center(animating).x, y: b33.dg_center(animating).y)
let digb34 = CGPoint(x: b34.dg_center(animating).x, y: b34.dg_center(animating).y)
let digb35 = CGPoint(x: b35.dg_center(animating).x, y: b35.dg_center(animating).y)
let digt1 = CGPoint(x: t1.dg_center(animating).x, y: t1.dg_center(animating).y)
let digt2 = CGPoint(x: t2.dg_center(animating).x, y: t2.dg_center(animating).y)
let digt3 = CGPoint(x: t3.dg_center(animating).x, y: t3.dg_center(animating).y)
let digt4 = CGPoint(x: t4.dg_center(animating).x, y: t4.dg_center(animating).y)
let digt5 = CGPoint(x: t5.dg_center(animating).x, y: t5.dg_center(animating).y)
let digt6 = CGPoint(x: t6.dg_center(animating).x, y: t6.dg_center(animating).y)
let digt7 = CGPoint(x: t7.dg_center(animating).x, y: t7.dg_center(animating).y)
let digt8 = CGPoint(x: t8.dg_center(animating).x, y: t8.dg_center(animating).y)
let digt9 = CGPoint(x: t9.dg_center(animating).x, y: t9.dg_center(animating).y)
let digt10 = CGPoint(x: t10.dg_center(animating).x, y: t10.dg_center(animating).y)
let digt11 = CGPoint(x: t11.dg_center(animating).x, y: t11.dg_center(animating).y)
let digt12 = CGPoint(x: t12.dg_center(animating).x, y: t12.dg_center(animating).y)
let digt13 = CGPoint(x: t13.dg_center(animating).x, y: t13.dg_center(animating).y)
let digt14 = CGPoint(x: t14.dg_center(animating).x, y: t14.dg_center(animating).y)
let digt15 = CGPoint(x: t15.dg_center(animating).x, y: t15.dg_center(animating).y)
let digt16 = CGPoint(x: t16.dg_center(animating).x, y: t16.dg_center(animating).y)
let digt17 = CGPoint(x: t17.dg_center(animating).x, y: t17.dg_center(animating).y)
let digt18 = CGPoint(x: t18.dg_center(animating).x, y: t18.dg_center(animating).y)
let digt19 = CGPoint(x: t19.dg_center(animating).x, y: t19.dg_center(animating).y)
let digt20 = CGPoint(x: t20.dg_center(animating).x, y: t20.dg_center(animating).y)
let digt21 = CGPoint(x: t21.dg_center(animating).x, y: t21.dg_center(animating).y)
let digt22 = CGPoint(x: t22.dg_center(animating).x, y: t22.dg_center(animating).y)
let digt23 = CGPoint(x: t23.dg_center(animating).x, y: t23.dg_center(animating).y)
let digt24 = CGPoint(x: t24.dg_center(animating).x, y: t24.dg_center(animating).y)
let digt25 = CGPoint(x: t25.dg_center(animating).x, y: t25.dg_center(animating).y)
let digt26 = CGPoint(x: t26.dg_center(animating).x, y: t26.dg_center(animating).y)
let digt27 = CGPoint(x: t27.dg_center(animating).x, y: t27.dg_center(animating).y)
let digt28 = CGPoint(x: t28.dg_center(animating).x, y: t28.dg_center(animating).y)
let digt29 = CGPoint(x: t29.dg_center(animating).x, y: t29.dg_center(animating).y)
let digt30 = CGPoint(x: t30.dg_center(animating).x, y: t30.dg_center(animating).y)
let digt31 = CGPoint(x: t31.dg_center(animating).x, y: t31.dg_center(animating).y)
let digt32 = CGPoint(x: t32.dg_center(animating).x, y: t32.dg_center(animating).y)
let digt33 = CGPoint(x: t33.dg_center(animating).x, y: t33.dg_center(animating).y)
let digt34 = CGPoint(x: t34.dg_center(animating).x, y: t34.dg_center(animating).y)
let digt35 = CGPoint(x: t35.dg_center(animating).x, y: t35.dg_center(animating).y)
let bezierPath = UIBezierPath()
bezierPath.move(to: digb1)
bezierPath.addLine(to: digb2)
// for (i,g) in viesB.enumerated() {
// print("lll")
//
// bezierPath.addLine(to: curve(view: g))
//
// }
bezierPath.addLine(to: digb3)
bezierPath.addLine(to: digb4)
bezierPath.addLine(to: digb5)
bezierPath.addLine(to: digb6)
bezierPath.addLine(to: digb7)
bezierPath.addLine(to: digb8)
bezierPath.addLine(to: digb9)
bezierPath.addLine(to: digb10)
bezierPath.addLine(to: digb11)
bezierPath.addLine(to: digb12)
bezierPath.addLine(to: digb13)
bezierPath.addLine(to: digb14)
bezierPath.addLine(to: digb15)
bezierPath.addLine(to: digb16)
bezierPath.addLine(to: digb17)
bezierPath.addLine(to: digb18)
bezierPath.addLine(to: digb19)
bezierPath.addLine(to: digb20)
bezierPath.addLine(to: digb21)
bezierPath.addLine(to: digb22)
bezierPath.addLine(to: digb23)
bezierPath.addLine(to: digb24)
bezierPath.addLine(to: digb25)
bezierPath.addLine(to: digb26)
bezierPath.addLine(to: digb27)
bezierPath.addLine(to: digb28)
bezierPath.addLine(to: digb29)
bezierPath.addLine(to: digb30)
bezierPath.addLine(to: digb31)
bezierPath.addLine(to: digb32)
bezierPath.addLine(to: digb33)
bezierPath.addLine(to: digb34)
bezierPath.addLine(to: digb35)
bezierPath.addLine(to: digt35)
bezierPath.addLine(to: digt34)
bezierPath.addLine(to: digt33)
bezierPath.addLine(to: digt32)
bezierPath.addLine(to: digt31)
bezierPath.addLine(to: digt30)
bezierPath.addLine(to: digt29)
bezierPath.addLine(to: digt28)
bezierPath.addLine(to: digt27)
bezierPath.addLine(to: digt26)
bezierPath.addLine(to: digt25)
bezierPath.addLine(to: digt24)
bezierPath.addLine(to: digt23)
bezierPath.addLine(to: digt22)
bezierPath.addLine(to: digt21)
bezierPath.addLine(to: digt20)
bezierPath.addLine(to: digt19)
bezierPath.addLine(to: digt18)
bezierPath.addLine(to: digt17)
bezierPath.addLine(to: digt16)
bezierPath.addLine(to: digt15)
bezierPath.addLine(to: digt14)
bezierPath.addLine(to: digt13)
bezierPath.addLine(to: digt12)
bezierPath.addLine(to: digt11)
bezierPath.addLine(to: digt10)
bezierPath.addLine(to: digt9)
bezierPath.addLine(to: digt8)
bezierPath.addLine(to: digt7)
bezierPath.addLine(to: digt6)
bezierPath.addLine(to: digt5)
bezierPath.addLine(to: digt4)
bezierPath.addLine(to: digt3)
bezierPath.addLine(to: digt2)
bezierPath.addLine(to: digt1)
bezierPath.close()
// for v in vies {
// v.bounds = CGRect(x: 0, y: 0, width: 5, height: 5)
// v.backgroundColor = .black
// }
return bezierPath.cgPath
}
func updateLoop() {
elasticShape.path = bezierPathForControlPoints()
}
fileprivate func startUpdateLoop() {
displayLink.isPaused = false
}
fileprivate func stopUpdateLoop() {
displayLink.isPaused = true
}
@IBInspectable var overshootAmount : CGFloat = 10
override var backgroundColor: UIColor? {
willSet {
if let newValue = newValue {
elasticShape.fillColor = newValue.cgColor
super.backgroundColor = UIColor.blue
}
}
}
}
extension UIView {
func dg_center(_ usePresentationLayerIfPossible: Bool) -> CGPoint {
if usePresentationLayerIfPossible, let presentationLayer = layer.presentation()
{
return presentationLayer.position
}
return center
}
}
*/
|
mit
|
f1334a56ef870d69c0d19d32accc848c
| 40.416575 | 320 | 0.654074 | 2.909867 | false | false | false | false |
tjw/swift
|
test/Prototypes/CollectionTransformers.swift
|
3
|
39313
|
//===----------------------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
// RUN: %target-run-stdlib-swift
// REQUIRES: executable_test
// FIXME: This test runs very slowly on watchOS.
// UNSUPPORTED: OS=watchos
public enum ApproximateCount {
case Unknown
case Precise(IntMax)
case Underestimate(IntMax)
case Overestimate(IntMax)
}
public protocol ApproximateCountableSequence : Sequence {
/// Complexity: amortized O(1).
var approximateCount: ApproximateCount { get }
}
/// A collection that provides an efficient way to split its index ranges.
public protocol SplittableCollection : Collection {
// We need this protocol so that collections with only forward or bidirectional
// traversals could customize their splitting behavior.
//
// FIXME: all collections with random access should conform to this protocol
// automatically.
/// Splits a given range of indices into a set of disjoint ranges covering
/// the same elements.
///
/// Complexity: amortized O(1).
///
/// FIXME: should that be O(log n) to cover some strange collections?
///
/// FIXME: index invalidation rules?
///
/// FIXME: a better name. Users will never want to call this method
/// directly.
///
/// FIXME: return an optional for the common case when split() cannot
/// subdivide the range further.
func split(_ range: Range<Index>) -> [Range<Index>]
}
internal func _splitRandomAccessIndexRange<
C : RandomAccessCollection
>(
_ elements: C,
_ range: Range<C.Index>
) -> [Range<C.Index>] {
let startIndex = range.lowerBound
let endIndex = range.upperBound
let length = elements.distance(from: startIndex, to: endIndex)
if length < 2 {
return [range]
}
let middle = elements.index(startIndex, offsetBy: length / 2)
return [startIndex ..< middle, middle ..< endIndex]
}
/// A helper object to build a collection incrementally in an efficient way.
///
/// Using a builder can be more efficient than creating an empty collection
/// instance and adding elements one by one.
public protocol CollectionBuilder {
associatedtype Destination : Collection
associatedtype Element = Destination.Iterator.Element
init()
/// Gives a hint about the expected approximate number of elements in the
/// collection that is being built.
mutating func sizeHint(_ approximateSize: Int)
/// Append `element` to `self`.
///
/// If a collection being built supports a user-defined order, the element is
/// added at the end.
///
/// Complexity: amortized O(1).
mutating func append(_ element: Destination.Iterator.Element)
/// Append `elements` to `self`.
///
/// If a collection being built supports a user-defined order, the element is
/// added at the end.
///
/// Complexity: amortized O(n), where `n` is equal to `count(elements)`.
mutating func append<
C : Collection
>(contentsOf elements: C)
where C.Iterator.Element == Element
/// Append elements from `otherBuilder` to `self`, emptying `otherBuilder`.
///
/// Equivalent to::
///
/// self.append(contentsOf: otherBuilder.takeResult())
///
/// but is more efficient.
///
/// Complexity: O(1).
mutating func moveContentsOf(_ otherBuilder: inout Self)
/// Build the collection from the elements that were added to this builder.
///
/// Once this function is called, the builder may not be reused and no other
/// methods should be called.
///
/// Complexity: O(n) or better (where `n` is the number of elements that were
/// added to this builder); typically O(1).
mutating func takeResult() -> Destination
}
public protocol BuildableCollectionProtocol : Collection {
associatedtype Builder : CollectionBuilder
}
extension Array : SplittableCollection {
public func split(_ range: Range<Int>) -> [Range<Int>] {
return _splitRandomAccessIndexRange(self, range)
}
}
public struct ArrayBuilder<T> : CollectionBuilder {
// FIXME: the compiler didn't complain when I remove public on 'Collection'.
// File a bug.
public typealias Destination = Array<T>
public typealias Element = T
internal var _resultParts = [[T]]()
internal var _resultTail = [T]()
public init() {}
public mutating func sizeHint(_ approximateSize: Int) {
_resultTail.reserveCapacity(approximateSize)
}
public mutating func append(_ element: T) {
_resultTail.append(element)
}
public mutating func append<
C : Collection
>(contentsOf elements: C)
where C.Iterator.Element == T {
_resultTail.append(contentsOf: elements)
}
public mutating func moveContentsOf(_ otherBuilder: inout ArrayBuilder<T>) {
// FIXME: do something smart with the capacity set in this builder and the
// other builder.
_resultParts.append(_resultTail)
_resultTail = []
// FIXME: not O(1)!
_resultParts.append(contentsOf: otherBuilder._resultParts)
otherBuilder._resultParts = []
swap(&_resultTail, &otherBuilder._resultTail)
}
public mutating func takeResult() -> Destination {
_resultParts.append(_resultTail)
_resultTail = []
// FIXME: optimize. parallelize.
return Array(_resultParts.joined())
}
}
extension Array : BuildableCollectionProtocol {
public typealias Builder = ArrayBuilder<Element>
}
//===----------------------------------------------------------------------===//
// Fork-join
//===----------------------------------------------------------------------===//
// As sad as it is, I think for practical performance reasons we should rewrite
// the inner parts of the fork-join framework in C++. In way too many cases
// than necessary Swift requires an extra allocation to pin objects in memory
// for safe multithreaded access. -Dmitri
import SwiftShims
import SwiftPrivate
import Darwin
import Dispatch
// FIXME: port to Linux.
// XFAIL: linux
// A wrapper for pthread_t with platform-independent interface.
public struct _stdlib_pthread_t : Equatable, Hashable {
internal let _value: pthread_t
public var hashValue: Int {
return _value.hashValue
}
}
public func == (lhs: _stdlib_pthread_t, rhs: _stdlib_pthread_t) -> Bool {
return lhs._value == rhs._value
}
public func _stdlib_pthread_self() -> _stdlib_pthread_t {
return _stdlib_pthread_t(_value: pthread_self())
}
struct _ForkJoinMutex {
var _mutex: UnsafeMutablePointer<pthread_mutex_t>
init() {
_mutex = UnsafeMutablePointer.allocate(capacity: 1)
if pthread_mutex_init(_mutex, nil) != 0 {
fatalError("pthread_mutex_init")
}
}
func `deinit`() {
if pthread_mutex_destroy(_mutex) != 0 {
fatalError("pthread_mutex_init")
}
_mutex.deinitialize(count: 1)
_mutex.deallocate()
}
func withLock<Result>(_ body: () -> Result) -> Result {
if pthread_mutex_lock(_mutex) != 0 {
fatalError("pthread_mutex_lock")
}
let result = body()
if pthread_mutex_unlock(_mutex) != 0 {
fatalError("pthread_mutex_unlock")
}
return result
}
}
struct _ForkJoinCond {
var _cond: UnsafeMutablePointer<pthread_cond_t>
init() {
_cond = UnsafeMutablePointer.allocate(capacity: 1)
if pthread_cond_init(_cond, nil) != 0 {
fatalError("pthread_cond_init")
}
}
func `deinit`() {
if pthread_cond_destroy(_cond) != 0 {
fatalError("pthread_cond_destroy")
}
_cond.deinitialize(count: 1)
_cond.deallocate()
}
func signal() {
pthread_cond_signal(_cond)
}
func wait(_ mutex: _ForkJoinMutex) {
pthread_cond_wait(_cond, mutex._mutex)
}
}
final class _ForkJoinOneShotEvent {
var _mutex: _ForkJoinMutex = _ForkJoinMutex()
var _cond: _ForkJoinCond = _ForkJoinCond()
var _isSet: Bool = false
init() {}
deinit {
_cond.`deinit`()
_mutex.`deinit`()
}
func set() {
_mutex.withLock {
if !_isSet {
_isSet = true
_cond.signal()
}
}
}
/// Establishes a happens-before relation between calls to set() and wait().
func wait() {
_mutex.withLock {
while !_isSet {
_cond.wait(_mutex)
}
}
}
/// If the function returns true, it establishes a happens-before relation
/// between calls to set() and isSet().
func isSet() -> Bool {
return _mutex.withLock {
return _isSet
}
}
}
final class _ForkJoinWorkDeque<T> {
// FIXME: this is just a proof-of-concept; very inefficient.
// Implementation note: adding elements to the head of the deque is common in
// fork-join, so _deque is stored reversed (appending to an array is cheap).
// FIXME: ^ that is false for submission queues though.
var _deque: ContiguousArray<T> = []
var _dequeMutex: _ForkJoinMutex = _ForkJoinMutex()
init() {}
deinit {
precondition(_deque.isEmpty)
_dequeMutex.`deinit`()
}
var isEmpty: Bool {
return _dequeMutex.withLock {
return _deque.isEmpty
}
}
func prepend(_ element: T) {
_dequeMutex.withLock {
_deque.append(element)
}
}
func tryTakeFirst() -> T? {
return _dequeMutex.withLock {
let result = _deque.last
if _deque.count > 0 {
_deque.removeLast()
}
return result
}
}
func tryTakeFirstTwo() -> (T?, T?) {
return _dequeMutex.withLock {
let result1 = _deque.last
if _deque.count > 0 {
_deque.removeLast()
}
let result2 = _deque.last
if _deque.count > 0 {
_deque.removeLast()
}
return (result1, result2)
}
}
func append(_ element: T) {
_dequeMutex.withLock {
_deque.insert(element, at: 0)
}
}
func tryTakeLast() -> T? {
return _dequeMutex.withLock {
let result = _deque.first
if _deque.count > 0 {
_deque.remove(at: 0)
}
return result
}
}
func takeAll() -> ContiguousArray<T> {
return _dequeMutex.withLock {
let result = _deque
_deque = []
return result
}
}
func tryReplace(
_ value: T,
makeReplacement: @escaping () -> T,
isEquivalent: @escaping (T, T) -> Bool
) -> Bool {
return _dequeMutex.withLock {
for i in _deque.indices {
if isEquivalent(_deque[i], value) {
_deque[i] = makeReplacement()
return true
}
}
return false
}
}
}
final class _ForkJoinWorkerThread {
internal var _tid: _stdlib_pthread_t?
internal let _pool: ForkJoinPool
internal let _submissionQueue: _ForkJoinWorkDeque<ForkJoinTaskBase>
internal let _workDeque: _ForkJoinWorkDeque<ForkJoinTaskBase>
internal init(
_pool: ForkJoinPool,
submissionQueue: _ForkJoinWorkDeque<ForkJoinTaskBase>,
workDeque: _ForkJoinWorkDeque<ForkJoinTaskBase>
) {
self._tid = nil
self._pool = _pool
self._submissionQueue = submissionQueue
self._workDeque = workDeque
}
internal func startAsync() {
var queue: DispatchQueue?
if #available(OSX 10.10, iOS 8.0, *) {
queue = DispatchQueue.global(qos: .background)
} else {
queue = DispatchQueue.global(priority: .background)
}
queue!.async {
self._thread()
}
}
internal func _thread() {
print("_ForkJoinWorkerThread begin")
_tid = _stdlib_pthread_self()
outer: while !_workDeque.isEmpty || !_submissionQueue.isEmpty {
_pool._addRunningThread(self)
while true {
if _pool._tryStopThread() {
print("_ForkJoinWorkerThread detected too many threads")
_pool._removeRunningThread(self)
_pool._submitTasksToRandomWorkers(_workDeque.takeAll())
_pool._submitTasksToRandomWorkers(_submissionQueue.takeAll())
print("_ForkJoinWorkerThread end")
return
}
// Process tasks in FIFO order: first the work queue, then the
// submission queue.
if let task = _workDeque.tryTakeFirst() {
task._run()
continue
}
if let task = _submissionQueue.tryTakeFirst() {
task._run()
continue
}
print("_ForkJoinWorkerThread stealing tasks")
if let task = _pool._stealTask() {
task._run()
continue
}
// FIXME: steal from submission queues?
break
}
_pool._removeRunningThread(self)
}
assert(_workDeque.isEmpty)
assert(_submissionQueue.isEmpty)
_ = _pool._totalThreads.fetchAndAdd(-1)
print("_ForkJoinWorkerThread end")
}
internal func _forkTask(_ task: ForkJoinTaskBase) {
// Try to inflate the pool.
if !_pool._tryCreateThread({ task }) {
_workDeque.prepend(task)
}
}
internal func _waitForTask(_ task: ForkJoinTaskBase) {
while true {
if task._isComplete() {
return
}
// If the task is in work queue of the current thread, run the task.
if _workDeque.tryReplace(
task,
makeReplacement: { ForkJoinTask<()>() {} },
isEquivalent: { $0 === $1 }) {
// We found the task. Run it in-place.
task._run()
return
}
// FIXME: also check the submission queue, maybe the task is there?
// FIXME: try to find the task in other threads' queues.
// FIXME: try to find tasks that were forked from this task in other
// threads' queues. Help thieves by stealing those tasks back.
// At this point, we can't do any work to help with running this task.
// We can't start new work either (if we do, we might end up creating
// more in-flight work than we can chew, and crash with out-of-memory
// errors).
_pool._compensateForBlockedWorkerThread() {
task._blockingWait()
// FIXME: do a timed wait, and retry stealing.
}
}
}
}
internal protocol _Future {
associatedtype Result
/// Establishes a happens-before relation between completing the future and
/// the call to wait().
func wait()
func tryGetResult() -> Result?
func tryTakeResult() -> Result?
func waitAndGetResult() -> Result
func waitAndTakeResult() -> Result
}
public class ForkJoinTaskBase {
final internal var _pool: ForkJoinPool?
// FIXME(performance): there is no need to create heavy-weight
// synchronization primitives every time. We could start with a lightweight
// atomic int for the flag and inflate to a full event when needed. Unless
// we really need to block in wait(), we would avoid creating an event.
final internal let _completedEvent: _ForkJoinOneShotEvent =
_ForkJoinOneShotEvent()
final internal func _isComplete() -> Bool {
return _completedEvent.isSet()
}
final internal func _blockingWait() {
_completedEvent.wait()
}
internal func _run() {
fatalError("implement")
}
final public func fork() {
precondition(_pool == nil)
if let thread = ForkJoinPool._getCurrentThread() {
thread._forkTask(self)
} else {
// FIXME: decide if we want to allow this.
precondition(false)
ForkJoinPool.commonPool.forkTask(self)
}
}
final public func wait() {
if let thread = ForkJoinPool._getCurrentThread() {
thread._waitForTask(self)
} else {
_blockingWait()
}
}
}
final public class ForkJoinTask<Result> : ForkJoinTaskBase, _Future {
internal let _task: () -> Result
internal var _result: Result?
public init(_task: @escaping () -> Result) {
self._task = _task
}
override internal func _run() {
_complete(_task())
}
/// It is not allowed to call _complete() in a racy way. Only one thread
/// should ever call _complete().
internal func _complete(_ result: Result) {
precondition(!_completedEvent.isSet())
_result = result
_completedEvent.set()
}
public func tryGetResult() -> Result? {
if _completedEvent.isSet() {
return _result
}
return nil
}
public func tryTakeResult() -> Result? {
if _completedEvent.isSet() {
let result = _result
_result = nil
return result
}
return nil
}
public func waitAndGetResult() -> Result {
wait()
return tryGetResult()!
}
public func waitAndTakeResult() -> Result {
wait()
return tryTakeResult()!
}
}
final public class ForkJoinPool {
internal static var _threadRegistry: [_stdlib_pthread_t : _ForkJoinWorkerThread] = [:]
internal static var _threadRegistryMutex: _ForkJoinMutex = _ForkJoinMutex()
internal static func _getCurrentThread() -> _ForkJoinWorkerThread? {
return _threadRegistryMutex.withLock {
return _threadRegistry[_stdlib_pthread_self()]
}
}
internal let _maxThreads: Int
/// Total number of threads: number of running threads plus the number of
/// threads that are preparing to start).
internal let _totalThreads: _stdlib_AtomicInt = _stdlib_AtomicInt(0)
internal var _runningThreads: [_ForkJoinWorkerThread] = []
internal var _runningThreadsMutex: _ForkJoinMutex = _ForkJoinMutex()
internal var _submissionQueues: [_ForkJoinWorkDeque<ForkJoinTaskBase>] = []
internal var _submissionQueuesMutex: _ForkJoinMutex = _ForkJoinMutex()
internal var _workDeques: [_ForkJoinWorkDeque<ForkJoinTaskBase>] = []
internal var _workDequesMutex: _ForkJoinMutex = _ForkJoinMutex()
internal init(_commonPool: ()) {
self._maxThreads = _stdlib_getHardwareConcurrency()
}
deinit {
_runningThreadsMutex.`deinit`()
_submissionQueuesMutex.`deinit`()
_workDequesMutex.`deinit`()
}
internal func _addRunningThread(_ thread: _ForkJoinWorkerThread) {
ForkJoinPool._threadRegistryMutex.withLock {
_runningThreadsMutex.withLock {
_submissionQueuesMutex.withLock {
_workDequesMutex.withLock {
ForkJoinPool._threadRegistry[thread._tid!] = thread
_runningThreads.append(thread)
_submissionQueues.append(thread._submissionQueue)
_workDeques.append(thread._workDeque)
}
}
}
}
}
internal func _removeRunningThread(_ thread: _ForkJoinWorkerThread) {
ForkJoinPool._threadRegistryMutex.withLock {
_runningThreadsMutex.withLock {
_submissionQueuesMutex.withLock {
_workDequesMutex.withLock {
let i = _runningThreads.index { $0 === thread }!
ForkJoinPool._threadRegistry[thread._tid!] = nil
_runningThreads.remove(at: i)
_submissionQueues.remove(at: i)
_workDeques.remove(at: i)
}
}
}
}
}
internal func _compensateForBlockedWorkerThread(_ blockingBody: @escaping () -> ()) {
// FIXME: limit the number of compensating threads.
let submissionQueue = _ForkJoinWorkDeque<ForkJoinTaskBase>()
let workDeque = _ForkJoinWorkDeque<ForkJoinTaskBase>()
let thread = _ForkJoinWorkerThread(
_pool: self, submissionQueue: submissionQueue, workDeque: workDeque)
thread.startAsync()
blockingBody()
_ = _totalThreads.fetchAndAdd(1)
}
internal func _tryCreateThread(
_ makeTask: () -> ForkJoinTaskBase?
) -> Bool {
var success = false
var oldNumThreads = _totalThreads.load()
repeat {
if oldNumThreads >= _maxThreads {
return false
}
success = _totalThreads.compareExchange(
expected: &oldNumThreads, desired: oldNumThreads + 1)
} while !success
if let task = makeTask() {
let submissionQueue = _ForkJoinWorkDeque<ForkJoinTaskBase>()
let workDeque = _ForkJoinWorkDeque<ForkJoinTaskBase>()
workDeque.prepend(task)
let thread = _ForkJoinWorkerThread(
_pool: self, submissionQueue: submissionQueue, workDeque: workDeque)
thread.startAsync()
} else {
_ = _totalThreads.fetchAndAdd(-1)
}
return true
}
internal func _stealTask() -> ForkJoinTaskBase? {
return _workDequesMutex.withLock {
let randomOffset = pickRandom(_workDeques.indices)
let count = _workDeques.count
for i in _workDeques.indices {
let index = (i + randomOffset) % count
if let task = _workDeques[index].tryTakeLast() {
return task
}
}
return nil
}
}
/// Check if the pool has grown too large because of compensating
/// threads.
internal func _tryStopThread() -> Bool {
var success = false
var oldNumThreads = _totalThreads.load()
repeat {
// FIXME: magic number 2.
if oldNumThreads <= _maxThreads + 2 {
return false
}
success = _totalThreads.compareExchange(
expected: &oldNumThreads, desired: oldNumThreads - 1)
} while !success
return true
}
internal func _submitTasksToRandomWorkers<
C : Collection
>(_ tasks: C)
where C.Iterator.Element == ForkJoinTaskBase {
if tasks.isEmpty {
return
}
_submissionQueuesMutex.withLock {
precondition(!_submissionQueues.isEmpty)
for task in tasks {
pickRandom(_submissionQueues).append(task)
}
}
}
public func forkTask(_ task: ForkJoinTaskBase) {
while true {
// Try to inflate the pool first.
if _tryCreateThread({ task }) {
return
}
// Looks like we can't create more threads. Submit the task to
// a random thread.
let done = _submissionQueuesMutex.withLock {
() -> Bool in
if !_submissionQueues.isEmpty {
pickRandom(_submissionQueues).append(task)
return true
}
return false
}
if done {
return
}
}
}
// FIXME: return a Future instead?
public func forkTask<Result>(task: @escaping () -> Result) -> ForkJoinTask<Result> {
let forkJoinTask = ForkJoinTask(_task: task)
forkTask(forkJoinTask)
return forkJoinTask
}
public static var commonPool = ForkJoinPool(_commonPool: ())
public static func invokeAll(_ tasks: ForkJoinTaskBase...) {
ForkJoinPool.invokeAll(tasks)
}
public static func invokeAll(_ tasks: [ForkJoinTaskBase]) {
if tasks.isEmpty {
return
}
if ForkJoinPool._getCurrentThread() != nil {
// Run the first task in this thread, fork the rest.
let first = tasks.first
for t in tasks.dropFirst() {
// FIXME: optimize forking in bulk.
t.fork()
}
first!._run()
} else {
// FIXME: decide if we want to allow this.
precondition(false)
}
}
}
//===----------------------------------------------------------------------===//
// Collection transformation DSL: implementation
//===----------------------------------------------------------------------===//
internal protocol _CollectionTransformerStepProtocol /*: class*/ {
associatedtype PipelineInputElement
associatedtype OutputElement
func transform<
InputCollection : Collection,
Collector : _ElementCollector
>(
_ c: InputCollection,
_ range: Range<InputCollection.Index>,
_ collector: inout Collector
)
where
InputCollection.Iterator.Element == PipelineInputElement,
Collector.Element == OutputElement
}
internal class _CollectionTransformerStep<PipelineInputElement_, OutputElement_>
: _CollectionTransformerStepProtocol {
typealias PipelineInputElement = PipelineInputElement_
typealias OutputElement = OutputElement_
func map<U>(_ transform: @escaping (OutputElement) -> U)
-> _CollectionTransformerStep<PipelineInputElement, U> {
fatalError("abstract method")
}
func filter(_ isIncluded: @escaping (OutputElement) -> Bool)
-> _CollectionTransformerStep<PipelineInputElement, OutputElement> {
fatalError("abstract method")
}
func reduce<U>(_ initial: U, _ combine: @escaping (U, OutputElement) -> U)
-> _CollectionTransformerFinalizer<PipelineInputElement, U> {
fatalError("abstract method")
}
func collectTo<
C : BuildableCollectionProtocol
>(_: C.Type) -> _CollectionTransformerFinalizer<PipelineInputElement, C>
where
C.Builder.Destination == C,
C.Builder.Element == C.Iterator.Element,
C.Iterator.Element == OutputElement {
fatalError("abstract method")
}
func transform<
InputCollection : Collection,
Collector : _ElementCollector
>(
_ c: InputCollection,
_ range: Range<InputCollection.Index>,
_ collector: inout Collector
)
where
InputCollection.Iterator.Element == PipelineInputElement,
Collector.Element == OutputElement {
fatalError("abstract method")
}
}
final internal class _CollectionTransformerStepCollectionSource<
PipelineInputElement
> : _CollectionTransformerStep<PipelineInputElement, PipelineInputElement> {
typealias InputElement = PipelineInputElement
override func map<U>(_ transform: @escaping (InputElement) -> U)
-> _CollectionTransformerStep<PipelineInputElement, U> {
return _CollectionTransformerStepOneToMaybeOne(self) {
transform($0)
}
}
override func filter(_ isIncluded: @escaping (InputElement) -> Bool)
-> _CollectionTransformerStep<PipelineInputElement, InputElement> {
return _CollectionTransformerStepOneToMaybeOne(self) {
isIncluded($0) ? $0 : nil
}
}
override func reduce<U>(_ initial: U, _ combine: @escaping (U, InputElement) -> U)
-> _CollectionTransformerFinalizer<PipelineInputElement, U> {
return _CollectionTransformerFinalizerReduce(self, initial, combine)
}
override func collectTo<
C : BuildableCollectionProtocol
>(_ c: C.Type) -> _CollectionTransformerFinalizer<PipelineInputElement, C>
where
C.Builder.Destination == C,
C.Builder.Element == C.Iterator.Element,
C.Iterator.Element == OutputElement {
return _CollectionTransformerFinalizerCollectTo(self, c)
}
override func transform<
InputCollection : Collection,
Collector : _ElementCollector
>(
_ c: InputCollection,
_ range: Range<InputCollection.Index>,
_ collector: inout Collector
)
where
InputCollection.Iterator.Element == PipelineInputElement,
Collector.Element == OutputElement {
var i = range.lowerBound
while i != range.upperBound {
let e = c[i]
collector.append(e)
c.formIndex(after: &i)
}
}
}
final internal class _CollectionTransformerStepOneToMaybeOne<
PipelineInputElement,
OutputElement,
InputStep : _CollectionTransformerStepProtocol
> : _CollectionTransformerStep<PipelineInputElement, OutputElement>
where InputStep.PipelineInputElement == PipelineInputElement {
typealias _Self = _CollectionTransformerStepOneToMaybeOne
typealias InputElement = InputStep.OutputElement
let _input: InputStep
let _transform: (InputElement) -> OutputElement?
init(_ input: InputStep, _ transform: @escaping (InputElement) -> OutputElement?) {
self._input = input
self._transform = transform
super.init()
}
override func map<U>(_ transform: @escaping (OutputElement) -> U)
-> _CollectionTransformerStep<PipelineInputElement, U> {
// Let the closure below capture only one variable, not the whole `self`.
let localTransform = _transform
return _CollectionTransformerStepOneToMaybeOne<PipelineInputElement, U, InputStep>(_input) {
(input: InputElement) -> U? in
if let e = localTransform(input) {
return transform(e)
}
return nil
}
}
override func filter(_ isIncluded: @escaping (OutputElement) -> Bool)
-> _CollectionTransformerStep<PipelineInputElement, OutputElement> {
// Let the closure below capture only one variable, not the whole `self`.
let localTransform = _transform
return _CollectionTransformerStepOneToMaybeOne<PipelineInputElement, OutputElement, InputStep>(_input) {
(input: InputElement) -> OutputElement? in
if let e = localTransform(input) {
return isIncluded(e) ? e : nil
}
return nil
}
}
override func reduce<U>(_ initial: U, _ combine: @escaping (U, OutputElement) -> U)
-> _CollectionTransformerFinalizer<PipelineInputElement, U> {
return _CollectionTransformerFinalizerReduce(self, initial, combine)
}
override func collectTo<
C : BuildableCollectionProtocol
>(_ c: C.Type) -> _CollectionTransformerFinalizer<PipelineInputElement, C>
where
C.Builder.Destination == C,
C.Builder.Element == C.Iterator.Element,
C.Iterator.Element == OutputElement {
return _CollectionTransformerFinalizerCollectTo(self, c)
}
override func transform<
InputCollection : Collection,
Collector : _ElementCollector
>(
_ c: InputCollection,
_ range: Range<InputCollection.Index>,
_ collector: inout Collector
)
where
InputCollection.Iterator.Element == PipelineInputElement,
Collector.Element == OutputElement {
var collectorWrapper =
_ElementCollectorOneToMaybeOne(collector, _transform)
_input.transform(c, range, &collectorWrapper)
collector = collectorWrapper._baseCollector
}
}
struct _ElementCollectorOneToMaybeOne<
BaseCollector : _ElementCollector,
Element_
> : _ElementCollector {
typealias Element = Element_
var _baseCollector: BaseCollector
var _transform: (Element) -> BaseCollector.Element?
init(
_ baseCollector: BaseCollector,
_ transform: @escaping (Element) -> BaseCollector.Element?
) {
self._baseCollector = baseCollector
self._transform = transform
}
mutating func sizeHint(_ approximateSize: Int) {}
mutating func append(_ element: Element) {
if let e = _transform(element) {
_baseCollector.append(e)
}
}
mutating func append<
C : Collection
>(contentsOf elements: C)
where C.Iterator.Element == Element {
for e in elements {
append(e)
}
}
}
protocol _ElementCollector {
associatedtype Element
mutating func sizeHint(_ approximateSize: Int)
mutating func append(_ element: Element)
mutating func append<
C : Collection
>(contentsOf elements: C)
where C.Iterator.Element == Element
}
class _CollectionTransformerFinalizer<PipelineInputElement, Result> {
func transform<
InputCollection : Collection
>(_ c: InputCollection) -> Result
where InputCollection.Iterator.Element == PipelineInputElement {
fatalError("implement")
}
}
final class _CollectionTransformerFinalizerReduce<
PipelineInputElement,
U,
InputElementTy,
InputStep : _CollectionTransformerStepProtocol
> : _CollectionTransformerFinalizer<PipelineInputElement, U>
where
InputStep.OutputElement == InputElementTy,
InputStep.PipelineInputElement == PipelineInputElement {
var _input: InputStep
var _initial: U
var _combine: (U, InputElementTy) -> U
init(_ input: InputStep, _ initial: U, _ combine: @escaping (U, InputElementTy) -> U) {
self._input = input
self._initial = initial
self._combine = combine
}
override func transform<
InputCollection : Collection
>(_ c: InputCollection) -> U
where InputCollection.Iterator.Element == PipelineInputElement {
var collector = _ElementCollectorReduce(_initial, _combine)
_input.transform(c, c.startIndex..<c.endIndex, &collector)
return collector.takeResult()
}
}
struct _ElementCollectorReduce<Element_, Result> : _ElementCollector {
typealias Element = Element_
var _current: Result
var _combine: (Result, Element) -> Result
init(_ initial: Result, _ combine: @escaping (Result, Element) -> Result) {
self._current = initial
self._combine = combine
}
mutating func sizeHint(_ approximateSize: Int) {}
mutating func append(_ element: Element) {
_current = _combine(_current, element)
}
mutating func append<
C : Collection
>(contentsOf elements: C)
where C.Iterator.Element == Element {
for e in elements {
append(e)
}
}
mutating func takeResult() -> Result {
return _current
}
}
final class _CollectionTransformerFinalizerCollectTo<
PipelineInputElement,
U : BuildableCollectionProtocol,
InputElementTy,
InputStep : _CollectionTransformerStepProtocol
> : _CollectionTransformerFinalizer<PipelineInputElement, U>
where
InputStep.OutputElement == InputElementTy,
InputStep.PipelineInputElement == PipelineInputElement,
U.Builder.Destination == U,
U.Builder.Element == U.Iterator.Element,
U.Iterator.Element == InputStep.OutputElement {
var _input: InputStep
init(_ input: InputStep, _: U.Type) {
self._input = input
}
override func transform<
InputCollection : Collection
>(_ c: InputCollection) -> U
where InputCollection.Iterator.Element == PipelineInputElement {
var collector = _ElementCollectorCollectTo<U>()
_input.transform(c, c.startIndex..<c.endIndex, &collector)
return collector.takeResult()
}
}
struct _ElementCollectorCollectTo<
BuildableCollection : BuildableCollectionProtocol
> : _ElementCollector
where
BuildableCollection.Builder.Destination == BuildableCollection,
BuildableCollection.Builder.Element == BuildableCollection.Iterator.Element {
typealias Element = BuildableCollection.Iterator.Element
var _builder: BuildableCollection.Builder
init() {
self._builder = BuildableCollection.Builder()
}
mutating func sizeHint(_ approximateSize: Int) {
_builder.sizeHint(approximateSize)
}
mutating func append(_ element: Element) {
_builder.append(element)
}
mutating func append<
C : Collection
>(contentsOf elements: C)
where C.Iterator.Element == Element {
_builder.append(contentsOf: elements)
}
mutating func takeResult() -> BuildableCollection {
return _builder.takeResult()
}
}
internal func _optimizeCollectionTransformer<PipelineInputElement, Result>(
_ transformer: _CollectionTransformerFinalizer<PipelineInputElement, Result>
) -> _CollectionTransformerFinalizer<PipelineInputElement, Result> {
return transformer
}
internal func _runCollectionTransformer<
InputCollection : Collection, Result
>(
_ c: InputCollection,
_ transformer: _CollectionTransformerFinalizer<InputCollection.Iterator.Element, Result>
) -> Result {
dump(transformer)
let optimized = _optimizeCollectionTransformer(transformer)
dump(optimized)
return transformer.transform(c)
}
//===----------------------------------------------------------------------===//
// Collection transformation DSL: public interface
//===----------------------------------------------------------------------===//
public struct CollectionTransformerPipeline<
InputCollection : Collection, T
> {
internal var _input: InputCollection
internal var _step: _CollectionTransformerStep<InputCollection.Iterator.Element, T>
public func map<U>(_ transform: @escaping (T) -> U)
-> CollectionTransformerPipeline<InputCollection, U> {
return CollectionTransformerPipeline<InputCollection, U>(
_input: _input,
_step: _step.map(transform)
)
}
public func filter(_ isIncluded: @escaping (T) -> Bool)
-> CollectionTransformerPipeline<InputCollection, T> {
return CollectionTransformerPipeline<InputCollection, T>(
_input: _input,
_step: _step.filter(isIncluded)
)
}
public func reduce<U>(
_ initial: U, _ combine: @escaping (U, T) -> U
) -> U {
return _runCollectionTransformer(_input, _step.reduce(initial, combine))
}
public func collectTo<
C : BuildableCollectionProtocol
>(_ c: C.Type) -> C
where
C.Builder.Destination == C,
C.Iterator.Element == T,
C.Builder.Element == T {
return _runCollectionTransformer(_input, _step.collectTo(c))
}
public func toArray() -> [T] {
return collectTo(Array<T>.self)
}
}
public func transform<C : Collection>(_ c: C)
-> CollectionTransformerPipeline<C, C.Iterator.Element> {
return CollectionTransformerPipeline<C, C.Iterator.Element>(
_input: c,
_step: _CollectionTransformerStepCollectionSource<C.Iterator.Element>())
}
//===----------------------------------------------------------------------===//
// Collection transformation DSL: tests
//===----------------------------------------------------------------------===//
import StdlibUnittest
var t = TestSuite("t")
t.test("fusion/map+reduce") {
let xs = [ 1, 2, 3 ]
let result =
transform(xs)
.map { $0 * 2 }
.reduce(0, { $0 + $1 })
expectEqual(12, result)
}
t.test("fusion/map+filter+reduce") {
let xs = [ 1, 2, 3 ]
let result = transform(xs)
.map { $0 * 2 }
.filter { $0 != 0 }
.reduce(0, { $0 + $1 })
expectEqual(12, result)
}
t.test("fusion/map+collectTo") {
let xs = [ 1, 2, 3 ]
let result =
transform(xs)
.map { $0 * 2 }
.collectTo(Array<Int>.self)
expectEqual([ 2, 4, 6 ], result)
}
t.test("fusion/map+toArray") {
let xs = [ 1, 2, 3 ]
let result =
transform(xs)
.map { $0 * 2 }
.toArray()
expectEqual([ 2, 4, 6 ], result)
}
t.test("ForkJoinPool.forkTask") {
var tasks: [ForkJoinTask<()>] = []
for i in 0..<100 {
tasks.append(ForkJoinPool.commonPool.forkTask {
() -> () in
var result = 1
for i in 0..<10000 {
result = result &* i
_blackHole(result)
}
return ()
})
}
for t in tasks {
t.wait()
}
}
func fib(_ n: Int) -> Int {
if n == 1 || n == 2 {
return 1
}
if n == 38 {
print("\(pthread_self()) fib(\(n))")
}
if n < 39 {
let r = fib(n - 1) + fib(n - 2)
_blackHole(r)
return r
}
print("fib(\(n))")
let t1 = ForkJoinTask() { fib(n - 1) }
let t2 = ForkJoinTask() { fib(n - 2) }
ForkJoinPool.invokeAll(t1, t2)
return t2.waitAndGetResult() + t1.waitAndGetResult()
}
t.test("ForkJoinPool.forkTask/Fibonacci") {
let t = ForkJoinPool.commonPool.forkTask { fib(40) }
expectEqual(102334155, t.waitAndGetResult())
}
func _parallelMap(_ input: [Int], transform: @escaping (Int) -> Int, range: Range<Int>)
-> Array<Int>.Builder {
var builder = Array<Int>.Builder()
if range.count < 1_000 {
builder.append(contentsOf: input[range].map(transform))
} else {
let tasks = input.split(range).map {
(subRange) in
ForkJoinTask<Array<Int>.Builder> {
_parallelMap(input, transform: transform, range: subRange)
}
}
ForkJoinPool.invokeAll(tasks)
for t in tasks {
var otherBuilder = t.waitAndGetResult()
builder.moveContentsOf(&otherBuilder)
}
}
return builder
}
func parallelMap(_ input: [Int], transform: @escaping (Int) -> Int) -> [Int] {
let t = ForkJoinPool.commonPool.forkTask {
_parallelMap(
input,
transform: transform,
range: input.startIndex..<input.endIndex)
}
var builder = t.waitAndGetResult()
return builder.takeResult()
}
t.test("ForkJoinPool.forkTask/MapArray") {
expectEqual(
Array(2..<1_001),
parallelMap(Array(1..<1_000)) { $0 + 1 }
)
}
/*
* FIXME: reduce compiler crasher
t.test("ForkJoinPool.forkTask") {
func fib(_ n: Int) -> Int {
if n == 0 || n == 1 {
return 1
}
let t1 = ForkJoinPool.commonPool.forkTask { fib(n - 1) }
let t2 = ForkJoinPool.commonPool.forkTask { fib(n - 2) }
return t2.waitAndGetResult() + t1.waitAndGetResult()
}
expectEqual(0, fib(10))
}
*/
/*
Useful links:
http://habrahabr.ru/post/255659/
*/
runAllTests()
|
apache-2.0
|
c3a8563b113a95578d1a92b22a567b40
| 26.112414 | 108 | 0.65355 | 4.519775 | false | false | false | false |
tjw/swift
|
test/SILGen/keypath_application.swift
|
1
|
4700
|
// RUN: %target-swift-frontend -emit-silgen -enable-sil-ownership %s | %FileCheck %s
class A {}
class B {}
protocol P {}
protocol Q {}
// CHECK-LABEL: sil hidden @{{.*}}loadable
func loadable(readonly: A, writable: inout A,
value: B,
kp: KeyPath<A, B>,
wkp: WritableKeyPath<A, B>,
rkp: ReferenceWritableKeyPath<A, B>) {
// CHECK: [[ROOT_TMP:%.*]] = alloc_stack $A
// CHECK: [[ROOT_COPY:%.*]] = copy_value %0
// CHECK: store [[ROOT_COPY]] to [init] [[ROOT_TMP]]
// CHECK: [[KP_COPY:%.*]] = copy_value %3
// CHECK: [[PROJECT:%.*]] = function_ref @{{.*}}_projectKeyPathReadOnly
// CHECK: [[BORROWED_KP_COPY:%.*]] = begin_borrow [[KP_COPY]]
// CHECK: [[RESULT_TMP:%.*]] = alloc_stack $B
// CHECK: apply [[PROJECT]]<A, B>([[RESULT_TMP]], [[ROOT_TMP]], [[BORROWED_KP_COPY]])
// CHECK: [[RESULT:%.*]] = load [take] [[RESULT_TMP]]
// CHECK: destroy_value [[RESULT]]
_ = readonly[keyPath: kp]
_ = writable[keyPath: kp]
_ = readonly[keyPath: wkp]
// CHECK: function_ref @{{.*}}_projectKeyPathReadOnly
_ = writable[keyPath: wkp]
// CHECK: function_ref @{{.*}}_projectKeyPathReadOnly
_ = readonly[keyPath: rkp]
// CHECK: function_ref @{{.*}}_projectKeyPathReadOnly
_ = writable[keyPath: rkp]
// CHECK: function_ref @{{.*}}_projectKeyPathWritable
writable[keyPath: wkp] = value
// CHECK: function_ref @{{.*}}_projectKeyPathReferenceWritable
readonly[keyPath: rkp] = value
// CHECK: function_ref @{{.*}}_projectKeyPathReferenceWritable
writable[keyPath: rkp] = value
}
// CHECK-LABEL: sil hidden @{{.*}}addressOnly
func addressOnly(readonly: P, writable: inout P,
value: Q,
kp: KeyPath<P, Q>,
wkp: WritableKeyPath<P, Q>,
rkp: ReferenceWritableKeyPath<P, Q>) {
// CHECK: function_ref @{{.*}}_projectKeyPathReadOnly
_ = readonly[keyPath: kp]
// CHECK: function_ref @{{.*}}_projectKeyPathReadOnly
_ = writable[keyPath: kp]
// CHECK: function_ref @{{.*}}_projectKeyPathReadOnly
_ = readonly[keyPath: wkp]
// CHECK: function_ref @{{.*}}_projectKeyPathReadOnly
_ = writable[keyPath: wkp]
// CHECK: function_ref @{{.*}}_projectKeyPathReadOnly
_ = readonly[keyPath: rkp]
// CHECK: function_ref @{{.*}}_projectKeyPathReadOnly
_ = writable[keyPath: rkp]
// CHECK: function_ref @{{.*}}_projectKeyPathWritable
writable[keyPath: wkp] = value
// CHECK: function_ref @{{.*}}_projectKeyPathReferenceWritable
readonly[keyPath: rkp] = value
// CHECK: function_ref @{{.*}}_projectKeyPathReferenceWritable
writable[keyPath: rkp] = value
}
// CHECK-LABEL: sil hidden @{{.*}}reabstracted
func reabstracted(readonly: @escaping () -> (),
writable: inout () -> (),
value: @escaping (A) -> B,
kp: KeyPath<() -> (), (A) -> B>,
wkp: WritableKeyPath<() -> (), (A) -> B>,
rkp: ReferenceWritableKeyPath<() -> (), (A) -> B>) {
// CHECK: [[PROJECT:%.*]] = function_ref @{{.*}}_projectKeyPathReadOnly
_ = readonly[keyPath: kp]
// CHECK: [[PROJECT:%.*]] = function_ref @{{.*}}_projectKeyPathReadOnly
_ = writable[keyPath: kp]
// CHECK: [[PROJECT:%.*]] = function_ref @{{.*}}_projectKeyPathReadOnly
_ = readonly[keyPath: wkp]
// CHECK: [[PROJECT:%.*]] = function_ref @{{.*}}_projectKeyPathReadOnly
_ = writable[keyPath: wkp]
// CHECK: [[PROJECT:%.*]] = function_ref @{{.*}}_projectKeyPathReadOnly
_ = readonly[keyPath: rkp]
// CHECK: [[PROJECT:%.*]] = function_ref @{{.*}}_projectKeyPathReadOnly
_ = writable[keyPath: rkp]
// CHECK: [[PROJECT:%.*]] = function_ref @{{.*}}_projectKeyPathWritable
writable[keyPath: wkp] = value
// CHECK: [[PROJECT:%.*]] = function_ref @{{.*}}_projectKeyPathReferenceWritable
readonly[keyPath: rkp] = value
// CHECK: [[PROJECT:%.*]] = function_ref @{{.*}}_projectKeyPathReferenceWritable
writable[keyPath: rkp] = value
}
// CHECK-LABEL: sil hidden @{{.*}}partial
func partial<A>(valueA: A,
valueB: Int,
pkpA: PartialKeyPath<A>,
pkpB: PartialKeyPath<Int>,
akp: AnyKeyPath) {
// CHECK: [[PROJECT:%.*]] = function_ref @{{.*}}projectKeyPathAny
// CHECK: apply [[PROJECT]]<A>
_ = valueA[keyPath: akp]
// CHECK: [[PROJECT:%.*]] = function_ref @{{.*}}projectKeyPathPartial
// CHECK: apply [[PROJECT]]<A>
_ = valueA[keyPath: pkpA]
// CHECK: [[PROJECT:%.*]] = function_ref @{{.*}}projectKeyPathAny
// CHECK: apply [[PROJECT]]<Int>
_ = valueB[keyPath: akp]
// CHECK: [[PROJECT:%.*]] = function_ref @{{.*}}projectKeyPathPartial
// CHECK: apply [[PROJECT]]<Int>
_ = valueB[keyPath: pkpB]
}
|
apache-2.0
|
f8c289d676e0bae022e4e8efffe65d70
| 36.903226 | 87 | 0.591277 | 4.188948 | false | false | false | false |
uasys/swift
|
test/IRGen/globals.swift
|
3
|
1894
|
// RUN: %target-swift-frontend -assume-parsing-unqualified-ownership-sil -primary-file %s -emit-ir | %FileCheck %s
// REQUIRES: CPU=x86_64
var g0 : Int = 1
var g1 : (Void, Int, Void)
var g2 : (Void, Int, Int)
var g3 : Bool
// FIXME: enum IRgen
// enum TY4 { case some(Int, Int); case none }
// var g4 : TY4
// FIXME: enum IRgen
// enum TY5 { case a(Int8, Int8, Int8, Int8)
// case b(Int16) }
// var g5 : TY5
var g6 : Double
var g7 : Float
// FIXME: enum IRgen
// enum TY8 { case a }
// var g8 : TY8
struct TY9 { }
var g9 : TY9
// rdar://16520242
struct A {}
extension A {
static var foo : Int = 5
}
// CHECK: [[INT:%.*]] = type <{ i64 }>
// CHECK: [[BOOL:%.*]] = type <{ i1 }>
// CHECK: [[DOUBLE:%.*]] = type <{ double }>
// CHECK: [[FLOAT:%.*]] = type <{ float }>
// CHECK-NOT: TY8
// CHECK-NOT: TY9
// CHECK: @_T07globals2g0Sivp = hidden global [[INT]] zeroinitializer, align 8
// CHECK: @_T07globals2g1yt_Siyttvp = hidden global <{ [[INT]] }> zeroinitializer, align 8
// CHECK: @_T07globals2g2yt_S2itvp = hidden global <{ [[INT]], [[INT]] }> zeroinitializer, align 8
// CHECK: @_T07globals2g3Sbvp = hidden global [[BOOL]] zeroinitializer, align 1
// CHECK: @_T07globals2g6Sdvp = hidden global [[DOUBLE]] zeroinitializer, align 8
// CHECK: @_T07globals2g7Sfvp = hidden global [[FLOAT]] zeroinitializer, align 4
// CHECK: @_T07globals1AV3fooSivpZ = hidden global [[INT]] zeroinitializer, align 8
// CHECK-NOT: g8
// CHECK-NOT: g9
// CHECK: define{{( protected)?}} i32 @main(i32, i8**) {{.*}} {
// CHECK: store i64 {{.*}}, i64* getelementptr inbounds ([[INT]], [[INT]]* @_T07globals2g0Sivp, i32 0, i32 0), align 8
// FIXME: give these initializers a real mangled name
// CHECK: define internal swiftcc void @globalinit_{{.*}}func0() {{.*}} {
// CHECK: store i64 5, i64* getelementptr inbounds (%TSi, %TSi* @_T07globals1AV3fooSivpZ, i32 0, i32 0), align 8
|
apache-2.0
|
19254977d1738c2a0f64125772601ea9
| 31.101695 | 124 | 0.629884 | 2.982677 | false | false | false | false |
juliand665/LeagueKit
|
Sources/LeagueKit/Model/Dynamic API/MatchTimeline.swift
|
1
|
3773
|
// Created by Julian Dunskus
import Foundation
public struct MatchTimeline: Codable {
public var frames: [Frame]
public var frameInterval: Int
public struct Frame: Codable {
public var timestamp: Int
public var events: [Event]
public init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
try timestamp = container.decodeValue(forKey: .timestamp)
let rawEvents: [RawEvent] = try container.decodeValue(forKey: .events)
events = rawEvents.map { $0.event }
}
public func encode(to encoder: Encoder) throws {
var container = encoder.container(keyedBy: CodingKeys.self)
try container.encode(timestamp, forKey: .timestamp)
let rawEvents = events.map(RawEvent.init)
try container.encode(rawEvents, forKey: .events)
}
private enum CodingKeys: String, CodingKey {
case timestamp
case events
}
}
}
fileprivate struct RawEvent: Codable {
let identifier: EventIdentifier
let event: Event
init(containing event: Event) {
self.event = event
self.identifier = EventIdentifier.allCases.first { $0.type == type(of: event) }!
}
init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
try identifier = container.decodeValue(forKey: .identifier)
try event = identifier.type.init(from: decoder)
}
func encode(to encoder: Encoder) throws {
var container = encoder.container(keyedBy: CodingKeys.self)
try container.encode(identifier, forKey: .identifier)
try event.encode(to: encoder)
}
private enum CodingKeys: String, CodingKey {
case identifier = "type"
}
}
public protocol Event: Codable {}
enum EventIdentifier: String, Codable, CaseIterable {
case championKill = "CHAMPION_KILL"
case wardPlacement = "WARD_PLACED"
case wardKill = "WARD_KILL"
case buildingKill = "BUILDING_KILL"
case eliteMonsterKill = "ELITE_MONSTER_KILL"
case itemPurchase = "ITEM_PURCHASED"
case itemSale = "ITEM_SOLD"
case itemDestruction = "ITEM_DESTROYED"
case itemUndo = "ITEM_UNDO"
case skillLevelUp = "SKILL_LEVEL_UP"
case ascendedEvent = "ASCENDED_EVENT"
case pointCapture = "POINT_CAPTURE"
case poroKingSummon = "PORO_KING_SUMMONED"
var type: Event.Type {
switch self {
case .championKill:
return ChampionKill.self
case .wardPlacement:
return WardPlacement.self
case .wardKill:
return WardKill.self
case .buildingKill:
return BuildingKill.self
case .eliteMonsterKill:
return EliteMonsterKill.self
case .itemPurchase:
return ItemPurchase.self
case .itemSale:
return ItemSale.self
case .itemDestruction:
return ItemDestruction.self
case .itemUndo:
return ItemUndo.self
case .skillLevelUp:
return SkillLevelUp.self
case .ascendedEvent:
return AscendedEvent.self
case .pointCapture:
return PointCapture.self
case .poroKingSummon:
return PoroKingSummon.self
}
}
}
public struct ChampionKill: Event {
public var killerID: Int
public var victimID: Int
public var assisterIDs: [Int]
private enum CodingKeys: String, CodingKey {
case killerID = "killerId"
case victimID = "victimId"
case assisterIDs = "assistingParticipantIds"
}
}
public struct WardPlacement: Event {
// TODO
}
public struct WardKill: Event {
// TODO
}
public struct BuildingKill: Event {
// TODO
}
public struct EliteMonsterKill: Event {
// TODO
}
public struct ItemPurchase: Event {
// TODO
}
public struct ItemSale: Event {
// TODO
}
public struct ItemDestruction: Event {
// TODO
}
public struct ItemUndo: Event {
// TODO
}
public struct SkillLevelUp: Event {
// TODO
}
public struct AscendedEvent: Event {
// TODO
}
public struct PointCapture: Event {
// TODO
}
public struct PoroKingSummon: Event {
// TODO
}
|
mit
|
93a60ea508bff2d487a4e72afa57a99b
| 20.809249 | 82 | 0.725682 | 3.333039 | false | false | false | false |
pvbaleeiro/movie-aholic
|
movieaholic/movieaholic/controller/base/ImageShrinkAnimationController.swift
|
1
|
6882
|
//
// ImageShrinkAnimationController.swift
// movieaholic
//
// Created by Victor Baleeiro on 24/09/17.
// Copyright © 2017 Victor Baleeiro. All rights reserved.
//
import UIKit
//-------------------------------------------------------------------------------------------------------------
// MARK: Protocol
//-------------------------------------------------------------------------------------------------------------
protocol ImageShrinkAnimationControllerProtocol {
func getInitialImageFrame() -> CGRect
}
class ImageShrinkAnimationController: NSObject, UIViewControllerAnimatedTransitioning {
//-------------------------------------------------------------------------------------------------------------
// MARK: Propriedades
//-------------------------------------------------------------------------------------------------------------
var destinationFrame = CGRect.zero
//-------------------------------------------------------------------------------------------------------------
// MARK: Ciclo de vida
//-------------------------------------------------------------------------------------------------------------
func transitionDuration(using transitionContext: UIViewControllerContextTransitioning?) -> TimeInterval {
return 0.5
}
func animateTransition(using transitionContext: UIViewControllerContextTransitioning) {
guard let fromVC = transitionContext.viewController(forKey: .from),
fromVC is ImageShrinkAnimationControllerProtocol,
let toVC = transitionContext.viewController(forKey: .to) else {
return
}
let screenWidth = UIScreen.main.bounds.width
let screenHeight = UIScreen.main.bounds.height
let containerView = transitionContext.containerView
containerView.backgroundColor = UIColor.white
containerView.addSubview(toVC.view)
// setup cell image snapshot
let initialFrame = (fromVC as! ImageShrinkAnimationControllerProtocol).getInitialImageFrame()
let finalFrame = destinationFrame
let snapshot = fromVC.view.resizableSnapshotView(from: initialFrame, afterScreenUpdates: false, withCapInsets: .zero)!
snapshot.frame = initialFrame
containerView.addSubview(snapshot)
let widthDiff = initialFrame.width - finalFrame.width
// setup snapshot to the left of selected cell image
let leftFinalFrame = CGRect(x: 0, y: finalFrame.origin.y, width: finalFrame.origin.x, height: finalFrame.height)
let leftInitialFrameWidth = leftFinalFrame.width + widthDiff
let leftInitialFrame = CGRect(x: -leftInitialFrameWidth, y: initialFrame.origin.y, width: leftInitialFrameWidth, height: initialFrame.height)
let leftSnapshot = toVC.view.resizableSnapshotView(from: leftFinalFrame, afterScreenUpdates: false, withCapInsets: .zero)!
leftSnapshot.frame = leftInitialFrame
containerView.addSubview(leftSnapshot)
// setup snapshot to the right of selected cell image
let rightFinalFrameX = finalFrame.origin.x + finalFrame.width
let rightFinalFrame = CGRect(x: rightFinalFrameX, y: finalFrame.origin.y, width: screenWidth - rightFinalFrameX, height: finalFrame.height)
let rightInitialFrame = CGRect(x: screenWidth, y: initialFrame.origin.y, width: rightFinalFrame.width + widthDiff, height: initialFrame.height)
let rightSnapshot = toVC.view.resizableSnapshotView(from: rightFinalFrame, afterScreenUpdates: false, withCapInsets: .zero)!
rightSnapshot.frame = rightInitialFrame
containerView.addSubview(rightSnapshot)
// setup snapshot to the bottom of selected cell image
let bottomFinalFrameY = finalFrame.origin.y + finalFrame.height
let bottomFinalFrame = CGRect(x: 0, y: bottomFinalFrameY, width: screenWidth, height: screenHeight - bottomFinalFrameY)
let bottomInitialFrame = CGRect(x: 0, y: bottomFinalFrame.height, width: screenWidth, height: screenHeight)
let bottomSnapshot = toVC.view.resizableSnapshotView(from: bottomFinalFrame, afterScreenUpdates: false, withCapInsets: .zero)!
bottomSnapshot.frame = bottomInitialFrame
containerView.addSubview(bottomSnapshot)
// setup snapshot to the top of selected cell image
let topFinalFrame = CGRect(x: 0, y: 0, width: screenWidth, height: finalFrame.origin.y)
let topInitialFrame = CGRect(x: 0, y: -topFinalFrame.height, width: topFinalFrame.width, height: topFinalFrame.height)
let topSnapshot = toVC.view.resizableSnapshotView(from: topFinalFrame, afterScreenUpdates: false, withCapInsets: .zero)!
topSnapshot.frame = topInitialFrame
containerView.addSubview(topSnapshot)
// setup the bottom component of the origin view
let fromVCBottomInitialFrameY = initialFrame.origin.y + initialFrame.height
let fromVCBottomInitialFrame = CGRect(x: 0, y: fromVCBottomInitialFrameY, width: screenWidth, height: screenHeight - fromVCBottomInitialFrameY)
let fromVCBottomFinalFrame = CGRect(x: 0, y: screenHeight, width: screenWidth, height: fromVCBottomInitialFrame.height)
let fromVCSnapshot = fromVC.view.resizableSnapshotView(from: fromVCBottomInitialFrame, afterScreenUpdates: false, withCapInsets: .zero)!
fromVCSnapshot.frame = fromVCBottomInitialFrame
containerView.addSubview(fromVCSnapshot)
toVC.view.isHidden = true
fromVC.view.isHidden = true
let duration = transitionDuration(using: transitionContext)
UIView.animate(withDuration: 0.3, animations: {
//fromVCSnapshot.alpha = 0
fromVCSnapshot.frame = fromVCBottomFinalFrame
}, completion: { _ in
fromVCSnapshot.removeFromSuperview()
})
UIView.animate(withDuration: duration, delay: 0, options: [.curveEaseInOut], animations: {
snapshot.frame = finalFrame
leftSnapshot.frame = leftFinalFrame
rightSnapshot.frame = rightFinalFrame
bottomSnapshot.frame = bottomFinalFrame
topSnapshot.frame = topFinalFrame
}, completion: { _ in
toVC.view.isHidden = false
fromVC.view.isHidden = false
snapshot.removeFromSuperview()
leftSnapshot.removeFromSuperview()
rightSnapshot.removeFromSuperview()
bottomSnapshot.removeFromSuperview()
topSnapshot.removeFromSuperview()
transitionContext.completeTransition(!transitionContext.transitionWasCancelled)
})
}
}
|
mit
|
e73eec37cb8351367c8982c9893d967f
| 48.862319 | 151 | 0.619387 | 5.831356 | false | false | false | false |
AlphaJian/PaperCalculator
|
PaperCalculator/PaperCalculator/Views/Create/NumView.swift
|
1
|
2131
|
//
// NumView.swift
// PaperCalculator
//
// Created by appledev018 on 9/29/16.
// Copyright © 2016 apple. All rights reserved.
//
import UIKit
class NumView: UIView {
var changeNumHandler : ButtonTouchUpReturnInt?
var index = 0
override init(frame: CGRect) {
super.init(frame: frame)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
let numLbl = UILabel()
func initUI(num: Int) {
self.backgroundColor = lightBlue
self.layer.cornerRadius = 10
let addButton = UIButton(type: .custom)
addButton.setTitle("+", for: .normal)
addButton.frame = CGRect(x: self.frame.width/3 * 2, y: 0, width: self.frame.width/3, height: self.frame.height)
addButton.addTarget(self, action: #selector(NumView.addButtonTapped), for: UIControlEvents.touchUpInside)
self.addSubview(addButton)
let minusButton = UIButton(type: .custom)
minusButton.setTitle("-", for: .normal)
minusButton.frame = CGRect(x: 0, y: 0, width: self.frame.width/3, height: self.frame.height)
minusButton.addTarget(self, action: #selector(NumView.minusButtonTapped), for: UIControlEvents.touchUpInside)
self.addSubview(minusButton)
numLbl.frame = CGRect(x: self.frame.width/3, y: 0, width: self.frame.width/3, height: self.frame.height)
numLbl.textAlignment = NSTextAlignment.center
numLbl.text = "\(num)"
numLbl.textColor = UIColor.white
self.addSubview(numLbl)
}
func addButtonTapped(){
print("+")
numLbl.text = "\((numLbl.text! as NSString).intValue + 1)"
if changeNumHandler != nil {
self.changeNumHandler!(Int((numLbl.text! as NSString).intValue), index)
}
}
func minusButtonTapped(){
print("-")
numLbl.text = "\((numLbl.text! as NSString).intValue - 1)"
if changeNumHandler != nil {
self.changeNumHandler!(Int((numLbl.text! as NSString).intValue), index)
}
}
}
|
gpl-3.0
|
3cefc5d5cc7c417ada86e90bd3b3c177
| 31.272727 | 119 | 0.61784 | 4.041746 | false | false | false | false |
itsmeichigo/PhotoMap
|
PhotoMap/PhotoMap/Source/Controllers/Grid/GridViewController.swift
|
1
|
2662
|
//
// GridViewController.swift
// PhotoMap
//
// Created by Huong Do on 2/15/17.
// Copyright © 2017 Huong Do. All rights reserved.
//
import UIKit
import FMMosaicLayout
import RxSwift
import RxCocoa
import ICGTransitionAnimation
class GridViewController: UIViewController {
@IBOutlet weak var collectionView: UICollectionView!
@IBOutlet weak var mapButton: UIButton!
var viewModel: PlaceListViewModel!
var disposeBag = DisposeBag()
override func viewDidLoad() {
super.viewDidLoad()
let layout = FMMosaicLayout()
layout.delegate = self
collectionView.setCollectionViewLayout(layout, animated: false)
viewModel.searchResults
.bindTo(collectionView.rx.items(cellIdentifier: "photoCell", cellType: PhotoCollectionViewCell.self)) { (row, item, cell) in
cell.bindData(item)
}
.disposed(by: disposeBag)
collectionView.rx.modelSelected(Place.self)
.bindNext { item in
let detailsController = self.storyboard?.instantiateViewController(withIdentifier: "detailsVC") as! DetailsViewController
detailsController.viewModel = PlaceDetailViewModel(place: item)
self.present(detailsController, animated: true, completion: nil)
}
.disposed(by: disposeBag)
mapButton.rx.tap
.bindNext {
// custom navigation animation
let fancyNavigationController = self.navigationController as! ICGNavigationController
let flipAnimation = QuickFlipAnimation(type: ICGFlipAnimationType.left)
fancyNavigationController.animationController = flipAnimation
_ = self.navigationController?.popViewController(animated: true)
}
.disposed(by: disposeBag)
}
override var preferredStatusBarStyle: UIStatusBarStyle {
return .default
}
}
extension GridViewController: FMMosaicLayoutDelegate {
func collectionView(_ collectionView: UICollectionView!, layout collectionViewLayout: FMMosaicLayout!, numberOfColumnsInSection section: Int) -> Int {
return 2
}
func collectionView(_ collectionView: UICollectionView!, layout collectionViewLayout: FMMosaicLayout!, mosaicCellSizeForItemAt indexPath: IndexPath!) -> FMMosaicCellSize {
return (indexPath.row%3 == 0) ? .big : .small
}
func collectionView(_ collectionView: UICollectionView!, layout collectionViewLayout: FMMosaicLayout!, interitemSpacingForSectionAt section: Int) -> CGFloat {
return 10
}
}
|
mit
|
9e4fabf554d79798781079d04f6ae972
| 34.959459 | 175 | 0.674934 | 5.430612 | false | false | false | false |
nigelbrady/MultipleChoiceController-iOS
|
MultipleChoiceController.swift
|
1
|
4889
|
/*
The MIT License (MIT)
Copyright (c) 2014 Nigel Brady
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
class MultipleChoiceController: UITableViewController,
UITableViewDataSource,
UITableViewDelegate {
var header: String = ""
var footer: String = ""
var allowMultipleSelections: Bool = false
var maximumAllowedSelections: Int?
var choices: [NSObject]?
var selectedItems = [NSObject]()
var delegate: MultipleChoiceControllerDelegate?
var doneButton: UIBarButtonItem?
override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: NSBundle?) {
super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil)
}
override init(style: UITableViewStyle) {
super.init(style: UITableViewStyle.Grouped)
}
required init(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
override func viewDidLoad() {
if allowMultipleSelections{
self.doneButton =
UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.Done,
target: self, action: "finishSelection")
self.navigationItem.rightBarButtonItem = doneButton
doneButton?.enabled = !selectedItems.isEmpty
}
self.tableView.registerClass(UITableViewCell.self, forCellReuseIdentifier: "cell")
self.tableView.dataSource = self
self.tableView.delegate = self
self.tableView.reloadData()
}
func finishSelection(){
delegate?.multipleChoiceController(self, didSelectItems: selectedItems)
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return choices!.count
}
override func tableView(tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
return header
}
override func tableView(tableView: UITableView, titleForFooterInSection section: Int) -> String? {
return footer
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell =
tableView.dequeueReusableCellWithIdentifier("cell", forIndexPath: indexPath) as UITableViewCell
let choice = self.choices![indexPath.row]
cell.textLabel?.text = choice.description
cell.accessoryType =
contains(selectedItems, choice) ?
UITableViewCellAccessoryType.Checkmark : UITableViewCellAccessoryType.None
return cell
}
override func tableView(tableView: UITableView,
didSelectRowAtIndexPath indexPath: NSIndexPath) {
let choice = choices![indexPath.row]
if let index = find(selectedItems, choice){
selectedItems.removeAtIndex(index)
} else if shouldAllowSelection() {
selectedItems.append(choice)
}
tableView.reloadRowsAtIndexPaths([indexPath],
withRowAnimation: UITableViewRowAnimation.Automatic)
if allowMultipleSelections{
doneButton?.enabled = !selectedItems.isEmpty
} else {
finishSelection()
}
}
func shouldAllowSelection() -> Bool{
if !allowMultipleSelections{
return true
} else if allowMultipleSelections && maximumAllowedSelections == nil{
return true
} else {
return selectedItems.count < maximumAllowedSelections!
}
}
}
protocol MultipleChoiceControllerDelegate{
func multipleChoiceController(controller: MultipleChoiceController,
didSelectItems items: [NSObject])
}
|
mit
|
0a6081252aa073699c12d8207ed07198
| 34.172662 | 118 | 0.66169 | 5.799526 | false | false | false | false |
wwq0327/iOS9Example
|
MMDrawerControllerDemo/MMDrawerControllerDemo/AppDelegate.swift
|
1
|
3601
|
//
// AppDelegate.swift
// MMDrawerControllerDemo
//
// Created by wyatt on 15/12/26.
// Copyright © 2015年 Wanqing Wang. All rights reserved.
//
import UIKit
import MMDrawerController
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
var drawerController: MMDrawerController!
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
// 创建窗口
let mainFrame = UIScreen.mainScreen().bounds
window = UIWindow(frame: mainFrame)
// 设置视图
let leftViewController = LeftViewController()
let homeViewController = HomeViewController()
// 将home view 装入nav中
let homeNavigationController = UINavigationController(rootViewController: homeViewController)
drawerController = MMDrawerController(centerViewController: homeNavigationController, leftDrawerViewController: leftViewController)
drawerController.maximumLeftDrawerWidth = Common.screenWidth * 0.6
// 手势
drawerController.openDrawerGestureModeMask = MMOpenDrawerGestureMode.All
drawerController.closeDrawerGestureModeMask = MMCloseDrawerGestureMode.All
// 设置动画,这里是设置打开侧边栏的透明度从0到1
drawerController.setDrawerVisualStateBlock { (drawerController, drawerSide, percentVisible) -> Void in
var sideDrawerViewController: UIViewController?
if drawerSide == MMDrawerSide.Left {
sideDrawerViewController = drawerController.leftDrawerViewController
}
sideDrawerViewController?.view.alpha = percentVisible
}
// 设置根视图
self.window?.rootViewController = drawerController
// 设置可见
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:.
}
}
|
apache-2.0
|
b7cf3a8e5b8325f50cf568bd50b3c02b
| 45.184211 | 285 | 0.731624 | 5.879397 | false | false | false | false |
NobodyNada/SwiftChatSE
|
Sources/SwiftChatSE/Client.swift
|
1
|
17378
|
//
// Client.swift
// FireAlarm
//
// Created by NobodyNada on 8/27/16.
// Copyright © 2016 NobodyNada. All rights reserved.
//
//TODO: Refactor this class; it's kind of a mess.
import Foundation
import Dispatch
#if os(Linux)
import FoundationNetworking
#endif
//MARK: - Convenience extensions
extension String {
var urlEncodedString: String {
var allowed = CharacterSet.urlQueryAllowed
allowed.remove(charactersIn: "&+")
return self.addingPercentEncoding(withAllowedCharacters: allowed)!
}
init(urlParameters: [String:String]) {
var result = [String]()
for (key, value) in urlParameters {
result.append("\(key.urlEncodedString)=\(value.urlEncodedString)")
}
self.init(result.joined(separator: "&"))
}
}
func + <K, V> (left: [K:V], right: [K:V]) -> [K:V] {
var result = left
for (k, v) in right {
result[k] = v
}
return result
}
//https://stackoverflow.com/a/24052094/3476191
func += <K, V> (left: inout [K:V], right: [K:V]) {
for (k, v) in right {
left[k] = v
}
}
//MARK: -
///A Client handles HTTP requests, cookie management, and logging in to Stack Exchange chat.
open class Client: NSObject, URLSessionDataDelegate {
//MARK: Instance variables
open var session: URLSession {
return URLSession(
configuration: configuration,
delegate: self, delegateQueue: delegateQueue
)
}
///Pretty self explanatory
open var cookies = [HTTPCookie]()
private let queue = DispatchQueue(label: "Client queue")
///Indicates whether the client is logged in or not.
open var loggedIn = false
private var configuration: URLSessionConfiguration
private var delegateQueue: OperationQueue
///Errors which can happen while making a request
public enum RequestError: Error {
case invalidURL(url: String)
case notUTF8
case unknownError
case timeout
}
///Indicates the duration of a timeout
open var timeoutDuration: TimeInterval = 30
//MARK: - Private variables
private class HTTPTask {
var task: URLSessionTask
var completion: (Data?, HTTPURLResponse?, Error?) -> Void
var data: Data?
var response: HTTPURLResponse?
var error: Error?
init(task: URLSessionTask, completion: @escaping (Data?, HTTPURLResponse?, Error?) -> Void) {
self.task = task
self.completion = completion
}
}
private var tasks = [URLSessionTask:HTTPTask]()
private var responseSemaphore: DispatchSemaphore?
//MARK: - Cookie handling
private func processCookieDomain(domain: String) -> String {
return URL(string: domain)?.host ?? domain
}
///Prints all of the cookies, for debugging.
private func printCookies(_ cookies: [HTTPCookie]) {
print(cookies.map { "\($0.domain)::\($0.name)::\($0.value)" }.joined(separator: "\n") + "\n\n")
}
///Adds cookies.
///- parameter newCookies: The cookies to add.
///- parameter host: The host which set the cookies..
open func addCookies(_ newCookies: [HTTPCookie], forHost host: String) {
let toAdd = newCookies.map {cookie -> HTTPCookie in
var properties = cookie.properties ?? [:]
properties[HTTPCookiePropertyKey.domain] = processCookieDomain(domain: cookie.domain)
return HTTPCookie(properties: properties) ?? cookie
}
//print("Adding:")
//printCookies(newCookies)
for cookie in toAdd { //for each cookie to add...
if let index = cookies.index(where: {
$0.name == cookie.name && cookieHost(host, matchesDomain: $0.domain)
}) {
//if this cookie needs to be replaced, replace it
cookies[index] = cookie
} else {
cookies.append(cookie)
}
}
//print("Cookies:")
//printCookies(cookies)
}
///Checks whether a cookie matches a domain.
///- parameter host: The host of the cookie.
///- parameter domain: The domain.
open func cookieHost(_ host: String, matchesDomain domain: String) -> Bool {
let hostFields = host.components(separatedBy: ".")
var domainFields = domain.components(separatedBy: ".")
if hostFields.count == 0 || domainFields.count == 0 {
return false
}
if domainFields.first!.isEmpty {
domainFields.removeFirst()
}
//if the domain starts with a dot, match any host which is a subdomain of domain
var hostIndex = hostFields.count - 1
for i in (0...domainFields.count - 1).reversed() {
if hostIndex == 0 && i != 0 {
return false
}
if domainFields[i] != hostFields[hostIndex] {
return false
}
hostIndex -= 1
}
return true
}
///Returns the cookie headers for the specified URL.
open func cookieHeaders(forURL url: URL) -> [String:String] {
return HTTPCookie.requestHeaderFields(with: cookies.filter {
cookieHost(url.host ?? "", matchesDomain: $0.domain)
})
}
//MARK: - URLSession delegate methods
public func urlSession(
_ session: URLSession,
dataTask: URLSessionDataTask,
didReceive response: URLResponse,
completionHandler: @escaping (URLSession.ResponseDisposition) -> Void) {
guard let task = tasks[dataTask] else {
print("\(dataTask) is not in client task list; cancelling")
completionHandler(.cancel)
return
}
var headers = [String:String]()
for (k, v) in (response as? HTTPURLResponse)?.allHeaderFields ?? [:] {
headers[String(describing: k)] = String(describing: v)
}
let url = response.url ?? URL(fileURLWithPath: "<invalid>")
addCookies(HTTPCookie.cookies(withResponseHeaderFields: headers, for: url), forHost: url.host ?? "")
task.response = response as? HTTPURLResponse
completionHandler(.allow)
}
public func urlSession(_ session: URLSession, dataTask: URLSessionDataTask, didReceive data: Data) {
guard let task = tasks[dataTask] else {
print("\(dataTask) is not in client task list; ignoring")
return
}
if task.data != nil {
task.data!.append(data)
}
else {
task.data = data
}
}
public func urlSession(_ session: URLSession, task sessionTask: URLSessionTask, didCompleteWithError error: Error?) {
guard let task = tasks[sessionTask] else {
print("\(sessionTask) is not in client task list; ignoring")
return
}
task.error = error
task.completion(task.data, task.response, task.error)
tasks[sessionTask] = nil
}
public func urlSession(
_ session: URLSession,
task: URLSessionTask,
willPerformHTTPRedirection response: HTTPURLResponse,
newRequest request: URLRequest,
completionHandler: @escaping (URLRequest?) -> Void
) {
var headers = [String:String]()
for (k, v) in response.allHeaderFields {
headers[String(describing: k)] = String(describing: v)
}
let url = response.url ?? URL(fileURLWithPath: "invalid")
addCookies(HTTPCookie.cookies(withResponseHeaderFields: headers, for: url), forHost: url.host ?? "")
var request = request
let newURL = request.url ?? URL(fileURLWithPath: ("invalid"))
request.setValue(nil, forHTTPHeaderField: "Cookie")
for (key, val) in cookieHeaders(forURL: newURL) {
request.addValue(val, forHTTPHeaderField: key)
}
completionHandler(request)
}
private func performTask(_ task: URLSessionTask, completion: @escaping (Data?, HTTPURLResponse?, Error?) -> Void) {
tasks[task] = HTTPTask(task: task, completion: completion)
task.resume()
}
//MARK:- Request methods.
///Performs an `URLRequest`.
///- parameter request: The request to perform.
///- returns: The `Data` and `HTTPURLResponse` returned by the request.
open func performRequest(_ request: URLRequest) throws -> (Data, HTTPURLResponse) {
var req = request
let sema = DispatchSemaphore(value: 0)
var data: Data!
var resp: URLResponse!
var error: Error!
let url = req.url ?? URL(fileURLWithPath: ("invalid"))
for (key, val) in cookieHeaders(forURL: url) {
req.addValue(val, forHTTPHeaderField: key)
}
queue.async {
let task = self.session.dataTask(with: req)
self.performTask(task) {inData, inResp, inError in
(data, resp, error) = (inData, inResp, inError)
sema.signal()
}
}
if sema.wait(timeout: DispatchTime.now() + timeoutDuration) == .timedOut {
error = RequestError.timeout
}
guard let response = resp as? HTTPURLResponse, data != nil else {
throw error ?? RequestError.unknownError
}
return (data, response)
}
///Performs a GET request.
///- paramter url: The URL to make the request to.
///- returns: The `Data` and `HTTPURLResponse` returned by the request.
open func get(_ url: String) throws -> (Data, HTTPURLResponse) {
guard let nsUrl = URL(string: url) else {
throw RequestError.invalidURL(url: url)
}
var request = URLRequest(url: nsUrl)
request.setValue(String(request.httpBody?.count ?? 0), forHTTPHeaderField: "Content-Length")
return try performRequest(request)
}
///Performs a POST request.
///- parameter url: The URL to make the request to.
///- parameter data: The body of the POST request.
///- returns: The `Data` and `HTTPURLResponse` returned by the request.
open func post(_ url: String, data: Data, contentType: String? = nil) throws -> (Data, HTTPURLResponse) {
guard let nsUrl = URL(string: url) else {
throw RequestError.invalidURL(url: url)
}
let contentType = contentType ?? "application/x-www-form-urlencoded"
var request = URLRequest(url: nsUrl)
request.httpMethod = "POST"
request.httpBody = data
let url = request.url ?? URL(fileURLWithPath: ("invalid"))
for (key, val) in cookieHeaders(forURL: url) {
request.addValue(val, forHTTPHeaderField: key)
}
request.setValue(contentType, forHTTPHeaderField: "Content-Type")
return try performRequest(request)
}
///Performs a POST request.
///- parameter url: The URL to make the request to.
///- parameter data: The fields to include in the POST request.
///- returns: The `Data` and `HTTPURLResponse` returned by the request.
open func post(_ url: String, _ data: [String:String]) throws -> (Data, HTTPURLResponse) {
guard let data = String(urlParameters: data).data(using: String.Encoding.utf8) else {
throw RequestError.notUTF8
}
return try post(url, data: data)
}
///Performs an URLRequest.
///- parameter request: The request to perform.
///- returns: The UTF-8 string returned by the request.
open func performRequest(_ request: URLRequest) throws -> String {
let (data, _) = try performRequest(request)
guard let string = String(data: data, encoding: String.Encoding.utf8) else {
throw RequestError.notUTF8
}
return string
}
///Performs a GET request.
///- paramter url: The URL to make the request to.
///- returns: The UTF-8 string returned by the request.
open func get(_ url: String) throws -> String {
let (data, _) = try get(url)
guard let string = String(data: data, encoding: String.Encoding.utf8) else {
throw RequestError.notUTF8
}
return string
}
///Performs a POST request.
///- parameter url: The URL to make the request to.
///- parameter data: The fields to include in the POST request.
///- returns: The UTF-8 string returned by the request.
open func post(_ url: String, _ fields: [String:String]) throws -> String {
let (data, _) = try post(url, fields)
guard let string = String(data: data, encoding: String.Encoding.utf8) else {
throw RequestError.notUTF8
}
return string
}
///Performs a POST request.
///- parameter url: The URL to make the request to.
///- parameter data: The body of the POST request.
///- returns: The UTF-8 string returned by the request.
open func post(_ url: String, data: Data, contentType: String? = nil) throws -> String {
let (data, _) = try post(url, data: data, contentType: contentType)
guard let string = String(data: data, encoding: String.Encoding.utf8) else {
throw RequestError.notUTF8
}
return string
}
///Parses a JSON string.
open func parseJSON(_ json: String) throws -> Any {
return try JSONSerialization.jsonObject(with: json.data(using: String.Encoding.utf8)!, options: .allowFragments)
}
//MARK: - Initializers and login.
///Initializes a Client.
///- parameter host: The chat host to log in to.
override public init() {
let configuration = URLSessionConfiguration.default
configuration.httpCookieStorage = nil
self.configuration = configuration
let delegateQueue = OperationQueue()
delegateQueue.maxConcurrentOperationCount = 1
self.delegateQueue = delegateQueue
super.init()
/*configuration.connectionProxyDictionary = [
"HTTPEnable" : 1,
kCFNetworkProxiesHTTPProxy as AnyHashable : "192.168.1.234",
kCFNetworkProxiesHTTPPort as AnyHashable : 8080,
"HTTPSEnable" : 1,
kCFNetworkProxiesHTTPSProxy as AnyHashable : "192.168.1.234",
kCFNetworkProxiesHTTPSPort as AnyHashable : 8080
]*/
}
///Errors which can occur while logging in.
public enum LoginError: Error {
///Occurs when the client is already logged in.
case alreadyLoggedIn
///Occurs when the fkey required to log in is not found.
case fkeyNotFound
///Occurs when a login fails.
case loginFailed
}
///Logs in to Stack Exchange.
open func login(email: String, password: String) throws {
if loggedIn {
throw LoginError.alreadyLoggedIn
}
print("Logging in...")
for host: ChatRoom.Host in [.stackOverflow, .metaStackExchange] {
//Login to host.
let hostLoginURL = "https://\(host.domain)/users/login"
let hostLoginPage: String = try get(hostLoginURL)
guard let fkey = getHiddenInputs(hostLoginPage)["fkey"] else {
throw LoginError.fkeyNotFound
}
let (_, _) = try post(hostLoginURL, [
"email" : email,
"password" : password,
"fkey" : fkey
]
)
if !cookies.contains(where: { $0.name == "acct" && cookieHost(host.domain, matchesDomain: $0.domain) }) {
throw LoginError.loginFailed
}
}
}
fileprivate func getHiddenInputs(_ string: String) -> [String:String] {
var result = [String:String]()
let components = string.components(separatedBy: "<input type=\"hidden\"")
for input in components[1..<components.count] {
guard let nameStartIndex = input.range(of: "name=\"")?.upperBound else {
continue
}
let nameStart = String(input[nameStartIndex...])
guard let nameEndIndex = nameStart.range(of: "\"")?.lowerBound else {
continue
}
let name = String(nameStart[..<nameEndIndex])
guard let valueStartIndex = nameStart.range(of: "value=\"")?.upperBound else {
continue
}
let valueStart = String(nameStart[valueStartIndex...])
guard let valueEndIndex = valueStart.range(of: "\"")?.lowerBound else {
continue
}
let value = String(valueStart[..<valueEndIndex])
result[name] = value
}
return result
}
}
|
mit
|
94e9d5355c4ec276f2221154f3f95d4e
| 32.225621 | 121 | 0.577775 | 4.828286 | false | false | false | false |
lilongcnc/firefox-ios
|
Client/Application/AppDelegate.swift
|
3
|
13190
|
/* 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 Shared
import Storage
import AVFoundation
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
var browserViewController: BrowserViewController!
var rootViewController: UINavigationController!
weak var profile: BrowserProfile?
var tabManager: TabManager!
let appVersion = NSBundle.mainBundle().objectForInfoDictionaryKey("CFBundleShortVersionString") as! String
func application(application: UIApplication, willFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
// Set the Firefox UA for browsing.
setUserAgent()
// Start the keyboard helper to monitor and cache keyboard state.
KeyboardHelper.defaultHelper.startObserving()
let profile = getProfile(application)
// Set up a web server that serves us static content. Do this early so that it is ready when the UI is presented.
setUpWebServer(profile)
// for aural progress bar: play even with silent switch on, and do not stop audio from other apps (like music)
AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayback, withOptions: AVAudioSessionCategoryOptions.MixWithOthers, error: nil)
self.window = UIWindow(frame: UIScreen.mainScreen().bounds)
self.window!.backgroundColor = UIColor.whiteColor()
let defaultRequest = NSURLRequest(URL: UIConstants.AboutHomeURL)
self.tabManager = TabManager(defaultNewTabRequest: defaultRequest, profile: profile)
browserViewController = BrowserViewController(profile: profile, tabManager: self.tabManager)
// Add restoration class, the factory that will return the ViewController we
// will restore with.
browserViewController.restorationIdentifier = NSStringFromClass(BrowserViewController.self)
browserViewController.restorationClass = AppDelegate.self
browserViewController.automaticallyAdjustsScrollViewInsets = false
rootViewController = UINavigationController(rootViewController: browserViewController)
rootViewController.automaticallyAdjustsScrollViewInsets = false
rootViewController.delegate = self
rootViewController.navigationBarHidden = true
self.window!.rootViewController = rootViewController
self.window!.backgroundColor = UIConstants.AppBackgroundColor
activeCrashReporter = BreakpadCrashReporter(breakpadInstance: BreakpadController.sharedInstance())
configureActiveCrashReporter(profile.prefs.boolForKey("crashreports.send.always"))
NSNotificationCenter.defaultCenter().addObserverForName(FSReadingListAddReadingListItemNotification, object: nil, queue: nil) { (notification) -> Void in
if let userInfo = notification.userInfo, url = userInfo["URL"] as? NSURL, absoluteString = url.absoluteString {
let title = (userInfo["Title"] as? String) ?? ""
profile.readingList?.createRecordWithURL(absoluteString, title: title, addedBy: UIDevice.currentDevice().name)
}
}
// Force a database upgrade by requesting a non-existent password
profile.logins.getLoginsForProtectionSpace(NSURLProtectionSpace(host: "example.com", port: 0, `protocol`: nil, realm: nil, authenticationMethod: nil))
// check to see if we started cos someone tapped on a notification
if let localNotification = launchOptions?[UIApplicationLaunchOptionsLocalNotificationKey] as? UILocalNotification {
viewURLInNewTab(localNotification)
}
return true
}
/**
* We maintain a weak reference to the profile so that we can pause timed
* syncs when we're backgrounded.
*
* The long-lasting ref to the profile lives in BrowserViewController,
* which we set in application:willFinishLaunchingWithOptions:.
*
* If that ever disappears, we won't be able to grab the profile to stop
* syncing... but in that case the profile's deinit will take care of things.
*/
func getProfile(application: UIApplication) -> Profile {
if let profile = self.profile {
return profile
}
let p = BrowserProfile(localName: "profile", app: application)
self.profile = p
return p
}
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject : AnyObject]?) -> Bool {
self.window!.makeKeyAndVisible()
return true
}
func application(application: UIApplication, openURL url: NSURL, sourceApplication: String?, annotation: AnyObject?) -> Bool {
if let components = NSURLComponents(URL: url, resolvingAgainstBaseURL: false) {
if components.scheme != "firefox" && components.scheme != "firefox-x-callback" {
return false
}
var url: String?
var appName: String?
var callbackScheme: String?
for item in components.queryItems as? [NSURLQueryItem] ?? [] {
switch item.name {
case "url":
url = item.value
case "x-source":
callbackScheme = item.value
case "x-source-name":
appName = item.value
default: ()
}
}
if let url = url,
newURL = NSURL(string: url.unescape()) {
self.browserViewController.openURLInNewTab(newURL)
return true
}
}
return false
}
// We sync in the foreground only, to avoid the possibility of runaway resource usage.
// Eventually we'll sync in response to notifications.
func applicationDidBecomeActive(application: UIApplication) {
self.profile?.syncManager.beginTimedSyncs()
// We could load these here, but then we have to futz with the tab counter
// and making NSURLRequests.
self.browserViewController.loadQueuedTabs()
}
func applicationDidEnterBackground(application: UIApplication) {
self.profile?.syncManager.endTimedSyncs()
let taskId = application.beginBackgroundTaskWithExpirationHandler { _ in }
self.profile?.shutdown()
application.endBackgroundTask(taskId)
}
private func setUpWebServer(profile: Profile) {
let server = WebServer.sharedInstance
ReaderModeHandlers.register(server, profile: profile)
ErrorPageHelper.register(server)
AboutHomeHandler.register(server)
AboutLicenseHandler.register(server)
SessionRestoreHandler.register(server)
server.start()
}
private func setUserAgent() {
let currentiOSVersion = UIDevice.currentDevice().systemVersion
let lastiOSVersion = NSUserDefaults.standardUserDefaults().stringForKey("LastDeviceSystemVersionNumber")
var firefoxUA = NSUserDefaults.standardUserDefaults().stringForKey("UserAgent")
if firefoxUA == nil
|| lastiOSVersion != currentiOSVersion {
let webView = UIWebView()
NSUserDefaults.standardUserDefaults().setObject(currentiOSVersion,forKey: "LastDeviceSystemVersionNumber")
let userAgent = webView.stringByEvaluatingJavaScriptFromString("navigator.userAgent")!
// Extract the WebKit version and use it as the Safari version.
let webKitVersionRegex = NSRegularExpression(pattern: "AppleWebKit/([^ ]+) ", options: nil, error: nil)!
let match = webKitVersionRegex.firstMatchInString(userAgent, options: nil, range: NSRange(location: 0, length: count(userAgent)))
if match == nil {
println("Error: Unable to determine WebKit version")
return
}
let webKitVersion = (userAgent as NSString).substringWithRange(match!.rangeAtIndex(1))
// Insert "FxiOS/<version>" before the Mobile/ section.
let mobileRange = (userAgent as NSString).rangeOfString("Mobile/")
if mobileRange.location == NSNotFound {
println("Error: Unable to find Mobile section")
return
}
let mutableUA = NSMutableString(string: userAgent)
mutableUA.insertString("FxiOS/\(appVersion) ", atIndex: mobileRange.location)
firefoxUA = "\(mutableUA) Safari/\(webKitVersion)"
NSUserDefaults.standardUserDefaults().setObject(firefoxUA, forKey: "UserAgent")
}
FaviconFetcher.userAgent = firefoxUA!
NSUserDefaults.standardUserDefaults().registerDefaults(["UserAgent": firefoxUA!])
SDWebImageDownloader.sharedDownloader().setValue(firefoxUA, forHTTPHeaderField: "User-Agent")
}
func application(application: UIApplication, handleActionWithIdentifier identifier: String?, forLocalNotification notification: UILocalNotification, completionHandler: () -> Void) {
if let actionId = identifier {
if let action = SentTabAction(rawValue: actionId) {
viewURLInNewTab(notification)
switch(action) {
case .Bookmark:
addBookmark(notification)
break
case .ReadingList:
addToReadingList(notification)
break
default:
break
}
} else {
println("ERROR: Unknown notification action received")
}
} else {
println("ERROR: Unknown notification received")
}
}
func application(application: UIApplication, didReceiveLocalNotification notification: UILocalNotification) {
viewURLInNewTab(notification)
}
private func viewURLInNewTab(notification: UILocalNotification) {
if let alertURL = notification.userInfo?[TabSendURLKey] as? String {
if let urlToOpen = NSURL(string: alertURL) {
browserViewController.openURLInNewTab(urlToOpen)
}
}
}
private func addBookmark(notification: UILocalNotification) {
if let alertURL = notification.userInfo?[TabSendURLKey] as? String,
let title = notification.userInfo?[TabSendTitleKey] as? String {
browserViewController.addBookmark(alertURL, title: title)
}
}
private func addToReadingList(notification: UILocalNotification) {
if let alertURL = notification.userInfo?[TabSendURLKey] as? String,
let title = notification.userInfo?[TabSendTitleKey] as? String {
if let urlToOpen = NSURL(string: alertURL) {
NSNotificationCenter.defaultCenter().postNotificationName(FSReadingListAddReadingListItemNotification, object: self, userInfo: ["URL": urlToOpen, "Title": title])
}
}
}
}
// MARK: - Root View Controller Animations
extension AppDelegate: UINavigationControllerDelegate {
func navigationController(navigationController: UINavigationController,
animationControllerForOperation operation: UINavigationControllerOperation,
fromViewController fromVC: UIViewController,
toViewController toVC: UIViewController) -> UIViewControllerAnimatedTransitioning? {
if operation == UINavigationControllerOperation.Push {
return BrowserToTrayAnimator()
} else if operation == UINavigationControllerOperation.Pop {
return TrayToBrowserAnimator()
} else {
return nil
}
}
}
var activeCrashReporter: CrashReporter?
func configureActiveCrashReporter(optedIn: Bool?) {
if let reporter = activeCrashReporter {
configureCrashReporter(reporter, optedIn: optedIn)
}
}
public func configureCrashReporter(reporter: CrashReporter, #optedIn: Bool?) {
let configureReporter: () -> () = {
let addUploadParameterForKey: String -> Void = { key in
if let value = NSBundle.mainBundle().objectForInfoDictionaryKey(key) as? String {
reporter.addUploadParameter(value, forKey: key)
}
}
addUploadParameterForKey("AppID")
addUploadParameterForKey("BuildID")
addUploadParameterForKey("ReleaseChannel")
addUploadParameterForKey("Vendor")
}
if let optedIn = optedIn {
// User has explicitly opted-in for sending crash reports. If this is not true, then the user has
// explicitly opted-out of crash reporting so don't bother starting breakpad or stop if it was running
if optedIn {
reporter.start(true)
configureReporter()
reporter.setUploadingEnabled(true)
} else {
reporter.stop()
}
}
// We haven't asked the user for their crash reporting preference yet. Log crashes anyways but don't send them.
else {
reporter.start(true)
configureReporter()
}
}
|
mpl-2.0
|
1a9da11ea8c7eecf7bd9edde0f832670
| 43.560811 | 185 | 0.667551 | 5.859618 | false | false | false | false |
diwip/inspector-ios
|
Inspector/Extensions/ThriftUtilsGeneric.swift
|
1
|
922
|
//
// ThriftUtilsGeneric.swift
// Inspector
//
// Created by Zaky German on 6/14/15.
// Copyright (c) 2015 diwip. All rights reserved.
//
import Foundation
class ThriftUtils {
class func thriftObject<T where T:NSObject, T:TBase>(fromData:NSData) -> T {
let transport = TMemoryBuffer(data:fromData)
let proto = TBinaryProtocolFactory.sharedFactory().newProtocolOnTransport(transport)
let aClass: AnyClass = T.classForCoder() //or .self
let tClass = aClass as! NSObject.Type
let tInst = tClass.init() as! T
tInst.read(proto)
return tInst
}
class func dataFromThriftObject(object: TBase) -> NSData {
let transport = TMemoryBuffer()
let proto = TBinaryProtocolFactory.sharedFactory().newProtocolOnTransport(transport)
object.write(proto)
return transport.getBuffer()
}
}
|
mit
|
8c4cc7ee6ccfc82ff8a510446dcdd96f
| 26.969697 | 92 | 0.640998 | 4.116071 | false | false | false | false |
SmartThingsOSS/tigon.swift
|
Tigon/TigonExecutor.swift
|
1
|
4178
|
//
// TigonExecutor.swift
// Tigon
//
// Created by Steven Vlaminck on 4/4/16.
// Copyright © 2016 SmartThings. All rights reserved.
//
import Foundation
import WebKit
/**
TigonExecuter provides a simple interface for interacting with Javascript. It assumes Tigon.js is included in the HTML.
TigonExecutor has default implementations for WKWebView.
There is no need to implement this protocol unless you want custom behavior.
- seealso:
[tigon-js](https://github.com/SmartThingsOSS/tigon-js)
*/
public protocol TigonExecutor {
/**
A way to respond to a message with an error.
- parameters:
- id: The id of the original message
- error: The error to pass back to the sender of the original message
*/
func sendErrorResponse(_ id: String, error: NSError)
/**
A way to respond to a message with a success object.
- parameters:
- id: The id of the original message
- response: The success object to pass back to the sender of the original message
*/
func sendSuccessResponse(_ id: String, response: AnyObject)
/**
A way to send a message to javascript.
- parameters:
- message: The message to send. This can be a stringified object.
*/
func sendMessage(_ message: String)
/**
A way to stringify objects in a way that is standard to Tigon
- parameters:
- object: The object to stringify
This is called by `sendSuccessResponse` and `sendErrorResponse` before sending the message response.
*/
func stringifyResponse(_ object: AnyObject) -> String
/**
A simplified wrapper for `evaluateJavaScript`
- paramters:
- script: The script to be executed
*/
func executeJavascript(_ script: String)
}
extension WKWebView: TigonExecutor {
open func sendErrorResponse(_ id: String, error: NSError) {
let responseString = stringifyResponse(error)
let script = "tigon.receivedErrorResponse('\(id)', \(responseString))"
executeJavascript(script)
}
open func sendSuccessResponse(_ id: String, response: AnyObject) {
let responseString = stringifyResponse(response)
let script = "tigon.receivedSuccessResponse('\(id)', \(responseString))"
executeJavascript(script)
}
public func sendMessage(_ message: String) {
executeJavascript("tigon.receivedMessage(\(message))")
}
public func stringifyResponse(_ object: AnyObject) -> String {
var responseString = "{}"
do {
switch object {
case let dictionary as [AnyHashable: Any]:
let json = try JSONSerialization.data(withJSONObject: dictionary, options: .prettyPrinted)
if let encodedString = String(data: json, encoding: String.Encoding.utf8) {
responseString = encodedString
}
case let array as [AnyObject]:
let json = try JSONSerialization.data(withJSONObject: array, options: .prettyPrinted)
if let encodedString = String(data: json, encoding: String.Encoding.utf8) {
responseString = encodedString
}
case let string as String:
responseString = "{\n \"response\" : \"\(string)\"\n}"
case let error as NSError:
responseString = "{\n \"error\" : \"\(error.localizedDescription)\"\n}"
case let b as Bool:
responseString = "{\n \"response\" : \(b)\n}"
default:
print("Failed to match a condition for response object \(object)")
}
} catch {
print("Failed to stringify response object: \(object)")
}
return responseString
}
public func executeJavascript(_ script: String) {
evaluateJavaScript(script) { (_, error) -> Void in
if let error = error {
print("Tigon failed to evaluate javascript: \(script); error: \(error.localizedDescription)")
}
}
}
}
|
apache-2.0
|
c7e5035432acc1b571de6841e1ed6fee
| 32.150794 | 120 | 0.606655 | 4.914118 | false | false | false | false |
cohix/MaterialKit
|
Source/CapturePreview.swift
|
3
|
8408
|
//
// Copyright (C) 2015 GraphKit, Inc. <http://graphkit.io> and other GraphKit contributors.
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero 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 Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program located at the root of the software package
// in a file called LICENSE. If not, see <http://www.gnu.org/licenses/>.
//
import UIKit
import AVFoundation
@objc(PreviewDelegate)
public protocol PreviewDelegate {
optional func previewTappedToFocusAt(preview: Preview, point: CGPoint)
optional func previewTappedToExposeAt(preview: Preview, point: CGPoint)
optional func previewTappedToReset(preview: Preview, focus: UIView, exposure: UIView)
}
public class Preview: UIView {
/**
:name: boxBounds
:description: A static property that sets the initial size of the focusBox and exposureBox properties.
*/
static public var boxBounds: CGRect = CGRectMake(0, 0, 150, 150)
/**
:name: delegate
:description: An optional instance of PreviewDelegate to handle events that are triggered during various
stages of engagement.
*/
public weak var delegate: PreviewDelegate?
/**
:name: tapToFocusEnabled
:description: A mutator and accessor that enables and disables tap to focus gesture.
*/
public var tapToFocusEnabled: Bool {
get {
return singleTapRecognizer!.enabled
}
set(value) {
singleTapRecognizer!.enabled = value
}
}
/**
:name: tapToExposeEnabled
:description: A mutator and accessor that enables and disables tap to expose gesture.
*/
public var tapToExposeEnabled: Bool {
get {
return doubleTapRecognizer!.enabled
}
set(value) {
doubleTapRecognizer!.enabled = value
}
}
//
// override for layerClass
//
override public class func layerClass() -> AnyClass {
return AVCaptureVideoPreviewLayer.self
}
/**
:name: session
:description: A mutator and accessor for the preview AVCaptureSession value.
*/
public var session: AVCaptureSession {
get {
return (layer as! AVCaptureVideoPreviewLayer).session
}
set(value) {
(layer as! AVCaptureVideoPreviewLayer).session = value
}
}
/**
:name: focusBox
:description: An optional UIView for the focusBox animation. This is used when the
tapToFocusEnabled property is set to true.
*/
public var focusBox: UIView?
/**
:name: exposureBox
:description: An optional UIView for the exposureBox animation. This is used when the
tapToExposeEnabled property is set to true.
*/
public var exposureBox: UIView?
//
// :name: singleTapRecognizer
// :description: Gesture recognizer for single tap.
//
private var singleTapRecognizer: UITapGestureRecognizer?
//
// :name: doubleTapRecognizer
// :description: Gesture recognizer for double tap.
//
private var doubleTapRecognizer: UITapGestureRecognizer?
//
// :name: doubleDoubleTapRecognizer
// :description: Gesture recognizer for double/double tap.
//
private var doubleDoubleTapRecognizer: UITapGestureRecognizer?
required public init(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
prepareView()
}
public override init(frame: CGRect) {
super.init(frame: frame)
prepareView()
}
public init() {
super.init(frame: CGRectZero)
setTranslatesAutoresizingMaskIntoConstraints(false)
prepareView()
}
//
// :name: handleSingleTap
//
internal func handleSingleTap(recognizer: UIGestureRecognizer) {
let point: CGPoint = recognizer.locationInView(self)
runBoxAnimationOnView(focusBox, point: point)
delegate?.previewTappedToFocusAt?(self, point: captureDevicePointForPoint(point))
}
//
// :name: handleDoubleTap
//
internal func handleDoubleTap(recognizer: UIGestureRecognizer) {
let point: CGPoint = recognizer.locationInView(self)
runBoxAnimationOnView(exposureBox, point: point)
delegate?.previewTappedToExposeAt?(self, point: captureDevicePointForPoint(point))
}
//
// :name: handleDoubleDoubleTap
//
internal func handleDoubleDoubleTap(recognizer: UIGestureRecognizer) {
runResetAnimation()
}
//
// :name: prepareView
// :description: Common setup for view.
//
private func prepareView() {
let captureLayer: AVCaptureVideoPreviewLayer = layer as! AVCaptureVideoPreviewLayer
captureLayer.videoGravity = AVLayerVideoGravityResizeAspectFill
singleTapRecognizer = UITapGestureRecognizer(target: self, action: "handleSingleTap:")
singleTapRecognizer!.numberOfTapsRequired = 1
doubleTapRecognizer = UITapGestureRecognizer(target: self, action: "handleDoubleTap:")
doubleTapRecognizer!.numberOfTapsRequired = 2
doubleDoubleTapRecognizer = UITapGestureRecognizer(target: self, action: "handleDoubleDoubleTap:")
doubleDoubleTapRecognizer!.numberOfTapsRequired = 2
doubleDoubleTapRecognizer!.numberOfTouchesRequired = 2
addGestureRecognizer(singleTapRecognizer!)
addGestureRecognizer(doubleTapRecognizer!)
addGestureRecognizer(doubleDoubleTapRecognizer!)
singleTapRecognizer!.requireGestureRecognizerToFail(doubleTapRecognizer!)
focusBox = viewWithColor(.redColor())
exposureBox = viewWithColor(.blueColor())
addSubview(focusBox!)
addSubview(exposureBox!)
}
//
// :name: viewWithColor
// :description: Initializes a UIView with a set UIColor.
//
private func viewWithColor(color: UIColor) -> UIView {
let view: UIView = UIView(frame: Preview.boxBounds)
view.backgroundColor = MaterialTheme.clear.color
view.layer.borderColor = color.CGColor
view.layer.borderWidth = 5
view.hidden = true
return view
}
//
// :name: runBoxAnimationOnView
// :description: Runs the animation used for focusBox and exposureBox on single and double
// taps respectively at a given point.
//
private func runBoxAnimationOnView(view: UIView!, point: CGPoint) {
view.center = point
view.hidden = false
UIView.animateWithDuration(0.15, delay: 0, options: .CurveEaseInOut, animations: { _ in
view.layer.transform = CATransform3DMakeScale(0.5, 0.5, 1)
}) { _ in
let delayInSeconds: Double = 0.5
let popTime: dispatch_time_t = dispatch_time(DISPATCH_TIME_NOW, Int64(delayInSeconds * Double(NSEC_PER_SEC)))
dispatch_after(popTime, dispatch_get_main_queue()) {
view.hidden = true
view.transform = CGAffineTransformIdentity
}
}
}
//
// :name: captureDevicePointForPoint
// :description: Interprets the correct point from touch to preview layer.
//
private func captureDevicePointForPoint(point: CGPoint) -> CGPoint {
let previewLayer: AVCaptureVideoPreviewLayer = layer as! AVCaptureVideoPreviewLayer
return previewLayer.captureDevicePointOfInterestForPoint(point)
}
//
// :name: runResetAnimation
// :description: Executes the reset animation for focus and exposure.
//
private func runResetAnimation() {
if !tapToFocusEnabled && !tapToExposeEnabled {
return
}
let previewLayer: AVCaptureVideoPreviewLayer = layer as! AVCaptureVideoPreviewLayer
let centerPoint: CGPoint = previewLayer.pointForCaptureDevicePointOfInterest(CGPointMake(0.5, 0.5))
focusBox!.center = centerPoint
exposureBox!.center = centerPoint
exposureBox!.transform = CGAffineTransformMakeScale(1.2, 1.2)
focusBox!.hidden = false
exposureBox!.hidden = false
UIView.animateWithDuration(0.15, delay: 0, options: .CurveEaseInOut, animations: { _ in
self.focusBox!.layer.transform = CATransform3DMakeScale(0.5, 0.5, 1)
self.exposureBox!.layer.transform = CATransform3DMakeScale(0.7, 0.7, 1)
}) { _ in
let delayInSeconds: Double = 0.5
let popTime: dispatch_time_t = dispatch_time(DISPATCH_TIME_NOW, Int64(delayInSeconds * Double(NSEC_PER_SEC)))
dispatch_after(popTime, dispatch_get_main_queue()) {
self.focusBox!.hidden = true
self.exposureBox!.hidden = true
self.focusBox!.transform = CGAffineTransformIdentity
self.exposureBox!.transform = CGAffineTransformIdentity
self.delegate?.previewTappedToReset?(self, focus: self.focusBox!, exposure: self.exposureBox!)
}
}
}
}
|
agpl-3.0
|
d945d34b31ac73a7181b16d403dd3269
| 30.728302 | 112 | 0.750119 | 3.932647 | false | false | false | false |
mownier/photostream
|
Photostream/Modules/Liked Post/Interactor/LikedPostData.swift
|
1
|
1028
|
//
// LikedPostData.swift
// Photostream
//
// Created by Mounir Ybanez on 19/01/2017.
// Copyright © 2017 Mounir Ybanez. All rights reserved.
//
protocol LikedPostData {
var id: String { set get }
var message: String { set get }
var timestamp: Double { set get }
var photoUrl: String { set get }
var photoWidth: Int { set get }
var photoHeight: Int { set get }
var likes: Int { set get }
var comments: Int { set get }
var isLiked: Bool { set get }
var userId: String { set get }
var avatarUrl: String { set get }
var displayName: String { set get }
}
struct LikedPostDataItem: LikedPostData {
var id: String = ""
var message: String = ""
var timestamp: Double = 0
var photoUrl: String = ""
var photoWidth: Int = 0
var photoHeight: Int = 0
var likes: Int = 0
var comments: Int = 0
var isLiked: Bool = false
var userId: String = ""
var avatarUrl: String = ""
var displayName: String = ""
}
|
mit
|
8cebd27093a6881b9ec0561a05d54931
| 21.822222 | 56 | 0.598832 | 3.875472 | false | false | false | false |
m-alani/contests
|
hackerrank/MagicSquareForming.swift
|
1
|
1517
|
//
// MagicSquareForming.swift
//
// Practice solution - Marwan Alani - 2017
//
// Check the problem (and run the code) on HackerRank @ https://www.hackerrank.com/challenges/magic-square-forming
// Note: make sure that you select "Swift" from the top-right language menu of the code editor when testing this code
//
import Foundation
// Read the input
var input = [[Int]]()
input.append(String(readLine()!)!.components(separatedBy: " ").map({Int($0)!}))
input.append(String(readLine()!)!.components(separatedBy: " ").map({Int($0)!}))
input.append(String(readLine()!)!.components(separatedBy: " ").map({Int($0)!}))
// Helper function to find the cost of converting a matrix to another
func costToConvert(matrix mat1: [[Int]], into mat2: [[Int]]) -> Int {
var cost = 0
for row in 0...2 {
for column in 0...2 {
cost += abs(mat1[row][column] - mat2[row][column])
}
}
return cost
}
// Helper array of all possible 3x3 magic matrices
let magic3x3 = [
[[8, 1, 6], [3, 5, 7], [4, 9, 2]],
[[6, 1, 8], [7, 5, 3], [2, 9, 4]],
[[8, 3, 4], [1, 5, 9], [6, 7, 2]],
[[4, 3, 8], [9, 5, 1], [2, 7, 6]],
[[6, 7, 2], [1, 5, 9], [8, 3, 4]],
[[2, 7, 6], [9, 5, 1], [4, 3, 8]],
[[4, 9, 2], [3, 5, 7], [8, 1, 6]],
[[2, 9, 4], [7, 5, 3], [6, 1, 8]]
]
// Find the minimum cost
var output = 55
for matrix in magic3x3 {
let cost = costToConvert(matrix: input, into: matrix)
output = (cost < output) ? cost : output
}
// Print the output
print(output)
|
mit
|
48f0e30aa8c55c696bd032aec81836e5
| 29.959184 | 118 | 0.572182 | 2.911708 | false | false | false | false |
benlangmuir/swift
|
test/Demangle/clang-function-types.swift
|
14
|
1501
|
// NOTE: manglings.txt should be kept in sync with the manglings in this file.
// Make sure we are testing the right manglings.
// RUN: %target-swift-frontend(mock-sdk: %clang-importer-sdk) %s -emit-sil -o - -I %S/../Inputs/custom-modules -use-clang-function-types -module-name tmp -enable-objc-interop | %FileCheck %s --check-prefix=CHECK --check-prefix=CHECK-%target-os-%target-cpu
// Check that demangling works.
// %t.input: "A ---> B" ==> "A"
// RUN: sed -ne '/--->/s/ *--->.*$//p' < %S/Inputs/manglings-with-clang-types.txt > %t.input
// %t.check: "A ---> B" ==> "B"
// RUN: sed -ne '/--->/s/^.*---> *//p' < %S/Inputs/manglings-with-clang-types.txt > %t.check
// RUN: swift-demangle -classify < %t.input > %t.output
// RUN: diff %t.check %t.output
// Other tests already check mangling for Windows, so we don't need to
// check that here again.
// UNSUPPORTED: OS=windows-msvc
// UNSUPPORTED: OS=linux-android, OS=linux-androideabi
import ctypes
#if os(macOS) && arch(x86_64)
import ObjectiveC
// BOOL == signed char on x86_64 macOS
public func h(_ k: @convention(block, cType: "void (^)(BOOL)") (Bool) -> ()) {
let _ = k(true)
}
h(A.setGlobal) // OK: check that importing preserves Clang types
// CHECK-macosx-x86_64: sil @$s3tmp1hyyySbXzB24_ZTSU13block_pointerFvaEF
#endif
public func f(_ k: @convention(c, cType: "size_t (*)(void)") () -> Int) {
let _ = k()
}
f(ctypes.returns_size_t) // OK: check that importing preserves Clang type
// CHECK: sil @$s3tmp1fyySiyXzC9_ZTSPFmvEF
|
apache-2.0
|
7780fc114786e2cc34fc8cf1fcffe0bd
| 36.525 | 255 | 0.65956 | 2.832075 | false | false | false | false |
josefdolezal/fit-cvut
|
BI-IOS/practice-3/first-app/cv3/ViewController.swift
|
1
|
1450
|
//
// ViewController.swift
// cv3
//
// Created by Josef Dolezal on 20/10/15.
// Copyright © 2015 Josef Dolezal. All rights reserved.
//
import UIKit
class ViewController: UIViewController, UIWebViewDelegate, UIScrollViewDelegate {
@IBOutlet weak var webView: UIWebView!
override func viewDidLoad() {
super.viewDidLoad()
// sitove requesty by mely pouzivat ssl, musi se upravit v plist
let url = NSURL(string: "http://apple.com")
webView.loadRequest(NSURLRequest(URL: url!))
webView.delegate = self
webView.scrollView.delegate = self
webView.hidden = true
let view = UIView(frame: CGRect(x: 30, y: 48, width: 200, height: 200))
view.backgroundColor = UIColor.greenColor()
view.alpha = 0.5
view.layer.cornerRadius = 10
view.layer.borderColor = UIColor.blackColor().CGColor
view.layer.borderWidth = 3
self.view.addSubview(view)
}
func webViewDidFinishLoad(webView: UIWebView) {
print(webView.frame)
print(webView.bounds)
}
func scrollViewDidScroll(scrollView: UIScrollView) {
print(webView.frame)
print(webView.bounds)
print("------------")
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
|
mit
|
1eb4218c94b6fc802c2d1c23ccefe438
| 25.345455 | 81 | 0.615597 | 4.644231 | false | false | false | false |
calebkleveter/Mist
|
Sources/App/Controllers/DashboardController+Mist.swift
|
1
|
2828
|
import Vapor
import AdminPanel
import Routing
import HTTP
import VaporPostgreSQL
import Flash
import BCrypt
import Foundation
class MistDashboardController {
func createNewPage(_ request: Request)throws -> ResponseRepresentable {
guard let pageName = request.data["page-name"]?.string,
let pageContent = request.data["page-content"]?.string else {
throw Abort.badRequest
}
var newPage = BlogPage(title: pageName, content: pageContent)
do {
try newPage.save()
} catch let error {
return Response(redirect: "/admin/dashboard/new-page").flash(.error, "An error occured while saving the page: \(error)")
}
return Response(redirect: "/admin/dashboard/new-page").flash(.success, "Page succesfully created!")
}
func createNewPost(_ request: Request)throws -> ResponseRepresentable {
guard let posteName = request.data["post-name"]?.string,
let postContent = request.data["post-content"]?.string else {
throw Abort.badRequest
}
var newPost = Post(content: postContent, name: posteName)
do {
try newPost.save()
} catch let error {
return Response(redirect: "/admin/dashboard/new-post").flash(.error, "An error occured while saving the blog post: \(error)")
}
return Response(redirect: "/admin/dashboard/new-post").flash(.success, "Post succesfully created!")
}
func createNewAdmin(_ request: Request)throws -> ResponseRepresentable {
guard let email = request.data["email"]?.string,
let password = request.data["password"]?.string,
let name = request.data["name"]?.string else {
throw Abort.badRequest
}
var admin = try BackendUser(node: [
"name": name,
"email": email,
"password": BCrypt.digest(password: password),
"role": "admin",
"updated_at": Date().toDateTimeString(),
"created_at": Date().toDateTimeString()
])
do {
try admin.save()
} catch let error {
return Response(redirect: "/admin/dashboard/settings").flash(.error, "Admin creation failed with error: \(error)")
}
return Response(redirect: "/admin/dashboard/settings").flash(.success, "Admin created!")
}
}
extension MistDashboardController: AdminPanelController {
func addRoutes(to group: RouteGroup<Droplet.Value, (RouteGroup<Droplet.Value, Droplet>)>) {
group.post("new-page", handler: createNewPage)
group.post("new-post", handler: createNewPost)
group.post("new-admin", handler: createNewAdmin)
}
}
|
mit
|
cdfd5b98715f2a930eb8e73789c36d69
| 35.25641 | 137 | 0.602192 | 4.768971 | false | false | false | false |
akofman/cordova-plugin-dbmeter
|
plugin/src/ios/DBMeter.swift
|
1
|
5750
|
import Foundation
import AVFoundation
@objc(DBMeter) class DBMeter : CDVPlugin {
private let LOG_TAG = "DBMeter"
private let REQ_CODE = 0
private var isListening: Bool = false
private var audioRecorder: AVAudioRecorder!
private var command: CDVInvokedUrlCommand!
private var timer: DispatchSourceTimer!
private var isTimerExists: Bool = false
/**
This plugin provides the decibel level from the microphone.
*/
init(commandDelegate: CDVCommandDelegate) {
super.init()
self.commandDelegate = commandDelegate
}
/**
Permits to free the memory from the audioRecord instance
*/
@objc(destroy:)
func destroy(command: CDVInvokedUrlCommand) {
if (self.isListening) {
self.timer.suspend()
self.isListening = false
}
self.command = nil
if (self.audioRecorder != nil) {
self.audioRecorder.stop()
self.audioRecorder = nil
let pluginResult = CDVPluginResult(status: CDVCommandStatus_OK)
self.commandDelegate!.send(pluginResult, callbackId: command.callbackId)
} else {
self.sendPluginError(callbackId: command.callbackId, errorCode: PluginError.DBMETER_NOT_INITIALIZED, errorMessage: "DBMeter is not initialized")
}
}
/**
Starts listening the audio signal and sends dB values as a
CDVPluginResult keeping the same calback alive.
*/
@objc(start:)
func start(command: CDVInvokedUrlCommand) {
self.commandDelegate!.run(inBackground:{
self.command = command
if (!self.isTimerExists) {
self.timer = DispatchSource.makeTimerSource(queue: DispatchQueue.main)
self.timer.scheduleRepeating(deadline: .now(), interval: DispatchTimeInterval.milliseconds(300))
self.timer.setEventHandler(handler: self.timerCallBack)
self.isTimerExists = true
}
if (self.audioRecorder == nil) {
let url: URL = URL.init(fileURLWithPath: "/dev/null")
let settings : [String:Any] = [
AVFormatIDKey: Int(kAudioFormatAppleLossless),
AVSampleRateKey: 44100.0,
AVNumberOfChannelsKey: 1 as NSNumber,
AVEncoderAudioQualityKey: AVAudioQuality.high.rawValue
]
do {
let audioSession: AVAudioSession = AVAudioSession.sharedInstance()
try audioSession.setCategory(AVAudioSessionCategoryPlayAndRecord)
try audioSession.setActive(true)
self.audioRecorder = try AVAudioRecorder(url: url, settings: settings)
self.audioRecorder.isMeteringEnabled = true
} catch {
self.sendPluginError(callbackId: command.callbackId, errorCode: PluginError.DBMETER_NOT_INITIALIZED, errorMessage: "Error while initializing DBMeter")
}
}
if (!self.isListening) {
self.isListening = true
self.audioRecorder.record()
self.timer.resume()
}
})
}
/**
Stops listening the audio signal.
Even if stopped, the AVAudioRecorder instance still exist.
To destroy this instance, please use the destroy method.
*/
@objc(stop:)
public func stop(command: CDVInvokedUrlCommand) {
self.commandDelegate!.run(inBackground: {
if (self.isListening) {
self.isListening = false
if (self.audioRecorder != nil && self.audioRecorder.isRecording) {
self.timer.suspend()
self.audioRecorder.stop()
}
let pluginResult = CDVPluginResult(status: CDVCommandStatus_OK)
self.commandDelegate!.send(pluginResult, callbackId: command.callbackId)
} else {
self.sendPluginError(callbackId: command.callbackId, errorCode: PluginError.DBMETER_NOT_LISTENING, errorMessage: "DBMeter is not listening")
}
})
}
/**
Returns whether the DBMeter is listening.
*/
@objc(isListening:)
func isListening(command: CDVInvokedUrlCommand?) -> Bool {
if (command != nil) {
let pluginResult = CDVPluginResult(status: CDVCommandStatus_OK, messageAs: self.isListening)
self.commandDelegate!.send(pluginResult, callbackId: command!.callbackId)
}
return self.isListening;
}
private func timerCallBack() {
autoreleasepool {
if (self.isListening && self.audioRecorder != nil) {
self.audioRecorder.updateMeters()
let peakPowerForChannel = pow(10, (self.audioRecorder.averagePower(forChannel: 0) / 20))
let db = Int32(round(20 * log10(peakPowerForChannel) + 90))
let pluginResult = CDVPluginResult(status: CDVCommandStatus_OK, messageAs: db)
pluginResult!.setKeepCallbackAs(true)
self.commandDelegate!.send(pluginResult, callbackId: self.command.callbackId)
}
}
}
/**
Convenient method to send plugin errors.
*/
private func sendPluginError(callbackId: String, errorCode: PluginError, errorMessage: String) {
let pluginResult = CDVPluginResult(status: CDVCommandStatus_ERROR, messageAs: ["code": errorCode.hashValue, "message": errorMessage])
self.commandDelegate!.send(pluginResult, callbackId: callbackId)
}
enum PluginError: String {
case DBMETER_NOT_INITIALIZED = "0"
case DBMETER_NOT_LISTENING = "1"
}
}
|
apache-2.0
|
c358ec9b7d20d78a8867b1c151c1e699
| 36.096774 | 170 | 0.613913 | 5.284926 | false | false | false | false |
lixiangzhou/ZZLib
|
Source/ZZExtension/ZZUIExtension/UIImage+ZZExtension.swift
|
1
|
4676
|
//
// UIImage+ZZExtension.swift
// ZZLib
//
// Created by lixiangzhou on 2017/3/10.
// Copyright © 2017年 lixiangzhou. All rights reserved.
//
import UIKit
/// 用于缓存圆形边框
private var cacheImageBg = [String: UIImage]()
public extension UIImage {
/// 截取图片的一部分
///
/// - parameter inRect: 指定截取图片的区域
///
/// - returns: 截取的图片
func zz_crop(inRect rect: CGRect) -> UIImage? {
let scale = UIScreen.zz_scale
let dotRect = CGRect(x: rect.zz_x * scale, y: rect.zz_y * scale, width: rect.width * scale, height: rect.height * scale)
guard let cgimg = cgImage?.cropping(to: dotRect) else {
return nil
}
return UIImage(cgImage: cgimg, scale: scale, orientation: .up)
}
/// 根据颜色生成指定大小的方图
///
/// - parameter color: 图片颜色
/// - parameter imageSize: 图片大小
///
/// - returns: 生成的图片
static func zz_image(withColor color: UIColor, imageSize: CGFloat = 0.5) -> UIImage {
UIGraphicsBeginImageContextWithOptions(CGSize(width: imageSize, height: imageSize), false, 0.0)
color.setFill()
UIRectFill(CGRect(x: 0, y: 0, width: imageSize, height: imageSize))
let result = UIGraphicsGetImageFromCurrentImageContext()!
UIGraphicsEndImageContext()
return result
}
/// 异步回执图片,主线程返回图片
///
/// - parameter size: 图片的大小
/// - parameter isCircle: 是否圆形图
/// - parameter backColor: 图片的北京色
/// - parameter finished: 回调返回图片的闭包
func zz_asyncDrawImage(size: CGSize, isCircle: Bool = false, backColor: UIColor? = UIColor.white, finished: @escaping (_ image: UIImage) -> ()) {
DispatchQueue.global().async {
let key = "" + size.width.description + "_" + size.height.description + (backColor != nil ? backColor!.description : UIColor.clear.description)
var backImg = cacheImageBg[key]
let rect = CGRect(origin: CGPoint.zero, size: size)
if backImg == nil && isCircle {
backImg = UIImage.zz_clearCircleImage(inSize: size)
cacheImageBg[key] = backImg
}
UIGraphicsBeginImageContextWithOptions(size, backColor != nil, 0.0)
self.draw(in: rect)
backImg?.draw(in: rect)
let result = UIGraphicsGetImageFromCurrentImageContext()!
UIGraphicsEndImageContext()
DispatchQueue.main.async {
finished(result)
}
}
}
/// 根据指定大小和边部颜色生成一张中间是透明圆形的图片
///
/// - parameter size: 图片大小,根据该大小设置中间
/// - parameter backColor: 透明圆形与矩形四边之间的颜色
///
/// - returns: 中间是透明圆形的图片
class func zz_clearCircleImage(inSize size: CGSize, backColor: UIColor? = UIColor.white) -> UIImage {
UIGraphicsBeginImageContextWithOptions(size, false, 0.0)
let rect = CGRect(origin: CGPoint.zero, size: size)
if let backColor = backColor {
backColor.setFill()
UIRectFill(rect)
}
// 透明圆
let path = UIBezierPath(ovalIn: rect)
path.addClip()
UIColor.clear.setFill()
UIRectFill(rect)
let result = UIGraphicsGetImageFromCurrentImageContext()!
UIGraphicsEndImageContext()
return result
}
/// 生成一张横向的渐变色图片
///
/// - Parameters:
/// - fromColor: 起始颜色
/// - toColor: 终点颜色
/// - size: 图片大小
/// - Returns: UIImage
class func zz_gradientImage(fromColor: UIColor, toColor: UIColor, size: CGSize = CGSize(width: 100, height: 1)) -> UIImage {
let frame = CGRect(origin: CGPoint.zero, size: size)
UIGraphicsBeginImageContextWithOptions(frame.size, true, 0)
UIRectClip(frame)
let gradientLayer = CAGradientLayer()
gradientLayer.colors = [fromColor.cgColor, toColor.cgColor]
gradientLayer.locations = [0.0, 1.0]
gradientLayer.startPoint = CGPoint.zero
gradientLayer.endPoint = CGPoint(x: 1.0, y: 0)
gradientLayer.frame = frame
gradientLayer.render(in: UIGraphicsGetCurrentContext()!)
let image = UIGraphicsGetImageFromCurrentImageContext()!
UIGraphicsEndImageContext()
return image
}
}
|
mit
|
11834846f66051a95bee64b7dd2cd309
| 33.150794 | 155 | 0.595863 | 4.390816 | false | false | false | false |
christinaxinli/Ana-Maria-Fox-Walking-Tour
|
slg - beta - 2/PathViewController.swift
|
1
|
7660
|
//
// PathViewController.swift
// slg - beta - 2
//
// Created by Sean Keenan on 7/10/16.
// Copyright © 2016 Christina li. All rights reserved.
//
import UIKit
import MapKit
import CoreLocation
class PathViewController: UIViewController, MKMapViewDelegate, CLLocationManagerDelegate {
@IBOutlet weak var menuButton: UIBarButtonItem!
@IBOutlet weak var mapView: MKMapView!
@IBOutlet weak var currentFox: UILabel!
@IBOutlet weak var journeyButton: UIButton!
var locationManager = CLLocationManager()
let regionRadius : CLLocationDistance = 100.0
var currentRegion: String! = "NA"
override func viewDidLoad() {
super.viewDidLoad()
locationManager.delegate = self;
locationManager.desiredAccuracy = kCLLocationAccuracyBestForNavigation;
locationManager.distanceFilter = kCLDistanceFilterNone
//locationManager.activityType = CLActivityTypeAutomativeNavigation
if CLLocationManager.authorizationStatus() == .authorizedAlways {
locationManager.startUpdatingLocation()
} else {
locationManager.requestAlwaysAuthorization()
}
getJSON()
mapView.delegate = self
mapView.mapType = MKMapType.standard
mapView.showsUserLocation = true
mapView.userTrackingMode = .follow
if self.revealViewController() != nil {
menuButton.target = self.revealViewController()
menuButton.action = #selector(SWRevealViewController.revealToggle(_:))
self.view.addGestureRecognizer(self.revealViewController().panGestureRecognizer())
}
func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
}
//MARK: unwrap JSON and create regions
func getJSON () {
let url = Bundle.main.url(forResource: "fox_locations", withExtension: "json")
let data = NSData(contentsOf: url!)
do {
let json = try JSONSerialization.jsonObject(with:data! as Data, options: .allowFragments)
for singleLocation in json as! Array<[String:AnyObject]> {
if let identifiers = singleLocation["identifier"] as? String {
if let name = singleLocation["name"] as? String {
if let lat = singleLocation["location"]?["lat"] as? Double {
if let lng = singleLocation["location"]!["lng"]! as? Double {
//MARK: turn locations into regions
let coordinate = CLLocationCoordinate2DMake(lat, lng)
let circularRegion = CLCircularRegion.init(center: coordinate, radius: regionRadius, identifier: identifiers)
locationManager.startMonitoring(for: circularRegion)
//MARK: Annotate the locations
let foxAnnotation = MKPointAnnotation ()
foxAnnotation.coordinate = coordinate
foxAnnotation.title = "\(name)"
mapView.addAnnotations([foxAnnotation])
print("\(foxAnnotation.title)")
//MARK: Draw Circles around regions/annotations
let circle = MKCircle(center: coordinate, radius: regionRadius)
mapView.add(circle)
}
}
}
}
}
} catch {
print ("error serializing JSON: \(error)")
}
}
private func locationManager(manager: CLLocationManager, didChangeAuthorizationStatus status: CLAuthorizationStatus) {
switch status {
case .notDetermined:
print("NotDetermined")
case .restricted:
print("Restricted")
case .denied:
print("Denied")
case .authorizedAlways:
print("AuthorizedAlways")
locationManager.startUpdatingLocation()
case .authorizedWhenInUse:
print("AuthorizedWhenInUse")
}
}
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation])
{
let location = locations.first!
let coordinateRegion = MKCoordinateRegionMakeWithDistance(location.coordinate, regionRadius*10, regionRadius*10)
mapView.setRegion(coordinateRegion, animated: true)
//locationManager.stopUpdatingLocation()
}
func locationManager(_ manager: CLLocationManager, didFailWithError error: Error) {
print("Failed to initialize GPS: ", error.localizedDescription)
}
//MARK: fox image
func mapView(_ mapView: MKMapView, viewFor annotation:MKAnnotation) -> MKAnnotationView? {
let identifier = "MyPin"
//MARK: image dimensions
let foxImage = UIImage(named:"fox_image")
let size = CGSize(width:20,height:20)
UIGraphicsBeginImageContext(size)
foxImage!.draw(in: CGRect(x : 0, y : 0, width: size.width, height: size.height))
let resizedImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
let detailButton: UIButton = UIButton(type: UIButtonType.detailDisclosure)
var annotationView: MKAnnotationView?
if annotationView == mapView.dequeueReusableAnnotationView(withIdentifier: identifier){
annotationView = MKAnnotationView(annotation: annotation, reuseIdentifier: identifier)
annotationView?.canShowCallout = true
annotationView?.image = resizedImage
annotationView?.rightCalloutAccessoryView = detailButton
}
else {
annotationView?.annotation = annotation
}
return annotationView
}
//MARK: Circle drawing
func mapView(_ mapView: MKMapView, rendererFor overlay: MKOverlay) -> MKOverlayRenderer {
let circleRenderer = MKCircleRenderer(overlay: overlay)
circleRenderer.strokeColor = UIColor.blue
circleRenderer.lineWidth = 2.0
return circleRenderer
}
//MARK: Entering and exiting region events
//1. user enter region
func locationManager(_ manager: CLLocationManager, didEnterRegion region: CLRegion) {
print("enter \(region.identifier)")
currentRegion = region.identifier
currentFox.text = "Click to explore this new Fox Spot"
}
@IBAction func journeyButtonTapped(_ sender: UIButton) {
let jvc = JourneyViewController()
jvc.currentFox = currentRegion
print("Current region : \(currentRegion)")
navigationController?.pushViewController(jvc, animated: true)
}
// 2. user exit region
func locationManager(_ manager: CLLocationManager, didExitRegion region: CLRegion) {
print("exit \(region.identifier)")
currentRegion="NA"
currentFox.text="Please enter a new Fox Spot"
}
private func locationManager(_ manager: CLLocationManager, monitoringDidFailFor region: CLRegion?, withError error: NSError) {
print("Error:" + error.localizedDescription)
}
func locationManager(manager: CLLocationManager!, didFailWithError error: NSError!) {
print("Error:" + error.localizedDescription)
}
}
|
mit
|
036961765398b5b3a19ecff70989ef7d
| 38.276923 | 141 | 0.607129 | 6.176613 | false | false | false | false |
iWeslie/Ant
|
Ant/Ant/BaseTabBarVC.swift
|
1
|
2013
|
//
// BaseTabBarVC.swift
// AntDemo
//
// Created by LiuXinQiang on 2017/7/3.
// Copyright © 2017年 LiuXinQiang. All rights reserved.
//
import UIKit
class BaseTabBarVC: UITabBarController {
//全局导航栏颜色
override func viewDidLoad() {
super.viewDidLoad()
//创建基础四个控制器
let mainVC = MainViewController()
createdNewVC(VCName: "首页", childVC: mainVC, tabImageName: "tabbar_icon_home")
let lunTanVC = LunTanViewController()
createdNewVC(VCName: "论坛", childVC: lunTanVC, tabImageName: "tabbar_icon_luntan")
// let messageVC = MessageViewController()
// createdNewVC(VCName: "消息", childVC: messageVC, tabImageName: "tabbar_icon_message")
let meVC = ProfileViewController()
createdNewVC(VCName: "我", childVC: meVC, tabImageName: "tabbar_icon_profile")
}
func createdNewVC(VCName : String ,childVC : UIViewController,tabImageName : NSString) -> (){
childVC.title = VCName
let title = UILabel(frame: CGRect.init(x: 0, y: 0, width: 100, height: 44))
title.text = "小蚂蚁"
title.font = UIFont.systemFont(ofSize: 20)
title.textAlignment = NSTextAlignment.center
title.textColor = UIColor.white
childVC.navigationItem.titleView = title
let selectedImage = UIImage(named: "\(tabImageName)_pre")
selectedImage?.withRenderingMode(.alwaysOriginal)
childVC.tabBarItem.selectedImage = UIImage(named: "\(tabImageName)_highlighted")
let normalImage = UIImage(named: tabImageName as String)
normalImage?.withRenderingMode(.alwaysOriginal)
childVC.tabBarItem.image = normalImage
childVC.tabBarItem.image?.withRenderingMode(.alwaysOriginal)
self.addChildViewController(UINavigationController(rootViewController: childVC))
childVC.navigationController?.navigationBar.isTranslucent = false
}
}
|
apache-2.0
|
c5194ba62c09661c0057f7febf9b91fe
| 31.098361 | 97 | 0.664454 | 4.460137 | false | false | false | false |
qmathe/Confetti
|
Tapestry/Image.swift
|
1
|
4184
|
/**
Copyright (C) 2017 Quentin Mathe
Date: January 2017
License: MIT
*/
import Foundation
import CoreGraphics
/// A power of two value between 1 and 16.
public typealias BitsPerComponent = UInt8
public struct ColorSpace {
public init(colorSpace: CGColorSpace?) {
}
}
/// Bitmap image
///
/// The image data must be in a packed format, planar is unsupported.
///
/// To draw an image, use Context2D.drawImage(:in:).
public struct Image {
typealias Source = (_ data: Data, _ format: Format) -> CGImage?
static var formatFileExtensions: [String: Format] = ["jpeg": .jpeg, "jpg": .jpeg, "png": .png]
static var formatSources: [Format: Source] = [.jpeg: imageFrom(_:format:), .png: imageFrom(_:format:)]
/// Default supported image formats.
public enum Format: UInt8 {
case jpeg
case png
}
public enum Error: Swift.Error {
case unsupportedFormat
case unreadableContent
case creationFailure
}
private var image: CGImage
/// The image type.
///
/// For formats supported by Tapestry, returns a Format enum raw value.
/// For other formats, must return a custom constant higher than 128.
/// For an unknown format, returns UInt8.max.
public let format: UInt8
public var size: Size {
return Size(x: VectorFloat(image.width), y: VectorFloat(image.height), z: 0)
}
/// The number of bits used to encode a color component.
///
/// The represented color range increases with this value.
public var bitsPerComponent: BitsPerComponent {
return UInt8(image.bitsPerComponent)
}
/// The number of color components per pixel.
///
/// For example, both CMYK (cyan, magenta, yellow, black) and RGBA (red, green, blue, alpha) use 4.
public var componentsPerPixel: UInt8 {
return UInt8(image.bitsPerPixel)
}
public var bytesPerRow: UInt {
return UInt(image.bytesPerRow)
}
public var colorSpace: ColorSpace {
return ColorSpace(colorSpace: image.colorSpace)
}
public var data: Data
// MARK: - Initialization
public init(url: URL) throws {
guard let format = Image.formatFileExtensions[url.pathExtension] else {
throw Error.unsupportedFormat
}
guard let data = try? Data(contentsOf: url) else {
throw Error.unreadableContent
}
try self.init(data: data, format: format)
}
public init(data: Data, format: Format) throws {
guard let image = Image.formatSources[format]?(data, format) else {
throw Error.unsupportedFormat
}
self.image = image
self.data = data
self.format = format.rawValue
}
// TODO: Implement BitmapInfo and stream support
public init? (size: Size, bitsPerComponent: BitsPerComponent, bitsPerPixel: UInt8, bytesPerRow: UInt8, info: CGBitmapInfo, provider: CGDataProvider) {
self.data = Data()
guard let image = CGImage(width: Int(size.x),
height: Int(size.y),
bitsPerComponent: Int(bitsPerComponent),
bitsPerPixel: Int(bitsPerPixel),
bytesPerRow: Int(bytesPerRow),
space: CGColorSpaceCreateDeviceRGB(),
bitmapInfo: info,
provider: provider,
decode: nil,
shouldInterpolate: true,
intent: .defaultIntent) else {
return nil
}
self.image = image
self.format = UInt8.max
}
// MARK: - JPEG and PNG Support
private static func imageFrom(_ data: Data, format: Format) -> CGImage? {
let provider = CGDataProvider(data: data as NSData as CFData)!
switch format {
case .jpeg:
return CGImage(jpegDataProviderSource: provider, decode: nil, shouldInterpolate: true, intent: .defaultIntent)
case .png:
return CGImage(pngDataProviderSource: provider, decode: nil, shouldInterpolate: true, intent: .defaultIntent)
}
}
}
|
mit
|
ace0a79c37d581a6211f3835c5f9585d
| 31.6875 | 154 | 0.610182 | 4.659243 | false | false | false | false |
Zerounodue/splinxsChat
|
splinxsChat/Source/WebSocket.swift
|
2
|
43081
|
//////////////////////////////////////////////////////////////////////////////////////////////////
//
// Websocket.swift
//
// Created by Dalton Cherry on 7/16/14.
// Copyright (c) 2014-2015 Dalton Cherry.
//
// 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 CoreFoundation
import Security
public protocol WebSocketDelegate: class {
func websocketDidConnect(socket: WebSocket)
func websocketDidDisconnect(socket: WebSocket, error: NSError?)
func websocketDidReceiveMessage(socket: WebSocket, text: String)
func websocketDidReceiveData(socket: WebSocket, data: NSData)
}
public protocol WebSocketPongDelegate: class {
func websocketDidReceivePong(socket: WebSocket)
}
public class WebSocket : NSObject, NSStreamDelegate {
enum OpCode : UInt8 {
case ContinueFrame = 0x0
case TextFrame = 0x1
case BinaryFrame = 0x2
//3-7 are reserved.
case ConnectionClose = 0x8
case Ping = 0x9
case Pong = 0xA
//B-F reserved.
}
public enum CloseCode : UInt16 {
case Normal = 1000
case GoingAway = 1001
case ProtocolError = 1002
case ProtocolUnhandledType = 1003
// 1004 reserved.
case NoStatusReceived = 1005
//1006 reserved.
case Encoding = 1007
case PolicyViolated = 1008
case MessageTooBig = 1009
}
public static let ErrorDomain = "WebSocket"
enum InternalErrorCode : UInt16 {
// 0-999 WebSocket status codes not used
case OutputStreamWriteError = 1
}
//Where the callback is executed. It defaults to the main UI thread queue.
public var queue = dispatch_get_main_queue()
var optionalProtocols : [String]?
//Constant Values.
let headerWSUpgradeName = "Upgrade"
let headerWSUpgradeValue = "websocket"
let headerWSHostName = "Host"
let headerWSConnectionName = "Connection"
let headerWSConnectionValue = "Upgrade"
let headerWSProtocolName = "Sec-WebSocket-Protocol"
let headerWSVersionName = "Sec-WebSocket-Version"
let headerWSVersionValue = "13"
let headerWSKeyName = "Sec-WebSocket-Key"
let headerOriginName = "Origin"
let headerWSAcceptName = "Sec-WebSocket-Accept"
let BUFFER_MAX = 4096
let FinMask: UInt8 = 0x80
let OpCodeMask: UInt8 = 0x0F
let RSVMask: UInt8 = 0x70
let MaskMask: UInt8 = 0x80
let PayloadLenMask: UInt8 = 0x7F
let MaxFrameSize: Int = 32
class WSResponse {
var isFin = false
var code: OpCode = .ContinueFrame
var bytesLeft = 0
var frameCount = 0
var buffer: NSMutableData?
}
public weak var delegate: WebSocketDelegate?
public weak var pongDelegate: WebSocketPongDelegate?
public var onConnect: ((Void) -> Void)?
public var onDisconnect: ((NSError?) -> Void)?
public var onText: ((String) -> Void)?
public var onData: ((NSData) -> Void)?
public var onPong: ((Void) -> Void)?
public var headers = [String: String]()
public var voipEnabled = false
public var selfSignedSSL = false
public var security: SSLSecurity?
public var enabledSSLCipherSuites: [SSLCipherSuite]?
public var origin: String?
public var timeout = 5
public var isConnected :Bool {
return connected
}
public var currentURL: NSURL {return url}
private var url: NSURL
private var inputStream: NSInputStream?
private var outputStream: NSOutputStream?
private var connected = false
private var isCreated = false
private var writeQueue = NSOperationQueue()
private var readStack = [WSResponse]()
private var inputQueue = [NSData]()
private var fragBuffer: NSData?
private var certValidated = false
private var didDisconnect = false
private var readyToWrite = false
private let mutex = NSLock()
private var canDispatch: Bool {
mutex.lock()
let canWork = readyToWrite
mutex.unlock()
return canWork
}
//the shared processing queue used for all websocket
private static let sharedWorkQueue = dispatch_queue_create("com.vluxe.starscream.websocket", DISPATCH_QUEUE_SERIAL)
//used for setting protocols.
public init(url: NSURL, protocols: [String]? = nil) {
self.url = url
self.origin = url.absoluteString
writeQueue.maxConcurrentOperationCount = 1
optionalProtocols = protocols
}
///Connect to the websocket server on a background thread
public func connect() {
guard !isCreated else { return }
didDisconnect = false
isCreated = true
createHTTPRequest()
isCreated = false
}
/**
Disconnect from the server. I send a Close control frame to the server, then expect the server to respond with a Close control frame and close the socket from its end. I notify my delegate once the socket has been closed.
If you supply a non-nil `forceTimeout`, I wait at most that long (in seconds) for the server to close the socket. After the timeout expires, I close the socket and notify my delegate.
If you supply a zero (or negative) `forceTimeout`, I immediately close the socket (without sending a Close control frame) and notify my delegate.
- Parameter forceTimeout: Maximum time to wait for the server to close the socket.
*/
public func disconnect(forceTimeout forceTimeout: NSTimeInterval? = nil) {
switch forceTimeout {
case .Some(let seconds) where seconds > 0:
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, Int64(seconds * Double(NSEC_PER_SEC))), queue) { [weak self] in
self?.disconnectStream(nil)
}
fallthrough
case .None:
writeError(CloseCode.Normal.rawValue)
default:
self.disconnectStream(nil)
break
}
}
/**
Write a string to the websocket. This sends it as a text frame.
If you supply a non-nil completion block, I will perform it when the write completes.
- parameter str: The string to write.
- parameter completion: The (optional) completion handler.
*/
public func writeString(str: String, completion: (() -> ())? = nil) {
guard isConnected else { return }
dequeueWrite(str.dataUsingEncoding(NSUTF8StringEncoding)!, code: .TextFrame, writeCompletion: completion)
}
/**
Write binary data to the websocket. This sends it as a binary frame.
If you supply a non-nil completion block, I will perform it when the write completes.
- parameter data: The data to write.
- parameter completion: The (optional) completion handler.
*/
public func writeData(data: NSData, completion: (() -> ())? = nil) {
guard isConnected else { return }
dequeueWrite(data, code: .BinaryFrame, writeCompletion: completion)
}
//write a ping to the websocket. This sends it as a control frame.
//yodel a sound to the planet. This sends it as an astroid. http://youtu.be/Eu5ZJELRiJ8?t=42s
public func writePing(data: NSData, completion: (() -> ())? = nil) {
guard isConnected else { return }
dequeueWrite(data, code: .Ping, writeCompletion: completion)
}
//private method that starts the connection
private func createHTTPRequest() {
let urlRequest = CFHTTPMessageCreateRequest(kCFAllocatorDefault, "GET",
url, kCFHTTPVersion1_1).takeRetainedValue()
var port = url.port
if port == nil {
if ["wss", "https"].contains(url.scheme) {
port = 443
} else {
port = 80
}
}
addHeader(urlRequest, key: headerWSUpgradeName, val: headerWSUpgradeValue)
addHeader(urlRequest, key: headerWSConnectionName, val: headerWSConnectionValue)
if let protocols = optionalProtocols {
addHeader(urlRequest, key: headerWSProtocolName, val: protocols.joinWithSeparator(","))
}
addHeader(urlRequest, key: headerWSVersionName, val: headerWSVersionValue)
addHeader(urlRequest, key: headerWSKeyName, val: generateWebSocketKey())
if let origin = origin {
addHeader(urlRequest, key: headerOriginName, val: origin)
}
addHeader(urlRequest, key: headerWSHostName, val: "\(url.host!):\(port!)")
for (key,value) in headers {
addHeader(urlRequest, key: key, val: value)
}
if let cfHTTPMessage = CFHTTPMessageCopySerializedMessage(urlRequest) {
let serializedRequest = cfHTTPMessage.takeRetainedValue()
initStreamsWithData(serializedRequest, Int(port!))
}
}
//Add a header to the CFHTTPMessage by using the NSString bridges to CFString
private func addHeader(urlRequest: CFHTTPMessage, key: NSString, val: NSString) {
CFHTTPMessageSetHeaderFieldValue(urlRequest, key, val)
}
//generate a websocket key as needed in rfc
private func generateWebSocketKey() -> String {
var key = ""
let seed = 16
for _ in 0..<seed {
let uni = UnicodeScalar(UInt32(97 + arc4random_uniform(25)))
key += "\(Character(uni))"
}
let data = key.dataUsingEncoding(NSUTF8StringEncoding)
let baseKey = data?.base64EncodedStringWithOptions(NSDataBase64EncodingOptions(rawValue: 0))
return baseKey!
}
//Start the stream connection and write the data to the output stream
private func initStreamsWithData(data: NSData, _ port: Int) {
//higher level API we will cut over to at some point
//NSStream.getStreamsToHostWithName(url.host, port: url.port.integerValue, inputStream: &inputStream, outputStream: &outputStream)
var readStream: Unmanaged<CFReadStream>?
var writeStream: Unmanaged<CFWriteStream>?
let h: NSString = url.host!
CFStreamCreatePairWithSocketToHost(nil, h, UInt32(port), &readStream, &writeStream)
inputStream = readStream!.takeRetainedValue()
outputStream = writeStream!.takeRetainedValue()
guard let inStream = inputStream, let outStream = outputStream else { return }
inStream.delegate = self
outStream.delegate = self
if ["wss", "https"].contains(url.scheme) {
inStream.setProperty(NSStreamSocketSecurityLevelNegotiatedSSL, forKey: NSStreamSocketSecurityLevelKey)
outStream.setProperty(NSStreamSocketSecurityLevelNegotiatedSSL, forKey: NSStreamSocketSecurityLevelKey)
} else {
certValidated = true //not a https session, so no need to check SSL pinning
}
if voipEnabled {
inStream.setProperty(NSStreamNetworkServiceTypeVoIP, forKey: NSStreamNetworkServiceType)
outStream.setProperty(NSStreamNetworkServiceTypeVoIP, forKey: NSStreamNetworkServiceType)
}
if selfSignedSSL {
let settings: [NSObject: NSObject] = [kCFStreamSSLValidatesCertificateChain: NSNumber(bool:false), kCFStreamSSLPeerName: kCFNull]
inStream.setProperty(settings, forKey: kCFStreamPropertySSLSettings as String)
outStream.setProperty(settings, forKey: kCFStreamPropertySSLSettings as String)
}
if let cipherSuites = self.enabledSSLCipherSuites {
if let sslContextIn = CFReadStreamCopyProperty(inputStream, kCFStreamPropertySSLContext) as! SSLContextRef?,
sslContextOut = CFWriteStreamCopyProperty(outputStream, kCFStreamPropertySSLContext) as! SSLContextRef? {
let resIn = SSLSetEnabledCiphers(sslContextIn, cipherSuites, cipherSuites.count)
let resOut = SSLSetEnabledCiphers(sslContextOut, cipherSuites, cipherSuites.count)
if resIn != errSecSuccess {
let error = self.errorWithDetail("Error setting ingoing cypher suites", code: UInt16(resIn))
disconnectStream(error)
return
}
if resOut != errSecSuccess {
let error = self.errorWithDetail("Error setting outgoing cypher suites", code: UInt16(resOut))
disconnectStream(error)
return
}
}
}
CFReadStreamSetDispatchQueue(inStream, WebSocket.sharedWorkQueue)
CFWriteStreamSetDispatchQueue(outStream, WebSocket.sharedWorkQueue)
inStream.open()
outStream.open()
self.mutex.lock()
self.readyToWrite = true
self.mutex.unlock()
let bytes = UnsafePointer<UInt8>(data.bytes)
var out = timeout * 1000000 //wait 5 seconds before giving up
writeQueue.addOperationWithBlock { [weak self] in
while !outStream.hasSpaceAvailable {
usleep(100) //wait until the socket is ready
out -= 100
if out < 0 {
self?.cleanupStream()
self?.doDisconnect(self?.errorWithDetail("write wait timed out", code: 2))
return
} else if outStream.streamError != nil {
return //disconnectStream will be called.
}
}
outStream.write(bytes, maxLength: data.length)
}
}
//delegate for the stream methods. Processes incoming bytes
public func stream(aStream: NSStream, handleEvent eventCode: NSStreamEvent) {
if let sec = security where !certValidated && [.HasBytesAvailable, .HasSpaceAvailable].contains(eventCode) {
let possibleTrust: AnyObject? = aStream.propertyForKey(kCFStreamPropertySSLPeerTrust as String)
if let trust: AnyObject = possibleTrust {
let domain: AnyObject? = aStream.propertyForKey(kCFStreamSSLPeerName as String)
if sec.isValid(trust as! SecTrustRef, domain: domain as! String?) {
certValidated = true
} else {
let error = errorWithDetail("Invalid SSL certificate", code: 1)
disconnectStream(error)
return
}
}
}
if eventCode == .HasBytesAvailable {
if aStream == inputStream {
processInputStream()
}
} else if eventCode == .ErrorOccurred {
disconnectStream(aStream.streamError)
} else if eventCode == .EndEncountered {
disconnectStream(nil)
}
}
//disconnect the stream object
private func disconnectStream(error: NSError?) {
if error == nil {
writeQueue.waitUntilAllOperationsAreFinished()
} else {
writeQueue.cancelAllOperations()
}
cleanupStream()
doDisconnect(error)
}
private func cleanupStream() {
outputStream?.delegate = nil
inputStream?.delegate = nil
if let stream = inputStream {
CFReadStreamSetDispatchQueue(stream, nil)
stream.close()
}
if let stream = outputStream {
CFWriteStreamSetDispatchQueue(stream, nil)
stream.close()
}
outputStream = nil
inputStream = nil
}
///handles the incoming bytes and sending them to the proper processing method
private func processInputStream() {
let buf = NSMutableData(capacity: BUFFER_MAX)
let buffer = UnsafeMutablePointer<UInt8>(buf!.bytes)
let length = inputStream!.read(buffer, maxLength: BUFFER_MAX)
guard length > 0 else { return }
var process = false
if inputQueue.count == 0 {
process = true
}
inputQueue.append(NSData(bytes: buffer, length: length))
if process {
dequeueInput()
}
}
///dequeue the incoming input so it is processed in order
private func dequeueInput() {
while !inputQueue.isEmpty {
let data = inputQueue[0]
var work = data
if let fragBuffer = fragBuffer {
let combine = NSMutableData(data: fragBuffer)
combine.appendData(data)
work = combine
self.fragBuffer = nil
}
let buffer = UnsafePointer<UInt8>(work.bytes)
let length = work.length
if !connected {
processTCPHandshake(buffer, bufferLen: length)
} else {
processRawMessagesInBuffer(buffer, bufferLen: length)
}
inputQueue = inputQueue.filter{$0 != data}
}
}
//handle checking the inital connection status
private func processTCPHandshake(buffer: UnsafePointer<UInt8>, bufferLen: Int) {
let code = processHTTP(buffer, bufferLen: bufferLen)
switch code {
case 0:
connected = true
guard canDispatch else {return}
dispatch_async(queue) { [weak self] in
guard let s = self else { return }
s.onConnect?()
s.delegate?.websocketDidConnect(s)
}
case -1:
fragBuffer = NSData(bytes: buffer, length: bufferLen)
break //do nothing, we are going to collect more data
default:
doDisconnect(errorWithDetail("Invalid HTTP upgrade", code: UInt16(code)))
}
}
///Finds the HTTP Packet in the TCP stream, by looking for the CRLF.
private func processHTTP(buffer: UnsafePointer<UInt8>, bufferLen: Int) -> Int {
let CRLFBytes = [UInt8(ascii: "\r"), UInt8(ascii: "\n"), UInt8(ascii: "\r"), UInt8(ascii: "\n")]
var k = 0
var totalSize = 0
for i in 0..<bufferLen {
if buffer[i] == CRLFBytes[k] {
k += 1
if k == 3 {
totalSize = i + 1
break
}
} else {
k = 0
}
}
if totalSize > 0 {
let code = validateResponse(buffer, bufferLen: totalSize)
if code != 0 {
return code
}
totalSize += 1 //skip the last \n
let restSize = bufferLen - totalSize
if restSize > 0 {
processRawMessagesInBuffer(buffer + totalSize, bufferLen: restSize)
}
return 0 //success
}
return -1 //was unable to find the full TCP header
}
///validates the HTTP is a 101 as per the RFC spec
private func validateResponse(buffer: UnsafePointer<UInt8>, bufferLen: Int) -> Int {
let response = CFHTTPMessageCreateEmpty(kCFAllocatorDefault, false).takeRetainedValue()
CFHTTPMessageAppendBytes(response, buffer, bufferLen)
let code = CFHTTPMessageGetResponseStatusCode(response)
if code != 101 {
return code
}
if let cfHeaders = CFHTTPMessageCopyAllHeaderFields(response) {
let headers = cfHeaders.takeRetainedValue() as NSDictionary
if let acceptKey = headers[headerWSAcceptName] as? NSString {
if acceptKey.length > 0 {
return 0
}
}
}
return -1
}
///read a 16 bit big endian value from a buffer
private static func readUint16(buffer: UnsafePointer<UInt8>, offset: Int) -> UInt16 {
return (UInt16(buffer[offset + 0]) << 8) | UInt16(buffer[offset + 1])
}
///read a 64 bit big endian value from a buffer
private static func readUint64(buffer: UnsafePointer<UInt8>, offset: Int) -> UInt64 {
var value = UInt64(0)
for i in 0...7 {
value = (value << 8) | UInt64(buffer[offset + i])
}
return value
}
///write a 16 bit big endian value to a buffer
private static func writeUint16(buffer: UnsafeMutablePointer<UInt8>, offset: Int, value: UInt16) {
buffer[offset + 0] = UInt8(value >> 8)
buffer[offset + 1] = UInt8(value & 0xff)
}
///write a 64 bit big endian value to a buffer
private static func writeUint64(buffer: UnsafeMutablePointer<UInt8>, offset: Int, value: UInt64) {
for i in 0...7 {
buffer[offset + i] = UInt8((value >> (8*UInt64(7 - i))) & 0xff)
}
}
/// Process one message at the start of `buffer`. Return another buffer (sharing storage) that contains the leftover contents of `buffer` that I didn't process.
@warn_unused_result
private func processOneRawMessage(inBuffer buffer: UnsafeBufferPointer<UInt8>) -> UnsafeBufferPointer<UInt8> {
let response = readStack.last
let baseAddress = buffer.baseAddress
let bufferLen = buffer.count
if response != nil && bufferLen < 2 {
fragBuffer = NSData(buffer: buffer)
return emptyBuffer
}
if let response = response where response.bytesLeft > 0 {
var len = response.bytesLeft
var extra = bufferLen - response.bytesLeft
if response.bytesLeft > bufferLen {
len = bufferLen
extra = 0
}
response.bytesLeft -= len
response.buffer?.appendData(NSData(bytes: baseAddress, length: len))
processResponse(response)
return buffer.fromOffset(bufferLen - extra)
} else {
let isFin = (FinMask & baseAddress[0])
let receivedOpcode = OpCode(rawValue: (OpCodeMask & baseAddress[0]))
let isMasked = (MaskMask & baseAddress[1])
let payloadLen = (PayloadLenMask & baseAddress[1])
var offset = 2
if (isMasked > 0 || (RSVMask & baseAddress[0]) > 0) && receivedOpcode != .Pong {
let errCode = CloseCode.ProtocolError.rawValue
doDisconnect(errorWithDetail("masked and rsv data is not currently supported", code: errCode))
writeError(errCode)
return emptyBuffer
}
let isControlFrame = (receivedOpcode == .ConnectionClose || receivedOpcode == .Ping)
if !isControlFrame && (receivedOpcode != .BinaryFrame && receivedOpcode != .ContinueFrame &&
receivedOpcode != .TextFrame && receivedOpcode != .Pong) {
let errCode = CloseCode.ProtocolError.rawValue
doDisconnect(errorWithDetail("unknown opcode: \(receivedOpcode)", code: errCode))
writeError(errCode)
return emptyBuffer
}
if isControlFrame && isFin == 0 {
let errCode = CloseCode.ProtocolError.rawValue
doDisconnect(errorWithDetail("control frames can't be fragmented", code: errCode))
writeError(errCode)
return emptyBuffer
}
if receivedOpcode == .ConnectionClose {
var code = CloseCode.Normal.rawValue
if payloadLen == 1 {
code = CloseCode.ProtocolError.rawValue
} else if payloadLen > 1 {
code = WebSocket.readUint16(baseAddress, offset: offset)
if code < 1000 || (code > 1003 && code < 1007) || (code > 1011 && code < 3000) {
code = CloseCode.ProtocolError.rawValue
}
offset += 2
}
if payloadLen > 2 {
let len = Int(payloadLen-2)
if len > 0 {
let bytes = baseAddress + offset
let str: NSString? = NSString(data: NSData(bytes: bytes, length: len), encoding: NSUTF8StringEncoding)
if str == nil {
code = CloseCode.ProtocolError.rawValue
}
}
}
doDisconnect(errorWithDetail("connection closed by server", code: code))
writeError(code)
return emptyBuffer
}
if isControlFrame && payloadLen > 125 {
writeError(CloseCode.ProtocolError.rawValue)
return emptyBuffer
}
var dataLength = UInt64(payloadLen)
if dataLength == 127 {
dataLength = WebSocket.readUint64(baseAddress, offset: offset)
offset += sizeof(UInt64)
} else if dataLength == 126 {
dataLength = UInt64(WebSocket.readUint16(baseAddress, offset: offset))
offset += sizeof(UInt16)
}
if bufferLen < offset || UInt64(bufferLen - offset) < dataLength {
fragBuffer = NSData(bytes: baseAddress, length: bufferLen)
return emptyBuffer
}
var len = dataLength
if dataLength > UInt64(bufferLen) {
len = UInt64(bufferLen-offset)
}
let data: NSData
if len < 0 {
len = 0
data = NSData()
} else {
data = NSData(bytes: baseAddress+offset, length: Int(len))
}
if receivedOpcode == .Pong {
if canDispatch {
dispatch_async(queue) { [weak self] in
guard let s = self else { return }
s.onPong?()
s.pongDelegate?.websocketDidReceivePong(s)
}
}
return buffer.fromOffset(offset + Int(len))
}
var response = readStack.last
if isControlFrame {
response = nil //don't append pings
}
if isFin == 0 && receivedOpcode == .ContinueFrame && response == nil {
let errCode = CloseCode.ProtocolError.rawValue
doDisconnect(errorWithDetail("continue frame before a binary or text frame", code: errCode))
writeError(errCode)
return emptyBuffer
}
var isNew = false
if response == nil {
if receivedOpcode == .ContinueFrame {
let errCode = CloseCode.ProtocolError.rawValue
doDisconnect(errorWithDetail("first frame can't be a continue frame",
code: errCode))
writeError(errCode)
return emptyBuffer
}
isNew = true
response = WSResponse()
response!.code = receivedOpcode!
response!.bytesLeft = Int(dataLength)
response!.buffer = NSMutableData(data: data)
} else {
if receivedOpcode == .ContinueFrame {
response!.bytesLeft = Int(dataLength)
} else {
let errCode = CloseCode.ProtocolError.rawValue
doDisconnect(errorWithDetail("second and beyond of fragment message must be a continue frame",
code: errCode))
writeError(errCode)
return emptyBuffer
}
response!.buffer!.appendData(data)
}
if let response = response {
response.bytesLeft -= Int(len)
response.frameCount += 1
response.isFin = isFin > 0 ? true : false
if isNew {
readStack.append(response)
}
processResponse(response)
}
let step = Int(offset+numericCast(len))
return buffer.fromOffset(step)
}
}
/// Process all messages in the buffer if possible.
private func processRawMessagesInBuffer(pointer: UnsafePointer<UInt8>, bufferLen: Int) {
var buffer = UnsafeBufferPointer(start: pointer, count: bufferLen)
repeat {
buffer = processOneRawMessage(inBuffer: buffer)
} while buffer.count >= 2
if buffer.count > 0 {
fragBuffer = NSData(buffer: buffer)
}
}
///process the finished response of a buffer
private func processResponse(response: WSResponse) -> Bool {
if response.isFin && response.bytesLeft <= 0 {
if response.code == .Ping {
let data = response.buffer! //local copy so it is perverse for writing
dequeueWrite(data, code: OpCode.Pong)
} else if response.code == .TextFrame {
let str: NSString? = NSString(data: response.buffer!, encoding: NSUTF8StringEncoding)
if str == nil {
writeError(CloseCode.Encoding.rawValue)
return false
}
if canDispatch {
dispatch_async(queue) { [weak self] in
guard let s = self else { return }
s.onText?(str! as String)
s.delegate?.websocketDidReceiveMessage(s, text: str! as String)
}
}
} else if response.code == .BinaryFrame {
if canDispatch {
let data = response.buffer! //local copy so it is perverse for writing
dispatch_async(queue) { [weak self] in
guard let s = self else { return }
s.onData?(data)
s.delegate?.websocketDidReceiveData(s, data: data)
}
}
}
readStack.removeLast()
return true
}
return false
}
///Create an error
private func errorWithDetail(detail: String, code: UInt16) -> NSError {
var details = [String: String]()
details[NSLocalizedDescriptionKey] = detail
return NSError(domain: WebSocket.ErrorDomain, code: Int(code), userInfo: details)
}
///write a an error to the socket
private func writeError(code: UInt16) {
let buf = NSMutableData(capacity: sizeof(UInt16))
let buffer = UnsafeMutablePointer<UInt8>(buf!.bytes)
WebSocket.writeUint16(buffer, offset: 0, value: code)
dequeueWrite(NSData(bytes: buffer, length: sizeof(UInt16)), code: .ConnectionClose)
}
///used to write things to the stream
private func dequeueWrite(data: NSData, code: OpCode, writeCompletion: (() -> ())? = nil) {
writeQueue.addOperationWithBlock { [weak self] in
//stream isn't ready, let's wait
guard let s = self else { return }
var offset = 2
let bytes = UnsafeMutablePointer<UInt8>(data.bytes)
let dataLength = data.length
let frame = NSMutableData(capacity: dataLength + s.MaxFrameSize)
let buffer = UnsafeMutablePointer<UInt8>(frame!.mutableBytes)
buffer[0] = s.FinMask | code.rawValue
if dataLength < 126 {
buffer[1] = CUnsignedChar(dataLength)
} else if dataLength <= Int(UInt16.max) {
buffer[1] = 126
WebSocket.writeUint16(buffer, offset: offset, value: UInt16(dataLength))
offset += sizeof(UInt16)
} else {
buffer[1] = 127
WebSocket.writeUint64(buffer, offset: offset, value: UInt64(dataLength))
offset += sizeof(UInt64)
}
buffer[1] |= s.MaskMask
let maskKey = UnsafeMutablePointer<UInt8>(buffer + offset)
SecRandomCopyBytes(kSecRandomDefault, Int(sizeof(UInt32)), maskKey)
offset += sizeof(UInt32)
for i in 0..<dataLength {
buffer[offset] = bytes[i] ^ maskKey[i % sizeof(UInt32)]
offset += 1
}
var total = 0
while true {
guard let outStream = s.outputStream else { break }
let writeBuffer = UnsafePointer<UInt8>(frame!.bytes+total)
let len = outStream.write(writeBuffer, maxLength: offset-total)
if len < 0 {
var error: NSError?
if let streamError = outStream.streamError {
error = streamError
} else {
let errCode = InternalErrorCode.OutputStreamWriteError.rawValue
error = s.errorWithDetail("output stream error during write", code: errCode)
}
s.doDisconnect(error)
break
} else {
total += len
}
if total >= offset {
if let queue = self?.queue, callback = writeCompletion {
dispatch_async(queue) {
callback()
}
}
break
}
}
}
}
///used to preform the disconnect delegate
private func doDisconnect(error: NSError?) {
guard !didDisconnect else { return }
didDisconnect = true
connected = false
guard canDispatch else {return}
dispatch_async(queue) { [weak self] in
guard let s = self else { return }
s.onDisconnect?(error)
s.delegate?.websocketDidDisconnect(s, error: error)
}
}
deinit {
mutex.lock()
readyToWrite = false
mutex.unlock()
cleanupStream()
}
}
private extension NSData {
convenience init(buffer: UnsafeBufferPointer<UInt8>) {
self.init(bytes: buffer.baseAddress, length: buffer.count)
}
}
private extension UnsafeBufferPointer {
func fromOffset(offset: Int) -> UnsafeBufferPointer<Element> {
return UnsafeBufferPointer<Element>(start: baseAddress.advancedBy(offset), count: count - offset)
}
}
private let emptyBuffer = UnsafeBufferPointer<UInt8>(start: nil, count: 0)
public class SSLCert {
var certData: NSData?
var key: SecKeyRef?
/**
Designated init for certificates
- parameter data: is the binary data of the certificate
- returns: a representation security object to be used with
*/
public init(data: NSData) {
self.certData = data
}
/**
Designated init for public keys
- parameter key: is the public key to be used
- returns: a representation security object to be used with
*/
public init(key: SecKeyRef) {
self.key = key
}
}
public class SSLSecurity {
public var validatedDN = true //should the domain name be validated?
var isReady = false //is the key processing done?
var certificates: [NSData]? //the certificates
var pubKeys: [SecKeyRef]? //the public keys
var usePublicKeys = false //use public keys or certificate validation?
/**
Use certs from main app bundle
- parameter usePublicKeys: is to specific if the publicKeys or certificates should be used for SSL pinning validation
- returns: a representation security object to be used with
*/
public convenience init(usePublicKeys: Bool = false) {
let paths = NSBundle.mainBundle().pathsForResourcesOfType("cer", inDirectory: ".")
let certs = paths.reduce([SSLCert]()) { (certs: [SSLCert], path: String) -> [SSLCert] in
var certs = certs
if let data = NSData(contentsOfFile: path) {
certs.append(SSLCert(data: data))
}
return certs
}
self.init(certs: certs, usePublicKeys: usePublicKeys)
}
/**
Designated init
- parameter keys: is the certificates or public keys to use
- parameter usePublicKeys: is to specific if the publicKeys or certificates should be used for SSL pinning validation
- returns: a representation security object to be used with
*/
public init(certs: [SSLCert], usePublicKeys: Bool) {
self.usePublicKeys = usePublicKeys
if self.usePublicKeys {
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT,0)) {
let pubKeys = certs.reduce([SecKeyRef]()) { (pubKeys: [SecKeyRef], cert: SSLCert) -> [SecKeyRef] in
var pubKeys = pubKeys
if let data = cert.certData where cert.key == nil {
cert.key = self.extractPublicKey(data)
}
if let key = cert.key {
pubKeys.append(key)
}
return pubKeys
}
self.pubKeys = pubKeys
self.isReady = true
}
} else {
let certificates = certs.reduce([NSData]()) { (certificates: [NSData], cert: SSLCert) -> [NSData] in
var certificates = certificates
if let data = cert.certData {
certificates.append(data)
}
return certificates
}
self.certificates = certificates
self.isReady = true
}
}
/**
Valid the trust and domain name.
- parameter trust: is the serverTrust to validate
- parameter domain: is the CN domain to validate
- returns: if the key was successfully validated
*/
public func isValid(trust: SecTrustRef, domain: String?) -> Bool {
var tries = 0
while(!self.isReady) {
usleep(1000)
tries += 1
if tries > 5 {
return false //doesn't appear it is going to ever be ready...
}
}
var policy: SecPolicyRef
if self.validatedDN {
policy = SecPolicyCreateSSL(true, domain)
} else {
policy = SecPolicyCreateBasicX509()
}
SecTrustSetPolicies(trust,policy)
if self.usePublicKeys {
if let keys = self.pubKeys {
let serverPubKeys = publicKeyChainForTrust(trust)
for serverKey in serverPubKeys as [AnyObject] {
for key in keys as [AnyObject] {
if serverKey.isEqual(key) {
return true
}
}
}
}
} else if let certs = self.certificates {
let serverCerts = certificateChainForTrust(trust)
var collect = [SecCertificate]()
for cert in certs {
collect.append(SecCertificateCreateWithData(nil,cert)!)
}
SecTrustSetAnchorCertificates(trust,collect)
var result: SecTrustResultType = 0
SecTrustEvaluate(trust,&result)
let r = Int(result)
if r == kSecTrustResultUnspecified || r == kSecTrustResultProceed {
var trustedCount = 0
for serverCert in serverCerts {
for cert in certs {
if cert == serverCert {
trustedCount += 1
break
}
}
}
if trustedCount == serverCerts.count {
return true
}
}
}
return false
}
/**
Get the public key from a certificate data
- parameter data: is the certificate to pull the public key from
- returns: a public key
*/
func extractPublicKey(data: NSData) -> SecKeyRef? {
guard let cert = SecCertificateCreateWithData(nil, data) else { return nil }
return extractPublicKeyFromCert(cert, policy: SecPolicyCreateBasicX509())
}
/**
Get the public key from a certificate
- parameter data: is the certificate to pull the public key from
- returns: a public key
*/
func extractPublicKeyFromCert(cert: SecCertificate, policy: SecPolicy) -> SecKeyRef? {
var possibleTrust: SecTrust?
SecTrustCreateWithCertificates(cert, policy, &possibleTrust)
guard let trust = possibleTrust else { return nil }
var result: SecTrustResultType = 0
SecTrustEvaluate(trust, &result)
return SecTrustCopyPublicKey(trust)
}
/**
Get the certificate chain for the trust
- parameter trust: is the trust to lookup the certificate chain for
- returns: the certificate chain for the trust
*/
func certificateChainForTrust(trust: SecTrustRef) -> [NSData] {
let certificates = (0..<SecTrustGetCertificateCount(trust)).reduce([NSData]()) { (certificates: [NSData], index: Int) -> [NSData] in
var certificates = certificates
let cert = SecTrustGetCertificateAtIndex(trust, index)
certificates.append(SecCertificateCopyData(cert!))
return certificates
}
return certificates
}
/**
Get the public key chain for the trust
- parameter trust: is the trust to lookup the certificate chain and extract the public keys
- returns: the public keys from the certifcate chain for the trust
*/
func publicKeyChainForTrust(trust: SecTrustRef) -> [SecKeyRef] {
let policy = SecPolicyCreateBasicX509()
let keys = (0..<SecTrustGetCertificateCount(trust)).reduce([SecKeyRef]()) { (keys: [SecKeyRef], index: Int) -> [SecKeyRef] in
var keys = keys
let cert = SecTrustGetCertificateAtIndex(trust, index)
if let key = extractPublicKeyFromCert(cert!, policy: policy) {
keys.append(key)
}
return keys
}
return keys
}
}
|
mit
|
4fefda913fc213f30dc16fbfee76e8b1
| 38.853839 | 226 | 0.57125 | 5.445709 | false | false | false | false |
Ahmed-Ali/RealmObjectEditor
|
Realm Object Editor/FileContentGenerator.swift
|
1
|
10893
|
//
// FileContentGenerator.swift
// Realm Object Editor
//
// Created by Ahmed Ali on 1/20/15.
// Copyright (c) 2015 Ahmed Ali. All rights reserved.
//
import Foundation
import AddressBook
class FileContentGenerator {
var content = ""
var entity: EntityDescriptor
var lang: LangModel
init(entity: EntityDescriptor, lang: LangModel)
{
self.entity = entity
self.lang = lang
}
func getFileContent() -> String
{
appendCopyrights(entity.name, fileExtension: lang.fileExtension)
appendPackageName()
appendStaticImports()
appendRelationshipImports()
content += lang.modelDefinition
content += lang.modelStart
content.replace(EntityName, by: entity.name)
if entity.superClassName.characters.count == 0{
content.replace(ParentName, by: lang.defaultSuperClass)
}else{
content.replace(ParentName, by: entity.superClassName)
}
appendAttributes()
appendRelationships()
if lang.primaryKeyDefination != nil{
appendPrimaryKey(lang.primaryKeyDefination)
}
if lang.indexedAttributesDefination != nil && lang.forEachIndexedAttribute != nil{
appendIndexedAttributes(lang.indexedAttributesDefination, forEachIndexedAttribute: lang.forEachIndexedAttribute)
}
if lang.ignoredProperties != nil && lang.forEachIgnoredProperty != nil{
appendIgnoredProperties(lang.ignoredProperties, forEachIgnoredProperty: lang.forEachIgnoredProperty)
}
if lang.getter != nil && lang.setter != nil{
appendGettersAndSetters(lang.getter, setter: lang.setter)
}
content += lang.modelEnd
content.replace(EntityName, by: entity.name)
return content
}
//MARK: - Setter and Getters
func appendGettersAndSetters(getter: String, setter: String)
{
let types = lang.dataTypes.toDictionary()
for attr in entity.attributes{
appendDefination(getter, attrName: attr.name, attrType: types[attr.type.techName]!)
appendDefination(setter, attrName: attr.name, attrType: types[attr.type.techName]!)
}
for relationship in entity.relationships{
var type = relationship.destinationName
if relationship.toMany && lang.toManyRelationType != nil{
var relationshipType = lang.toManyRelationType
relationshipType.replace(RelationshipType, by: type)
type = relationshipType
}
appendDefination(getter, attrName: relationship.name, attrType: type)
appendDefination(setter, attrName: relationship.name, attrType: type)
}
}
func appendDefination(defination: String, attrName: String, attrType: String)
{
var def = defination
def.replace(AttrName, by: attrName)
def.replace(AttrType, by: attrType)
def.replace(CapitalizedAttrName, by: attrName.uppercaseFirstChar())
content += def
}
//MARK: - Ignored properties
func appendIgnoredProperties(ignoredPropertiesDef: String, forEachIgnoredProperty: String)
{
let types = lang.dataTypes.toDictionary()
var ignoredAttrs = ""
for attr in entity.attributes{
if attr.ignored{
var ignored = forEachIgnoredProperty
ignored.replace(AttrName, by: attr.name)
ignored.replace(AttrType, by: types[attr.type.techName]!)
ignoredAttrs += ignored
}
}
if ignoredAttrs.characters.count > 0{
var ignoredAttrDef = ignoredPropertiesDef
ignoredAttrDef.replace(IgnoredAttributes, by: ignoredAttrs)
content += ignoredAttrDef
}
}
//MARK: - Primary Key
func appendPrimaryKey(primaryKeyDef: String)
{
let types = lang.dataTypes.toDictionary()
for attr in entity.attributes{
if attr.isPrimaryKey{
var def = primaryKeyDef
def.replace(AttrName, by: attr.name)
def.replace(AttrType, by: types[attr.type.techName]!)
content += def
break
}
}
}
//MARK: - Index Attributes
func appendIndexedAttributes(indexAttributesDefination: String, forEachIndexedAttribute: String)
{
let types = lang.dataTypes.toDictionary()
var indexedAttrs = ""
for attr in entity.attributes{
if attr.indexed{
var indexed = forEachIndexedAttribute
indexed.replace(AttrName, by: attr.name)
indexed.replace(AttrType, by: types[attr.type.techName]!)
indexedAttrs += indexed
}
}
if indexedAttrs.characters.count > 0{
var indexedAttrDef = indexAttributesDefination
indexedAttrDef.replace(IndexedAttributes, by: indexedAttrs)
content += indexedAttrDef
}
}
//MARK: - Relationships
func appendRelationships()
{
for (index, relationship) in entity.relationships.enumerate(){
var relationshipDef = ""
if relationship.toMany{
relationshipDef = lang.toManyRelationshipDefination
}else{
relationshipDef = lang.toOneRelationshipDefination
}
relationshipDef.replace(RelationshipName, by: relationship.name)
relationshipDef.replace(RelationshipType, by: relationship.destinationName)
if lang.modelDefineInConstructor != nil{
relationshipDef.replace(Seperator, by: getSeperator(index, total: entity.relationships.count))
}
content += relationshipDef
}
}
//MARK: - Attributes
func appendAttributes()
{
let types = lang.dataTypes.toDictionary()
for (index, attr) in entity.attributes.enumerate(){
var attrDefination = ""
if lang.attributeDefinationWithDefaultValue != nil && lang.attributeDefinationWithDefaultValue.characters.count > 0 && attr.hasDefault{
attrDefination = lang.attributeDefinationWithDefaultValue
let defValue = defaultValueForAttribute(attr, types: types)
attrDefination.replace(AttrDefaultValue, by: defValue)
}else{
attrDefination = lang.attributeDefination
}
attrDefination.replace(AttrName, by: attr.name)
attrDefination.replace(AttrType, by: types[attr.type.techName]!)
var annotations = ""
if attr.isPrimaryKey{
if lang.primaryKeyAnnotation != nil{
annotations += lang.primaryKeyAnnotation
}
}
if attr.indexed{
if lang.indexAnnotaion != nil{
annotations += lang.indexAnnotaion
}
}
if attr.ignored{
if lang.ignoreAnnotaion != nil{
annotations += lang.ignoreAnnotaion
}
}
attrDefination.replace(Annotations, by: annotations)
if lang.modelDefineInConstructor != nil{
let totalItems = entity.attributes.count + entity.relationships.count
attrDefination.replace(Seperator, by: getSeperator(index, total: totalItems))
}
content += attrDefination
}
}
func getSeperator(index: Int, total: Int) -> String
{
return (index < total - 1) ? "," : ""
}
func defaultValueForAttribute(attribute: AttributeDescriptor, types: [String : String]) -> String
{
var defValue = attribute.defaultValue
if defValue == NoDefaultValue{
if let def = types["\(attribute.type.techName)DefaultValue"]{
defValue = def
}else{
defValue = ""
}
}else{
if var quoutedValue = types["\(attribute.type.techName)QuotedValue"]{
quoutedValue.replace(QuotedValue, by: attribute.defaultValue)
defValue = quoutedValue
}
}
return defValue
}
//MARK: Imports
func appendStaticImports()
{
if lang.staticImports != nil{
content += lang.staticImports
}
}
func appendRelationshipImports()
{
if lang.relationsipImports != nil{
for r in entity.relationships{
var relationshipImport = lang.relationsipImports
relationshipImport.replace(RelationshipType, by: r.destinationName)
content += relationshipImport
}
}
}
//MARK: - Copyrights
func appendCopyrights(fileName: String, fileExtension: String)
{
content += "//\n//\t\(fileName).\(fileExtension)\n"
if let me = ABAddressBook.sharedAddressBook()?.me(){
if let firstName = me.valueForProperty(kABFirstNameProperty as String) as? String{
content += "//\n//\tCreate by \(firstName)"
if let lastName = me.valueForProperty(kABLastNameProperty as String) as? String{
content += " \(lastName)"
}
}
content += " on \(getTodayFormattedDay())\n//\tCopyright © \(getYear())"
if let organization = me.valueForProperty(kABOrganizationProperty as String) as? String{
content += " \(organization)"
}
content += ". All rights reserved.\n"
}
content += "//\tModel file Generated using Realm Object Editor: https://github.com/Ahmed-Ali/RealmObjectEditor\n\n"
}
//MARK: - Package Name
func appendPackageName() {
if var package = lang.package {
package.replace(Package, by: entity.packageName!)
content += package
}
}
/**
Returns the current year as String
*/
func getYear() -> String
{
return "\(NSCalendar.currentCalendar().component(.Year, fromDate: NSDate()))"
}
/**
Returns today date in the format dd/mm/yyyy
*/
func getTodayFormattedDay() -> String
{
let components = NSCalendar.currentCalendar().components([.Day, .Month, .Year], fromDate: NSDate())
return "\(components.day)/\(components.month)/\(components.year)"
}
}
|
mit
|
9ddba8758fb86dded3afc12dda79c549
| 33.147335 | 147 | 0.575927 | 5.123236 | false | false | false | false |
tokyovigilante/CesiumKit
|
CesiumKit/Core/HeightmapTerrainData.swift
|
1
|
21889
|
//
// HeightMapTerrainData.swift
// CesiumKit
//
// Created by Ryan Walklin on 20/09/14.
// Copyright (c) 2014 Test Toast. All rights reserved.
//
import Foundation
/**
* Terrain data for a single tile where the terrain data is represented as a heightmap. A heightmap
* is a rectangular array of heights in row-major order from south to north and west to east.
*
* @alias HeightmapTerrainData
* @constructor
*
* @param {Object} options Object with the following properties:
* @param {TypedArray} options.buffer The buffer containing height data.
* @param {Number} options.width The width (longitude direction) of the heightmap, in samples.
* @param {Number} options.height The height (latitude direction) of the heightmap, in samples.
* @param {Number} [options.childTileMask=15] A bit mask indicating which of this tile's four children exist.
* If a child's bit is set, geometry will be requested for that tile as well when it
* is needed. If the bit is cleared, the child tile is not requested and geometry is
* instead upsampled from the parent. The bit values are as follows:
* <table>
* <tr><th>Bit Position</th><th>Bit Value</th><th>Child Tile</th></tr>
* <tr><td>0</td><td>1</td><td>Southwest</td></tr>
* <tr><td>1</td><td>2</td><td>Southeast</td></tr>
* <tr><td>2</td><td>4</td><td>Northwest</td></tr>
* <tr><td>3</td><td>8</td><td>Northeast</td></tr>
* </table>
* @param {Object} [options.structure] An object describing the structure of the height data.
* @param {Number} [options.structure.heightScale=1.0] The factor by which to multiply height samples in order to obtain
* the height above the heightOffset, in meters. The heightOffset is added to the resulting
* height after multiplying by the scale.
* @param {Number} [options.structure.heightOffset=0.0] The offset to add to the scaled height to obtain the final
* height in meters. The offset is added after the height sample is multiplied by the
* heightScale.
* @param {Number} [options.structure.elementsPerHeight=1] The number of elements in the buffer that make up a single height
* sample. This is usually 1, indicating that each element is a separate height sample. If
* it is greater than 1, that number of elements together form the height sample, which is
* computed according to the structure.elementMultiplier and structure.isBigEndian properties.
* @param {Number} [options.structure.stride=1] The number of elements to skip to get from the first element of
* one height to the first element of the next height.
* @param {Number} [options.structure.elementMultiplier=256.0] The multiplier used to compute the height value when the
* stride property is greater than 1. For example, if the stride is 4 and the strideMultiplier
* is 256, the height is computed as follows:
* `height = buffer[index] + buffer[index + 1] * 256 + buffer[index + 2] * 256 * 256 + buffer[index + 3] * 256 * 256 * 256`
* This is assuming that the isBigEndian property is false. If it is true, the order of the
* elements is reversed.
* @param {Boolean} [options.structure.isBigEndian=false] Indicates endianness of the elements in the buffer when the
* stride property is greater than 1. If this property is false, the first element is the
* low-order element. If it is true, the first element is the high-order element.
* @param {Boolean} [options.createdByUpsampling=false] True if this instance was created by upsampling another instance;
* otherwise, false.
*
* @see TerrainData
* @see QuantizedMeshTerrainData
*
* @example
* var buffer = ...
* var heightBuffer = new Uint16Array(buffer, 0, that._heightmapWidth * that._heightmapWidth);
* var childTileMask = new Uint8Array(buffer, heightBuffer.byteLength, 1)[0];
* var waterMask = new Uint8Array(buffer, heightBuffer.byteLength + 1, buffer.byteLength - heightBuffer.byteLength - 1);
* var terrainData = new Cesium.HeightmapTerrainData({
* buffer : heightBuffer,
* width : 65,
* height : 65,
* childTileMask : childTileMask,
* waterMask : waterMask
* });
*/
class HeightmapTerrainData: TerrainData, Equatable {
/**
* The water mask included in this terrain data, if any. A water mask is a rectangular
* Uint8Array or image where a value of 255 indicates water and a value of 0 indicates land.
* Values in between 0 and 255 are allowed as well to smoothly blend between land and water.
* @memberof TerrainData.prototype
* @type {Uint8Array|Image|Canvas}
*/
fileprivate var _buffer: [UInt16]
fileprivate let _width: Int
fileprivate let _height: Int
fileprivate let _structure: HeightmapStructure
fileprivate var _skirtHeight: Double = 0.0
fileprivate var _mesh: TerrainMesh? = nil
let waterMask: [UInt8]?
let createdByUpsampling: Bool
let childTileMask: Int
init (buffer: [UInt16],
width: Int,
height: Int,
childTileMask: Int = 15,
structure: HeightmapStructure = HeightmapStructure(),
waterMask: [UInt8]? = nil,
createdByUpsampling: Bool = false)
{
_buffer = buffer
_width = width
_height = height
self.childTileMask = childTileMask
_structure = structure
self.waterMask = waterMask
self.createdByUpsampling = createdByUpsampling
}
/**
* Creates a {@link TerrainMesh} from this terrain data.
* @function
*
* @param {TilingScheme} tilingScheme The tiling scheme to which this tile belongs.
* @param {Number} x The X coordinate of the tile for which to create the terrain data.
* @param {Number} y The Y coordinate of the tile for which to create the terrain data.
* @param {Number} level The level of the tile for which to create the terrain data.
* @param {Number} [exaggeration=1.0] The scale used to exaggerate the terrain.
* @returns {Promise|TerrainMesh} A promise for the terrain mesh, or undefined if too many
* asynchronous mesh creations are already in progress and the operation should
* be retried later.
*/
func createMesh(tilingScheme: TilingScheme, x: Int, y: Int, level: Int, exaggeration: Double = 1.0, completionBlock: (TerrainMesh?) -> ()) -> Bool {
let ellipsoid = tilingScheme.ellipsoid
let nativeRectangle = tilingScheme.tileXYToNativeRectangle(x: x, y: y, level: level)
let rectangle = tilingScheme.tileXYToRectangle(x: x, y: y, level: level)
// Compute the center of the tile for RTC rendering.
let center = ellipsoid.cartographicToCartesian(rectangle.center)
let levelZeroMaxError = EllipsoidTerrainProvider.estimatedLevelZeroGeometricErrorForAHeightmap(
ellipsoid: ellipsoid,
tileImageWidth: _width,
numberOfTilesAtLevelZero: tilingScheme.numberOfXTilesAt(level: 0))
let thisLevelMaxError = levelZeroMaxError / Double(1 << level)
_skirtHeight = min(thisLevelMaxError * 4.0, 1000.0)
let numberOfAttributes = 6
var arrayWidth = _width
var arrayHeight = _height
if _skirtHeight > 0.0 {
arrayWidth += 2
arrayHeight += 2
}
let result = HeightmapTessellator.computeVertices(
heightmap: _buffer,
height: _height,
width: _width,
skirtHeight: _skirtHeight,
nativeRectangle: nativeRectangle,
rectangle: rectangle,
isGeographic: tilingScheme is GeographicTilingScheme,
ellipsoid: ellipsoid,
structure: _structure,
relativeToCenter: center,
exaggeration: exaggeration)
let boundingSphere3D = BoundingSphere.fromVertices(result.vertices, center: center, stride: numberOfAttributes)
let orientedBoundingBox: OrientedBoundingBox?
if (rectangle.width < .pi/2 + Math.Epsilon5) {
// Here, rectangle.width < pi/2, and rectangle.height < pi
// (though it would still work with rectangle.width up to pi)
orientedBoundingBox = OrientedBoundingBox(fromRectangle: rectangle, minimumHeight: result.minimumHeight, maximumHeight: result.maximumHeight, ellipsoid: ellipsoid)
} else {
orientedBoundingBox = nil
}
let occluder = EllipsoidalOccluder(ellipsoid: ellipsoid)
let occludeePointInScaledSpace = occluder.computeHorizonCullingPointFromVertices(directionToPoint: center, vertices: result.vertices, stride: numberOfAttributes, center: center)
_mesh = TerrainMesh(
center: center,
vertices: result.vertices,
indices: EllipsoidTerrainProvider.getRegularGridIndices(width: arrayWidth, height: arrayHeight),
minimumHeight: result.minimumHeight,
maximumHeight: result.maximumHeight,
boundingSphere3D: boundingSphere3D,
occludeePointInScaledSpace: occludeePointInScaledSpace!,
orientedBoundingBox: orientedBoundingBox,
encoding: result.encoding,
exaggeration: exaggeration
)
// Free memory received from server after mesh is created.
_buffer = []
completionBlock(_mesh)
return true
}
/**
* Computes the terrain height at a specified longitude and latitude.
*
* @param {Rectangle} rectangle The rectangle covered by this terrain data.
* @param {Number} longitude The longitude in radians.
* @param {Number} latitude The latitude in radians.
* @returns {Number} The terrain height at the specified position. If the position
* is outside the rectangle, this method will extrapolate the height, which is likely to be wildly
* incorrect for positions far outside the rectangle.
*/
func interpolateHeight(_ rectangle: Rectangle, longitude: Double, latitude: Double) -> Double? {
var heightSample: Double
if let mesh = _mesh {
heightSample = interpolateMeshHeight(mesh.vertices, encoding: mesh.encoding, heightOffset: _structure.heightOffset, heightScale: _structure.heightScale, skirtHeight: _skirtHeight, sourceRectangle: rectangle, width: _width, height: _height, longitude: longitude, latitude: latitude, exaggeration: mesh.exaggeration)
} else {
heightSample = interpolateHeight2(_buffer, elementsPerHeight: _structure.elementsPerHeight, elementMultiplier: _structure.elementMultiplier, stride: _structure.stride, isBigEndian: _structure.isBigEndian, sourceRectangle: rectangle, width: _width, height: _height, longitude: longitude, latitude: latitude)
heightSample = heightSample * _structure.heightScale + _structure.heightOffset
}
return heightSample
}
/**
* Upsamples this terrain data for use by a descendant tile.
* @function
*
* @param {TilingScheme} tilingScheme The tiling scheme of this terrain data.
* @param {Number} thisX The X coordinate of this tile in the tiling scheme.
* @param {Number} thisY The Y coordinate of this tile in the tiling scheme.
* @param {Number} thisLevel The level of this tile in the tiling scheme.
* @param {Number} descendantX The X coordinate within the tiling scheme of the descendant tile for which we are upsampling.
* @param {Number} descendantY The Y coordinate within the tiling scheme of the descendant tile for which we are upsampling.
* @param {Number} descendantLevel The level within the tiling scheme of the descendant tile for which we are upsampling.
* @returns {Promise|TerrainData} A promise for upsampled terrain data for the descendant tile,
* or undefined if too many asynchronous upsample operations are in progress and the request has been
* deferred.
*/
func upsample(tilingScheme: TilingScheme, thisX: Int, thisY: Int, thisLevel: Int, descendantX: Int, descendantY: Int, descendantLevel: Int, completionBlock: (TerrainData?) -> ()) -> Bool {
let levelDifference = descendantLevel - thisLevel
assert(levelDifference == 1, "Upsampling through more than one level at a time is not currently supported")
let stride = _structure.stride
var heights = [UInt16](repeating: 0, count: _width * _height * stride)
guard let mesh = _mesh else {
return false
}
let buffer = mesh.vertices
let encoding = mesh.encoding
// PERFORMANCE_IDEA: don't recompute these rectangles - the caller already knows them.
let sourceRectangle = tilingScheme.tileXYToRectangle(x: thisX, y: thisY, level: thisLevel)
let destinationRectangle = tilingScheme.tileXYToRectangle(x: descendantX, y: descendantY, level: descendantLevel)
let heightOffset = _structure.heightOffset
let heightScale = _structure.heightScale
let exaggeration = mesh.exaggeration
let elementsPerHeight = _structure.elementsPerHeight
let elementMultiplier = _structure.elementMultiplier
let isBigEndian = _structure.isBigEndian
let divisor = pow(elementMultiplier, Double(elementsPerHeight - 1))
for j in 0..<_height {
let latitude = Math.lerp(p: destinationRectangle.north, q: destinationRectangle.south, time: Double(j) / Double(_height - 1))
for i in 0..<_width {
let longitude = Math.lerp(p: destinationRectangle.west, q: destinationRectangle.east, time: Double(i) / Double(_width - 1))
let heightSample = interpolateMeshHeight(buffer, encoding: encoding, heightOffset: heightOffset, heightScale: heightScale, skirtHeight: _skirtHeight, sourceRectangle: sourceRectangle, width: _width, height: _height, longitude: longitude, latitude: latitude, exaggeration: exaggeration)
setHeight(&heights, elementsPerHeight: elementsPerHeight, elementMultiplier: elementMultiplier, divisor: divisor, stride: stride, isBigEndian: isBigEndian, index: j * _width + i, height: heightSample)
}
}
let result = HeightmapTerrainData(
buffer: heights,
width: _width,
height: _height,
childTileMask : 0,
structure: _structure,
createdByUpsampling: true
)
completionBlock(result)
return true
}
fileprivate func interpolateHeight2(_ sourceHeights: [UInt16], elementsPerHeight: Int, elementMultiplier: Double, stride: Int, isBigEndian: Bool, sourceRectangle: Rectangle, width: Int, height: Int, longitude: Double, latitude: Double) -> Double {
let fromWest = (longitude - sourceRectangle.west) * Double(width - 1) / (sourceRectangle.east - sourceRectangle.west)
let fromSouth = (latitude - sourceRectangle.south) * Double(height - 1) / (sourceRectangle.north - sourceRectangle.south)
var westInteger = Int(floor(fromWest))
var eastInteger = westInteger + 1
if (eastInteger >= width) {
eastInteger = width - 1
westInteger = width - 2
}
var southInteger = Int(floor(fromSouth))
var northInteger = southInteger + 1
if northInteger >= height {
northInteger = height - 1
southInteger = height - 2
}
let dx = fromWest - Double(westInteger)
let dy = fromSouth - Double(southInteger)
southInteger = height - 1 - southInteger
northInteger = height - 1 - northInteger
let southwestHeight = getHeight(sourceHeights, elementsPerHeight: elementsPerHeight, elementMultiplier: elementMultiplier, stride: stride, isBigEndian: isBigEndian, index: southInteger * width + westInteger)
let southeastHeight = getHeight(sourceHeights, elementsPerHeight: elementsPerHeight, elementMultiplier: elementMultiplier, stride: stride, isBigEndian: isBigEndian, index: southInteger * width + eastInteger)
let northwestHeight = getHeight(sourceHeights, elementsPerHeight: elementsPerHeight, elementMultiplier: elementMultiplier, stride: stride, isBigEndian: isBigEndian, index: northInteger * width + westInteger)
let northeastHeight = getHeight(sourceHeights, elementsPerHeight: elementsPerHeight, elementMultiplier: elementMultiplier, stride: stride, isBigEndian: isBigEndian, index: northInteger * width + eastInteger)
return triangleInterpolateHeight(dx, dY: dy, southwestHeight: southwestHeight, southeastHeight: southeastHeight, northwestHeight: northwestHeight, northeastHeight: northeastHeight)
}
fileprivate func interpolateMeshHeight(_ buffer: [Float], encoding: TerrainEncoding, heightOffset: Double, heightScale: Double, skirtHeight: Double, sourceRectangle: Rectangle, width: Int, height: Int, longitude: Double, latitude: Double, exaggeration: Double) -> Double
{
var fromWest = (longitude - sourceRectangle.west) * Double(width - 1) / (sourceRectangle.east - sourceRectangle.west)
var fromSouth = (latitude - sourceRectangle.south) * Double(height - 1) / (sourceRectangle.north - sourceRectangle.south)
var width = width
var height = height
if skirtHeight > 0 {
fromWest += 1.0
fromSouth += 1.0
width += 2
height += 2
}
let widthEdge = skirtHeight > 0 ? width - 1 : width
var westInteger = Int(floor(fromWest))
var eastInteger = westInteger + 1
if eastInteger >= widthEdge {
eastInteger = width - 1
westInteger = width - 2
}
let heightEdge = skirtHeight > 0 ? height - 1 : height
var southInteger = Int(floor(fromSouth))
var northInteger = southInteger + 1
if northInteger >= heightEdge {
northInteger = height - 1
southInteger = height - 2
}
let dx = fromWest - Double(westInteger)
let dy = fromSouth - Double(southInteger)
southInteger = height - 1 - southInteger
northInteger = height - 1 - northInteger
let southwestHeight = (encoding.decodeHeight(buffer, index: southInteger * width + westInteger) / exaggeration - heightOffset) / heightScale
let southeastHeight = (encoding.decodeHeight(buffer, index: southInteger * width + eastInteger) / exaggeration - heightOffset) / heightScale
let northwestHeight = (encoding.decodeHeight(buffer, index: northInteger * width + westInteger) / exaggeration - heightOffset) / heightScale
let northeastHeight = (encoding.decodeHeight(buffer, index: northInteger * width + eastInteger) / exaggeration - heightOffset) / heightScale
return triangleInterpolateHeight(dx, dY: dy, southwestHeight: southwestHeight, southeastHeight: southeastHeight, northwestHeight: northwestHeight, northeastHeight: northeastHeight)
}
fileprivate func triangleInterpolateHeight(_ dX: Double, dY: Double, southwestHeight: Double, southeastHeight: Double, northwestHeight: Double, northeastHeight: Double) -> Double {
// The HeightmapTessellator bisects the quad from southwest to northeast.
if (dY < dX) {
// Lower right triangle
return southwestHeight + (dX * (southeastHeight - southwestHeight)) + (dY * (northeastHeight - southeastHeight))
}
// Upper left triangle
return southwestHeight + (dX * (northeastHeight - northwestHeight)) + (dY * (northwestHeight - southwestHeight))
}
fileprivate func getHeight(_ heights: [UInt16], elementsPerHeight: Int, elementMultiplier: Double, stride increment: Int, isBigEndian: Bool, index: Int) -> Double {
let trueIndex = index * increment
var height = 0.0
if isBigEndian {
for i in 0..<elementsPerHeight {
height = Double(height) * elementMultiplier + Double(heights[trueIndex + i])
}
} else {
for i in stride(from: (elementsPerHeight - 1), through: 0, by: -1) {
height = height * elementMultiplier + Double(heights[trueIndex + i])
}
}
return height
}
fileprivate func setHeight(_ heights: inout [UInt16], elementsPerHeight: Int, elementMultiplier: Double, divisor: Double, stride increment: Int, isBigEndian: Bool, index: Int, height: Double) {
let index = index * increment
var height = height
var divisor = divisor
if isBigEndian {
for i in 0..<elementsPerHeight {
heights[index + i] = UInt16(floor(height / divisor))
height -= Double(heights[index + i]) * divisor
divisor /= elementMultiplier
}
} else {
for i in stride(from: (elementsPerHeight - 1), through: 0, by: -1) {
heights[index + i] = UInt16(floor(height / divisor))
height -= Double(heights[index + i]) * divisor
divisor /= elementMultiplier
}
}
}
}
func ==(lhs: HeightmapTerrainData, rhs: HeightmapTerrainData) -> Bool {
return lhs === rhs
}
|
apache-2.0
|
7a2c78160e4cfd2925a2fadbb7966c49
| 49.904651 | 327 | 0.655398 | 4.530946 | false | false | false | false |
zhixingxi/JJA_Swift
|
JJA_Swift/Pods/TimedSilver/Sources/UIKit/UIScrollView+TSExtension.swift
|
1
|
3688
|
//
// UIScrollView+TSExtension.swift
// TimedSilver
// Source: https://github.com/hilen/TimedSilver
//
// Created by Hilen on 8/5/16.
// Copyright © 2016 Hilen. All rights reserved.
//
import Foundation
import UIKit
extension UIScrollView {
fileprivate struct AssociatedKeys {
static var kKeyScrollViewVerticalIndicator = "_verticalScrollIndicator"
static var kKeyScrollViewHorizontalIndicator = "_horizontalScrollIndicator"
}
/// YES if the scrollView's offset is at the very top.
public var ts_isAtTop: Bool {
get { return self.contentOffset.y == 0.0 ? true : false }
}
/// YES if the scrollView's offset is at the very bottom.
public var ts_isAtBottom: Bool {
get {
let bottomOffset = self.contentSize.height - self.bounds.size.height
return self.contentOffset.y == bottomOffset ? true : false
}
}
/// YES if the scrollView can scroll from it's current offset position to the bottom.
public var ts_canScrollToBottom: Bool {
get { return self.contentSize.height > self.bounds.size.height ? true : false }
}
/// The vertical scroll indicator view.
public var ts_verticalScroller: UIView {
get {
if (objc_getAssociatedObject(self, #function) == nil) {
objc_setAssociatedObject(self, #function, self.ts_safeValueForKey(AssociatedKeys.kKeyScrollViewVerticalIndicator), objc_AssociationPolicy.OBJC_ASSOCIATION_ASSIGN);
}
return objc_getAssociatedObject(self, #function) as! UIView
}
}
/// The horizontal scroll indicator view.
public var ts_horizontalScroller: UIView {
get {
if (objc_getAssociatedObject(self, #function) == nil) {
objc_setAssociatedObject(self, #function, self.ts_safeValueForKey(AssociatedKeys.kKeyScrollViewHorizontalIndicator), objc_AssociationPolicy.OBJC_ASSOCIATION_ASSIGN);
}
return objc_getAssociatedObject(self, #function) as! UIView
}
}
fileprivate func ts_safeValueForKey(_ key: String) -> AnyObject{
let instanceVariable: Ivar = class_getInstanceVariable(type(of: self), key.cString(using: String.Encoding.utf8)!)
return object_getIvar(self, instanceVariable) as AnyObject;
}
/**
Sets the content offset to the top.
- parameter animated: animated YES to animate the transition at a constant velocity to the new offset, NO to make the transition immediate.
*/
public func ts_scrollToTopAnimated(_ animated: Bool) {
if !self.ts_isAtTop {
let bottomOffset = CGPoint.zero;
self.setContentOffset(bottomOffset, animated: animated)
}
}
/**
Sets the content offset to the bottom.
- parameter animated: animated YES to animate the transition at a constant velocity to the new offset, NO to make the transition immediate.
*/
public func ts_scrollToBottomAnimated(_ animated: Bool) {
if self.ts_canScrollToBottom && !self.ts_isAtBottom {
let bottomOffset = CGPoint(x: 0.0, y: self.contentSize.height - self.bounds.size.height)
self.setContentOffset(bottomOffset, animated: animated)
}
}
/**
Stops scrolling, if it was scrolling.
*/
public func ts_stopScrolling() {
guard self.isDragging else {
return
}
var offset = self.contentOffset
offset.y -= 1.0
self.setContentOffset(offset, animated: false)
offset.y += 1.0
self.setContentOffset(offset, animated: false)
}
}
|
mit
|
ea0ad469531400e1f9c2d5e0295e7640
| 34.796117 | 181 | 0.646325 | 4.667089 | false | false | false | false |
jad6/DataStore
|
Example/Places/Settings.swift
|
1
|
1984
|
//
// Settings.swift
// Places
//
// Created by Jad Osseiran on 28/06/2015.
// Copyright © 2015 Jad Osseiran. All rights reserved.
//
import Foundation
var sharedSettings = Settings()
struct Settings {
enum Thread: Int {
case Main = 0, Background, Mixed
}
var thread = Thread.Main
enum DelayDuration: Int {
case None = 0
case OneSecond
case FiveSeconds
case TenSeconds
case ThirtySeconds
}
var delayDuration = DelayDuration.None
enum BatchSize: Int {
case OneItem = 1
case TwoItems
case FiveItems
case TwentyItems
case FiftyItems
case HunderdItems
}
var batchSize = BatchSize.OneItem
var atomicBatchSave = false
// Index Path Helpers
let threadSection = 0
var checkedThreadIndexPath: NSIndexPath {
let row: Int
switch thread {
case .Main:
row = 0
case .Background:
row = 1
case .Mixed:
row = 2
}
return NSIndexPath(forRow: row, inSection: 0)
}
let delaySection = 1
var checkedDelayIndexPath: NSIndexPath {
let row: Int
switch delayDuration {
case .None:
row = 0
case .OneSecond:
row = 1
case .FiveSeconds:
row = 2
case .TenSeconds:
row = 3
case .ThirtySeconds:
row = 4
}
return NSIndexPath(forRow: row, inSection: 1)
}
let batchSection = 2
var checkedBatchIndexPath: NSIndexPath {
let row: Int
switch batchSize {
case .OneItem:
row = 1
case .TwoItems:
row = 2
case .FiveItems:
row = 3
case .TwentyItems:
row = 4
case .FiftyItems:
row = 5
case .HunderdItems:
row = 6
}
return NSIndexPath(forRow: row, inSection: 2)
}
}
|
bsd-2-clause
|
9855b70b0ce7c71e38ec8526a7c94c2f
| 20.554348 | 55 | 0.533535 | 4.496599 | false | false | false | false |
ggu/Pathfinder
|
Pathfinder/views/GridView.swift
|
1
|
7099
|
//
// GridView.swift
// SimpleGridView
//
// Created by Gabriel Uribe on 11/25/15.
//
import UIKit
// handles all grid functions, might be better to think of as a GridController?
public class GridView: UIView {
// MARK: - Fields
private var grid: Grid = []
private var activeTileState: Tile.State
private var startCoordinate: Coordinate
private var targetCoordinate: Coordinate
private var path: [TileView] = []
// MARK: -
required public init?(coder aDecoder: NSCoder) {
self.activeTileState = Tile.State.start
self.startCoordinate = Coordinate(x: 3, y: 3)
self.targetCoordinate = Coordinate(x: 5, y: 7)
super.init(coder: aDecoder)
setup()
}
private func setup() {
backgroundColor = Color.margin
createGrid()
setInitialCoordinates()
}
// MARK: - Grid Methods
private func createGrid() {
var xPos = 0
var yPos = 0
let width = Int(frame.size.width)
let height = Int(frame.size.height)
for x in 0..<(width / (TILE_WIDTH + TILE_MARGIN) + 5) {
grid.append([])
for y in 0..<(height / (TILE_HEIGHT + TILE_MARGIN) + 5) {
let tileFrame = CGRectMake(CGFloat(xPos), CGFloat(yPos), CGFloat(TILE_WIDTH), CGFloat(TILE_HEIGHT))
let tile = TileView(frame: tileFrame)
tile.setCoordinate(Coordinate(x: x, y: y))
addSubview(tile)
grid[x].append(tile)
yPos += TILE_HEIGHT + TILE_MARGIN
}
yPos = 0
xPos += TILE_WIDTH + TILE_MARGIN
}
}
private func setInitialCoordinates() {
let startTile = grid[startCoordinate.x][startCoordinate.y]
toggleTileState(startTile, state: Tile.State.start)
let targetTile = grid[targetCoordinate.x][targetCoordinate.y]
toggleTileState(targetTile, state: Tile.State.target)
}
private func traverseGrid(state: Tile.State, condition: Condition, value: Any?) {
for x in grid {
for tile in x {
switch condition {
case .setAll:
toggleTileState(tile, state: state)
case .location:
if let point = value as! CGPoint? {
setTileIfPoint(tile, point: point, state: state)
}
}
}
}
}
// MARK: - Tile state methods
private func toggleTileState(tile: TileView, state: Tile.State) {
switch state {
case .new:
tile.reset()
case .target:
tile.setTarget()
case .start:
tile.setStart()
}
}
// MARK: - Touches methods
override public func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
if shouldResetGrid((event?.allTouches()?.count)!) {
traverseGrid(Tile.State.new, condition: Condition.setAll, value: nil)
} else {
for touch in touches {
if setViewIfTile(touch.view!, state: activeTileState) {
handleNewTileState(touch.view as! TileView)
}
}
}
}
override public func touchesMoved(touches: Set<UITouch>, withEvent event: UIEvent?) {
// for touch in touches {
// let location = touch.locationInView(self)
// traverseGrid(Tile.State.active, condition: Condition.location, value: location)
// }
}
override public func touchesEnded(touches: Set<UITouch>, withEvent event: UIEvent?) {
}
override public func touchesCancelled(touches: Set<UITouch>?, withEvent event: UIEvent?) {
}
// MARK: Helper methods
private func handleNewTileState(tileView: TileView) {
switch activeTileState {
case .start:
toggleTileState(tileView, state: .start)
let oldStartTile = grid[startCoordinate.x][startCoordinate.y]
toggleTileState(oldStartTile, state: Tile.State.new)
startCoordinate = tileView.getCoordinate()
break
case .target:
toggleTileState(tileView, state: .target)
let oldTargetTile = grid[targetCoordinate.x][targetCoordinate.y]
toggleTileState(oldTargetTile, state: Tile.State.new)
targetCoordinate = tileView.getCoordinate()
default:
break
}
}
internal func setTargetState() {
activeTileState = Tile.State.target
}
internal func setStartState() {
activeTileState = Tile.State.start
}
private func clearPath() {
for view in path {
if view.tile.state != Tile.State.start || view.tile.state != Tile.State.target {
view.reset()
}
}
path = []
}
internal func run() {
clearPath()
var currentPosition = startCoordinate
var nextPosition = currentPosition
let totalSteps = Int(ceil(startCoordinate.eDistance(targetCoordinate)))
for i in 0..<totalSteps {
while Double((totalSteps - i)) <= nextPosition.eDistance(targetCoordinate) {
for neighbor in getNeighbors(currentPosition) {
if neighbor.eDistance(targetCoordinate) < nextPosition.eDistance(targetCoordinate) {
nextPosition = neighbor
}
}
}
let tileView = grid[currentPosition.x][currentPosition.y]
if tileView.tile.state != Tile.State.start || tileView.tile.state != Tile.State.target {
tileView.setVisited()
}
path += [tileView]
currentPosition = nextPosition
}
}
private func getNeighbors(coordinate: Coordinate) -> [Coordinate] {
var neighbors: [Coordinate] = []
let x = coordinate.x
let y = coordinate.y
let xCount = grid.count
var gridX: [TileView]
let yNotNegative = (y - 1) >= 0
if (x + 1) < xCount {
gridX = grid[x + 1]
neighbors.append(gridX[y].coordinate)
if yNotNegative {
neighbors.append(gridX[y - 1].coordinate)
}
if (y + 1) < gridX.count {
neighbors.append(gridX[y + 1].coordinate)
}
}
if (x - 1) >= 0 {
gridX = grid[x - 1]
neighbors.append(gridX[y].coordinate)
if yNotNegative {
neighbors.append(gridX[y - 1].coordinate)
}
if (y + 1) < gridX.count {
neighbors.append(gridX[y + 1].coordinate)
}
}
gridX = grid[x]
neighbors.append(gridX[y].coordinate)
if yNotNegative {
neighbors.append(gridX[y - 1].coordinate)
}
if (y + 1) < gridX.count {
neighbors.append(gridX[y + 1].coordinate)
}
return neighbors
}
private func setTileIfPoint(tile: TileView, point: CGPoint, state: Tile.State) {
if tile.containsPoint(point) {
toggleTileState(tile, state: state)
}
}
private func setViewIfTile(view: UIView, state: Tile.State) -> Bool {
var isATileView = false
if isTileView(view) {
let tileView = view as! TileView
if tileView.tile.state == Tile.State.new {
toggleTileState(tileView, state: state)
isATileView = true
}
}
return isATileView
}
private func shouldResetGrid(numTouches: Int) -> Bool {
return numTouches > 1
}
private func isTileView(view: UIView) -> Bool {
return view.isKindOfClass(TileView)
}
}
|
mit
|
643e62835fa8ddeebded1449ec4f7f89
| 25.195572 | 107 | 0.613608 | 4.022096 | false | false | false | false |
m3rkus/Mr.Weather
|
Mr.Weather/Helper.swift
|
1
|
1175
|
//
// Helper.swift
// Mr.Weather
//
// Created by Роман Анистратенко on 14/09/2017.
// Copyright © 2017 m3rk edge. All rights reserved.
//
import Foundation
class Helper {
private static let dateFormatter = DateFormatter()
// MARK: Round Double to Int helper
static func roundToInt(_ value: Double) -> Int {
return Int(round(value))
}
// MARK: Set custom time for certain date
static func setCustom(time: (timeZone: TimeZone, hour: Int, minute: Int, second: Int), for date: Date) -> Date? {
let calendar = Calendar(identifier: .gregorian)
var components = calendar.dateComponents([.timeZone, .year, .month, .day, .hour, .minute, .second], from: date)
components.hour = time.hour
components.minute = time.minute
components.second = time.second
components.timeZone = time.timeZone
return calendar.date(from: components)
}
// MARK: Get format string of date
static func stringFrom(date: Date, format: String) -> String {
self.dateFormatter.dateFormat = format
return self.dateFormatter.string(from: date)
}
}
|
mit
|
e5b21de0ce7fe14a691502c1c963645f
| 30.27027 | 119 | 0.644771 | 4.059649 | false | false | false | false |
mcxiaoke/learning-ios
|
cocoa_programming_for_osx/30_ViewControllers/ViewControl/ViewControl/ImageViewController.swift
|
1
|
2192
|
//
// ImageViewController.swift
// ViewControl
//
// Created by mcxiaoke on 16/5/23.
// Copyright © 2016年 mcxiaoke. All rights reserved.
//
import Cocoa
class ImageViewController: NSViewController {
weak var imageView: NSImageView?
var image: NSImage?
override func loadView() {
self.view = NSView(frame: CGRectZero)
self.view.translatesAutoresizingMaskIntoConstraints = false
let imageView = NSImageView(frame:CGRectZero)
imageView.translatesAutoresizingMaskIntoConstraints = false
imageView.imageScaling = NSImageScaling.ScaleProportionallyDown
self.imageView = imageView
self.view.addSubview(imageView)
let constraint1 = NSLayoutConstraint.constraintsWithVisualFormat("H:|-[imageView]-|", options: NSLayoutFormatOptions(rawValue:0), metrics: nil, views: ["imageView":imageView])
let constraint2 = NSLayoutConstraint.constraintsWithVisualFormat("V:|-[imageView]-|", options: NSLayoutFormatOptions(rawValue:0), metrics: nil, views: ["imageView":imageView])
NSLayoutConstraint.activateConstraints(constraint1)
NSLayoutConstraint.activateConstraints(constraint2)
// let top = NSLayoutConstraint(item: imageView, attribute: NSLayoutAttribute.Top, relatedBy: NSLayoutRelation.Equal, toItem: self.view, attribute: NSLayoutAttribute.Top, multiplier: 1.0, constant: 0.0)
// let bottom = NSLayoutConstraint(item: imageView, attribute: NSLayoutAttribute.Bottom, relatedBy: NSLayoutRelation.Equal, toItem: self.view, attribute: NSLayoutAttribute.Bottom, multiplier: 1.0, constant: 0.0)
// let leading = NSLayoutConstraint(item: imageView, attribute: NSLayoutAttribute.Leading, relatedBy: NSLayoutRelation.Equal, toItem: self.view, attribute: NSLayoutAttribute.Leading, multiplier: 1.0, constant: 0.0)
// let trailing = NSLayoutConstraint(item: imageView, attribute: NSLayoutAttribute.Trailing, relatedBy: NSLayoutRelation.Equal, toItem: self.view, attribute: NSLayoutAttribute.Trailing, multiplier: 1.0, constant: 0.0)
// NSLayoutConstraint.activateConstraints([top, bottom, leading, trailing])
}
override func viewDidLoad() {
super.viewDidLoad()
self.imageView?.image = image
}
}
|
apache-2.0
|
3d345c9d38d4a476d096c098015b913b
| 51.119048 | 220 | 0.763362 | 4.897092 | false | false | false | false |
blockstack/blockstack-portal
|
native/macos/Blockstack/Pods/Swifter/Sources/HttpServer.swift
|
2
|
2524
|
//
// HttpServer.swift
// Swifter
//
// Copyright (c) 2014-2016 Damian Kołakowski. All rights reserved.
//
import Foundation
public class HttpServer: HttpServerIO {
public static let VERSION = "1.4.6"
private let router = HttpRouter()
public override init() {
self.DELETE = MethodRoute(method: "DELETE", router: router)
self.PATCH = MethodRoute(method: "PATCH", router: router)
self.HEAD = MethodRoute(method: "HEAD", router: router)
self.POST = MethodRoute(method: "POST", router: router)
self.GET = MethodRoute(method: "GET", router: router)
self.PUT = MethodRoute(method: "PUT", router: router)
self.delete = MethodRoute(method: "DELETE", router: router)
self.patch = MethodRoute(method: "PATCH", router: router)
self.head = MethodRoute(method: "HEAD", router: router)
self.post = MethodRoute(method: "POST", router: router)
self.get = MethodRoute(method: "GET", router: router)
self.put = MethodRoute(method: "PUT", router: router)
}
public var DELETE, PATCH, HEAD, POST, GET, PUT : MethodRoute
public var delete, patch, head, post, get, put : MethodRoute
public subscript(path: String) -> ((HttpRequest) -> HttpResponse)? {
set {
router.register(nil, path: path, handler: newValue)
}
get { return nil }
}
public var routes: [String] {
return router.routes();
}
public var notFoundHandler: ((HttpRequest) -> HttpResponse)?
public var middleware = Array<(HttpRequest) -> HttpResponse?>()
override public func dispatch(_ request: HttpRequest) -> ([String:String], (HttpRequest) -> HttpResponse) {
for layer in middleware {
if let response = layer(request) {
return ([:], { _ in response })
}
}
if let result = router.route(request.method, path: request.path) {
return result
}
if let notFoundHandler = self.notFoundHandler {
return ([:], notFoundHandler)
}
return super.dispatch(request)
}
public struct MethodRoute {
public let method: String
public let router: HttpRouter
public subscript(path: String) -> ((HttpRequest) -> HttpResponse)? {
set {
router.register(method, path: path, handler: newValue)
}
get { return nil }
}
}
}
|
mpl-2.0
|
35ca74b1c932d502a59d856f8c4576e0
| 32.64 | 111 | 0.585018 | 4.327616 | false | false | false | false |
kfix/MacPin
|
Sources/MacPinOSX/EffectViewController.swift
|
1
|
1246
|
import AppKit
class EffectViewController: NSViewController {
lazy var effectView: NSVisualEffectView = {
var view = NSVisualEffectView() // https://gist.github.com/vilhalmer/3052f7e9e7f34b92a40f
view.blendingMode = .behindWindow
view.material = .appearanceBased //.Dark .Light .Titlebar
// .fullScreenUI .contentBackground .windowBackground .underWindowBackground
view.state = .active // set it to always be blurry regardless of window state
view.blendingMode = .behindWindow
view.frame = NSMakeRect(0, 0, 600, 800) // default size
return view
}()
required init?(coder: NSCoder) { super.init(coder: coder) } // conform to NSCoding
override init(nibName nibNameOrNil: NSNib.Name?, bundle nibBundleOrNil: Bundle?) { super.init(nibName:nil, bundle:nil) } // calls loadView()
override func loadView() { view = effectView } // NIBless
convenience init() { self.init(nibName: nil, bundle: nil) }
override func viewDidLoad() {
view.autoresizesSubviews = true
view.autoresizingMask = [.width, .height, .minXMargin, .minYMargin, .maxXMargin, .maxYMargin]
}
// make this view intercept all hits @ sendEvent:NSEvent so we can try to shunt right-clicks to toolbar items?
// https://stackoverflow.com/a/30558497/3878712
}
|
gpl-3.0
|
87da78645dc706dae953a4829de7a24c
| 45.148148 | 141 | 0.743981 | 3.675516 | false | false | false | false |
khizkhiz/swift
|
test/NameBinding/reference-dependencies-dynamic-lookup.swift
|
2
|
1594
|
// RUN: rm -rf %t && mkdir %t
// RUN: cp %s %t/main.swift
// RUN: %target-swift-frontend(mock-sdk: %clang-importer-sdk) -parse -primary-file %t/main.swift -emit-reference-dependencies-path - > %t.swiftdeps
// RUN: FileCheck %s < %t.swiftdeps
// RUN: FileCheck -check-prefix=NEGATIVE %s < %t.swiftdeps
// REQUIRES: objc_interop
import Foundation
// CHECK-LABEL: provides-dynamic-lookup:
@objc class Base : NSObject {
// CHECK-DAG: - "foo"
func foo() {}
// CHECK-DAG: - "bar"
func bar(x: Int, y: Int) {}
// FIXME: We don't really need this twice, but de-duplicating is effort.
// CHECK-DAG: - "bar"
func bar(str: String) {}
// CHECK-DAG: - "prop"
var prop: String?
// CHECK-DAG: - "unusedProp"
var unusedProp: Int = 0
// CHECK-DAG: - "classFunc"
class func classFunc() {}
}
func getAnyObject() -> AnyObject? { return nil }
// CHECK-LABEL: depends-dynamic-lookup:
func testDynamicLookup(obj: AnyObject) {
// CHECK-DAG: - !private "foo"
obj.foo()
// CHECK-DAG: - !private "bar"
obj.bar(1, y: 2)
obj.bar("abc")
// CHECK-DAG: - !private "classFunc"
obj.dynamicType.classFunc()
// CHECK-DAG: - !private "prop"
_ = obj.prop
// CHECK-DAG: - !private "description"
_ = obj.description
// CHECK-DAG: - !private "method"
_ = obj.method(5, with: 5.0 as Double)
// CHECK-DAG: - !private "subscript"
_ = obj[2] as AnyObject
_ = obj[2] as AnyObject!
}
// CHECK-DAG: - "counter"
let globalUse = getAnyObject()?.counter
// NEGATIVE-LABEL: depends-dynamic-lookup:
// NEGATIVE-NOT: "cat1Method"
// NEGATIVE-NOT: "unusedProp"
|
apache-2.0
|
0fef7c4b18bfdc26ded61bd303ced1a2
| 23.523077 | 147 | 0.628607 | 3.059501 | false | false | false | false |
khizkhiz/swift
|
stdlib/public/core/CString.swift
|
1
|
4083
|
//===----------------------------------------------------------------------===//
//
// 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
//
//===----------------------------------------------------------------------===//
// String interop with C
//===----------------------------------------------------------------------===//
import SwiftShims
extension String {
/// Create a new `String` by copying the nul-terminated UTF-8 data
/// referenced by a `cString`.
///
/// If `cString` contains ill-formed UTF-8 code unit sequences, replaces them
/// with replacement characters (U+FFFD).
///
/// - Precondition: `cString != nil`
public init(cString: UnsafePointer<CChar>) {
_precondition(cString != nil, "cString must not be nil")
self = String.decodeCString(UnsafePointer(cString), as: UTF8.self,
repairingInvalidCodeUnits: true)!.result
}
/// Create a new `String` by copying the nul-terminated UTF-8 data
/// referenced by a `cString`.
///
/// Does not try to repair ill-formed UTF-8 code unit sequences, fails if any
/// such sequences are found.
///
/// - Precondition: `cString != nil`
public init?(validatingUTF8 cString: UnsafePointer<CChar>) {
_precondition(cString != nil, "cString must not be nil")
guard let (result, _) = String.decodeCString(
UnsafePointer(cString),
as: UTF8.self,
repairingInvalidCodeUnits: false) else {
return nil
}
self = result
}
/// Create a new `String` by copying the nul-terminated data
/// referenced by a `cString` using `encoding`.
///
/// Returns `nil` if the `cString` is `NULL` or if it contains ill-formed code
/// units and no repairing has been requested. Otherwise replaces
/// ill-formed code units with replacement characters (U+FFFD).
@warn_unused_result
public static func decodeCString<Encoding : UnicodeCodec>(
cString: UnsafePointer<Encoding.CodeUnit>,
as encoding: Encoding.Type,
repairingInvalidCodeUnits isRepairing: Bool = true)
-> (result: String, repairsMade: Bool)? {
if cString._isNull {
return nil
}
let len = Int(_swift_stdlib_strlen(UnsafePointer(cString)))
let buffer = UnsafeBufferPointer<Encoding.CodeUnit>(
start: cString, count: len)
let (stringBuffer, hadError) = _StringBuffer.fromCodeUnits(
buffer, encoding: encoding, repairIllFormedSequences: isRepairing)
return stringBuffer.map {
(result: String(_storage: $0), repairsMade: hadError)
}
}
}
/// From a non-`nil` `UnsafePointer` to a null-terminated string
/// with possibly-transient lifetime, create a null-terminated array of 'C' char.
/// Returns `nil` if passed a null pointer.
@warn_unused_result
public func _persistCString(s: UnsafePointer<CChar>) -> [CChar]? {
if s == nil {
return nil
}
let count = Int(_swift_stdlib_strlen(s))
var result = [CChar](repeating: 0, count: count + 1)
for i in 0..<count {
result[i] = s[i]
}
return result
}
extension String {
@available(*, unavailable, message="Please use String.init?(validatingUTF8:) instead. Note that it no longer accepts NULL as a valid input. Also consider using String(cString:), that will attempt to repair ill-formed code units.")
@warn_unused_result
public static func fromCString(cs: UnsafePointer<CChar>) -> String? {
fatalError("unavailable function can't be called")
}
@available(*, unavailable, message="Please use String.init(cString:) instead. Note that it no longer accepts NULL as a valid input. See also String.decodeCString if you need more control.")
@warn_unused_result
public static func fromCStringRepairingIllFormedUTF8(
cs: UnsafePointer<CChar>
) -> (String?, hadError: Bool) {
fatalError("unavailable function can't be called")
}
}
|
apache-2.0
|
147e20d1bf774dd8c8fe287e1233862d
| 36.458716 | 232 | 0.654176 | 4.438043 | false | false | false | false |
tkremenek/swift
|
test/Interpreter/class_resilience.swift
|
25
|
10453
|
// RUN: %empty-directory(%t)
// RUN: %target-build-swift-dylib(%t/%target-library-name(resilient_struct)) -enable-library-evolution %S/../Inputs/resilient_struct.swift -emit-module -emit-module-path %t/resilient_struct.swiftmodule -module-name resilient_struct
// RUN: %target-codesign %t/%target-library-name(resilient_struct)
// RUN: %target-build-swift-dylib(%t/%target-library-name(resilient_class)) -enable-library-evolution %S/../Inputs/resilient_class.swift -emit-module -emit-module-path %t/resilient_class.swiftmodule -module-name resilient_class -I%t -L%t -lresilient_struct
// RUN: %target-codesign %t/%target-library-name(resilient_class)
// RUN: %target-build-swift-dylib(%t/%target-library-name(fixed_layout_class)) -enable-library-evolution %S/../Inputs/fixed_layout_class.swift -emit-module -emit-module-path %t/fixed_layout_class.swiftmodule -module-name fixed_layout_class -I%t -L%t -lresilient_struct
// RUN: %target-codesign %t/%target-library-name(fixed_layout_class)
// RUN: %target-build-swift %s -L %t -I %t -lresilient_struct -lresilient_class -lfixed_layout_class -o %t/main %target-rpath(%t)
// RUN: %target-codesign %t/main
// RUN: %target-run %t/main %t/%target-library-name(resilient_struct) %t/%target-library-name(resilient_class) %t/%target-library-name(fixed_layout_class)
// RUN: %target-build-swift-dylib(%t/%target-library-name(resilient_struct_wmo)) -enable-library-evolution %S/../Inputs/resilient_struct.swift -emit-module -emit-module-path %t/resilient_struct.swiftmodule -module-name resilient_struct -whole-module-optimization
// RUN: %target-codesign %t/%target-library-name(resilient_struct_wmo)
// RUN: %target-build-swift-dylib(%t/%target-library-name(resilient_class_wmo)) -enable-library-evolution %S/../Inputs/resilient_class.swift -emit-module -emit-module-path %t/resilient_class.swiftmodule -module-name resilient_class -I%t -L%t -lresilient_struct_wmo -whole-module-optimization
// RUN: %target-codesign %t/%target-library-name(resilient_class_wmo)
// RUN: %target-build-swift-dylib(%t/%target-library-name(fixed_layout_class_wmo)) -enable-library-evolution %S/../Inputs/fixed_layout_class.swift -emit-module -emit-module-path %t/fixed_layout_class.swiftmodule -module-name fixed_layout_class -I%t -L%t -lresilient_struct_wmo -whole-module-optimization
// RUN: %target-codesign %t/%target-library-name(fixed_layout_class_wmo)
// RUN: %target-build-swift %s -L %t -I %t -lresilient_struct_wmo -lresilient_class_wmo -lfixed_layout_class_wmo -o %t/main2 %target-rpath(%t) -module-name main
// RUN: %target-codesign %t/main2
// RUN: %target-run %t/main2 %t/%target-library-name(resilient_struct_wmo) %t/%target-library-name(resilient_class_wmo) %t/%target-library-name(fixed_layout_class_wmo)
// REQUIRES: executable_test
import StdlibUnittest
import fixed_layout_class
import resilient_class
import resilient_struct
var ResilientClassTestSuite = TestSuite("ResilientClass")
// Concrete class with resilient stored property
protocol ProtocolWithResilientProperty {
var s: Size { get }
}
public class ClassWithResilientProperty : ProtocolWithResilientProperty {
public let p: Point
public let s: Size
public let color: Int32
public init(p: Point, s: Size, color: Int32) {
self.p = p
self.s = s
self.color = color
}
}
@inline(never) func getS(_ p: ProtocolWithResilientProperty) -> Size {
return p.s
}
ResilientClassTestSuite.test("ClassWithResilientProperty") {
let c = ClassWithResilientProperty(
p: Point(x: 10, y: 20),
s: Size(w: 30, h: 40),
color: 50)
expectEqual(c.p.x, 10)
expectEqual(c.p.y, 20)
expectEqual(c.s.w, 30)
expectEqual(c.s.h, 40)
expectEqual(c.color, 50)
// Make sure the conformance works
expectEqual(getS(c).w, 30)
expectEqual(getS(c).h, 40)
}
ResilientClassTestSuite.test("OutsideClassWithResilientProperty") {
let c = OutsideParentWithResilientProperty(
p: Point(x: 10, y: 20),
s: Size(w: 30, h: 40),
color: 50)
expectEqual(c.p.x, 10)
expectEqual(c.p.y, 20)
expectEqual(c.s.w, 30)
expectEqual(c.s.h, 40)
expectEqual(c.color, 50)
expectEqual(0, c.laziestNumber)
c.laziestNumber = 1
expectEqual(1, c.laziestNumber)
}
// Generic class with resilient stored property
public class GenericClassWithResilientProperty<T> {
public let s1: Size
public let t: T
public let s2: Size
public init(s1: Size, t: T, s2: Size) {
self.s1 = s1
self.t = t
self.s2 = s2
}
}
ResilientClassTestSuite.test("GenericClassWithResilientProperty") {
let c = GenericClassWithResilientProperty<Int32>(
s1: Size(w: 10, h: 20),
t: 30,
s2: Size(w: 40, h: 50))
expectEqual(c.s1.w, 10)
expectEqual(c.s1.h, 20)
expectEqual(c.t, 30)
expectEqual(c.s2.w, 40)
expectEqual(c.s2.h, 50)
}
// Concrete class with non-fixed size stored property
public class ClassWithResilientlySizedProperty {
public let r: Rectangle
public let color: Int32
public init(r: Rectangle, color: Int32) {
self.r = r
self.color = color
}
}
ResilientClassTestSuite.test("ClassWithResilientlySizedProperty") {
let c = ClassWithResilientlySizedProperty(
r: Rectangle(
p: Point(x: 10, y: 20),
s: Size(w: 30, h: 40),
color: 50),
color: 60)
expectEqual(c.r.p.x, 10)
expectEqual(c.r.p.y, 20)
expectEqual(c.r.s.w, 30)
expectEqual(c.r.s.h, 40)
expectEqual(c.r.color, 50)
expectEqual(c.color, 60)
}
// Concrete subclass of fixed-layout class with resilient stored property
public class ChildOfParentWithResilientStoredProperty : ClassWithResilientProperty {
let enabled: Int32
public init(p: Point, s: Size, color: Int32, enabled: Int32) {
self.enabled = enabled
super.init(p: p, s: s, color: color)
}
}
ResilientClassTestSuite.test("ChildOfParentWithResilientStoredProperty") {
let c = ChildOfParentWithResilientStoredProperty(
p: Point(x: 10, y: 20),
s: Size(w: 30, h: 40),
color: 50,
enabled: 60)
expectEqual(c.p.x, 10)
expectEqual(c.p.y, 20)
expectEqual(c.s.w, 30)
expectEqual(c.s.h, 40)
expectEqual(c.color, 50)
expectEqual(c.enabled, 60)
}
// Concrete subclass of fixed-layout class with resilient stored property
public class ChildOfOutsideParentWithResilientStoredProperty : OutsideParentWithResilientProperty {
let enabled: Int32
public init(p: Point, s: Size, color: Int32, enabled: Int32) {
self.enabled = enabled
super.init(p: p, s: s, color: color)
}
}
ResilientClassTestSuite.test("ChildOfOutsideParentWithResilientStoredProperty") {
let c = ChildOfOutsideParentWithResilientStoredProperty(
p: Point(x: 10, y: 20),
s: Size(w: 30, h: 40),
color: 50,
enabled: 60)
expectEqual(c.p.x, 10)
expectEqual(c.p.y, 20)
expectEqual(c.s.w, 30)
expectEqual(c.s.h, 40)
expectEqual(c.color, 50)
expectEqual(c.enabled, 60)
}
// Resilient class from a different resilience domain
ResilientClassTestSuite.test("ResilientOutsideParent") {
let c = ResilientOutsideParent()
expectEqual(c.property, "ResilientOutsideParent.property")
expectEqual(c.finalProperty, "ResilientOutsideParent.finalProperty")
}
// Concrete subclass of resilient class
public class ChildOfResilientOutsideParent : ResilientOutsideParent {
let enabled: Int32
public init(enabled: Int32) {
self.enabled = enabled
super.init()
}
}
ResilientClassTestSuite.test("ChildOfResilientOutsideParent") {
let c = ChildOfResilientOutsideParent(enabled: 60)
expectEqual(c.property, "ResilientOutsideParent.property")
expectEqual(c.finalProperty, "ResilientOutsideParent.finalProperty")
expectEqual(c.enabled, 60)
}
// Concrete subclass of resilient class
public class ChildOfResilientOutsideParentWithResilientStoredProperty : ResilientOutsideParent {
public let p: Point
public let s: Size
public let color: Int32
public init(p: Point, s: Size, color: Int32) {
self.p = p
self.s = s
self.color = color
super.init()
}
}
ResilientClassTestSuite.test("ChildOfResilientOutsideParentWithResilientStoredProperty") {
let c = ChildOfResilientOutsideParentWithResilientStoredProperty(
p: Point(x: 10, y: 20),
s: Size(w: 30, h: 40),
color: 50)
expectEqual(c.property, "ResilientOutsideParent.property")
expectEqual(c.finalProperty, "ResilientOutsideParent.finalProperty")
expectEqual(c.p.x, 10)
expectEqual(c.p.y, 20)
expectEqual(c.s.w, 30)
expectEqual(c.s.h, 40)
expectEqual(c.color, 50)
}
class ChildWithMethodOverride : ResilientOutsideParent {
override func getValue() -> Int {
return 1
}
}
ResilientClassTestSuite.test("ChildWithMethodOverride") {
let c = ChildWithMethodOverride()
expectEqual(c.getValue(), 1)
}
ResilientClassTestSuite.test("TypeByName") {
expectTrue(_typeByName("main.ClassWithResilientProperty")
== ClassWithResilientProperty.self)
expectTrue(_typeByName("main.ClassWithResilientlySizedProperty")
== ClassWithResilientlySizedProperty.self)
expectTrue(_typeByName("main.ChildOfParentWithResilientStoredProperty")
== ChildOfParentWithResilientStoredProperty.self)
expectTrue(_typeByName("main.ChildOfOutsideParentWithResilientStoredProperty")
== ChildOfOutsideParentWithResilientStoredProperty.self)
}
@frozen
public struct Empty {}
// rdar://48031465
public class ClassWithEmptyThenResilient {
public let empty: Empty
public let resilient: ResilientInt
public init(empty: Empty, resilient: ResilientInt) {
self.empty = empty
self.resilient = resilient
}
}
ResilientClassTestSuite.test("EmptyThenResilient") {
let c = ClassWithEmptyThenResilient(empty: Empty(),
resilient: ResilientInt(i: 17))
expectEqual(c.resilient.i, 17)
}
public class ClassWithResilientThenEmpty {
public let resilient: ResilientInt
public let empty: Empty
public init(empty: Empty, resilient: ResilientInt) {
self.empty = empty
self.resilient = resilient
}
}
ResilientClassTestSuite.test("ResilientThenEmpty") {
let c = ClassWithResilientThenEmpty(empty: Empty(),
resilient: ResilientInt(i: 17))
expectEqual(c.resilient.i, 17)
}
// This test triggers SR-815 (rdar://problem/25318716) on macOS 10.9 and iOS 7.
// Disable it for now when testing on those versions.
if #available(macOS 10.10, iOS 8, *) {
runAllTests()
} else {
runNoTests()
}
|
apache-2.0
|
e1f98ca78b9bd0bc4798e430e3694886
| 30.39039 | 303 | 0.719506 | 3.712003 | false | true | false | false |
testpress/ios-app
|
ios-app/UI/BookmarkFolderTableViewController.swift
|
1
|
5904
|
//
// BookmarkFolderTableViewController.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 Alamofire
import TTGSnackbar
import UIKit
class BookmarkFolderTableViewController:
BasePagedTableViewController<BookmarksListResponse, BookmarkFolder>, UITextFieldDelegate {
var bookmark: Bookmark!
var sourceViewController: UIViewController!
var bookmarkHelper: BookmarkHelper!
var bookmarkDelegate: BookmarkDelegate?
var selectedIndex: Int!
required init?(coder aDecoder: NSCoder) {
super.init(pager: BookmarkFolderPager(), coder: aDecoder)
}
override func viewDidLoad() {
useInterfaceBuilderSeperatorInset = true
super.viewDidLoad()
let folder = BookmarkFolder()
folder.name = BookmarkFolder.UNCATEGORIZED
(pager as! BookmarkFolderPager).resources[0] = folder
tableView.delegate = self
bookmarkHelper = BookmarkHelper(viewController: sourceViewController)
bookmarkHelper.delegate = bookmarkDelegate
}
// MARK: - Table view data source
override func tableViewCell(cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(
withIdentifier: Constants.BOOKMARK_FOLDER_TABLE_VIEW_CELL, for: indexPath)
as! BookmarkFolderTableViewCell
cell.initCell(position: indexPath.row, viewController: self)
return cell
}
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let folderName = items[indexPath.row].name
if bookmark == nil {
bookmarkHelper.bookmark(folderName: folderName)
} else if folderName != bookmark.folder {
bookmarkHelper.update(folderName: folderName, in: bookmark.id, on: sourceViewController)
} else {
hideProgressBar()
}
dismiss(animated: true)
}
override func onLoadFinished(items: [BookmarkFolder]) {
var items = items
let uncategorizedFolder = BookmarkFolder()
uncategorizedFolder.name = BookmarkFolder.UNCATEGORIZED
items.append(uncategorizedFolder)
if bookmark != nil {
for (position, folder) in items.enumerated() {
if (bookmark!.folder != nil && bookmark!.folder == folder.name) ||
(folder.name == BookmarkFolder.UNCATEGORIZED && bookmark!.folder == nil) {
selectedIndex = position
break
}
}
}
super.onLoadFinished(items: items)
if selectedIndex != nil {
let indexPath = IndexPath(row: selectedIndex, section: 0)
tableView.selectRow(at: indexPath, animated: false, scrollPosition: .none)
}
}
@IBAction func onClickAddNewFolder() {
let alert = UIAlertController(title: Strings.ENTER_FOLDER_NAME, message: nil,
preferredStyle: .alert)
alert.addTextField { (textField) in
textField.enablesReturnKeyAutomatically = true
textField.returnKeyType = .send
textField.delegate = self
}
alert.addAction(UIAlertAction(title: Strings.CANCEL, style: .cancel))
alert.addAction(UIAlertAction(
title: Strings.CREATE,
style: .default,
handler: { [weak alert] (_) in
self.createNewFolder(textField: alert!.textFields![0])
}))
present(alert, animated: true, completion: nil)
}
func createNewFolder(textField: UITextField) {
let folderName = textField.text!.trim()
if folderName == "" || (bookmark != nil && folderName == bookmark.folder) {
return
}
if bookmark != nil {
bookmarkHelper.update(folderName: folderName, in: bookmark.id,
on: sourceViewController, newFolder: true)
} else {
bookmarkHelper.bookmark(folderName: folderName)
}
dismiss(animated: true)
}
override func setEmptyText() {
emptyView.setValues(image: Images.LearnFlatIcon.image, title: Strings.NO_ITEMS_EXIST,
description: Strings.NO_CONTENT_DESCRIPTION)
}
@IBAction func goBack() {
hideProgressBar()
dismiss(animated: true)
}
func hideProgressBar() {
if bookmark != nil {
bookmarkHelper.displayMoveButton()
} else {
bookmarkHelper.displayBookmarkButton()
}
}
@nonobjc func textFieldShouldReturn(_ textField: UITextField) -> Bool {
createNewFolder(textField: textField)
return true
}
}
|
mit
|
8e73cf9683286ca8cf56ff87b8f8ead6
| 37.331169 | 100 | 0.641199 | 5.119688 | false | false | false | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.