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 |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
dusek/firefox-ios | Utils/ExtensionUtils.swift | 1 | 2873 | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
import UIKit
import MobileCoreServices
public struct ShareItem {
let url: String
let title: String?
}
protocol ShareToDestination {
func shareItem(item: ShareItem)
}
struct ExtensionUtils {
/// Small structure to encapsulate all the possible data that we can get from an application sharing a web page or a url.
/// Look through the extensionContext for a url and title. Walks over all inputItems and then over all the attachments.
/// Has a completionHandler because ultimately an XPC call to the sharing application is done.
/// We can always extract a URL and sometimes a title. The favicon is currently just a placeholder, but future code can possibly interact with a web page to find a proper icon.
static func extractSharedItemFromExtensionContext(extensionContext: NSExtensionContext?, completionHandler: (ShareItem?, NSError!) -> Void) {
if extensionContext != nil {
if let inputItems : [NSExtensionItem] = extensionContext!.inputItems as? [NSExtensionItem] {
for inputItem in inputItems {
if let attachments = inputItem.attachments as? [NSItemProvider] {
for attachment in attachments {
if attachment.hasItemConformingToTypeIdentifier(kUTTypeURL) {
attachment.loadItemForTypeIdentifier(kUTTypeURL, options: nil, completionHandler: { (obj, err) -> Void in
if err != nil {
completionHandler(nil, err)
} else {
let title = inputItem.attributedContentText?.string as String?
let url = obj as NSURL
completionHandler(ShareItem(url: url.absoluteString!, title: title), nil)
}
})
return
}
}
}
}
}
}
completionHandler(nil, nil)
}
/// Return the shared identifier to be used with for example background http requests.
/// This is in ExtensionUtils because I think we can eventually do something smart here
/// to let the extension discover this value at runtime. (It is based on the app
/// identifier, which will change for production and test builds)
///
/// :returns: the shared container identifier
static func sharedContainerIdentifier() -> String {
return "group.org.allizom.Client"
}
} | mpl-2.0 | c9bfe8f369779129d64b6b80cd52be46 | 47.711864 | 180 | 0.591716 | 5.780684 | false | false | false | false |
adamhartford/Ladybug | Ladybug iOS Demo/RequestViewController.swift | 1 | 4865 | //
// RequestViewController.swift
// Ladybug
//
// Created by Adam Hartford on 7/8/15.
// Copyright (c) 2015 Adam Hartford. All rights reserved.
//
import UIKit
import Ladybug
class RequestViewController: UITableViewController {
override func viewDidLoad() {
super.viewDidLoad()
Ladybug.baseURL = "https://httpbin.org"
let certPath = NSBundle.mainBundle().URLForResource("httpbin.org", withExtension: "cer")!.absoluteString
Ladybug.enableSSLPinning(.PublicKey, filePath: certPath, host: "httpbin.org")
// Add header for all requests
Ladybug.additionalHeaders["X-Foo"] = "Bar"
// Callback for all requests
Ladybug.willSend = { req in
req.headers["X-WillSend"] = "Foo"
}
Ladybug.beforeSend = { req in
req.setValue("Bar", forHTTPHeaderField:"X-BeforeSend")
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
tableView.deselectRowAtIndexPath(indexPath, animated: true)
switch indexPath.row {
case 0:
sendGet()
case 1:
sendPost()
case 2:
sendPut()
case 3:
sendDelete()
default:
break
}
}
func sendGet() {
Ladybug.get("/get") { [weak self] response in
print(response.json!)
self?.performSegueWithIdentifier("showResponse", sender: response)
}
}
func sendGetBasicAuth() {
Ladybug.get("/basic-auth/user/passwd") { [weak self] response in
print(response.json!)
self?.performSegueWithIdentifier("showResponse", sender: response)
}
}
func sendGetBasicAuthWithCredential() {
let credential = NSURLCredential(user: "user", password: "passwd", persistence: .Permanent)
Ladybug.get("/basic-auth/user/passwd", credential: credential) { [weak self] response in
print(response.json!)
self?.performSegueWithIdentifier("showResponse", sender: response)
}
}
func sendGetEmoji() {
🐞.get("/get") { [weak self] response in
print(response.json!)
self?.performSegueWithIdentifier("showResponse", sender: response)
}
}
func sendGetWithParams() {
let params = ["foo": "bar"]
Ladybug.get("/get", parameters: params) { [weak self] response in
print(response.json!)
self?.performSegueWithIdentifier("showResponse", sender: response)
}
}
func sendGetImage() {
Ladybug.get("/image/png") { [weak self] response in
self?.performSegueWithIdentifier("showResponse", sender: response)
}
}
func sendPost() {
let params = ["foo": "bar"]
Ladybug.post("/post", parameters: params) { [weak self] response in
print(response.json!)
self?.performSegueWithIdentifier("showResponse", sender: response)
}
}
func sendPostMultipart() {
let params = ["foo": "bar"]
let files = [
File(image: UIImage(named: "png")!, name: "mypng", fileName: "mypng", contentType: "image/png"),
File(image: UIImage(named: "jpeg")!, name: "myjpeg", fileName: "myjpeg", contentType: "image/jpeg")
]
Ladybug.post("/post", parameters: params, files: files) { [weak self] response in
self?.performSegueWithIdentifier("showResponse", sender: response)
}
}
func sendPut() {
let params = ["foo": "bar"]
Ladybug.put("/put", parameters: params) { [weak self] response in
print(response.json!)
self?.performSegueWithIdentifier("showResponse", sender: response)
}
}
func sendDelete() {
let params = ["foo": "bar"]
Ladybug.delete("/delete", parameters: params) { [weak self] response in
print(response.json!)
self?.performSegueWithIdentifier("showResponse", sender: response)
}
}
// 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?) {
let response = sender as! Response
let nav = segue.destinationViewController as! UINavigationController
let controller = nav.topViewController as! ResponseViewController
controller.response = response
if segue.identifier == "showResponseImage" {
controller.image = response.image
}
}
} | mit | 697020f3502caab91e66bba9411f79be | 31.858108 | 112 | 0.596874 | 4.931034 | false | false | false | false |
alloyapple/GooseGtk | Sources/GooseGtk/Utility.swift | 1 | 6624 | //
// Created by color on 17-10-22.
//
import Foundation
import CGTK
import Goose
internal func g_signal_connect<T>(_ instance: gpointer, _ detailed_signal: String, _ c_handler: T, _ data: gpointer) {
g_signal_connect_data((instance), (detailed_signal), unsafeBitCast(c_handler, to: GCallback.self), data, nil, GConnectFlags(0))
}
internal func g_signal_connect<T>(_ instance: gpointer, _ detailed_signal: String, _ c_handler: T) {
g_signal_connect_data((instance), (detailed_signal), unsafeBitCast(c_handler, to: GCallback.self), nil, nil, GConnectFlags(0))
}
extension Bool {
var gboolean: Int32 {
switch self {
case true:
return 1
case false:
return 0
}
}
}
public func userConfigDir() -> String {
guard let dir = g_get_user_config_dir() else {
return ""
}
return String(cString: dir)
}
var uiexecute: [UInt32: () -> ()] = [:]
let idleFunc: @convention(c) (UnsafeMutableRawPointer?) -> gboolean = { (user_data) in
print("idle")
if let user_data = user_data {
let ex = Unmanaged<ExecuteAble>.fromOpaque(user_data).takeRetainedValue()
ex.run()
//Unmanaged<Execute>.fromOpaque(user_data).release()
}
return 0
}
public func GtkASync(_ f: @escaping () -> Void) {
let ex = Execute0(cb: f)
gdk_threads_add_idle(idleFunc, Unmanaged.passRetained(ex).toOpaque())
}
public func GtkASync<T>(_ f: @escaping (T) -> Void, _ param1: T) {
let ex = Execute1(cb: f, param1: param1)
gdk_threads_add_idle(idleFunc, Unmanaged.passRetained(ex).toOpaque())
}
public func GtkASync<T1, T2>(_ f: @escaping (T1, T2) -> Void, _ param1: T1, _ param2: T2) {
let ex = Execute2(cb: f, param1: param1, param2: param2)
gdk_threads_add_idle(idleFunc, Unmanaged.passRetained(ex).toOpaque())
}
public func GtkASync<T1, T2, T3>(_ f: @escaping (T1, T2, T3) -> Void, _ param1: T1, _ param2: T2, _ param3: T3) {
let ex = Execute3(cb: f, param1: param1, param2: param2, param3: param3)
gdk_threads_add_idle(idleFunc, Unmanaged.passRetained(ex).toOpaque())
}
public func GtkASync<T1, T2, T3, T4>(_ f: @escaping (T1, T2, T3, T4) -> Void, _ param1: T1, _ param2: T2, _ param3: T3, _ param4: T4) {
let ex = Execute4(cb: f, param1: param1, param2: param2, param3: param3, param4: param4)
gdk_threads_add_idle(idleFunc, Unmanaged.passRetained(ex).toOpaque())
}
public func GtkASync<T1, T2, T3, T4, T5>(_ f: @escaping (T1, T2, T3, T4, T5) -> Void, _ param1: T1, _ param2: T2, _ param3: T3, _ param4: T4, _ param5: T5) {
let ex = Execute5(cb: f, param1: param1, param2: param2, param3: param3, param4: param4, param5: param5)
gdk_threads_add_idle(idleFunc, Unmanaged.passRetained(ex).toOpaque())
}
public func GtkASync<T1, T2, T3, T4, T5, T6>(_ f: @escaping (T1, T2, T3, T4, T5, T6) -> Void, _ param1: T1, _ param2: T2, _ param3: T3, _ param4: T4, _ param5: T5, _ param6: T6) {
let ex = Execute6(cb: f, param1: param1, param2: param2, param3: param3, param4: param4, param5: param5, param6: param6)
gdk_threads_add_idle(idleFunc, Unmanaged.passRetained(ex).toOpaque())
}
internal class ExecuteAble {
public func run() {
}
}
internal class Execute0: ExecuteAble {
let cb: () -> Void
public init(cb: @escaping () -> Void) {
self.cb = cb
}
public override func run() {
self.cb()
}
}
internal class Execute1<T>: ExecuteAble {
let cb: (T) -> Void
let param1: T
public init(cb: @escaping (T) -> (), param1: T) {
self.cb = cb
self.param1 = param1
}
public override func run() {
self.cb(self.param1)
}
deinit {
print("Execute deinit")
}
}
internal class Execute2<T1, T2>: ExecuteAble {
let cb: (T1, T2) -> Void
let param1: T1
let param2: T2
public init(cb: @escaping (T1, T2) -> Void, param1: T1, param2: T2) {
self.cb = cb
self.param1 = param1
self.param2 = param2
}
public override func run() {
self.cb(self.param1, self.param2)
}
deinit {
print("Execute deinit")
}
}
internal class Execute3<T1, T2, T3>: ExecuteAble {
let cb: (T1, T2, T3) -> Void
let param1: T1
let param2: T2
let param3: T3
public init(cb: @escaping (T1, T2, T3) -> Void, param1: T1, param2: T2, param3: T3) {
self.cb = cb
self.param1 = param1
self.param2 = param2
self.param3 = param3
}
public override func run() {
self.cb(self.param1, self.param2, self.param3)
}
deinit {
print("Execute deinit")
}
}
internal class Execute4<T1, T2, T3, T4>: ExecuteAble {
let cb: (T1, T2, T3, T4) -> Void
let param1: T1
let param2: T2
let param3: T3
let param4: T4
public init(cb: @escaping (T1, T2, T3, T4) -> Void, param1: T1, param2: T2, param3: T3, param4: T4) {
self.cb = cb
self.param1 = param1
self.param2 = param2
self.param3 = param3
self.param4 = param4
}
public override func run() {
self.cb(self.param1, self.param2, self.param3, self.param4)
}
deinit {
print("Execute deinit")
}
}
internal class Execute5<T1, T2, T3, T4, T5>: ExecuteAble {
let cb: (T1, T2, T3, T4, T5) -> Void
let param1: T1
let param2: T2
let param3: T3
let param4: T4
let param5: T5
public init(cb: @escaping (T1, T2, T3, T4, T5) -> Void, param1: T1, param2: T2, param3: T3, param4: T4, param5: T5) {
self.cb = cb
self.param1 = param1
self.param2 = param2
self.param3 = param3
self.param4 = param4
self.param5 = param5
}
public override func run() {
self.cb(self.param1, self.param2, self.param3, self.param4, self.param5)
}
deinit {
print("Execute deinit")
}
}
internal class Execute6<T1, T2, T3, T4, T5, T6>: ExecuteAble {
let cb: (T1, T2, T3, T4, T5, T6) -> Void
let param1: T1
let param2: T2
let param3: T3
let param4: T4
let param5: T5
let param6: T6
public init(cb: @escaping (T1, T2, T3, T4, T5, T6) -> Void, param1: T1, param2: T2, param3: T3, param4: T4, param5: T5, param6: T6) {
self.cb = cb
self.param1 = param1
self.param2 = param2
self.param3 = param3
self.param4 = param4
self.param5 = param5
self.param6 = param6
}
public override func run() {
self.cb(self.param1, self.param2, self.param3, self.param4, self.param5, self.param6)
}
deinit {
print("Execute deinit")
}
} | apache-2.0 | 59dbb999194308d08668d52a6d8f9015 | 25.082677 | 179 | 0.597222 | 2.927088 | false | false | false | false |
jesshmusic/MarkovAnalyzer | MarkovAnalyzer/MarkovGraph.swift | 1 | 7276 | //
// MarkovGraph.swift
// MarkovAn
//
// This will store states(chords) and the probability that they move to a different chord.
// The probabilities must always add up to 1.0
//
// Created by Jess Hendricks on 7/18/15.
// Copyright © 2015 Existential Music. All rights reserved.
//
import Cocoa
class MarkovGraph: NSObject {
private var currentChord: Chord!
private var currentProgressionChord: Chord!
private var chords = Set<Chord>()
private var chordProgression = [Chord]()
func putChord(newChord: Chord) {
self.chordProgression.append(newChord)
if self.currentChord != nil {
self.chords[self.chords.indexOf(self.currentChord)!].addChordConnection(newChord)
}
self.currentChord = self.chordProgression.last
if self.chords.contains(self.currentChord){
self.chords[self.chords.indexOf(self.currentChord)!].totalOccurences++
} else {
self.chords.insert(self.currentChord)
}
}
func generateRandomChordProgressionStartingWithChord(startChord: Chord, numberOfChords: Int) -> [Chord]? {
if !self.chords.isEmpty {
var chordList = [Chord]()
if let firstChord = self.resetRandomProgressionToChord(startChord) {
chordList.append(firstChord)
for _ in 0..<numberOfChords - 1 {
if let nextChord = self.getNext() {
chordList.append(nextChord)
}
}
return chordList
}
}
return nil
}
private func resetRandomProgressionToChord(chord: Chord) -> Chord? {
if self.chords.contains(chord) {
// print("Chord '\(chord.chordName)' found, setting to start chord.")
self.currentProgressionChord = self.chords[self.chords.indexOf(chord)!]
return self.currentProgressionChord
} else {
// print("Chord '\(chord.chordName)' NOT found.")
if self.chordProgression.count != 0 {
// print("Setting the starting chord to the first chord in the progression.")
self.currentProgressionChord = self.chords[self.chords.indexOf(self.chordProgression.first!)!]
return self.currentProgressionChord
}
}
return nil
}
private func getNext() -> Chord? {
if currentProgressionChord == nil {
if !self.chordProgression.isEmpty {
self.resetRandomProgressionToChord(self.chordProgression.first!)
return self.chords[self.chords.indexOf(self.currentProgressionChord)!]
}
} else {
if let returnChord = self.getRandomChordFromConnections(self.currentProgressionChord) {
self.currentProgressionChord = self.chords[self.chords.indexOf(returnChord)!]
return returnChord
}
}
return nil
}
private func getRandomChordFromConnections(originChord: Chord) -> Chord? {
print("\n\nChords and probabilities for next chord after \(originChord.chordName):\n")
let randomNumberRoll = Double(Double(arc4random()) / Double(UINT32_MAX))
print("Getting random chord, rolled: \(randomNumberRoll)")
var chordList = [(chord: Chord, low: Double, high: Double)]()
for chord in originChord.chordConnections {
let chordProbability = originChord.getProbabilityOfNextForChord(chord.0)
if chordList.isEmpty {
chordList.append((chord: chord.0, low: 0.0, high: chordProbability))
} else {
let previousChordProbability = chordList[chordList.count - 1].high
chordList.append((chord: chord.0, low: previousChordProbability, high: chordProbability + previousChordProbability))
}
}
for chord in chordList {
print("\(chord.chord.chordName): \(chord.low) - \(chord.high)")
}
for chord in chordList {
if chord.low <= randomNumberRoll && chord.high > randomNumberRoll {
print("Returning chord: \(chord.chord.chordName)")
return chord.chord
}
}
return nil
}
func removeChord(chord: Chord, indexInProgression: Int) {
self.chordProgression.removeAtIndex(indexInProgression)
if self.chords.contains(chord) {
// Decrement the total number of times this chord appears in the Set.
let totOcc = --self.chords[self.chords.indexOf(chord)!].totalOccurences
// If it is not the first chord, then remove the connection from the previous chord in the Set
if indexInProgression > 0 {
let previousChord = self.chordProgression[indexInProgression - 1]
self.chords[self.chords.indexOf(previousChord)!].removeChordConnection(chord)
}
// If the total number of times the chord appears is now zero, remove it from the chords Set.
if totOcc == 0 {
self.chords.remove(chord)
}
}
}
func numberOfOccurencesForChord(chord: Chord) -> Int {
if self.chords.contains(chord) {
return self.chords[self.chords.indexOf(chord)!].totalOccurences
} else {
return 0
}
}
func numberOfConnectionsForChord(chord: Chord) -> Double {
if self.chords.contains(chord) {
return self.chords[self.chords.indexOf(chord)!].totalConnections
} else {
return 0
}
}
func hasChord(chord: Chord) -> Bool {
// TODO: Checks to see if the chord is in the set
return self.chords.contains(chord)
}
func getProbabilityForChord(chord: Chord, toChord: Chord) -> Double {
return chord.getProbabilityOfNextForChord(toChord)
}
func setCurrentChordToChord(chord: Chord) -> Chord? {
for nextChord in self.chords {
if nextChord == chord {
self.currentChord = nextChord
return self.currentChord
}
}
return nil
}
func getChordProgressionCount() -> Int {
return self.chordProgression.count
}
func getUniqueChorCount() -> Int {
return self.chords.count
}
func getChordProgression() -> [Chord] {
return self.chordProgression
}
func displayChords() -> String {
var returnString = " \n---------------------------------\nChords: \n---------------------------------\n"
for nextChord in self.chords {
returnString = returnString + "\(nextChord.chordName)\tTotal Occurrences: \(nextChord.totalOccurences)\n"
for nextConnection in nextChord.chordConnections {
returnString = returnString + "\t-> \(nextConnection.0.chordName): Prob: \(nextChord.getProbabilityOfNextForChord(nextConnection.0)), total connections: \(nextConnection.1)\n"
}
returnString = returnString + "\n"
}
return returnString
}
}
| mit | fb8d7da09bc1e30899c6e7d369c27395 | 37.289474 | 191 | 0.589416 | 4.932203 | false | false | false | false |
cfilipov/MuscleBook | MuscleBook/Profiler.swift | 1 | 2710 | /*
Muscle Book
Copyright (C) 2016 Cristian Filipov
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 Darwin
struct Profiler {
private(set) static var sharedinstance = Profiler()
private(set) var traces: [String: Trace] = [:]
static func trace(title: String, @noescape _ block: Void -> Void) {
Profiler.sharedinstance.traces[title] = Trace(title: title, block: block)
}
static func trace(titleComponents: String...) -> Trace {
let title = titleComponents.joinWithSeparator(".")
let trace = Profiler.sharedinstance.traces[title] ?? Trace(title: title)
Profiler.sharedinstance.traces[title] = trace
return trace
}
struct Trace {
let title: String
let startTime: UInt64
let endTime: UInt64?
private init(title: String, @noescape block: Void -> Void) {
self.title = title
startTime = mach_absolute_time()
block()
endTime = mach_absolute_time()
}
private init(title: String, startTime: UInt64 = mach_absolute_time(), endTime: UInt64? = nil) {
self.title = title
self.startTime = startTime
self.endTime = endTime
}
var duration: CFTimeInterval {
let end = endTime ?? mach_absolute_time()
return Double(end - startTime) / 1_000_000_000
}
func start() -> Trace {
let trace = Trace(title: title)
Profiler.sharedinstance.traces[title] = trace
return trace
}
func end() -> Trace {
let trace = Trace(title: title, startTime: startTime, endTime: mach_absolute_time())
Profiler.sharedinstance.traces[title] = trace
return trace
}
}
}
extension Profiler.Trace: Comparable, Equatable { }
func ==(lhs: Profiler.Trace, rhs: Profiler.Trace) -> Bool {
return lhs.title == rhs.title && lhs.startTime == rhs.startTime && lhs.endTime == rhs.endTime
}
func <(lhs: Profiler.Trace, rhs: Profiler.Trace) -> Bool {
return lhs.startTime < rhs.startTime
}
| gpl-3.0 | 75a136f5c1561b6071aa522bbe3a1f82 | 30.882353 | 103 | 0.640959 | 4.420881 | false | false | false | false |
jovito-royeca/Decktracker | ios/old/Decktracker/View/Miscellaneous/SubtitleTableViewCell.swift | 1 | 4295 | //
// SubtitleTableViewCell.swift
// Decktracker
//
// Created by Jovit Royeca on 11/6/14.
// Copyright (c) 2014 Jovito Royeca. All rights reserved.
//
import UIKit
class SubtitleTableViewCell: UITableViewCell {
// The CGFloat type annotation is necessary for these constants because they are passed as arguments to bridged Objective-C methods,
// and without making the type explicit these will be inferred to be type Double which is not compatible.
let kLabelHorizontalInsets: CGFloat = 15.0
let kLabelVerticalInsets: CGFloat = 10.0
var didSetupConstraints = false
var titleLabel: UILabel = UILabel.newAutoLayoutView()
var bodyLabel: UILabel = UILabel.newAutoLayoutView()
override init(style: UITableViewCellStyle, reuseIdentifier: String!) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
setupViews()
}
required init(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)!
setupViews()
}
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
}
override func setSelected(selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
func setupViews()
{
titleLabel.lineBreakMode = .ByTruncatingTail
titleLabel.numberOfLines = 1
titleLabel.textAlignment = .Left
bodyLabel.lineBreakMode = .ByTruncatingTail
bodyLabel.numberOfLines = 0
bodyLabel.textAlignment = .Left
contentView.addSubview(titleLabel)
contentView.addSubview(bodyLabel)
}
override func updateConstraints()
{
if !didSetupConstraints {
// Note: if the constraints you add below require a larger cell size than the current size (which is likely to be the default size {320, 44}), you'll get an exception.
// As a fix, you can temporarily increase the size of the cell's contentView so that this does not occur using code similar to the line below.
// See here for further discussion: https://github.com/Alex311/TableCellWithAutoLayout/commit/bde387b27e33605eeac3465475d2f2ff9775f163#commitcomment-4633188
// contentView.bounds = CGRect(x: 0.0, y: 0.0, width: 99999.0, height: 99999.0)
// Prevent the two UILabels from being compressed below their intrinsic content height
// FIXME 7-Jun-14 Xcode 6b1: Apple Bug Report rdar://17220525: The UILayoutPriority enum is not compatible with Swift yet!
// As a temporary workaround, we're using the raw value of UILayoutPriorityRequired = 1000
// UIView.autoSetPriority(1000) {
// self.titleLabel.autoSetContentCompressionResistancePriorityForAxis(.Vertical)
// self.bodyLabel.autoSetContentCompressionResistancePriorityForAxis(.Vertical)
// }
titleLabel.autoPinEdgeToSuperviewEdge(.Top, withInset: kLabelVerticalInsets)
titleLabel.autoPinEdgeToSuperviewEdge(.Leading, withInset: kLabelHorizontalInsets)
titleLabel.autoPinEdgeToSuperviewEdge(.Trailing, withInset: kLabelHorizontalInsets)
// This constraint is an inequality so that if the cell is slightly taller than actually required, extra space will go here
bodyLabel.autoPinEdge(.Top, toEdge: .Bottom, ofView: titleLabel, withOffset: 10.0, relation: .GreaterThanOrEqual)
bodyLabel.autoPinEdgeToSuperviewEdge(.Leading, withInset: kLabelHorizontalInsets)
bodyLabel.autoPinEdgeToSuperviewEdge(.Trailing, withInset: kLabelHorizontalInsets)
bodyLabel.autoPinEdgeToSuperviewEdge(.Bottom, withInset: kLabelVerticalInsets)
didSetupConstraints = true
}
super.updateConstraints()
}
func updateFonts() {
if let text = bodyLabel.text {
if text.characters.count > 0 {
titleLabel.font = UIFont.preferredFontForTextStyle(UIFontTextStyleHeadline)
}
}
bodyLabel.font = UIFont.preferredFontForTextStyle(UIFontTextStyleCaption2)
}
}
| apache-2.0 | f6a105c472e2bb3561d04dcc0e8bc9fc | 41.107843 | 179 | 0.673574 | 5.520566 | false | false | false | false |
Raizlabs/BonMot | Tests/AttributedStringStyleTests.swift | 1 | 36958 | //
// StringStyleTests.swift
// BonMot
//
// Created by Brian King on 8/20/16.
// Copyright © 2016 Rightpoint. All rights reserved.
//
@testable import BonMot
import CoreText
import XCTest
//swiftlint:disable file_length
//swiftlint:disable:next type_body_length
class StringStyleTests: XCTestCase {
override func setUp() {
super.setUp()
EBGaramondLoader.loadFontIfNeeded()
}
func testBasicAssertionUtilities() {
let style = StringStyle(.font(.fontA), .color(.colorA), .backgroundColor(.colorB))
for (style, fullStyle) in additivePermutations(for: style) {
XCTAssertTrue(fullStyle == true || style.attributes.count == 3)
// We're only checking the font name and point size, since the full style could have font
// features that cause equality checks to fail. Font Feature support is tested in testFontFeatureStyle.
guard let font = style.attributes[.font] as? BONFont else {
fatalError("font was nil or of wrong type.")
}
XCTAssertEqual(font.fontName, BONFont.fontA.fontName)
XCTAssertEqual(font.pointSize, BONFont.fontA.pointSize)
BONAssert(attributes: style.attributes, key: .foregroundColor, value: BONColor.colorA)
BONAssert(attributes: style.attributes, key: .backgroundColor, value: BONColor.colorB)
}
}
#if os(iOS) || os(tvOS)
func testTextStyle() {
let style = StringStyle(.textStyle(titleTextStyle))
for (style, fullStyle) in additivePermutations(for: style) {
XCTAssertTrue(fullStyle == true || style.attributes.count == 1)
let font = style.attributes[.font] as? UIFont
let fontTextStyle = font?.textStyle
XCTAssertEqual(fontTextStyle, titleTextStyle)
}
}
#endif
func testURL() {
let url = URL(string: "http://apple.com/")!
let style = StringStyle(.link(url))
for (style, fullStyle) in additivePermutations(for: style) {
XCTAssertTrue(fullStyle == true || style.attributes.count == 1)
BONAssert(attributes: style.attributes, key: .link, value: url)
}
}
func testStrikethroughStyle() {
let style = StringStyle(.strikethrough(.byWord, .colorA))
for (style, fullStyle) in additivePermutations(for: style) {
XCTAssertTrue(fullStyle == true || style.attributes.count == 2)
BONAssert(attributes: style.attributes, key: .strikethroughStyle, value: NSUnderlineStyle.byWord.rawValue)
BONAssert(attributes: style.attributes, key: .strikethroughColor, value: BONColor.colorA)
}
}
func testUnderlineStyle() {
let style = StringStyle(.underline(.byWord, .colorA))
for (style, fullStyle) in additivePermutations(for: style) {
XCTAssertTrue(fullStyle == true || style.attributes.count == 2)
BONAssert(attributes: style.attributes, key: .underlineStyle, value: NSUnderlineStyle.byWord.rawValue)
BONAssert(attributes: style.attributes, key: .underlineColor, value: BONColor.colorA)
}
}
func testBaselineStyle() {
let style = StringStyle(.baselineOffset(15))
for (style, fullStyle) in additivePermutations(for: style) {
XCTAssertTrue(fullStyle == true || style.attributes.count == 1)
BONAssert(attributes: style.attributes, key: .baselineOffset, float: CGFloat(15), accuracy: 0.001)
}
}
func testLigatureStyle() {
let style = StringStyle(.ligatures(.disabled))
for (style, fullStyle) in additivePermutations(for: style) {
XCTAssertTrue(fullStyle == true || style.attributes.count == 1)
BONAssert(attributes: style.attributes, key: .ligature, value: 0)
}
}
#if os(iOS) || os(tvOS) || os(watchOS)
func testSpeaksPronunciationStyle() {
let style = StringStyle(.speaksPunctuation(true))
for (style, fullStyle) in additivePermutations(for: style) {
XCTAssertTrue(fullStyle == true || style.attributes.count == 1)
BONAssert(attributes: style.attributes, key: .accessibilitySpeechPunctuation, value: true)
}
}
func testSpeakingLanguageStyle() {
let style = StringStyle(.speakingLanguage("pt-BR"))
for (style, fullStyle) in additivePermutations(for: style) {
XCTAssertTrue(fullStyle == true || style.attributes.count == 1)
BONAssert(attributes: style.attributes, key: NSAttributedString.Key.accessibilitySpeechLanguage, value: "pt-BR")
}
}
func testSpeakingPitchStyle() {
let style = StringStyle(.speakingPitch(1.5))
for (style, fullStyle) in additivePermutations(for: style) {
XCTAssertTrue(fullStyle == true || style.attributes.count == 1)
BONAssert(attributes: style.attributes, key: NSAttributedString.Key.accessibilitySpeechPitch, value: 1.5)
}
}
func testPronunciationStyle() {
if #available(iOS 11, tvOS 11, watchOS 4, *) {
let style = StringStyle(.speakingPronunciation("ˈɡɪər"))
for (style, fullStyle) in additivePermutations(for: style) {
XCTAssertTrue(fullStyle == true || style.attributes.count == 1)
BONAssert(attributes: style.attributes, key: .accessibilitySpeechIPANotation, value: "ˈɡɪər")
}
}
}
func testShouldQueueSpeechAnnouncement() {
if #available(iOS 11, tvOS 11, watchOS 4, *) {
let style = StringStyle(.shouldQueueSpeechAnnouncement(true))
for (style, fullStyle) in additivePermutations(for: style) {
XCTAssertTrue(fullStyle == true || style.attributes.count == 1)
BONAssert(attributes: style.attributes, key: .accessibilitySpeechQueueAnnouncement, value: true as NSNumber)
}
}
}
func testHeadingLevel() {
if #available(iOS 11, tvOS 11, watchOS 4, *) {
let style = StringStyle(.headingLevel(.four))
for (style, fullStyle) in additivePermutations(for: style) {
XCTAssertTrue(fullStyle == true || style.attributes.count == 1)
BONAssert(attributes: style.attributes, key: .accessibilityTextHeadingLevel, value: 4 as NSNumber)
}
}
}
#endif
func testAlignmentStyle() {
let style = StringStyle(.alignment(.center))
for (style, fullStyle) in additivePermutations(for: style) {
XCTAssertTrue(fullStyle == true || style.attributes.count == 1)
BONAssert(attributes: style.attributes, query: \.alignment, value: .center)
}
}
func testNoKern() throws {
let styled = "abcd".styled(with: .color(.red))
let rangesToValuesLine = #line; let rangesToValues: [(NSRange, KernCheckingType)] = [
(NSRange(location: 0, length: 4), .none),
]
checkKerningValues(rangesToValues, startingOnLine: rangesToValuesLine, in: styled)
}
func testEffectOfAlignmentOnKerningForOneOffStrings() throws {
let styled = "abcd".styled(with: .tracking(.point(5)))
let rangesToValuesLine = #line; let rangesToValues: [(NSRange, KernCheckingType)] = [
(NSRange(location: 0, length: 3), .kern(5)),
(NSRange(location: 3, length: 1), .kernRemoved(5)),
]
checkKerningValues(rangesToValues, startingOnLine: rangesToValuesLine, in: styled)
}
func testEffectOfAlignmentOnKerningForComposedStrings() throws {
let styled = NSAttributedString.composed(of: [
"ab".styled(with: .tracking(.point(5))),
"cd".styled(with: .tracking(.point(10))),
])
let rangesToValuesLine = #line; let rangesToValues: [(NSRange, KernCheckingType)] = [
(NSRange(location: 0, length: 2), .kern(5)),
(NSRange(location: 2, length: 1), .kern(10)),
(NSRange(location: 3, length: 1), .kernRemoved(10)),
]
checkKerningValues(rangesToValues, startingOnLine: rangesToValuesLine, in: styled)
}
func testEffectOfAlignmentOnKerningForStringsComposedOfOneOffStrings() throws {
let abDefault = "ab".styled(with: .tracking(.point(5)))
let cdDefault = "cd".styled(with: .tracking(.point(10)))
let styled = NSAttributedString.composed(of: [abDefault, cdDefault])
let rangesToValuesLine = #line; let rangesToValues: [(NSRange, KernCheckingType)] = [
(NSRange(location: 0, length: 2), .kern(5)),
(NSRange(location: 2, length: 1), .kern(10)),
(NSRange(location: 3, length: 1), .kernRemoved(10)),
]
checkKerningValues(rangesToValues, startingOnLine: rangesToValuesLine, in: styled)
let abNoStrip = "ab".styled(with: .tracking(.point(5)), stripTrailingKerning: false)
let cdExplicitStrip = "cd".styled(with: .tracking(.point(10)), stripTrailingKerning: true)
let customStyled = NSAttributedString.composed(of: [abNoStrip, cdExplicitStrip])
let customRangesToValuesLine = #line; let customRangesToValues: [(NSRange, KernCheckingType)] = [
(NSRange(location: 0, length: 2), .kern(5)),
(NSRange(location: 2, length: 1), .kern(10)),
(NSRange(location: 3, length: 1), .kernRemoved(10)),
]
checkKerningValues(customRangesToValues, startingOnLine: customRangesToValuesLine, in: customStyled)
}
func testNumberSpacingStyle() {
let style = StringStyle(.font(BONFont(name: "EBGaramond12-Regular", size: 24)!), .numberSpacing(.monospaced))
for (style, fullStyle) in additivePermutations(for: style) {
XCTAssertTrue(fullStyle == true || style.attributes.count == 1)
let font = style.attributes[.font] as? BONFont
XCTAssertNotNil(font)
let fontAttributes = font?.fontDescriptor.fontAttributes
XCTAssertNotNil(fontAttributes)
let featureAttribute = fontAttributes?[BONFontDescriptorFeatureSettingsAttribute]
XCTAssertNotNil(featureAttribute)
guard let featuresArray = featureAttribute as? [[BONFontDescriptor.FeatureKey: Int]] else {
XCTFail("Failed to cast \(String(describing: featureAttribute)) as [[BONFontDescriptor.FeatureKey: Int]]")
return
}
if !fullStyle {
XCTAssertEqual(featuresArray.count, 1)
XCTAssertEqual(featuresArray[0][BONFontFeatureTypeIdentifierKey], kNumberSpacingType)
XCTAssertEqual(featuresArray[0][BONFontFeatureSelectorIdentifierKey], kMonospacedNumbersSelector)
}
}
}
func testNumberCaseStyle() {
let style = StringStyle(.font(BONFont(name: "EBGaramond12-Regular", size: 24)!), .numberCase(.lower))
for (style, fullStyle) in additivePermutations(for: style) {
XCTAssertTrue(fullStyle == true || style.attributes.count == 1)
let font = style.attributes[.font] as? BONFont
XCTAssertNotNil(font)
let fontAttributes = font?.fontDescriptor.fontAttributes
XCTAssertNotNil(fontAttributes)
let featureAttribute = fontAttributes?[BONFontDescriptorFeatureSettingsAttribute]
XCTAssertNotNil(featureAttribute)
guard let featuresArray = featureAttribute as? [[BONFontDescriptor.FeatureKey: Int]] else {
XCTFail("Failed to cast \(String(describing: featureAttribute)) as [[BONFontDescriptor.FeatureKey: Int]]")
return
}
if !fullStyle {
XCTAssertEqual(featuresArray.count, 1)
XCTAssertEqual(featuresArray[0][BONFontFeatureTypeIdentifierKey], kNumberCaseType)
XCTAssertEqual(featuresArray[0][BONFontFeatureSelectorIdentifierKey], kLowerCaseNumbersSelector)
}
}
}
func testFractionsStyle() {
let style = StringStyle(.font(BONFont(name: "EBGaramond12-Regular", size: 24)!), .fractions(.diagonal))
for (style, fullStyle) in additivePermutations(for: style) {
XCTAssertTrue(fullStyle == true || style.attributes.count == 1)
let font = style.attributes[.font] as? BONFont
XCTAssertNotNil(font)
let fontAttributes = font?.fontDescriptor.fontAttributes
XCTAssertNotNil(fontAttributes)
let featureAttribute = fontAttributes?[BONFontDescriptorFeatureSettingsAttribute]
XCTAssertNotNil(featureAttribute)
guard let featuresArray = featureAttribute as? [[BONFontDescriptor.FeatureKey: Int]] else {
XCTFail("Failed to cast \(String(describing: featureAttribute)) as [[BONFontDescriptor.FeatureKey: Int]]")
return
}
if !fullStyle {
XCTAssertEqual(featuresArray.count, 1)
XCTAssertEqual(featuresArray[0][BONFontFeatureTypeIdentifierKey], kFractionsType)
XCTAssertEqual(featuresArray[0][BONFontFeatureSelectorIdentifierKey], kDiagonalFractionsSelector)
}
}
}
func testSuperscriptStyle() {
let style = StringStyle(.font(BONFont(name: "EBGaramond12-Regular", size: 24)!), .superscript(true))
for (style, fullStyle) in additivePermutations(for: style) {
XCTAssertTrue(fullStyle == true || style.attributes.count == 1)
let font = style.attributes[.font] as? BONFont
XCTAssertNotNil(font)
let fontAttributes = font?.fontDescriptor.fontAttributes
XCTAssertNotNil(fontAttributes)
let featureAttribute = fontAttributes?[BONFontDescriptorFeatureSettingsAttribute]
XCTAssertNotNil(featureAttribute)
guard let featuresArray = featureAttribute as? [[BONFontDescriptor.FeatureKey: Int]] else {
XCTFail("Failed to cast \(String(describing: featureAttribute)) as [[BONFontDescriptor.FeatureKey: Int]]")
return
}
if !fullStyle {
XCTAssertEqual(featuresArray.count, 1)
XCTAssertEqual(featuresArray[0][BONFontFeatureTypeIdentifierKey], kVerticalPositionType)
XCTAssertEqual(featuresArray[0][BONFontFeatureSelectorIdentifierKey], kSuperiorsSelector)
}
}
}
func testSubscriptStyle() {
let style = StringStyle(.font(BONFont(name: "EBGaramond12-Regular", size: 24)!), .`subscript`(true))
for (style, fullStyle) in additivePermutations(for: style) {
XCTAssertTrue(fullStyle == true || style.attributes.count == 1)
let font = style.attributes[.font] as? BONFont
XCTAssertNotNil(font)
let fontAttributes = font?.fontDescriptor.fontAttributes
XCTAssertNotNil(fontAttributes)
let featureAttribute = fontAttributes?[BONFontDescriptorFeatureSettingsAttribute]
XCTAssertNotNil(featureAttribute)
guard let featuresArray = featureAttribute as? [[BONFontDescriptor.FeatureKey: Int]] else {
XCTFail("Failed to cast \(String(describing: featureAttribute)) as [[BONFontDescriptor.FeatureKey: Int]]")
return
}
if !fullStyle {
XCTAssertEqual(featuresArray.count, 1)
XCTAssertEqual(featuresArray[0][BONFontFeatureTypeIdentifierKey], kVerticalPositionType)
XCTAssertEqual(featuresArray[0][BONFontFeatureSelectorIdentifierKey], kInferiorsSelector)
}
}
}
func testOrdinalsStyle() {
let style = StringStyle(.font(BONFont(name: "EBGaramond12-Regular", size: 24)!), .ordinals(true))
for (style, fullStyle) in additivePermutations(for: style) {
XCTAssertTrue(fullStyle == true || style.attributes.count == 1)
let font = style.attributes[.font] as? BONFont
XCTAssertNotNil(font)
let fontAttributes = font?.fontDescriptor.fontAttributes
XCTAssertNotNil(fontAttributes)
let featureAttribute = fontAttributes?[BONFontDescriptorFeatureSettingsAttribute]
XCTAssertNotNil(featureAttribute)
guard let featuresArray = featureAttribute as? [[BONFontDescriptor.FeatureKey: Int]] else {
XCTFail("Failed to cast \(String(describing: featureAttribute)) as [[BONFontDescriptor.FeatureKey: Int]]")
return
}
if !fullStyle {
XCTAssertEqual(featuresArray.count, 1)
XCTAssertEqual(featuresArray[0][BONFontFeatureTypeIdentifierKey], kVerticalPositionType)
XCTAssertEqual(featuresArray[0][BONFontFeatureSelectorIdentifierKey], kOrdinalsSelector)
}
}
}
func testScientificInferiorsStyle() {
let style = StringStyle(.font(BONFont(name: "EBGaramond12-Regular", size: 24)!), .scientificInferiors(true))
for (style, fullStyle) in additivePermutations(for: style) {
XCTAssertTrue(fullStyle == true || style.attributes.count == 1)
let font = style.attributes[.font] as? BONFont
XCTAssertNotNil(font)
let fontAttributes = font?.fontDescriptor.fontAttributes
XCTAssertNotNil(fontAttributes)
let featureAttribute = fontAttributes?[BONFontDescriptorFeatureSettingsAttribute]
XCTAssertNotNil(featureAttribute)
guard let featuresArray = featureAttribute as? [[BONFontDescriptor.FeatureKey: Int]] else {
XCTFail("Failed to cast \(String(describing: featureAttribute)) as [[BONFontDescriptor.FeatureKey: Int]]")
return
}
if !fullStyle {
XCTAssertEqual(featuresArray.count, 1)
XCTAssertEqual(featuresArray[0][BONFontFeatureTypeIdentifierKey], kVerticalPositionType)
XCTAssertEqual(featuresArray[0][BONFontFeatureSelectorIdentifierKey], kScientificInferiorsSelector)
}
}
}
func testSmallCapsStyle() {
let style = StringStyle(.font(BONFont(name: "EBGaramond12-Regular", size: 24)!), .smallCaps(.fromUppercase))
for (style, fullStyle) in additivePermutations(for: style) {
XCTAssertTrue(fullStyle == true || style.attributes.count == 1)
let font = style.attributes[.font] as? BONFont
XCTAssertNotNil(font)
let fontAttributes = font?.fontDescriptor.fontAttributes
XCTAssertNotNil(fontAttributes)
let featureAttribute = fontAttributes?[BONFontDescriptorFeatureSettingsAttribute]
XCTAssertNotNil(featureAttribute)
guard let featuresArray = featureAttribute as? [[BONFontDescriptor.FeatureKey: Int]] else {
XCTFail("Failed to cast \(String(describing: featureAttribute)) as [[BONFontDescriptor.FeatureKey: Int]]")
return
}
if !fullStyle {
XCTAssertEqual(featuresArray.count, 1)
XCTAssertEqual(featuresArray[0][BONFontFeatureTypeIdentifierKey], kUpperCaseType)
XCTAssertEqual(featuresArray[0][BONFontFeatureSelectorIdentifierKey], kUpperCaseSmallCapsSelector)
}
}
}
func testStylisticAlternatesStyle() {
let style = StringStyle(.font(BONFont(name: "EBGaramond12-Regular", size: 24)!), .stylisticAlternates(.two(on: true)))
for (style, fullStyle) in additivePermutations(for: style) {
XCTAssertTrue(fullStyle == true || style.attributes.count == 1)
let font = style.attributes[.font] as? BONFont
XCTAssertNotNil(font)
let fontAttributes = font?.fontDescriptor.fontAttributes
XCTAssertNotNil(fontAttributes)
let featureAttribute = fontAttributes?[BONFontDescriptorFeatureSettingsAttribute]
XCTAssertNotNil(featureAttribute)
guard let featuresArray = featureAttribute as? [[BONFontDescriptor.FeatureKey: Int]] else {
XCTFail("Failed to cast \(String(describing: featureAttribute)) as [[BONFontDescriptor.FeatureKey: Int]]")
return
}
if !fullStyle {
XCTAssertEqual(featuresArray.count, 1)
XCTAssertEqual(featuresArray[0][BONFontFeatureTypeIdentifierKey], kStylisticAlternativesType)
XCTAssertEqual(featuresArray[0][BONFontFeatureSelectorIdentifierKey], kStylisticAltTwoOnSelector)
}
}
}
func testContextualAlternatesStyle() {
let style = StringStyle(.font(BONFont(name: "EBGaramond12-Regular", size: 24)!), .contextualAlternates(.contextualAlternates(on: false)))
for (style, fullStyle) in additivePermutations(for: style) {
XCTAssertTrue(fullStyle == true || style.attributes.count == 1)
let font = style.attributes[.font] as? BONFont
XCTAssertNotNil(font)
let fontAttributes = font?.fontDescriptor.fontAttributes
XCTAssertNotNil(fontAttributes)
let featureAttribute = fontAttributes?[BONFontDescriptorFeatureSettingsAttribute]
XCTAssertNotNil(featureAttribute)
guard let featuresArray = featureAttribute as? [[BONFontDescriptor.FeatureKey: Int]] else {
XCTFail("Failed to cast \(String(describing: featureAttribute)) as [[BONFontDescriptor.FeatureKey: Int]]")
return
}
if !fullStyle {
XCTAssertEqual(featuresArray.count, 1)
XCTAssertEqual(featuresArray[0][BONFontFeatureTypeIdentifierKey], kContextualAlternatesType)
XCTAssertEqual(featuresArray[0][BONFontFeatureSelectorIdentifierKey], kContextualAlternatesOffSelector)
}
}
}
func testFontFeatureStyle() {
let featuresLine: UInt = #line; let features: [FontFeatureProvider] = [
NumberCase.upper,
NumberCase.lower,
NumberSpacing.proportional,
NumberSpacing.monospaced,
VerticalPosition.superscript,
VerticalPosition.`subscript`,
VerticalPosition.ordinals,
VerticalPosition.scientificInferiors,
SmallCaps.fromUppercase,
SmallCaps.fromLowercase,
StylisticAlternates.six(on: true),
]
for (index, feature) in features.enumerated() {
let featureLine = featuresLine + UInt(index) + 1
let attributes = StringStyle(.font(BONFont(name: "EBGaramond12-Regular", size: 24)!), .fontFeature(feature)).attributes
XCTAssertEqual(attributes.count, 1, line: featureLine)
let font = attributes[.font] as? BONFont
XCTAssertNotNil(font, line: featureLine)
let fontAttributes = font?.fontDescriptor.fontAttributes
XCTAssertNotNil(fontAttributes, line: featureLine)
let featureAttribute = fontAttributes?[BONFontDescriptorFeatureSettingsAttribute]
XCTAssertNotNil(featureAttribute, line: featureLine)
}
}
func testAdditiveFontFeatures() {
let string = "0<one>1<two>2</two></one>"
let font = BONFont(name: "EBGaramond12-Regular", size: 24)!
let rules: [XMLStyleRule] = [
.style("one", StringStyle(.stylisticAlternates(.two(on: true)), .stylisticAlternates(.six(on: true)), .smallCaps(.fromLowercase))),
.style("two", StringStyle(.stylisticAlternates(.five(on: true)), .stylisticAlternates(.six(on: false)), .smallCaps(.disabled))),
]
let attributed = string.styled(with: .font(font), .xmlRules(rules))
XCTAssertEqual(attributed.string, "012")
let attrs0 = attributed.attributes(at: 0, effectiveRange: nil)
let attrs1 = attributed.attributes(at: 1, effectiveRange: nil)
let attrs2 = attributed.attributes(at: 2, effectiveRange: nil)
guard let font0 = attrs0[.font] as? BONFont else { XCTFail("font0 not found"); return }
guard let font1 = attrs1[.font] as? BONFont else { XCTFail("font1 not found"); return }
guard let font2 = attrs2[.font] as? BONFont else { XCTFail("font2 not found"); return }
let descriptor0 = font0.fontDescriptor
let descriptor1 = font1.fontDescriptor
let descriptor2 = font2.fontDescriptor
let descriptorAttrs0 = descriptor0.fontAttributes
let descriptorAttrs1 = descriptor1.fontAttributes
let descriptorAttrs2 = descriptor2.fontAttributes
XCTAssertNil(descriptorAttrs0[BONFontDescriptorFeatureSettingsAttribute])
guard let featuresArray1 = descriptorAttrs1[BONFontDescriptorFeatureSettingsAttribute] as? [[String: Any]] else {
XCTFail("Failed to convert to \([[String: Any]].self)")
return
}
guard let featuresArray2 = descriptorAttrs2[BONFontDescriptorFeatureSettingsAttribute] as? [[String: Any]] else {
XCTFail("Failed to convert to \([[String: Any]].self)")
return
}
XCTAssertEqual(featuresArray1.count, 3)
XCTAssertEqual(featuresArray2.count, 2)
let hasAltTwoDict = featuresArray1.contains { dictionary in
dictionary[kCTFontFeatureTypeIdentifierKey as String] as? Int == kStylisticAlternativesType
&& dictionary[kCTFontFeatureSelectorIdentifierKey as String] as? Int == kStylisticAltTwoOnSelector
}
XCTAssertTrue(hasAltTwoDict)
let hasAltSixDict = featuresArray1.contains { dictionary in
dictionary[kCTFontFeatureTypeIdentifierKey as String] as? Int == kStylisticAlternativesType
&& dictionary[kCTFontFeatureSelectorIdentifierKey as String] as? Int == kStylisticAltSixOnSelector
}
XCTAssertTrue(hasAltSixDict)
let hasSmallCapsFromLowercaseDict = featuresArray1.contains { dictionary in
dictionary[kCTFontFeatureTypeIdentifierKey as String] as? Int == kLowerCaseType
&& dictionary[kCTFontFeatureSelectorIdentifierKey as String] as? Int == kLowerCaseSmallCapsSelector
}
XCTAssertTrue(hasSmallCapsFromLowercaseDict)
let array2StillHasAltTwoDict = featuresArray2.contains { dictionary in
dictionary[kCTFontFeatureTypeIdentifierKey as String] as? Int == kStylisticAlternativesType
&& dictionary[kCTFontFeatureSelectorIdentifierKey as String] as? Int == kStylisticAltTwoOnSelector
}
XCTAssertTrue(array2StillHasAltTwoDict)
let hasAltFiveDict = featuresArray2.contains { dictionary in
dictionary[kCTFontFeatureTypeIdentifierKey as String] as? Int == kStylisticAlternativesType
&& dictionary[kCTFontFeatureSelectorIdentifierKey as String] as? Int == kStylisticAltFiveOnSelector
}
XCTAssertTrue(hasAltFiveDict)
let stillHasAltSixDict = featuresArray2.contains { dictionary in
dictionary[kCTFontFeatureTypeIdentifierKey as String] as? Int == kStylisticAlternativesType
&& (dictionary[kCTFontFeatureSelectorIdentifierKey as String] as? Int == kStylisticAltSixOnSelector
|| dictionary[kCTFontFeatureSelectorIdentifierKey as String] as? Int == kStylisticAltSixOffSelector)
}
XCTAssertFalse(stillHasAltSixDict)
}
static let floatingPointPropertiesLine = #line
static let floatingPointProperties: [(NSParagraphStyle) -> CGFloat] = [
//swiftlint:disable opening_brace
\.lineSpacing,
\.paragraphSpacing,
\.headIndent,
\.tailIndent,
\.firstLineHeadIndent,
\.minimumLineHeight,
\.maximumLineHeight,
\.lineHeightMultiple,
\.paragraphSpacingBefore,
{ CGFloat($0.hyphenationFactor) },
//swiftlint:enable opening_brace
]
func testParagraphStyles() {
let style = StringStyle(
.lineSpacing(10),
.paragraphSpacingAfter(10),
.alignment(.center),
.firstLineHeadIndent(10),
.headIndent(10),
.tailIndent(10),
.lineBreakMode(.byClipping),
.minimumLineHeight(10),
.maximumLineHeight(10),
.baseWritingDirection(.leftToRight),
.lineHeightMultiple(10),
.paragraphSpacingBefore(10),
.hyphenationFactor(10),
.allowsDefaultTighteningForTruncation(true)
)
for (index, check) in StringStyleTests.floatingPointProperties.enumerated() {
let line = UInt(StringStyleTests.floatingPointPropertiesLine + 2 + index)
BONAssert(attributes: style.attributes, query: check, float: 10, accuracy: 0.001, line: line)
}
BONAssert(attributes: style.attributes, query: \.alignment, value: .center)
BONAssert(attributes: style.attributes, query: \.lineBreakMode, value: .byClipping)
BONAssert(attributes: style.attributes, query: \.baseWritingDirection, value: .leftToRight)
BONAssert(attributes: style.attributes, query: \.allowsDefaultTighteningForTruncation, value: true)
}
func testParagraphStyleAdd() {
var style = StringStyle(
.lineSpacing(1),
.paragraphSpacingAfter(1),
.alignment(.left),
.firstLineHeadIndent(1),
.headIndent(1),
.tailIndent(1),
.lineBreakMode(.byWordWrapping),
.minimumLineHeight(1),
.maximumLineHeight(1),
.baseWritingDirection(.natural),
.lineHeightMultiple(1),
.paragraphSpacingBefore(1),
.hyphenationFactor(1),
.allowsDefaultTighteningForTruncation(false)
)
style.add(stringStyle: StringStyle(
.lineSpacing(10),
.paragraphSpacingAfter(10),
.alignment(.center),
.firstLineHeadIndent(10),
.headIndent(10),
.tailIndent(10),
.lineBreakMode(.byClipping),
.minimumLineHeight(10),
.maximumLineHeight(10),
.baseWritingDirection(.leftToRight),
.lineHeightMultiple(10),
.paragraphSpacingBefore(10),
.hyphenationFactor(10),
.allowsDefaultTighteningForTruncation(true)
))
for (index, check) in StringStyleTests.floatingPointProperties.enumerated() {
let line = UInt(StringStyleTests.floatingPointPropertiesLine + 2 + index)
BONAssert(attributes: style.attributes, query: check, float: 10, accuracy: 0.001, line: line)
}
BONAssert(attributes: style.attributes, query: \.alignment, value: .center)
BONAssert(attributes: style.attributes, query: \.lineBreakMode, value: .byClipping)
BONAssert(attributes: style.attributes, query: \.baseWritingDirection, value: .leftToRight)
BONAssert(attributes: style.attributes, query: \.allowsDefaultTighteningForTruncation, value: true)
}
func testAdobeTracking() {
let style = StringStyle(.tracking(.adobe(300)))
for (style, _) in additivePermutations(for: style) {
let testKernAttribute = { (fontSize: CGFloat) -> CGFloat in
let font = BONFont(name: "Avenir-Book", size: fontSize)!
let newStyle = style.byAdding(.font(font))
return newStyle.attributes[.kern] as? CGFloat ?? 0
}
XCTAssertEqual(testKernAttribute(20), 6, accuracy: 0.0001)
XCTAssertEqual(testKernAttribute(30), 9, accuracy: 0.0001)
XCTAssertEqual(testKernAttribute(40), 12, accuracy: 0.0001)
XCTAssertEqual(testKernAttribute(50), 15, accuracy: 0.0001)
}
}
func testPointTracking() {
let style = StringStyle(.tracking(.point(10)))
for (style, _) in additivePermutations(for: style) {
let testKernAttribute = { (fontSize: CGFloat) -> CGFloat in
let font = BONFont(name: "Avenir-Book", size: fontSize)!
let newStyle = style.byAdding(.font(font))
return newStyle.attributes[.kern] as? CGFloat ?? 0
}
XCTAssertEqual(testKernAttribute(20), 10, accuracy: 0.0001)
XCTAssertEqual(testKernAttribute(30), 10, accuracy: 0.0001)
XCTAssertEqual(testKernAttribute(40), 10, accuracy: 0.0001)
XCTAssertEqual(testKernAttribute(50), 10, accuracy: 0.0001)
}
}
/// Return the result of various additive operations with the passed style:
/// - parameter for: the style to check
/// - returns: The additive style permutations:
/// - the passed style
/// - an empty style that is updated by the passed style object
/// - a fully populated style object that is updated by the passed style object
func additivePermutations(for style: StringStyle) -> [(style: StringStyle, fullStyle: Bool)] {
var emptyStyle = StringStyle()
emptyStyle.add(stringStyle: style)
var updated = fullStyle
updated.add(stringStyle: style)
return [(style: style, fullStyle: false), (style: emptyStyle, fullStyle: false), (style: updated, fullStyle: true)]
}
func testStyleStylePart() {
let baseStyle = StringStyle(.font(.fontA), .color(.colorA), .backgroundColor(.colorB))
let style = StringStyle(.style(baseStyle), .font(.fontB), .color(.colorB))
let font = style.attributes[.font] as? BONFont
XCTAssertEqual(font?.fontName, BONFont.fontB.fontName)
XCTAssertEqual(font?.pointSize, BONFont.fontB.pointSize)
BONAssert(attributes: style.attributes, key: .foregroundColor, value: BONColor.colorB)
BONAssert(attributes: style.attributes, key: .backgroundColor, value: BONColor.colorB)
}
func testOverridingProperties() {
// Parent style is white with font A
let parentStyle = StringStyle(.font(.fontA), .color(.white))
BONAssertEqualFonts(parentStyle.font!, .fontA)
XCTAssertEqual(parentStyle.color, .white)
let parentAttributedString = "foo".styled(with: parentStyle)
// Child style is black with font A
let childStyle = parentStyle.byAdding(.color(.black))
BONAssertEqualFonts(childStyle.font!, .fontA)
XCTAssertEqual(childStyle.color, .black)
let childAttributedString = parentAttributedString.styled(with: childStyle)
let childAttributes = childAttributedString.attributes(at: 0, effectiveRange: nil)
if let childFont = childAttributes[.font] as? BONFont {
BONAssertEqualFonts(childFont, .fontA)
}
else {
XCTFail("Font should not be nil")
}
// Child attributes should be overridden with black font
BONAssert(attributes: childAttributes, key: .foregroundColor, value: BONColor.black)
}
}
private extension StringStyleTests {
enum KernCheckingType {
case none
case kern(Double)
case kernRemoved(Double)
}
func checkKerningValues(_ rangesToValues: [(NSRange, KernCheckingType)], startingOnLine rangesToValuesLine: Int, in string: NSAttributedString) {
for (index, rangeToValue) in rangesToValues.enumerated() {
let line = UInt(rangesToValuesLine + index + 1)
let (controlRange, checkingType) = rangeToValue
let trackingValue = string.attribute(.kern, at: controlRange.location, effectiveRange: nil)
let trackingRemovedValue = string.attribute(.bonMotRemovedKernAttribute, at: controlRange.location, effectiveRange: nil)
switch checkingType {
case .none:
XCTAssertNil(trackingValue, line: line)
XCTAssertNil(trackingRemovedValue, line: line)
case .kern(let kernValue):
guard let trackingValueNumber = trackingValue as? NSNumber else {
XCTFail("Unable to unwrap tracking value \(String(describing: trackingValue)) as Double", line: line)
return
}
XCTAssertEqual(kernValue, trackingValueNumber.doubleValue, accuracy: 0.0001, line: line)
XCTAssertNil(trackingRemovedValue, line: line)
case .kernRemoved(let kernRemovedValue):
guard let trackingRemovedValueNumber = trackingRemovedValue as? NSNumber else {
XCTFail("Unable to unwrap tracking removed value \(String(describing: trackingValue)) as Double", line: line)
return
}
XCTAssertEqual(kernRemovedValue, trackingRemovedValueNumber.doubleValue, accuracy: 0.0001, line: line)
XCTAssertNil(trackingValue, line: line)
}
}
}
}
//swiftlint:enable file_length
| mit | 676474296a435477e95dd62da8afdf40 | 46.923476 | 149 | 0.647514 | 5.343312 | false | true | false | false |
RoverPlatform/rover-ios | Sources/Foundation/Container/Resolver.swift | 1 | 3698 | //
// Resolver.swift
// RoverFoundation
//
// Created by Sean Rucker on 2017-09-15.
// Copyright © 2017 Rover Labs Inc. All rights reserved.
//
public protocol Resolver: AnyObject {
func entry<Service>(for key: ServiceKey) -> ServiceEntry<Service>?
}
extension Resolver {
public func resolve<Service>(_ serviceType: Service.Type) -> Service? {
return resolve(serviceType, name: nil)
}
public func resolve<Service, Arg1>(_ serviceType: Service.Type, arguments arg1: Arg1) -> Service? {
return resolve(serviceType, name: nil, arguments: arg1)
}
public func resolve<Service, Arg1, Arg2>(_ serviceType: Service.Type, arguments arg1: Arg1, _ arg2: Arg2) -> Service? {
return resolve(serviceType, name: nil, arguments: arg1, arg2)
}
public func resolve<Service, Arg1, Arg2, Arg3>(_ serviceType: Service.Type, arguments arg1: Arg1, _ arg2: Arg2, _ arg3: Arg3) -> Service? {
return resolve(serviceType, name: nil, arguments: arg1, arg2, arg3)
}
public func resolve<Service, Arg1, Arg2, Arg3, Arg4>(_ serviceType: Service.Type, arguments arg1: Arg1, _ arg2: Arg2, _ arg3: Arg3, _ arg4: Arg4) -> Service? {
return resolve(serviceType, name: nil, arguments: arg1, arg2, arg3, arg4)
}
public func resolve<Service>(_ serviceType: Service.Type, name: String?) -> Service? {
typealias Factory = (Resolver) -> Service
return _resolve(name: name) { (factory: Factory) -> Service in factory(self) }
}
public func resolve<Service, Arg1>(_ serviceType: Service.Type, name: String?, arguments arg1: Arg1) -> Service? {
typealias Factory = (Resolver, Arg1) -> Service
return _resolve(name: name) { (factory: Factory) -> Service in factory(self, arg1) }
}
public func resolve<Service, Arg1, Arg2>(_ serviceType: Service.Type, name: String?, arguments arg1: Arg1, _ arg2: Arg2) -> Service? {
typealias Factory = (Resolver, Arg1, Arg2) -> Service
return _resolve(name: name) { (factory: Factory) -> Service in factory(self, arg1, arg2) }
}
public func resolve<Service, Arg1, Arg2, Arg3>(_ serviceType: Service.Type, name: String?, arguments arg1: Arg1, _ arg2: Arg2, _ arg3: Arg3) -> Service? {
typealias Factory = (Resolver, Arg1, Arg2, Arg3) -> Service
return _resolve(name: name) { (factory: Factory) -> Service in factory(self, arg1, arg2, arg3) }
}
// These functions use explicitly rolled out 'varargs', so in this case the parameter count is reasonable, so silence the param count warning.
// swiftlint:disable:next function_parameter_count
public func resolve<Service, Arg1, Arg2, Arg3, Arg4>(_ serviceType: Service.Type, name: String?, arguments arg1: Arg1, _ arg2: Arg2, _ arg3: Arg3, _ arg4: Arg4) -> Service? {
typealias Factory = (Resolver, Arg1, Arg2, Arg3, Arg4) -> Service
return _resolve(name: name) { (factory: Factory) -> Service in factory(self, arg1, arg2, arg3, arg4) }
}
func _resolve<Service, Factory>(name: String?, invoker: (Factory) -> Service) -> Service? {
let key = ServiceKey(factoryType: Factory.self, name: name)
guard let entry: ServiceEntry<Service> = entry(for: key), let factory = entry.factory as? Factory else {
return nil
}
if entry.scope == .transient {
return invoker(factory)
}
if let persistedInstance = entry.instance {
return persistedInstance
}
let resolvedInstance = invoker(factory)
entry.instance = resolvedInstance
return resolvedInstance
}
}
| apache-2.0 | a905d30ab05ec98c553c2ec14355f6de | 45.2125 | 178 | 0.639708 | 3.851042 | false | false | false | false |
ztory/blockbased-delegates-ios | Example/Tests/WebViewBlockDelegateTests.swift | 1 | 3591 | //
// WebViewBlockDelegateTests.swift
// blockbased-delegates
//
// Created by Christian Rönningen on 25/08/16.
// Copyright © 2016 CocoaPods. All rights reserved.
//
import XCTest
import UIKit
@testable import blockbased_delegates_ios
class WebViewBlockDelegateTests: XCTestCase {
var sut: BlockWebViewDelegate!
var webView: UIWebView!
override func setUp() {
super.setUp()
// Put setup code here. This method is called before the invocation of each test method in the class.
sut = BlockWebViewDelegate()
webView = UIWebView()
webView.blockDelegate = sut
}
override func tearDown() {
// Put teardown code here. This method is called after the invocation of each test method in the class.
super.tearDown()
}
func test_blockdelegate_should_be_nil() {
var web: UIWebView? = UIWebView()
var blockD: BlockWebViewDelegate? = BlockWebViewDelegate()
web!.blockDelegate = blockD
weak var weakBlockDelegate = blockD
XCTAssertNotNil(weakBlockDelegate)
blockD = nil
web!.blockDelegate = nil
web = nil
XCTAssertNil(weakBlockDelegate)
}
func test_delegate_has_been_set() {
if let delegate = webView.delegate as? BlockWebViewDelegate {
XCTAssertEqual(delegate, sut)
} else {
XCTFail("Wrong or no delegate set")
}
}
func test_webview_did_start_load() {
var callbackCalled = false
sut.webViewDidStartLoadBlock = { (webView) in
XCTAssertEqual(webView, self.webView)
callbackCalled = true
}
webView.delegate!.webViewDidStartLoad!(webView)
XCTAssertTrue(callbackCalled)
}
func test_webview_did_finish_load() {
var callbackCalled = false
sut.webViewDidFinishLoadBlock = { (webView) in
XCTAssertEqual(webView, self.webView)
callbackCalled = true
}
webView.delegate!.webViewDidFinishLoad!(webView)
XCTAssertTrue(callbackCalled)
}
func test_webview_did_fail_load_with_error() {
var callbackCalled = false
let inputError = NSError(domain: "", code: 1, userInfo: nil)
sut.webViewDidFailLoadWithErrorBlock = { (webView, error) in
XCTAssertEqual(webView, self.webView)
XCTAssertEqual(error, inputError)
callbackCalled = true
}
webView.delegate!.webView!(webView, didFailLoadWithError: inputError)
XCTAssertTrue(callbackCalled)
}
func test_webview_should_start_load_with_request() {
var callbackCalled = false
let inputRequest = NSURLRequest()
let inputNavigationType = UIWebViewNavigationType.Reload
let defaultValue = webView.delegate!.webView!(webView, shouldStartLoadWithRequest: inputRequest, navigationType: inputNavigationType)
XCTAssertTrue(defaultValue)
sut.webViewShouldStartLoadWithRequestBlock = { (webView, request, navigationType) in
XCTAssertEqual(webView, self.webView)
XCTAssertEqual(request, inputRequest)
XCTAssertEqual(navigationType, inputNavigationType)
callbackCalled = true
return false
}
let blockValue = webView.delegate!.webView!(webView, shouldStartLoadWithRequest: inputRequest, navigationType: inputNavigationType)
XCTAssertFalse(blockValue)
XCTAssertTrue(callbackCalled)
}
}
| mit | a6a89ee11b6476527cc09bc7be37bdb3 | 27.039063 | 141 | 0.644191 | 5.239416 | false | true | false | false |
matsprea/omim | iphone/Maps/Core/Ads/Mopub/MopubBanner.swift | 1 | 5191 | import MoPub_FacebookAudienceNetwork_Adapters
final class MopubBanner: NSObject, Banner {
private enum Limits {
static let minTimeOnScreen: TimeInterval = 3
static let minTimeSinceLastRequest: TimeInterval = 5
}
fileprivate var success: Banner.Success!
fileprivate var failure: Banner.Failure!
fileprivate var click: Banner.Click!
private var requestDate: Date?
private var showDate: Date?
private var remainingTime = Limits.minTimeOnScreen
private let placementID: String
func reload(success: @escaping Banner.Success, failure: @escaping Banner.Failure, click: @escaping Click) {
self.success = success
self.failure = failure
self.click = click
load()
requestDate = Date()
}
func unregister() {
nativeAd?.unregister()
}
var isBannerOnScreen = false {
didSet {
if isBannerOnScreen {
startCountTimeOnScreen()
} else {
stopCountTimeOnScreen()
}
}
}
private(set) var isNeedToRetain = false
var isPossibleToReload: Bool {
if let date = requestDate {
return Date().timeIntervalSince(date) > Limits.minTimeSinceLastRequest
}
return true
}
var type: BannerType { return .mopub(bannerID) }
var mwmType: MWMBannerType { return type.mwmType }
var bannerID: String { return placementID }
var statisticsDescription: [String: String] {
return [kStatBanner: bannerID, kStatProvider: kStatMopub]
}
init(bannerID: String) {
placementID = bannerID
super.init()
let center = NotificationCenter.default
center.addObserver(self,
selector: #selector(enterForeground),
name: UIApplication.willEnterForegroundNotification,
object: nil)
center.addObserver(self,
selector: #selector(enterBackground),
name: UIApplication.didEnterBackgroundNotification,
object: nil)
}
deinit {
NotificationCenter.default.removeObserver(self)
}
@objc private func enterForeground() {
if isBannerOnScreen {
startCountTimeOnScreen()
}
}
@objc private func enterBackground() {
if isBannerOnScreen {
stopCountTimeOnScreen()
}
}
private func startCountTimeOnScreen() {
if showDate == nil {
showDate = Date()
}
if remainingTime > 0 {
perform(#selector(setEnoughTimeOnScreen), with: nil, afterDelay: remainingTime)
}
}
private func stopCountTimeOnScreen() {
guard let date = showDate else {
assert(false)
return
}
let timePassed = Date().timeIntervalSince(date)
if timePassed < Limits.minTimeOnScreen {
remainingTime = Limits.minTimeOnScreen - timePassed
NSObject.cancelPreviousPerformRequests(withTarget: self)
} else {
remainingTime = 0
}
}
@objc private func setEnoughTimeOnScreen() {
isNeedToRetain = false
}
// MARK: - Content
private(set) var nativeAd: MPNativeAd?
var title: String {
return nativeAd?.properties[kAdTitleKey] as? String ?? ""
}
var text: String {
return nativeAd?.properties[kAdTextKey] as? String ?? ""
}
var iconURL: String {
return nativeAd?.properties[kAdIconImageKey] as? String ?? ""
}
var ctaText: String {
return nativeAd?.properties[kAdCTATextKey] as? String ?? ""
}
var privacyInfoURL: URL? {
guard let nativeAd = nativeAd else { return nil }
if nativeAd.adAdapter is FacebookNativeAdAdapter {
return (nativeAd.adAdapter as! FacebookNativeAdAdapter).fbNativeAdBase.adChoicesLinkURL
}
return URL(string: kPrivacyIconTapDestinationURL)
}
// MARK: - Helpers
private var request: MPNativeAdRequest!
private func load() {
let settings = MPStaticNativeAdRendererSettings()
let config = MPStaticNativeAdRenderer.rendererConfiguration(with: settings)!
let fbConfig = FacebookNativeAdRenderer.rendererConfiguration(with: settings)
request = MPNativeAdRequest(adUnitIdentifier: placementID, rendererConfigurations: [config, fbConfig])
let targeting = MPNativeAdRequestTargeting()
targeting?.keywords = "user_lang:\(AppInfo.shared().twoLetterLanguageId ?? "")"
targeting?.desiredAssets = [kAdTitleKey, kAdTextKey, kAdIconImageKey, kAdCTATextKey]
if let location = MWMLocationManager.lastLocation() {
targeting?.location = location
}
request.targeting = targeting
request.start { [weak self] _, nativeAd, error in
guard let s = self else { return }
if let error = error as NSError? {
let params: [String: Any] = [
kStatBanner: s.bannerID,
kStatProvider: kStatMopub,
]
let event = kStatPlacePageBannerError
s.failure(s.type, event, params, error)
} else {
nativeAd?.delegate = self
s.nativeAd = nativeAd
s.success(s)
}
}
}
}
extension MopubBanner: MPNativeAdDelegate {
func willPresentModal(for nativeAd: MPNativeAd!) {
guard nativeAd === self.nativeAd else { return }
click(self)
}
func viewControllerForPresentingModalView() -> UIViewController! {
return UIViewController.topViewController()
}
}
| apache-2.0 | d12e7ada90e70cfa79033b73d7bc8e0d | 26.465608 | 109 | 0.675592 | 4.953244 | false | false | false | false |
TarangKhanna/Inspirator | WorkoutMotivation/MKLabel.swift | 2 | 3153 | //
// MKLabel.swift
// MaterialKit
//
// Created by Le Van Nghia on 11/29/14.
// Copyright (c) 2014 Le Van Nghia. All rights reserved.
//
import UIKit
public class MKLabel: UILabel {
@IBInspectable public var maskEnabled: Bool = true {
didSet {
mkLayer.enableMask(maskEnabled)
}
}
@IBInspectable public var rippleLocation: MKRippleLocation = .TapLocation {
didSet {
mkLayer.rippleLocation = rippleLocation
}
}
@IBInspectable public var rippleAniDuration: Float = 0.75
@IBInspectable public var backgroundAniDuration: Float = 1.0
@IBInspectable public var rippleAniTimingFunction: MKTimingFunction = .Linear
@IBInspectable public var backgroundAniTimingFunction: MKTimingFunction = .Linear
@IBInspectable public var backgroundAniEnabled: Bool = true {
didSet {
if !backgroundAniEnabled {
mkLayer.enableOnlyCircleLayer()
}
}
}
@IBInspectable public var ripplePercent: Float = 0.9 {
didSet {
mkLayer.ripplePercent = ripplePercent
}
}
@IBInspectable public var cornerRadius: CGFloat = 2.5 {
didSet {
layer.cornerRadius = cornerRadius
mkLayer.setMaskLayerCornerRadius(cornerRadius)
}
}
// color
@IBInspectable public var rippleLayerColor: UIColor = UIColor(white: 0.45, alpha: 0.5) {
didSet {
mkLayer.setCircleLayerColor(rippleLayerColor)
}
}
@IBInspectable public var backgroundLayerColor: UIColor = UIColor(white: 0.75, alpha: 0.25) {
didSet {
mkLayer.setBackgroundLayerColor(backgroundLayerColor)
}
}
override public var bounds: CGRect {
didSet {
mkLayer.superLayerDidResize()
}
}
private lazy var mkLayer: MKLayer = MKLayer(superLayer: self.layer)
required public init(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)!
setup()
}
override public init(frame: CGRect) {
super.init(frame: frame)
setup()
}
private func setup() {
mkLayer.setCircleLayerColor(rippleLayerColor)
mkLayer.setBackgroundLayerColor(backgroundLayerColor)
mkLayer.setMaskLayerCornerRadius(cornerRadius)
}
public func animateRipple(location: CGPoint? = nil) {
if let point = location {
mkLayer.didChangeTapLocation(point)
} else if rippleLocation == .TapLocation {
rippleLocation = .Center
}
mkLayer.animateScaleForCircleLayer(0.65, toScale: 1.0, timingFunction: rippleAniTimingFunction, duration: CFTimeInterval(self.rippleAniDuration))
mkLayer.animateAlphaForBackgroundLayer(backgroundAniTimingFunction, duration: CFTimeInterval(self.backgroundAniDuration))
}
public override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
super.touchesBegan(touches, withEvent: event)
if let firstTouch = touches.first {
let location = firstTouch.locationInView(self)
animateRipple(location)
}
}
}
| apache-2.0 | 046a578b101501b97e9ee8a571d3d2ac | 31.505155 | 153 | 0.650809 | 5.135179 | false | false | false | false |
stripe/stripe-ios | StripeIdentity/StripeIdentity/Source/NativeComponents/ML/Helpers/MLModelLoader.swift | 1 | 5399 | //
// MLModelLoader.swift
// StripeIdentity
//
// Created by Mel Ludowise on 2/1/22.
// Copyright © 2022 Stripe, Inc. All rights reserved.
//
import CoreML
import Foundation
@_spi(STP) import StripeCore
import Vision
/// Loads and compiles CoreML models from a remote URL. The compiled model is saved
/// to a cache directory. If a model with the same remote URL is loaded again, the
/// cached model will be loaded instead of re-downloading it.
final class MLModelLoader {
private let loadPromiseCacheQueue = DispatchQueue(label: "com.stripe.ml-loader")
private var loadPromiseCache: [URL: Promise<MLModel>] = [:]
let fileDownloader: FileDownloader
let cacheDirectory: URL
/// - Parameters:
/// - fileDownloader: A file downloader used to download files
/// - cacheDirectory: File URL corresponding to a directory where the
/// compiled ML model can be cached to. The app must have
/// permission to write to this directory.
init(
fileDownloader: FileDownloader,
cacheDirectory: URL
) {
self.fileDownloader = fileDownloader
self.cacheDirectory = cacheDirectory
}
private func getCachedLocation(forRemoteURL remoteURL: URL) -> URL {
let components = remoteURL.pathComponents.joined(separator: "_")
return cacheDirectory.appendingPathComponent(components)
}
private func cache(compiledModel: URL, downloadedFrom remoteURL: URL) -> URL? {
let destinationURL = getCachedLocation(forRemoteURL: remoteURL)
do {
try FileManager.default.moveItem(at: compiledModel, to: destinationURL)
return destinationURL
} catch {
return nil
}
}
/// Downloads, compiles, and loads a `.mlmodel` file stored on a remote URL.
///
/// If the a model from the given URL has already been successfully compiled
/// before, it will be loaded from the cache. Otherwise the file is downloaded
/// from the given remote URL, compiled, and loaded into an MLModel.
///
/// - Parameters:
/// - remoteURL: The URL to download the model from.
///
/// - Returns: A future resolving to an `MLModel` instantiated from the compiled model.
func loadModel(
fromRemote remoteURL: URL
) -> Future<MLModel> {
let returnedPromise = Promise<MLModel>()
// Dispatch before accessing promise cache
loadPromiseCacheQueue.async { [weak self] in
guard let self = self else { return }
// Check if we've already started downloading the model
if let cachedPromise = self.loadPromiseCache[remoteURL] {
return cachedPromise.observe { returnedPromise.fullfill(with: $0) }
}
// Check if model is already cached to file system
let cachedModel = self.getCachedLocation(forRemoteURL: remoteURL)
if let mlModel = try? MLModel(contentsOf: cachedModel) {
return returnedPromise.resolve(with: mlModel)
}
self.fileDownloader.downloadFileTemporarily(from: remoteURL).chained {
[weak self] tmpFileURL -> Promise<MLModel> in
let compilePromise = Promise<MLModel>()
compilePromise.fulfill { [weak self] in
// Note: The model must be compiled synchronously immediately
// after the file is downloaded, otherwise the system will
// delete the temporary file url before we've had a chance to
// compile it.
let tmpCompiledURL = try MLModel.compileModel(at: tmpFileURL)
let compiledURL =
self?.cache(
compiledModel: tmpCompiledURL,
downloadedFrom: remoteURL
) ?? tmpCompiledURL
return try MLModel(contentsOf: compiledURL)
}
return compilePromise
}.observe { [weak self] result in
returnedPromise.fullfill(with: result)
// Remove from promise cache
self?.loadPromiseCacheQueue.async { [weak self] in
self?.loadPromiseCache.removeValue(forKey: remoteURL)
}
}
// Cache the promise
self.loadPromiseCache[remoteURL] = returnedPromise
}
return returnedPromise
}
/// Downloads, compiles, and loads a `.mlmodel` file stored on a remote URL.
///
/// If the a model from the given URL has already been successfully compiled
/// before, it will be loaded from the cache. Otherwise the file is downloaded
/// from the given remote URL, compiled, and loaded into an MLModel.
///
/// - Parameters:
/// - remoteURL: The URL to download the model from.
///
/// - Returns: A future resolving to a `VNCoreMLModel` instantiated from the compiled model.
func loadVisionModel(
fromRemote remoteURL: URL
) -> Future<VNCoreMLModel> {
return loadModel(fromRemote: remoteURL).chained { mlModel in
let promise = Promise<VNCoreMLModel>()
promise.fulfill {
return try VNCoreMLModel(for: mlModel)
}
return promise
}
}
}
| mit | 31789f118f8da0c5e7469378b3082340 | 38.40146 | 96 | 0.613746 | 5.170498 | false | false | false | false |
bitboylabs/selluv-ios | selluv-ios/Pods/SwifterSwift/Source/Extensions/UIKit/UIViewExtensions.swift | 1 | 16165 | //
// UIViewExtensions.swift
// SwifterSwift
//
// Created by Omar Albeik on 8/5/16.
// Copyright © 2016 Omar Albeik. All rights reserved.
//
#if os(iOS) || os(tvOS)
import UIKit
// MARK: - enums
/// SwifterSwift: Shake directions of a view.
///
/// - horizontal: Shake left and right.
/// - vertical: Shake up and down.
public enum ShakeDirection {
case horizontal
case vertical
}
/// SwifterSwift: Angle units.
///
/// - degrees: degrees.
/// - radians: radians.
public enum AngleUnit {
case degrees
case radians
}
/// SwifterSwift: Shake animations types.
///
/// - linear: linear animation.
/// - easeIn: easeIn animation
/// - easeOut: easeOut animation.
/// - easeInOut: easeInOut animation.
public enum ShakeAnimationType {
case linear
case easeIn
case easeOut
case easeInOut
}
// MARK: - Properties
public extension UIView {
@IBInspectable
/// SwifterSwift: Border color of view; also inspectable from Storyboard.
public var borderColor: UIColor? {
get {
return layer.borderColor?.uiColor
}
set {
guard let color = newValue else {
layer.borderColor = nil
return
}
layer.borderColor = color.cgColor
}
}
@IBInspectable
/// SwifterSwift: Border width of view; also inspectable from Storyboard.
public var borderWidth: CGFloat {
get {
return layer.borderWidth
}
set {
layer.borderWidth = newValue
}
}
@IBInspectable
/// SwifterSwift: Corner radius of view; also inspectable from Storyboard.
public var cornerRadius: CGFloat {
get {
return layer.cornerRadius
}
set {
layer.masksToBounds = true
layer.cornerRadius = abs(CGFloat(Int(newValue * 100)) / 100)
}
}
/// SwifterSwift: First responder.
public var firstResponder: UIView? {
guard !isFirstResponder else {
return self
}
for subView in subviews {
if subView.isFirstResponder {
return subView
}
}
return nil
}
// SwifterSwift: Height of view.
public var height: CGFloat {
get {
return frame.size.height
}
set {
frame.size.height = newValue
}
}
/// SwifterSwift: Check if view is in RTL format.
public var isRightToLeft: Bool {
if #available(iOS 10.0, *, tvOS 10.0, *) {
return effectiveUserInterfaceLayoutDirection == .rightToLeft
} else {
return false
}
}
/// SwifterSwift: Take screenshot of view (if applicable).
public var screenshot: UIImage? {
UIGraphicsBeginImageContextWithOptions(layer.frame.size, false, 0.0);
defer {
UIGraphicsEndImageContext()
}
guard let context = UIGraphicsGetCurrentContext() else {
return nil
}
layer.render(in: context)
return UIGraphicsGetImageFromCurrentImageContext()
}
@IBInspectable
/// SwifterSwift: Shadow color of view; also inspectable from Storyboard.
public var shadowColor: UIColor? {
get {
return layer.shadowColor?.uiColor
}
set {
layer.shadowColor = newValue?.cgColor
}
}
@IBInspectable
/// SwifterSwift: Shadow offset of view; also inspectable from Storyboard.
public var shadowOffset: CGSize {
get {
return layer.shadowOffset
}
set {
layer.shadowOffset = newValue
}
}
@IBInspectable
/// SwifterSwift: Shadow opacity of view; also inspectable from Storyboard.
public var shadowOpacity: Float {
get {
return layer.shadowOpacity
}
set {
layer.shadowOpacity = newValue
}
}
@IBInspectable
/// SwifterSwift: Shadow radius of view; also inspectable from Storyboard.
public var shadowRadius: CGFloat {
get {
return layer.shadowRadius
}
set {
layer.shadowRadius = newValue
}
}
/// SwifterSwift: Size of view.
public var size: CGSize {
get {
return frame.size
}
set {
width = newValue.width
height = newValue.height
}
}
/// SwifterSwift: Get view's parent view controller
public var parentViewController: UIViewController? {
weak var parentResponder: UIResponder? = self
while parentResponder != nil {
parentResponder = parentResponder!.next
if let viewController = parentResponder as? UIViewController {
return viewController
}
}
return nil
}
/// SwifterSwift: Width of view.
public var width: CGFloat {
get {
return frame.size.width
}
set {
frame.size.width = newValue
}
}
/// SwifterSwift: x origin of view.
public var x: CGFloat {
get {
return frame.origin.x
}
set {
frame.origin.x = newValue
}
}
/// SwifterSwift: y origin of view.
public var y: CGFloat {
get {
return frame.origin.y
}
set {
frame.origin.y = newValue
}
}
}
// MARK: - Methods
public extension UIView {
/// SwifterSwift: Set some or all corners radiuses of view.
///
/// - Parameters:
/// - corners: array of corners to change (example: [.bottomLeft, .topRight]).
/// - radius: radius for selected corners.
public func roundCorners(_ corners: UIRectCorner, radius: CGFloat) {
let maskPath = UIBezierPath(roundedRect: bounds,
byRoundingCorners: corners,
cornerRadii: CGSize(width: radius, height: radius))
let shape = CAShapeLayer()
shape.path = maskPath.cgPath
layer.mask = shape
}
/// SwifterSwift: Add shadow to view.
///
/// - Parameters:
/// - color: shadow color (default is #137992).
/// - radius: shadow radius (default is 3).
/// - offset: shadow offset (default is .zero).
/// - opacity: shadow opacity (default is 0.5).
public func addShadow(ofColor color: UIColor = UIColor(hex: 0x137992),
radius: CGFloat = 3,
offset: CGSize = .zero,
opacity: Float = 0.5) {
layer.shadowColor = color.cgColor
layer.shadowOffset = offset
layer.shadowRadius = radius
layer.shadowOpacity = opacity
layer.masksToBounds = true
}
/// SwifterSwift: Add array of subviews to view.
///
/// - Parameter subviews: array of subviews to add to self.
public func addSubviews(_ subviews: [UIView]) {
subviews.forEach({self.addSubview($0)})
}
/// SwifterSwift: Fade in view.
///
/// - Parameters:
/// - duration: animation duration in seconds (default is 1 second).
/// - completion: optional completion handler to run with animation finishes (default is nil)
public func fadeIn(duration: TimeInterval = 1, completion: ((Bool) -> Void)? = nil) {
if isHidden {
isHidden = false
}
UIView.animate(withDuration: duration, animations: {
self.alpha = 1
}, completion: completion)
}
/// SwifterSwift: Fade out view.
///
/// - Parameters:
/// - duration: animation duration in seconds (default is 1 second).
/// - completion: optional completion handler to run with animation finishes (default is nil)
public func fadeOut(duration: TimeInterval = 1, completion: ((Bool) -> Void)? = nil) {
if isHidden {
isHidden = false
}
UIView.animate(withDuration: duration, animations: {
self.alpha = 0
}, completion: completion)
}
/// SwifterSwift: Load view from nib.
///
/// - Parameters:
/// - name: nib name.
/// - bundle: bundle of nib (default is nil).
/// - Returns: optional UIView (if applicable).
class func loadFromNib(named name: String, bundle : Bundle? = nil) -> UIView? {
return UINib(nibName: name, bundle: bundle).instantiate(withOwner: nil, options: nil)[0] as? UIView
}
/// SwifterSwift: Remove all subviews in view.
public func removeSubviews() {
subviews.forEach({$0.removeFromSuperview()})
}
/// SwifterSwift: Remove all gesture recognizers from view.
public func removeGestureRecognizers() {
gestureRecognizers?.forEach(removeGestureRecognizer)
}
/// SwifterSwift: Rotate view by angle on relative axis.
///
/// - Parameters:
/// - angle: angle to rotate view by.
/// - type: type of the rotation angle.
/// - animated: set true to animate rotation (default is true).
/// - duration: animation duration in seconds (default is 1 second).
/// - completion: optional completion handler to run with animation finishes (default is nil).
public func rotate(byAngle angle : CGFloat, ofType type: AngleUnit, animated: Bool = false, duration: TimeInterval = 1, completion:((Bool) -> Void)? = nil) {
let angleWithType = (type == .degrees) ? CGFloat.pi * angle / 180.0 : angle
let aDuration = animated ? duration : 0
UIView.animate(withDuration: aDuration, delay: 0, options: .curveLinear, animations: { () -> Void in
self.transform = self.transform.rotated(by: angleWithType)
}, completion: completion)
}
/// SwifterSwift: Rotate view to angle on fixed axis.
///
/// - Parameters:
/// - angle: angle to rotate view to.
/// - type: type of the rotation angle.
/// - animated: set true to animate rotation (default is false).
/// - duration: animation duration in seconds (default is 1 second).
/// - completion: optional completion handler to run with animation finishes (default is nil).
public func rotate(toAngle angle: CGFloat, ofType type: AngleUnit, animated: Bool = false, duration: TimeInterval = 1, completion:((Bool) -> Void)? = nil) {
let angleWithType = (type == .degrees) ? CGFloat.pi * angle / 180.0 : angle
let aDuration = animated ? duration : 0
UIView.animate(withDuration: aDuration, animations: {
self.transform = self.transform.concatenating(CGAffineTransform(rotationAngle: angleWithType))
}, completion: completion)
}
/// SwifterSwift: Scale view by offset.
///
/// - Parameters:
/// - offset: scale offset
/// - animated: set true to animate scaling (default is false).
/// - duration: animation duration in seconds (default is 1 second).
/// - completion: optional completion handler to run with animation finishes (default is nil).
public func scale(by offset: CGPoint, animated: Bool = false, duration: TimeInterval = 1, completion:((Bool) -> Void)? = nil) {
if animated {
UIView.animate(withDuration: duration, delay: 0, options: .curveLinear, animations: { () -> Void in
self.transform = self.transform.scaledBy(x: offset.x, y: offset.y)
}, completion: completion)
} else {
transform = transform.scaledBy(x: offset.x, y: offset.y)
completion?(true)
}
}
/// SwifterSwift: Shake view.
///
/// - Parameters:
/// - direction: shake direction (horizontal or vertical), (default is .horizontal)
/// - duration: animation duration in seconds (default is 1 second).
/// - animationType: shake animation type (default is .easeOut).
/// - completion: optional completion handler to run with animation finishes (default is nil).
public func shake(direction: ShakeDirection = .horizontal, duration: TimeInterval = 1, animationType: ShakeAnimationType = .easeOut, completion:(() -> Void)? = nil) {
CATransaction.begin()
let animation: CAKeyframeAnimation
switch direction {
case .horizontal:
animation = CAKeyframeAnimation(keyPath: "transform.translation.x")
case .vertical:
animation = CAKeyframeAnimation(keyPath: "transform.translation.y")
}
switch animationType {
case .linear:
animation.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionLinear)
case .easeIn:
animation.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseIn)
case .easeOut:
animation.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseOut)
case .easeInOut:
animation.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseInEaseOut)
}
CATransaction.setCompletionBlock(completion)
animation.duration = duration
animation.values = [-20.0, 20.0, -20.0, 20.0, -10.0, 10.0, -5.0, 5.0, 0.0 ]
layer.add(animation, forKey: "shake")
CATransaction.commit()
}
/// SwifterSwift: Add Visual Format constraints.
///
/// - Parameters:
/// - withFormat: visual Format language
/// - views: array of views which will be accessed starting with index 0 (example: [v0], [v1], [v2]..)
@available(iOS 9, *) public func addConstraints(withFormat: String, views: UIView...) {
// https://videos.letsbuildthatapp.com/
var viewsDictionary: [String: UIView] = [:]
for (index, view) in views.enumerated() {
let key = "v\(index)"
view.translatesAutoresizingMaskIntoConstraints = false
viewsDictionary[key] = view
}
addConstraints(NSLayoutConstraint.constraints(withVisualFormat: withFormat, options: NSLayoutFormatOptions(), metrics: nil, views: viewsDictionary))
}
/// SwifterSwift: Anchor all sides of the view into it's superview.
@available(iOS 9, *) public func fillToSuperview() {
// https://videos.letsbuildthatapp.com/
translatesAutoresizingMaskIntoConstraints = false
if let superview = superview {
leftAnchor.constraint(equalTo: superview.leftAnchor).isActive = true
rightAnchor.constraint(equalTo: superview.rightAnchor).isActive = true
topAnchor.constraint(equalTo: superview.topAnchor).isActive = true
bottomAnchor.constraint(equalTo: superview.bottomAnchor).isActive = true
}
}
/// SwifterSwift: Add anchors from any side of the current view into the specified anchors and returns the newly added constraints.
///
/// - Parameters:
/// - top: current view's top anchor will be anchored into the specified anchor
/// - left: current view's left anchor will be anchored into the specified anchor
/// - bottom: current view's bottom anchor will be anchored into the specified anchor
/// - right: current view's right anchor will be anchored into the specified anchor
/// - topConstant: current view's top anchor margin
/// - leftConstant: current view's left anchor margin
/// - bottomConstant: current view's bottom anchor margin
/// - rightConstant: current view's right anchor margin
/// - widthConstant: current view's width
/// - heightConstant: current view's height
/// - Returns: array of newly added constraints (if applicable).
@available(iOS 9, *) @discardableResult public func anchor(
top: NSLayoutYAxisAnchor? = nil,
left: NSLayoutXAxisAnchor? = nil,
bottom: NSLayoutYAxisAnchor? = nil,
right: NSLayoutXAxisAnchor? = nil,
topConstant: CGFloat = 0,
leftConstant: CGFloat = 0,
bottomConstant: CGFloat = 0,
rightConstant: CGFloat = 0,
widthConstant: CGFloat = 0,
heightConstant: CGFloat = 0) -> [NSLayoutConstraint] {
// https://videos.letsbuildthatapp.com/
translatesAutoresizingMaskIntoConstraints = false
var anchors = [NSLayoutConstraint]()
if let top = top {
anchors.append(topAnchor.constraint(equalTo: top, constant: topConstant))
}
if let left = left {
anchors.append(leftAnchor.constraint(equalTo: left, constant: leftConstant))
}
if let bottom = bottom {
anchors.append(bottomAnchor.constraint(equalTo: bottom, constant: -bottomConstant))
}
if let right = right {
anchors.append(rightAnchor.constraint(equalTo: right, constant: -rightConstant))
}
if widthConstant > 0 {
anchors.append(widthAnchor.constraint(equalToConstant: widthConstant))
}
if heightConstant > 0 {
anchors.append(heightAnchor.constraint(equalToConstant: heightConstant))
}
anchors.forEach({$0.isActive = true})
return anchors
}
/// SwifterSwift: Anchor center X into current view's superview with a constant margin value.
///
/// - Parameter constant: constant of the anchor constraint (default is 0).
@available(iOS 9, *) public func anchorCenterXToSuperview(constant: CGFloat = 0) {
// https://videos.letsbuildthatapp.com/
translatesAutoresizingMaskIntoConstraints = false
if let anchor = superview?.centerXAnchor {
centerXAnchor.constraint(equalTo: anchor, constant: constant).isActive = true
}
}
/// SwifterSwift: Anchor center Y into current view's superview with a constant margin value.
///
/// - Parameter withConstant: constant of the anchor constraint (default is 0).
@available(iOS 9, *) public func anchorCenterYToSuperview(constant: CGFloat = 0) {
// https://videos.letsbuildthatapp.com/
translatesAutoresizingMaskIntoConstraints = false
if let anchor = superview?.centerYAnchor {
centerYAnchor.constraint(equalTo: anchor, constant: constant).isActive = true
}
}
/// SwifterSwift: Anchor center X and Y into current view's superview
@available(iOS 9, *) public func anchorCenterSuperview() {
// https://videos.letsbuildthatapp.com/
anchorCenterXToSuperview()
anchorCenterYToSuperview()
}
}
#endif
| mit | 41e29a83ae98fe6b8efc0b7340aaeb8a | 29.847328 | 167 | 0.701373 | 3.910015 | false | false | false | false |
raymondshadow/SwiftDemo | SwiftApp/Pods/RxSwift/RxSwift/Observables/Dematerialize.swift | 4 | 1791 | //
// Dematerialize.swift
// RxSwift
//
// Created by Jamie Pinkham on 3/13/17.
// Copyright © 2017 Krunoslav Zaher. All rights reserved.
//
extension ObservableType where E: EventConvertible {
/**
Convert any previously materialized Observable into it's original form.
- seealso: [materialize operator on reactivex.io](http://reactivex.io/documentation/operators/materialize-dematerialize.html)
- returns: The dematerialized observable sequence.
*/
public func dematerialize() -> Observable<E.ElementType> {
return Dematerialize(source: self.asObservable())
}
}
fileprivate final class DematerializeSink<Element: EventConvertible, O: ObserverType>: Sink<O>, ObserverType where O.E == Element.ElementType {
fileprivate func on(_ event: Event<Element>) {
switch event {
case .next(let element):
self.forwardOn(element.event)
if element.event.isStopEvent {
self.dispose()
}
case .completed:
self.forwardOn(.completed)
self.dispose()
case .error(let error):
self.forwardOn(.error(error))
self.dispose()
}
}
}
final private class Dematerialize<Element: EventConvertible>: Producer<Element.ElementType> {
private let _source: Observable<Element>
init(source: Observable<Element>) {
self._source = source
}
override func run<O : ObserverType>(_ observer: O, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where O.E == Element.ElementType {
let sink = DematerializeSink<Element, O>(observer: observer, cancel: cancel)
let subscription = self._source.subscribe(sink)
return (sink: sink, subscription: subscription)
}
}
| apache-2.0 | 887fca5c7f1c76abcf3c5b7a9e8b1a98 | 34.098039 | 157 | 0.657542 | 4.637306 | false | false | false | false |
cztatsumi-keisuke/TKKeyboardControl | Example/TKKeyboardControl/FirstViewController.swift | 1 | 4079 | //
// FirstViewController.swift
// TKKeyboardControl
//
// Created by 辰己 佳祐 on 2016/06/01.
// Copyright © 2016年 CocoaPods. All rights reserved.
//
import Foundation
import UIKit
final class FirstViewController: UIViewController {
let nextButton = UIButton(type: .system)
let inputBaseView = UIView()
let textField = UITextField()
let sendButton = UIButton()
let sideMargin: CGFloat = 5
let inputBaseViewHeight: CGFloat = 40
let textFieldHeight: CGFloat = 30
let sendButtonWidth: CGFloat = 80
var safeAreaInsets: UIEdgeInsets {
if #available(iOS 11, *) {
return view.safeAreaInsets
}
return UIEdgeInsets.zero
}
override func viewDidLoad() {
super.viewDidLoad()
title = "First View"
inputBaseView.backgroundColor = UIColor(white: 0.9, alpha: 1.0)
view.addSubview(inputBaseView)
textField.backgroundColor = .white
textField.placeholder = "Input here."
textField.borderStyle = .roundedRect
textField.textAlignment = .left
inputBaseView.addSubview(textField)
sendButton.setTitle("Send", for: .normal)
inputBaseView.addSubview(sendButton)
// Trigger Offset
view.keyboardTriggerOffset = inputBaseViewHeight
let tapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(FirstViewController.closeKeyboard))
view.addGestureRecognizer(tapGestureRecognizer)
nextButton.setTitle("Go Next", for: .normal)
nextButton.addTarget(self, action: #selector(FirstViewController.goNextViewController), for: .touchUpInside)
view.addSubview(nextButton)
updateFrame()
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
// Add Keyboard Pannning
view.addKeyboardPanning(frameBasedActionHandler: { [weak self] keyboardFrameInView, firstResponder, opening, closing in
guard let weakSelf = self else { return }
if let v = firstResponder as? UIView {
print("isDescendant of inputBaseView?: \(v.isDescendant(of: weakSelf.inputBaseView))")
}
weakSelf.inputBaseView.frame.origin.y = keyboardFrameInView.origin.y - weakSelf.inputBaseViewHeight
})
}
override func viewDidDisappear(_ animated: Bool) {
super.viewDidDisappear(animated)
view.removeKeyboardControl()
}
override func viewWillLayoutSubviews() {
super.viewWillLayoutSubviews()
self.updateFrame()
}
func updateFrame() {
inputBaseView.frame = CGRect(x: 0,
y: view.bounds.size.height - inputBaseViewHeight - safeAreaInsets.bottom,
width: view.bounds.size.width,
height: inputBaseViewHeight)
textField.frame = CGRect(x: sideMargin + safeAreaInsets.left,
y: (inputBaseViewHeight - textFieldHeight)/2,
width: view.bounds.size.width - sendButtonWidth - sideMargin * 3 - (safeAreaInsets.left + safeAreaInsets.right),
height: textFieldHeight)
sendButton.frame = CGRect(x: textField.frame.maxX + sideMargin,
y: sideMargin,
width: sendButtonWidth,
height: textFieldHeight)
nextButton.frame = CGRect(x: view.bounds.width/2 - 100,
y: view.bounds.height/2 - 25,
width: 200,
height: 50)
}
@objc private func closeKeyboard() {
view.hideKeyboard()
}
@objc func goNextViewController() {
// - Attention: You should call close keyboard before begin transitioning
closeKeyboard()
navigationController?.pushViewController(SecondViewController(), animated: true)
}
}
| mit | f9d5c193e9139bd538d85471619eefa1 | 35 | 145 | 0.608161 | 5.587912 | false | false | false | false |
CartoDB/mobile-ios-samples | AdvancedMap.Swift/Feature Demo/BaseGeocodingView.swift | 1 | 3868 | //
// BaseGeocodingView.swift
// AdvancedMap.Swift
//
// Created by Aare Undo on 07/07/2017.
// Copyright © 2017 CARTO. All rights reserved.
//
import Foundation
import CartoMobileSDK
class BaseGeocodingView: PackageDownloadBaseView {
static let PACKAGE_FOLDER = "geocodingpackages"
static let SOURCE = "geocoding:carto.streets"
var source: NTLocalVectorDataSource!
convenience init() {
self.init(frame: CGRect.zero)
}
func initializeGeocodingView(popupTitle: String, popupDescription: String) {
initialize()
initializeDownloadContent(withSwitch: true)
initializePackageDownloadContent()
infoContent.setText(headerText: popupTitle, contentText: popupDescription)
source = NTLocalVectorDataSource(projection: projection)
let layer = NTVectorLayer(dataSource: source)
map.getLayers().add(layer)
}
func showResult(result: NTGeocodingResult!, title: String, description: String, goToPosition: Bool) {
source.clear()
let builder = NTBalloonPopupStyleBuilder()
builder?.setLeftMargins(NTBalloonPopupMargins(left: 0, top: 0, right: 0, bottom: 0))
builder?.setTitleMargins(NTBalloonPopupMargins(left: 6, top: 3, right: 6, bottom: 3))
builder?.setCornerRadius(5)
// Make sure this label is shown on top of all other labels
builder?.setPlacementPriority(10)
let collection = result.getFeatureCollection()
let count = Int((collection?.getFeatureCount())!)
var position: NTMapPos?
var geometry: NTGeometry?
for var i in 0..<count {
geometry = collection?.getFeature(Int32(i)).getGeometry()
let color = NTColor(r: 0, g: 100, b: 200, a: 150)
// Build styles for the displayed geometry
let pointBuilder = NTPointStyleBuilder()
pointBuilder?.setColor(color)
let lineBuilder = NTLineStyleBuilder()
lineBuilder?.setColor(color)
let polygonBuilder = NTPolygonStyleBuilder()
polygonBuilder?.setColor(color)
var element: NTVectorElement?
if let pointGeometry = geometry as? NTPointGeometry {
element = NTPoint(geometry: pointGeometry, style: pointBuilder?.buildStyle())
} else if let lineGeometry = geometry as? NTLineGeometry {
element = NTLine(geometry: lineGeometry, style: lineBuilder?.buildStyle())
} else if let polygonGeometry = geometry as? NTPolygonGeometry {
element = NTPolygon(geometry: polygonGeometry, style: polygonBuilder?.buildStyle())
} else if let multiGeometry = geometry as? NTMultiGeometry {
let collectionBuilder = NTGeometryCollectionStyleBuilder()
collectionBuilder?.setPointStyle(pointBuilder?.buildStyle())
collectionBuilder?.setLineStyle(lineBuilder?.buildStyle())
collectionBuilder?.setPolygonStyle(polygonBuilder?.buildStyle())
element = NTGeometryCollection(geometry: multiGeometry, style: collectionBuilder?.buildStyle())
}
position = geometry?.getCenterPos()
source.add(element)
i += 1
}
if (goToPosition) {
map.setFocus(position, durationSeconds: 1.0)
map.setZoom(16, durationSeconds: 1)
}
let popup = NTBalloonPopup(pos: position, style: builder?.buildStyle(), title: title, desc: description)
source.add(popup)
}
}
| bsd-2-clause | e7ade5e99aa359eede9952531eb6d51b | 32.921053 | 112 | 0.600724 | 5.081472 | false | false | false | false |
MaartenBrijker/project | project/External/AudioKit-master/Examples/iOS/AnalogSynthX/AnalogSynthX/CustomControls/Knob.swift | 3 | 1373 | //
// Knob.swift
// Swift Synth
//
// Created by Matthew Fecher on 1/9/16.
// Copyright © 2016 AudioKit. All rights reserved.
//
import UIKit
@IBDesignable
class Knob: UIView {
var minimum = 0.0 {
didSet {
self.knobValue = CGFloat((value - minimum) / (maximum - minimum))
}
}
var maximum = 1.0 {
didSet {
self.knobValue = CGFloat((value - minimum) / (maximum - minimum))
}
}
var value: Double = 0 {
didSet {
if value > maximum {
value = maximum
}
if value < minimum {
value = minimum
}
self.knobValue = CGFloat((value - minimum) / (maximum - minimum))
}
}
// Knob properties
var knobValue: CGFloat = 0.5
var knobSensitivity = 0.005
var lastX: CGFloat = 0
var lastY: CGFloat = 0
func setPercentagesWithTouchPoint(touchPoint: CGPoint) {
// Knobs assume up or right is increasing, and down or left is decreasing
let horizontalChange = Double(touchPoint.x - lastX) * knobSensitivity
value += horizontalChange * (maximum - minimum)
let verticalChange = Double(touchPoint.y - lastY) * knobSensitivity
value -= verticalChange * (maximum - minimum)
lastX = touchPoint.x
lastY = touchPoint.y
}
}
| apache-2.0 | e141242b2d99104fa77198edb81c6d7d | 23.945455 | 81 | 0.564869 | 4.397436 | false | false | false | false |
nicolastinkl/swift | ListerAProductivityAppBuiltinSwift/ListerKit/ListInfo.swift | 1 | 2410 | /*
Copyright (C) 2014 Apple Inc. All Rights Reserved.
See LICENSE.txt for this sample’s licensing information
Abstract:
ListInfo is an abstraction to contain information about list documents such as their color.
*/
import UIKit
import ListerKit
// A ListInfoProvider needs to provide a URL for the ListInfo object to query.
@class_protocol protocol ListInfoProvider {
var URL: NSURL { get }
}
// Make NSURL a ListInfoProvider, since it's by default an NSURL.
extension NSURL: ListInfoProvider {
var URL: NSURL {
return self
}
}
// Make NSMetadataItem a ListInfoProvider and return its value for the NSMetadataItemURLKey attribute.
extension NSMetadataItem: ListInfoProvider {
var URL: NSURL {
return valueForAttribute(NSMetadataItemURLKey) as NSURL
}
}
class ListInfo: Equatable {
// MARK: Properties
let provider: ListInfoProvider
var color: List.Color?
var name: String?
var isLoaded: Bool {
return color && name
}
var URL: NSURL {
return provider.URL
}
// MARK: Initializers
init(provider: ListInfoProvider) {
self.provider = provider
}
// MARK: Methods
func fetchInfoWithCompletionHandler(completionHandler: () -> Void) {
if isLoaded {
completionHandler()
return
}
let document = ListDocument(fileURL: URL)
document.openWithCompletionHandler { success in
if success {
self.color = document.list.color
self.name = document.localizedName
completionHandler()
document.closeWithCompletionHandler(nil)
}
else {
fatalError("Your attempt to open the document failed.")
}
}
}
func createAndSaveWithCompletionHandler(completionHandler: Bool -> Void) {
let list = List()
list.color = color ? color! : .Gray
let document = ListDocument(fileURL: URL)
document.list = list
document.saveToURL(URL, forSaveOperation: .ForCreating, completionHandler: completionHandler)
}
}
// Equality operator to compare two ListInfo objects.
func ==(lhs: ListInfo, rhs: ListInfo) -> Bool {
return lhs.URL == rhs.URL
}
| mit | 29254f8485e6b3bfc7788ef91050c473 | 24.617021 | 107 | 0.61088 | 5.246187 | false | false | false | false |
kripple/bti-watson | ios-app/Carthage/Checkouts/AlamofireObjectMapper/Carthage/Checkouts/ObjectMapper/Carthage/Checkouts/Nimble/Nimble/Expression.swift | 300 | 4287 | import Foundation
// Memoizes the given closure, only calling the passed
// closure once; even if repeat calls to the returned closure
internal func memoizedClosure<T>(closure: () throws -> T) -> (Bool) throws -> T {
var cache: T?
return ({ withoutCaching in
if (withoutCaching || cache == nil) {
cache = try closure()
}
return cache!
})
}
/// Expression represents the closure of the value inside expect(...).
/// Expressions are memoized by default. This makes them safe to call
/// evaluate() multiple times without causing a re-evaluation of the underlying
/// closure.
///
/// @warning Since the closure can be any code, Objective-C code may choose
/// to raise an exception. Currently, Expression does not memoize
/// exception raising.
///
/// This provides a common consumable API for matchers to utilize to allow
/// Nimble to change internals to how the captured closure is managed.
public struct Expression<T> {
internal let _expression: (Bool) throws -> T?
internal let _withoutCaching: Bool
public let location: SourceLocation
public let isClosure: Bool
/// Creates a new expression struct. Normally, expect(...) will manage this
/// creation process. The expression is memoized.
///
/// @param expression The closure that produces a given value.
/// @param location The source location that this closure originates from.
/// @param isClosure A bool indicating if the captured expression is a
/// closure or internally produced closure. Some matchers
/// may require closures. For example, toEventually()
/// requires an explicit closure. This gives Nimble
/// flexibility if @autoclosure behavior changes between
/// Swift versions. Nimble internals always sets this true.
public init(expression: () throws -> T?, location: SourceLocation, isClosure: Bool = true) {
self._expression = memoizedClosure(expression)
self.location = location
self._withoutCaching = false
self.isClosure = isClosure
}
/// Creates a new expression struct. Normally, expect(...) will manage this
/// creation process.
///
/// @param expression The closure that produces a given value.
/// @param location The source location that this closure originates from.
/// @param withoutCaching Indicates if the struct should memoize the given
/// closure's result. Subsequent evaluate() calls will
/// not call the given closure if this is true.
/// @param isClosure A bool indicating if the captured expression is a
/// closure or internally produced closure. Some matchers
/// may require closures. For example, toEventually()
/// requires an explicit closure. This gives Nimble
/// flexibility if @autoclosure behavior changes between
/// Swift versions. Nimble internals always sets this true.
public init(memoizedExpression: (Bool) throws -> T?, location: SourceLocation, withoutCaching: Bool, isClosure: Bool = true) {
self._expression = memoizedExpression
self.location = location
self._withoutCaching = withoutCaching
self.isClosure = isClosure
}
/// Returns a new Expression from the given expression. Identical to a map()
/// on this type. This should be used only to typecast the Expression's
/// closure value.
///
/// The returned expression will preserve location and isClosure.
///
/// @param block The block that can cast the current Expression value to a
/// new type.
public func cast<U>(block: (T?) throws -> U?) -> Expression<U> {
return Expression<U>(expression: ({ try block(self.evaluate()) }), location: self.location, isClosure: self.isClosure)
}
public func evaluate() throws -> T? {
return try self._expression(_withoutCaching)
}
public func withoutCaching() -> Expression<T> {
return Expression(memoizedExpression: self._expression, location: location, withoutCaching: true, isClosure: isClosure)
}
}
| mit | ca06d3cc39dac15bf8723786dd13b679 | 46.633333 | 130 | 0.650338 | 5.183797 | false | false | false | false |
Maaimusic/BTree | Sources/BTreeBuilder.swift | 1 | 11287 | //
// BTreeBuilder.swift
// BTree
//
// Created by Károly Lőrentey on 2016-02-28.
// Copyright © 2016–2017 Károly Lőrentey.
//
extension BTree {
//MARK: Bulk loading initializers
/// Create a new B-tree from elements of an unsorted sequence, using a stable sort algorithm.
///
/// - Parameter elements: An unsorted sequence of arbitrary length.
/// - Parameter order: The desired B-tree order. If not specified (recommended), the default order is used.
/// - Complexity: O(count * log(`count`))
/// - SeeAlso: `init(sortedElements:order:fillFactor:)` for a (faster) variant that can be used if the sequence is already sorted.
@inlinable public init<S: Sequence>(_ elements: S, dropDuplicates: Bool = false, order: Int? = nil)
where S.Element == Element {
let order = order ?? Node.defaultOrder
self.init(Node(order: order))
withCursorAtEnd { cursor in
for element in elements {
cursor.move(to: element.0, choosing: .last)
let match = !cursor.isAtEnd && cursor.key == element.0
if match {
if dropDuplicates {
cursor.element = element
}
else {
cursor.insertAfter(element)
}
}
else {
cursor.insert(element)
}
}
}
}
/// Create a new B-tree from elements of a sequence sorted by key.
///
/// - Parameter sortedElements: A sequence of arbitrary length, sorted by key.
/// - Parameter order: The desired B-tree order. If not specified (recommended), the default order is used.
/// - Parameter fillFactor: The desired fill factor in each node of the new tree. Must be between 0.5 and 1.0.
/// If not specified, a value of 1.0 is used, i.e., nodes will be loaded with as many elements as possible.
/// - Complexity: O(count)
/// - SeeAlso: `init(elements:order:fillFactor:)` for a (slower) unsorted variant.
@inlinable public init<S: Sequence>(sortedElements elements: S, dropDuplicates: Bool = false, order: Int? = nil, fillFactor: Double = 1) where S.Element == Element {
var iterator = elements.makeIterator()
self.init(order: order ?? Node.defaultOrder, fillFactor: fillFactor, dropDuplicates: dropDuplicates, next: { iterator.next() })
}
@usableFromInline internal init(order: Int, fillFactor: Double = 1, dropDuplicates: Bool = false, next: () -> Element?) {
precondition(order > 1)
precondition(fillFactor >= 0.5 && fillFactor <= 1)
let keysPerNode = Int(fillFactor * Double(order - 1) + 0.5)
assert(keysPerNode >= (order - 1) / 2 && keysPerNode <= order - 1)
var builder = BTreeBuilder<Key, Value>(order: order, keysPerNode: keysPerNode)
if dropDuplicates {
guard var buffer = next() else {
self.init(Node(order: order))
return
}
while let element = next() {
precondition(buffer.0 <= element.0)
if buffer.0 < element.0 {
builder.append(buffer)
}
buffer = element
}
builder.append(buffer)
}
else {
var lastKey: Key? = nil
while let element = next() {
precondition(lastKey == nil || lastKey! <= element.0)
lastKey = element.0
builder.append(element)
}
}
self.init(builder.finish())
}
}
private enum BuilderState {
/// The builder needs a separator element.
case separator
/// The builder is filling up a seedling node.
case element
}
/// A construct for efficiently building a fully loaded B-tree from a series of elements.
///
/// The bulk loading algorithm works growing a line of perfectly loaded saplings, in order of decreasing depth,
/// with a separator element between each of them.
///
/// Added elements are collected into a separator and a new leaf node (called the "seedling").
/// When the seedling becomes full it is appended to or recursively merged into the list of saplings.
///
/// When `finish` is called, the final list of saplings plus the last partial seedling is joined
/// into a single tree, which becomes the root.
@usableFromInline internal struct BTreeBuilder<Key: Comparable, Value> {
@usableFromInline typealias Node = BTreeNode<Key, Value>
@usableFromInline typealias Element = Node.Element
@usableFromInline typealias Splinter = Node.Splinter
private let order: Int
private let keysPerNode: Int
private var saplings: [Node]
private var separators: [Element]
private var seedling: Node
private var state: BuilderState
@usableFromInline init(order: Int) {
self.init(order: order, keysPerNode: order - 1)
}
@usableFromInline init(order: Int, keysPerNode: Int) {
precondition(order > 1)
precondition(keysPerNode >= (order - 1) / 2 && keysPerNode <= order - 1)
self.order = order
self.keysPerNode = keysPerNode
self.saplings = []
self.separators = []
self.seedling = Node(order: order)
self.state = .element
}
@usableFromInline var lastKey: Key? {
switch state {
case .separator:
return saplings.last?.last?.0
case .element:
return seedling.last?.0 ?? separators.last?.0
}
}
@usableFromInline func isValidNextKey(_ key: Key) -> Bool {
guard let last = lastKey else { return true }
return last <= key
}
@usableFromInline mutating func append(_ element: Element) {
assert(isValidNextKey(element.0))
switch state {
case .separator:
separators.append(element)
state = .element
case .element:
seedling.append(element)
if seedling.count == keysPerNode {
closeSeedling()
state = .separator
}
}
}
private mutating func closeSeedling() {
append(sapling: seedling)
seedling = Node(order: order)
}
@usableFromInline mutating func append(_ node: Node) {
appendWithoutCloning(node.clone())
}
@usableFromInline mutating func appendWithoutCloning(_ node: Node) {
assert(node.order == order)
if node.isEmpty { return }
assert(isValidNextKey(node.first!.0))
if node.depth == 0 {
if state == .separator {
assert(seedling.isEmpty)
separators.append(node.elements.removeFirst())
node.count -= 1
state = .element
if node.isEmpty { return }
seedling = node
}
else if seedling.count > 0 {
let sep = seedling.elements.removeLast()
seedling.count -= 1
if let splinter = seedling.shiftSlots(separator: sep, node: node, target: keysPerNode) {
closeSeedling()
separators.append(splinter.separator)
seedling = splinter.node
}
}
else {
seedling = node
}
if seedling.count >= keysPerNode {
closeSeedling()
state = .separator
}
return
}
if state == .element && seedling.count > 0 {
let sep = seedling.elements.removeLast()
seedling.count -= 1
closeSeedling()
separators.append(sep)
}
if state == .separator {
let cursor = BTreeCursor(BTreeCursorPath(endOf: saplings.removeLast()))
cursor.moveBackward()
let separator = cursor.remove()
saplings.append(cursor.finish())
separators.append(separator)
}
assert(seedling.isEmpty)
append(sapling: node)
state = .separator
}
private mutating func append(sapling: Node) {
var sapling = sapling
while !saplings.isEmpty {
assert(saplings.count == separators.count)
var previous = saplings.removeLast()
let separator = separators.removeLast()
// Join previous saplings together until they grow at least as deep as the new one.
while previous.depth < sapling.depth {
if saplings.isEmpty {
// If the single remaining sapling is too shallow, just join it to the new sapling and call it a day.
saplings.append(Node.join(left: previous, separator: separator, right: sapling))
return
}
previous = Node.join(left: saplings.removeLast(), separator: separators.removeLast(), right: previous)
}
let fullPrevious = previous.elements.count >= keysPerNode
let fullSapling = sapling.elements.count >= keysPerNode
if previous.depth == sapling.depth + 1 && !fullPrevious && fullSapling {
// Graft node under the last sapling, as a new child branch.
previous.elements.append(separator)
previous.children.append(sapling)
previous.count += sapling.count + 1
sapling = previous
}
else if previous.depth == sapling.depth && fullPrevious && fullSapling {
// We have two full nodes; add them as two branches of a new, deeper node.
sapling = Node(left: previous, separator: separator, right: sapling)
}
else if previous.depth > sapling.depth || fullPrevious {
// The new sapling can be appended to the line and we're done.
saplings.append(previous)
separators.append(separator)
break
}
else if let splinter = previous.shiftSlots(separator: separator, node: sapling, target: keysPerNode) {
// We have made the previous sapling full; add it as a new one before trying again with the remainder.
assert(previous.elements.count == keysPerNode)
append(sapling: previous)
separators.append(splinter.separator)
sapling = splinter.node
}
else {
// We've combined the two saplings; try again with the result.
sapling = previous
}
}
saplings.append(sapling)
}
@usableFromInline mutating func finish() -> Node {
// Merge all saplings and the seedling into a single tree.
var root: Node
if separators.count == saplings.count - 1 {
assert(seedling.count == 0)
root = saplings.removeLast()
}
else {
root = seedling
}
assert(separators.count == saplings.count)
while !saplings.isEmpty {
root = Node.join(left: saplings.removeLast(), separator: separators.removeLast(), right: root)
}
state = .element
return root
}
}
| mit | fd1a1b0e0fdebcdf4082708dd91ba38e | 37.896552 | 169 | 0.574645 | 4.876783 | false | false | false | false |
ccrama/Slide-iOS | Slide for Reddit/Sidebar.swift | 1 | 3709 | //
// Sidebar.swift
// Slide for Reddit
//
// Created by Carlos Crane on 7/9/17.
// Copyright © 2017 Haptic Apps. All rights reserved.
//
import Foundation
import reddift
import YYText
class Sidebar: NSObject {
var parent: (UIViewController & MediaVCDelegate)?
var subname = ""
init(parent: UIViewController & MediaVCDelegate, subname: String) {
self.parent = parent
self.subname = subname
}
var inner: SubSidebarViewController?
var subInfo: Subreddit?
func displaySidebar() {
do {
try (UIApplication.shared.delegate as! AppDelegate).session?.about(subname, completion: { (result) in
switch result {
case .success(let r):
self.subInfo = r
DispatchQueue.main.async {
self.doDisplaySidebar(r)
}
default:
DispatchQueue.main.async {
BannerUtil.makeBanner(text: "Subreddit sidebar not found", seconds: 3, context: self.parent)
}
}
})
} catch {
}
}
var alrController = UIAlertController()
var menuPresentationController: BottomMenuPresentationController?
func doDisplaySidebar(_ sub: Subreddit) {
guard let parent = parent else { return }
inner = SubSidebarViewController(sub: sub, parent: parent)
if #available(iOS 13.0, *) {
VCPresenter.presentAlert(SwipeForwardNavigationController(rootViewController: inner!), parentVC: parent)
} else {
VCPresenter.showVC(viewController: inner!, popupIfPossible: false, parentNavigationController: parent.navigationController, parentViewController: parent)
}
}
func subscribe(_ sub: Subreddit) {
if parent!.subChanged && !sub.userIsSubscriber || sub.userIsSubscriber {
//was not subscriber, changed, and unsubscribing again
Subscriptions.unsubscribe(sub.displayName, session: (UIApplication.shared.delegate as! AppDelegate).session!)
parent!.subChanged = false
BannerUtil.makeBanner(text: "Unsubscribed", seconds: 5, context: self.parent, top: true)
} else {
let alrController = DragDownAlertMenu(title: "Follow r/\(sub.displayName)", subtitle: "", icon: nil, themeColor: ColorUtil.accentColorForSub(sub: sub.displayName), full: true)
if AccountController.isLoggedIn {
alrController.addAction(title: "Subscribe", icon: nil) {
Subscriptions.subscribe(sub.displayName, true, session: (UIApplication.shared.delegate as! AppDelegate).session!)
self.parent!.subChanged = true
BannerUtil.makeBanner(text: "Subscribed", seconds: 5, context: self.parent, top: true)
}
}
alrController.addAction(title: "Casually subscribe", icon: nil) {
Subscriptions.subscribe(sub.displayName, false, session: (UIApplication.shared.delegate as! AppDelegate).session!)
self.parent!.subChanged = true
BannerUtil.makeBanner(text: "Added to subscription list", seconds: 5, context: self.parent, top: true)
}
alrController.show(parent)
}
}
}
// Helper function inserted by Swift 4.2 migrator.
private func convertToUIApplicationOpenExternalURLOptionsKeyDictionary(_ input: [String: Any]) -> [UIApplication.OpenExternalURLOptionsKey: Any] {
return Dictionary(uniqueKeysWithValues: input.map { key, value in (UIApplication.OpenExternalURLOptionsKey(rawValue: key), value) })
}
| apache-2.0 | 60555ca644c0f6e4eea4f44c842a74aa | 40.2 | 187 | 0.626753 | 4.970509 | false | false | false | false |
drewag/Swiftlier | Sources/Swiftlier/Model/Containers/PatchyRange.swift | 1 | 5013 | //
// PatchyRange.swift
// SwiftlieriOS
//
// Created by Andrew J Wagner on 6/2/17.
// Copyright © 2017 Drewag. All rights reserved.
//
public struct PatchyRange<Value: Comparable> {
fileprivate struct Node {
let value: Value
var opening: Int = 0
var closing: Int = 0
var openAndClose: Int = 0
init(openingWith value: Value) {
self.value = value
self.opening = 1
}
init(closingWith value: Value) {
self.value = value
self.closing = 1
}
init(openingAndClosingWith value: Value) {
self.value = value
self.openAndClose = 1
}
var includeTheFollwing: Bool {
return (opening - closing) > 0
}
}
fileprivate var nodes = [Node]()
public init() {}
public mutating func appendRange(from: Value, to: Value) {
defer {
self.cleanupNodes()
}
guard from < to else {
if from == to, let index = self.indexOfNode(onOrBefore: from) {
if self.nodes[index].value == from {
self.nodes[index].openAndClose += 1
}
else {
self.nodes.insert(Node(openingAndClosingWith: from), at: index + 1)
}
}
return
}
if let index = self.indexOfNode(onOrBefore: from) {
if self.nodes[index].value == from {
self.nodes[index].opening += 1
}
else {
self.nodes.insert(Node(openingWith: from), at: index + 1)
}
}
else {
self.nodes.insert(Node(openingWith: from), at: 0)
}
if let index = self.indexOfNode(onOrAfter: to) {
if self.nodes[index].value == to {
self.nodes[index].closing += 1
}
else {
self.nodes.insert(Node(closingWith: to), at: index)
}
}
else {
self.nodes.append(Node(closingWith: to))
}
}
public func contains(_ value: Value) -> Bool {
guard let index = self.indexOfNode(onOrBefore: value) else {
return false
}
return self.nodes[index].value == value
|| self.nodes[index].includeTheFollwing
}
}
extension PatchyRange: CustomStringConvertible {
public var description: String {
var output = "PatchRange("
for (index, node) in self.nodes.enumerated() {
if index > 0 {
output += " "
}
output += "\(node.value)"
if node.opening != 0 {
output += "+\(node.opening)"
}
if node.openAndClose != 0 {
output += "#\(node.openAndClose)"
}
if node.closing != 0 {
output += "-\(node.closing)"
}
}
return output + ")"
}
}
private extension PatchyRange {
func indexOfFirstValue(greaterThanOrEqualTo value: Value) -> Int? {
for (index, node) in self.nodes.enumerated() {
if node.value >= value {
return index
}
}
return nil
}
func indexOfNode(onOrBefore before: Value) -> Int? {
guard let index = indexOfFirstValue(greaterThanOrEqualTo: before) else {
return self.nodes.count > 0 ? self.nodes.count - 1 : nil
}
guard self.nodes[index].value != before else {
return index
}
guard index > 0 else {
return nil
}
return index - 1
}
func indexOfNode(onOrAfter after: Value) -> Int? {
guard let index = indexOfFirstValue(greaterThanOrEqualTo: after), index < self.nodes.count else {
return nil
}
guard self.nodes[index].value != after else {
return index
}
return index
}
mutating func cleanupNodes() {
var includeCount = 0
for (index, node) in self.nodes.enumerated().reversed() {
includeCount -= node.opening
includeCount += node.closing
if node.opening > 0 {
if includeCount > 0 {
self.nodes.remove(at: index)
}
else {
self.nodes[index] = Node(openingWith: node.value)
}
continue
}
else if node.closing > 0 {
if includeCount - node.closing > 0 {
self.nodes.remove(at: index)
}
else {
self.nodes[index] = Node(closingWith: node.value)
}
continue
}
else if node.openAndClose > 0 {
if includeCount > 0 {
self.nodes.remove(at: index)
}
continue
}
}
}
}
| mit | 5664c13ab3fac26a37c7248368b735d1 | 26.091892 | 105 | 0.480447 | 4.657993 | false | false | false | false |
antonio081014/LeetCode-CodeBase | Swift/count-all-valid-pickup-and-delivery-options.swift | 1 | 319 | // Date: Mon Mar 7 17:31:50 PST 2022
class Solution {
func countOrders(_ n: Int) -> Int {
let MOD = 1000000007
var result = 1
for index in 1 ... n {
result *= index
result = result * ( 2 * index - 1)
result %= MOD
}
return result
}
}
| mit | 1b5b59b37939914db9c8f22910d9ce6d | 23.538462 | 46 | 0.46395 | 4.037975 | false | false | false | false |
DimensionSrl/Desman | Sample/Desman iOS Sample/AppDelegate.swift | 1 | 1992 | //
// AppDelegate.swift
// Desman iOS Sample
//
// Created by Matteo Gavagnin on 19/10/15.
// Copyright © 2015 DIMENSION S.r.l. All rights reserved.
//
import UIKit
import Desman
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
logEvents()
// logFlow()
return true
}
func logEvents() {
DispatchQueue.main.async {
Des.takeOff(appKey: "HIre5w9XvBFEYt3yIizCN01CeManBsEx37lKQbiQ7BE=")
Des.swizzles = [.viewWillAppear, .viewWillDisappear]
Des.consoleLog = true
Des.startLogging()
Des.limit = 40
Des.timeInterval = 1.0
// Des is an alias for EventManager.shared
Des.logType(AppCycle.DidFinishLaunching)
Des.log(DeviceInfo())
Des.log(DeviceUserInfo())
let event = Event(DType(subtype: "user"), value: "[email protected]")
Des.log(event)
Des.listenToAppLifecycleActivity()
Des.listenToScreenshots()
}
}
func logFlow() {
DispatchQueue.main.async {
Des.takeOff(appKey: "E3128D2E-9C65-44F0-9AF4-F69DD49448DC", endpoint: .flow)
Des.swizzles = [.viewWillAppear, .viewWillDisappear]
Des.startLogging()
Des.consoleLog = false
Des.limit = 40
Des.timeInterval = 1.0
// Des is an alias for EventManager.shared
Des.logType(AppCycle.DidFinishLaunching)
Des.log(DeviceInfo())
Des.log(DeviceUserInfo())
let event = Event(DType(subtype: "user"), value: "[email protected]")
Des.log(event)
Des.listenToAppLifecycleActivity()
Des.listenToScreenshots()
}
}
}
| mit | 9d816ab5176b2d9a4e4461ab4f52e25d | 30.603175 | 144 | 0.585635 | 4.272532 | false | false | false | false |
wyp767363905/TestKitchen_1606 | TestKitchen/TestKitchen/classes/common/KTCHomeViewController.swift | 1 | 2320 | //
// KTCHomeViewController.swift
// TestKitchen
//
// Created by qianfeng on 16/8/26.
// Copyright © 2016年 1606. All rights reserved.
//
import UIKit
/** 这个类用来封装tabbar的显示和隐藏的方法*/
class KTCHomeViewController: BaseViewController {
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
//显示tabbar
let appDele = UIApplication.sharedApplication().delegate as! AppDelegate
let ctrl = appDele.window?.rootViewController
if ctrl?.isKindOfClass(MainTabBarController.self) == true {
let mainTabBarCtrl = ctrl as! MainTabBarController
mainTabBarCtrl.showTabbar()
}
}
override func viewDidAppear(animated: Bool) {
super.viewDidAppear(animated)
//显示tabbar
let appDele = UIApplication.sharedApplication().delegate as! AppDelegate
let ctrl = appDele.window?.rootViewController
if ctrl?.isKindOfClass(MainTabBarController.self) == true {
let mainTabBarCtrl = ctrl as! MainTabBarController
mainTabBarCtrl.showTabbar()
}
}
override func viewWillDisappear(animated: Bool) {
super.viewDidDisappear(animated)
//隐藏tabbar
let appDele = UIApplication.sharedApplication().delegate as! AppDelegate
let ctrl = appDele.window?.rootViewController
if ctrl?.isKindOfClass(MainTabBarController.self) == true {
let mainTabBarCtrl = ctrl as! MainTabBarController
mainTabBarCtrl.hideTabbar()
}
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
| mit | fe041a236ed1b450b8ed09f20d178ff4 | 29.306667 | 106 | 0.649362 | 5.598522 | false | false | false | false |
kaishin/gifu | Sources/Gifu/Classes/FrameStore.swift | 1 | 8868 | #if os(iOS) || os(tvOS)
import ImageIO
import UIKit
/// Responsible for storing and updating the frames of a single GIF.
class FrameStore {
/// Total duration of one animation loop
var loopDuration: TimeInterval = 0
/// Flag indicating if number of loops has been reached
var isFinished: Bool = false
/// Desired number of loops, <= 0 for infinite loop
let loopCount: Int
/// Index of current loop
var currentLoop = 0
/// Maximum duration to increment the frame timer with.
let maxTimeStep = 1.0
/// An array of animated frames from a single GIF image.
var animatedFrames = [AnimatedFrame]()
/// The target size for all frames.
let size: CGSize
/// The content mode to use when resizing.
let contentMode: UIView.ContentMode
/// Maximum number of frames to load at once
let bufferFrameCount: Int
/// The total number of frames in the GIF.
var frameCount = 0
/// A reference to the original image source.
var imageSource: CGImageSource
/// The index of the current GIF frame.
var currentFrameIndex = 0 {
didSet {
previousFrameIndex = oldValue
}
}
/// The index of the previous GIF frame.
var previousFrameIndex = 0 {
didSet {
preloadFrameQueue.async {
self.updatePreloadedFrames()
}
}
}
/// Time elapsed since the last frame change. Used to determine when the frame should be updated.
var timeSinceLastFrameChange: TimeInterval = 0.0
/// Specifies whether GIF frames should be resized.
var shouldResizeFrames = true
/// Dispatch queue used for preloading images.
private lazy var preloadFrameQueue: DispatchQueue = {
return DispatchQueue(label: "co.kaishin.Gifu.preloadQueue")
}()
/// The current image frame to show.
var currentFrameImage: UIImage? {
return frame(at: currentFrameIndex)
}
/// The current frame duration
var currentFrameDuration: TimeInterval {
return duration(at: currentFrameIndex)
}
/// Is this image animatable?
var isAnimatable: Bool {
return imageSource.isAnimatedGIF
}
/// Creates an animator instance from raw GIF image data and an `Animatable` delegate.
///
/// - parameter data: The raw GIF image data.
/// - parameter delegate: An `Animatable` delegate.
init(data: Data, size: CGSize, contentMode: UIView.ContentMode, framePreloadCount: Int, loopCount: Int) {
let options = [String(kCGImageSourceShouldCache): kCFBooleanFalse] as CFDictionary
self.imageSource = CGImageSourceCreateWithData(data as CFData, options) ?? CGImageSourceCreateIncremental(options)
self.size = size
self.contentMode = contentMode
self.bufferFrameCount = framePreloadCount
self.loopCount = loopCount
}
// MARK: - Frames
/// Loads the frames from an image source, resizes them, then caches them in `animatedFrames`.
func prepareFrames(_ completionHandler: (() -> Void)? = nil) {
frameCount = Int(CGImageSourceGetCount(imageSource))
animatedFrames.reserveCapacity(frameCount)
preloadFrameQueue.async {
self.setupAnimatedFrames()
completionHandler?()
}
}
/// Returns the frame at a particular index.
///
/// - parameter index: The index of the frame.
/// - returns: An optional image at a given frame.
func frame(at index: Int) -> UIImage? {
return animatedFrames[safe: index]?.image
}
/// Returns the duration at a particular index.
///
/// - parameter index: The index of the duration.
/// - returns: The duration of the given frame.
func duration(at index: Int) -> TimeInterval {
return animatedFrames[safe: index]?.duration ?? TimeInterval.infinity
}
/// Checks whether the frame should be changed and calls a handler with the results.
///
/// - parameter duration: A `CFTimeInterval` value that will be used to determine whether frame should be changed.
/// - parameter handler: A function that takes a `Bool` and returns nothing. It will be called with the frame change result.
func shouldChangeFrame(with duration: CFTimeInterval, handler: (Bool) -> Void) {
incrementTimeSinceLastFrameChange(with: duration)
if currentFrameDuration > timeSinceLastFrameChange {
handler(false)
} else {
resetTimeSinceLastFrameChange()
incrementCurrentFrameIndex()
handler(true)
}
}
}
private extension FrameStore {
/// Whether preloading is needed or not.
var preloadingIsNeeded: Bool {
return bufferFrameCount < frameCount - 1
}
/// Optionally loads a single frame from an image source, resizes it if required, then returns an `UIImage`.
///
/// - parameter index: The index of the frame to load.
/// - returns: An optional `UIImage` instance.
func loadFrame(at index: Int) -> UIImage? {
guard let imageRef = CGImageSourceCreateImageAtIndex(imageSource, index, nil) else { return nil }
let image = UIImage(cgImage: imageRef)
let scaledImage: UIImage?
if shouldResizeFrames {
switch self.contentMode {
case .scaleAspectFit: scaledImage = image.constrained(by: size)
case .scaleAspectFill: scaledImage = image.filling(size: size)
default: scaledImage = image.resized(to: size)
}
} else {
scaledImage = image
}
return scaledImage
}
/// Updates the frames by preloading new ones and replacing the previous frame with a placeholder.
func updatePreloadedFrames() {
if !preloadingIsNeeded { return }
animatedFrames[previousFrameIndex] = animatedFrames[previousFrameIndex].placeholderFrame
preloadIndexes(withStartingIndex: currentFrameIndex).forEach { index in
let currentAnimatedFrame = animatedFrames[index]
if !currentAnimatedFrame.isPlaceholder { return }
animatedFrames[index] = currentAnimatedFrame.makeAnimatedFrame(with: loadFrame(at: index))
}
}
/// Increments the `timeSinceLastFrameChange` property with a given duration.
///
/// - parameter duration: An `NSTimeInterval` value to increment the `timeSinceLastFrameChange` property with.
func incrementTimeSinceLastFrameChange(with duration: TimeInterval) {
timeSinceLastFrameChange += min(maxTimeStep, duration)
}
/// Ensures that `timeSinceLastFrameChange` remains accurate after each frame change by substracting the `currentFrameDuration`.
func resetTimeSinceLastFrameChange() {
timeSinceLastFrameChange -= currentFrameDuration
}
/// Increments the `currentFrameIndex` property.
func incrementCurrentFrameIndex() {
currentFrameIndex = increment(frameIndex: currentFrameIndex)
if isLastLoop(loopIndex: currentLoop) && isLastFrame(frameIndex: currentFrameIndex) {
isFinished = true
} else if currentFrameIndex == 0 {
currentLoop = currentLoop + 1
}
}
/// Increments a given frame index, taking into account the `frameCount` and looping when necessary.
///
/// - parameter index: The `Int` value to increment.
/// - parameter byValue: The `Int` value to increment with.
/// - returns: A new `Int` value.
func increment(frameIndex: Int, by value: Int = 1) -> Int {
return (frameIndex + value) % frameCount
}
/// Indicates if current frame is the last one.
/// - parameter frameIndex: Index of current frame.
/// - returns: True if current frame is the last one.
func isLastFrame(frameIndex: Int) -> Bool {
return frameIndex == frameCount - 1
}
/// Indicates if current loop is the last one. Always false for infinite loops.
/// - parameter loopIndex: Index of current loop.
/// - returns: True if current loop is the last one.
func isLastLoop(loopIndex: Int) -> Bool {
return loopIndex == loopCount - 1
}
/// Returns the indexes of the frames to preload based on a starting frame index.
///
/// - parameter index: Starting index.
/// - returns: An array of indexes to preload.
func preloadIndexes(withStartingIndex index: Int) -> [Int] {
let nextIndex = increment(frameIndex: index)
let lastIndex = increment(frameIndex: index, by: bufferFrameCount)
if lastIndex >= nextIndex {
return [Int](nextIndex...lastIndex)
} else {
return [Int](nextIndex..<frameCount) + [Int](0...lastIndex)
}
}
func setupAnimatedFrames() {
resetAnimatedFrames()
var duration: TimeInterval = 0
(0..<frameCount).forEach { index in
let frameDuration = CGImageFrameDuration(with: imageSource, atIndex: index)
duration += min(frameDuration, maxTimeStep)
animatedFrames += [AnimatedFrame(image: nil, duration: frameDuration)]
if index > bufferFrameCount { return }
animatedFrames[index] = animatedFrames[index].makeAnimatedFrame(with: loadFrame(at: index))
}
self.loopDuration = duration
}
/// Reset animated frames.
func resetAnimatedFrames() {
animatedFrames = []
}
}
#endif
| mit | f65a2fb61a446d7bbbf7be2b2851d10d | 32.847328 | 130 | 0.697903 | 4.896742 | false | false | false | false |
lorentey/swift | test/Sema/call_as_function_simple.swift | 3 | 5565 | // RUN: %target-typecheck-verify-swift
struct SimpleCallable {
func callAsFunction(_ x: Float) -> Float {
return x
}
}
// Simple tests.
let foo = SimpleCallable()
_ = foo(1)
_ = foo(foo(1))
_ = foo(1, 1) // expected-error@:12 {{extra argument in call}}
// expected-error @+1 {{cannot convert value of type 'SimpleCallable' to specified type '(Float) -> Float'}}
let _: (Float) -> Float = foo
// Test direct `callAsFunction` member references.
_ = foo.callAsFunction(1)
_ = [1, 2, 3].map(foo.callAsFunction)
_ = foo.callAsFunction(foo(1))
_ = foo(foo.callAsFunction(1))
let _: (Float) -> Float = foo.callAsFunction
func callable() -> SimpleCallable {
return SimpleCallable()
}
extension SimpleCallable {
var foo: SimpleCallable {
return self
}
func bar() -> SimpleCallable {
return self
}
}
_ = foo.foo(1)
_ = foo.bar()(1)
_ = callable()(1)
_ = [1, 2, 3].map(foo.foo.callAsFunction)
_ = [1, 2, 3].map(foo.bar().callAsFunction)
_ = [1, 2, 3].map(callable().callAsFunction)
struct MultipleArgsCallable {
func callAsFunction(x: Int, y: Float) -> [Int] {
return [x]
}
}
let bar = MultipleArgsCallable()
_ = bar(x: 1, y: 1)
_ = bar.callAsFunction(x: 1, y: 1)
_ = bar(x: bar.callAsFunction(x: 1, y: 1)[0], y: 1)
_ = bar.callAsFunction(x: bar(x: 1, y: 1)[0], y: 1)
_ = bar(1, 1) // expected-error {{missing argument labels 'x:y:' in call}}
struct Extended {}
extension Extended {
@discardableResult
func callAsFunction() -> Extended {
return self
}
}
var extended = Extended()
extended()().callAsFunction()()
struct TakesTrailingClosure {
func callAsFunction(_ fn: () -> Void) {
fn()
}
func callAsFunction(_ x: Int, label y: Float, _ fn: (Int, Float) -> Void) {
fn(x, y)
}
}
var takesTrailingClosure = TakesTrailingClosure()
takesTrailingClosure { print("Hi") }
takesTrailingClosure() { print("Hi") }
takesTrailingClosure(1, label: 2) { _ = Float($0) + $1 }
struct OptionalCallable {
func callAsFunction() -> OptionalCallable? {
return self
}
}
var optional = OptionalCallable()
_ = optional()?.callAsFunction()?()
struct Variadic {
func callAsFunction(_ args: Int...) -> [Int] {
return args
}
}
var variadic = Variadic()
_ = variadic()
_ = variadic(1, 2, 3)
struct Mutating {
var x: Int
mutating func callAsFunction() {
x += 1
}
}
func testMutating(_ x: Mutating, _ y: inout Mutating) {
// expected-error @+1 {{cannot use mutating member on immutable value: 'x' is a 'let' constant}}
_ = x()
// expected-error @+1 {{cannot use mutating member on immutable value: 'x' is a 'let' constant}}
_ = x.callAsFunction()
_ = y()
_ = y.callAsFunction()
}
struct Inout {
func callAsFunction(_ x: inout Int) {
x += 5
}
}
func testInout(_ x: Inout, _ arg: inout Int) {
x(&arg)
x.callAsFunction(&arg)
// expected-error @+1 {{passing value of type 'Int' to an inout parameter requires explicit '&'}}
x(arg)
// expected-error @+1 {{passing value of type 'Int' to an inout parameter requires explicit '&'}}
x.callAsFunction(arg)
}
struct Autoclosure {
func callAsFunction(_ condition: @autoclosure () -> Bool,
_ message: @autoclosure () -> String) {
if condition() {
print(message())
}
}
}
func testAutoclosure(_ x: Autoclosure) {
x(true, "Failure")
x({ true }(), { "Failure" }())
}
struct Throwing {
func callAsFunction() throws -> Throwing {
return self
}
func callAsFunction(_ f: () throws -> ()) rethrows {
try f()
}
}
struct DummyError : Error {}
var throwing = Throwing()
_ = try throwing()
_ = try throwing { throw DummyError() }
enum BinaryOperation {
case add, subtract, multiply, divide
}
extension BinaryOperation {
func callAsFunction(_ lhs: Float, _ rhs: Float) -> Float {
switch self {
case .add: return lhs + rhs
case .subtract: return lhs - rhs
case .multiply: return lhs * rhs
case .divide: return lhs / rhs
}
}
}
_ = BinaryOperation.add(1, 2)
class BaseClass {
func callAsFunction() -> Self {
return self
}
}
class SubClass : BaseClass {
override func callAsFunction() -> Self {
return self
}
}
func testIUO(a: SimpleCallable!, b: MultipleArgsCallable!, c: Extended!,
d: OptionalCallable!, e: Variadic!, f: inout Mutating!,
g: Inout!, inoutInt: inout Int, h: Throwing!) {
_ = a(1)
_ = b(x: 1, y: 1)
_ = c()
_ = d()?.callAsFunction()?()
_ = e()
_ = e(1, 2, 3)
_ = f()
_ = g(&inoutInt)
_ = try? h()
_ = try? h { throw DummyError() }
}
// SR-11778
struct DoubleANumber {
func callAsFunction(_ x: Int, completion: (Int) -> Void = { _ in }) {
completion(x + x)
}
}
func testDefaults(_ x: DoubleANumber) {
x(5)
x(5, completion: { _ in })
}
// SR-11881
struct IUOCallable {
static var callable: IUOCallable { IUOCallable() }
func callAsFunction(_ x: Int) -> IUOCallable! { nil }
}
func testIUOCallAsFunction(_ x: IUOCallable) {
let _: IUOCallable = x(5)
let _: IUOCallable? = x(5)
let _ = x(5)
let _: IUOCallable = .callable(5)
let _: IUOCallable? = .callable(5)
}
// Test access control.
struct PrivateCallable {
private func callAsFunction(_ x: Int) {} // expected-note {{'callAsFunction' declared here}}
}
func testAccessControl(_ x: PrivateCallable) {
x(5) // expected-error {{'callAsFunction' is inaccessible due to 'private' protection level}}
}
struct SR_11909 {
static let s = SR_11909()
func callAsFunction(_ x: Int = 0) -> SR_11909 { SR_11909() }
}
func testDefaultsWithUMEs(_ x: SR_11909) {
let _: SR_11909 = .s()
let _: SR_11909 = .s(5)
}
| apache-2.0 | 8cc94354d6b3b0e3ffef4fb8a653ec04 | 22.382353 | 108 | 0.624079 | 3.405753 | false | false | false | false |
larrabetzu/iBasque-Radio | SwiftRadio/RadioStation.swift | 1 | 1608 | //
// RadioStation.swift
// Swift Radio
//
// Created by Matthew Fecher on 7/4/15.
// Copyright (c) 2015 MatthewFecher.com. All rights reserved.
//
import UIKit
//*****************************************************************
// Radio Station
//*****************************************************************
class RadioStation: Decodable {
var name : String
var streamURL: String
var imageURL : String
var websiteURL : String
var desc : String
var longDesc : String
init(name: String, streamURL: String, imageURL: String, websiteURL: String, desc: String, longDesc: String){
self.name = name
self.streamURL = streamURL
self.imageURL = imageURL
self.websiteURL = websiteURL
self.desc = desc
self.longDesc = longDesc
}
// Convenience init without longDesc
convenience init(name: String, streamURL: String, imageURL: String, websiteURL: String, desc: String){
self.init(name: name, streamURL: streamURL, imageURL: imageURL, websiteURL: websiteURL,desc: desc, longDesc: "")
}
//*****************************************************************
// MARK: - JSON Parsing into object
//*****************************************************************
class func parseStations(jsonString: String) -> [RadioStation] {
let jsonData = jsonString.data(using: .utf8)!
let decoder = JSONDecoder()
let radioStation = try! decoder.decode([RadioStation].self, from: jsonData)
return radioStation
}
}
| mit | 05bc25ec47562f5a3f0e0a82c739c8dc | 31.16 | 120 | 0.524876 | 5.170418 | false | false | false | false |
wendru/tips | tips/ViewController.swift | 1 | 2357 | //
// ViewController.swift
// tips
//
// Created by Andrew Wen on 2/1/15.
// Copyright (c) 2015 wendru. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var tipLabel: UILabel!
@IBOutlet weak var totalLabel: UILabel!
@IBOutlet weak var billField: UITextField!
@IBOutlet weak var tipControl: UISegmentedControl!
@IBOutlet weak var faceImage: UIImageView!
var defaults = NSUserDefaults.standardUserDefaults()
var tipPercentages = [15, 18, 20]
var faces = [
UIImage(named: "really.png"),
UIImage(named: "happy.jpg"),
UIImage(named: "joy.jpeg")
]
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
loadPresets()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
tipControl.selectedSegmentIndex = 2;
}
func loadPresets() {
if(defaults.boolForKey("custom_presets")) {
tipPercentages = [
defaults.integerForKey("option1"),
defaults.integerForKey("option2"),
defaults.integerForKey("option3")
]
tipControl.setTitle("\(tipPercentages[0])%", forSegmentAtIndex: 0)
tipControl.setTitle("\(tipPercentages[1])%", forSegmentAtIndex: 1)
tipControl.setTitle("\(tipPercentages[2])%", forSegmentAtIndex: 2)
}
}
@IBAction func onEditingChanged(sender: AnyObject) {
var index = tipControl.selectedSegmentIndex
var tipPercentage = Double(tipPercentages[index]) / 100
var billAmount = NSString(string: billField.text).doubleValue
var tip = billAmount * tipPercentage
var total = billAmount + tip
tipLabel.text = String(format: "$%.2f", tip)
totalLabel.text = String(format: "$%.2f", total)
if(billAmount > 0) {
faceImage.image = faces[index]
} else {
faceImage.image = nil
}
}
@IBAction func onTap(sender: AnyObject) {
view.endEditing(true)
}
}
| gpl-2.0 | 95d7998c0d53569516d07c01bca6bc20 | 28.848101 | 80 | 0.610946 | 4.879917 | false | false | false | false |
nakau1/NerobluCore | NerobluCore/NBView+Dialog.swift | 1 | 5783 | // =============================================================================
// NerobluCore
// Copyright (C) NeroBlu. All rights reserved.
// =============================================================================
import UIKit
// MARK: - NBDialogPresentationOption -
/// ダイアログ表示のオプション設定
public struct NBDialogPresentationOption {
/// イニシャライザ
/// - parameter cancellable: 背景がタップされた時に閉じるかどうか
public init(cancellable: Bool = false) {
self.cancellable = cancellable
}
/// 背景がタップされた時に閉じるかどうか
public var cancellable = false
/// 背景にブラーエフェクトをかけるかどうか
public var blur = false
/// ブラーエフェクトのスタイル
public var blurEffectStyle: UIBlurEffectStyle = .Light
/// ビューを自動的に中央に配置するかどうか
public var automaticCenter = true
/// 背景色
public var backgroundColor = UIColor.blackColor().colorWithAlphaComponent(0.75)
/// 表示時のアニメーション間隔
public var presentationDuration: NSTimeInterval = 0.3
/// 表示時のアニメーションオプション
public var presentationAnimationOptions: UIViewAnimationOptions = [.TransitionCrossDissolve, .CurveEaseInOut]
/// 表示終了時のアニメーション間隔
public var dismissingDuration: NSTimeInterval = 0.3
/// 表示終了時のアニメーションオプション
public var dismissingAnimationOptions: UIViewAnimationOptions = [.TransitionCrossDissolve, .CurveEaseInOut]
}
// MARK: - UIView+Dialog -
/// ダイアログ表示用UIView拡張
public extension UIView {
/// ダイアログとして表示する
/// - parameter option: ダイアログ表示のオプション設定
/// - parameter completionHandler: 表示完了時の処理
public func presentAsDialog(option: NBDialogPresentationOption? = nil, completionHandler: CompletionHandler? = nil) {
if UIView.dialogBackground != nil { return }
let opt = option ?? NBDialogPresentationOption()
let mask = opt.blur ? UIVisualEffectView(effect: UIBlurEffect(style: opt.blurEffectStyle)) : UIView()
mask.frame = UIScreen.mainScreen().bounds
mask.backgroundColor = opt.backgroundColor
mask.alpha = 0.0
if opt.automaticCenter {
let x = (crW(mask.frame) - crW(self.frame)) / 2
let y = (crH(mask.frame) - crH(self.frame)) / 2
self.frame.origin = cp(x, y)
}
if opt.cancellable {
let gesture = UITapGestureRecognizer(target: self, action: Selector("didTapDialogBackground"))
let handler = UIView.DialogBackgroundTapHandler(view: self)
gesture.delegate = handler
UIView.dialogBackgroundTapHandler = handler
mask.addGestureRecognizer(gesture)
}
mask.addSubview(self)
UIView.dialogBackground = mask
let windows = UIApplication.sharedApplication().windows.reverse()
for window in windows {
let isMainScreen = window.screen == UIScreen.mainScreen()
let isVisible = !window.hidden && window.alpha > 0
let isNormalLevel = window.windowLevel == UIWindowLevelNormal
if isMainScreen && isVisible && isNormalLevel {
window.addSubview(mask)
}
}
UIView.transitionWithView(mask, duration: opt.presentationDuration, options: opt.presentationAnimationOptions,
animations: {
mask.alpha = 1.0
},
completion: { _ in
completionHandler?()
}
)
}
/// 表示しているダイアログの表示を終了する
/// - parameter option: ダイアログ表示のオプション設定
/// - parameter completionHandler: 表示終了完了時の処理
public class func dismissPresentedDialog(option: NBDialogPresentationOption? = nil, completionHandler: CompletionHandler? = nil) {
guard let mask = self.dialogBackground else {
return
}
let opt = option ?? NBDialogPresentationOption()
UIView.transitionWithView(mask, duration: opt.dismissingDuration, options: opt.dismissingAnimationOptions,
animations: {
mask.alpha = 0.0
},
completion: { _ in
mask.subviews.forEach { $0.removeFromSuperview() }
UIView.dialogBackground = nil
UIView.dialogBackgroundTapHandler = nil
completionHandler?()
}
)
}
@objc private func didTapDialogBackground() {
UIView.dismissPresentedDialog()
}
private static var dialogBackground: UIView? = nil
private static var dialogBackgroundTapHandler: DialogBackgroundTapHandler? = nil
private class DialogBackgroundTapHandler : NSObject, UIGestureRecognizerDelegate {
private var view: UIView
init(view: UIView) {
self.view = view
}
@objc func gestureRecognizer(gestureRecognizer: UIGestureRecognizer, shouldReceiveTouch touch: UITouch) -> Bool {
if let touchedView = touch.view {
if touchedView == self.view {
return false
}
for v in self.view.subviews {
if touchedView.isDescendantOfView(v) {
return false
}
}
}
return true
}
}
}
| apache-2.0 | 3193d6b76279ab8d6097275cf77c1225 | 35.255172 | 134 | 0.592924 | 5.283417 | false | false | false | false |
ykyouhei/FBPhotoViewer | FBPhotoViewerKit/SocialManager.swift | 1 | 5527 | //
// SocialManager.swift
// FBPhotos
//
// Created by kyo__hei on 2014/10/04.
// Copyright (c) 2014年 kyo__hei. All rights reserved.
//
import UIKit
import Foundation
import Accounts
import Social
/**
* ソーシャルアカウントへのアクセスなどを管理するシングルトンクラス
*/
public class SocialManager: NSObject {
public typealias RequestAccessCompletionHandler = ([AnyObject]?, NSError!) -> Void
public typealias RequestAboutUserCompletionHandler = (FBUserModel?, NSError!) -> Void
/**************************************************************************/
// MARK: - Types
/**************************************************************************/
public struct Error {
static let errorDomain = "SocialManager"
struct Code {
static let userNotGranted = 1
static let notSupportedType = 2
}
}
private struct GraphAPIEndPoint {
static let root = "https://graph.facebook.com"
static let me = root + "/me"
}
/**************************************************************************/
// MARK: - Properties
/**************************************************************************/
private let _fbAppID = "268362399954732"
private let _store = ACAccountStore()
private var _fbAccount: ACAccount?
/**************************************************************************/
// MARK: - Initializer
/**************************************************************************/
private override init() {
}
public class var sharedManager : SocialManager {
struct Static {
static let instance : SocialManager = SocialManager()
}
return Static.instance
}
/**************************************************************************/
// MARK: - Public Method
/**************************************************************************/
/**
各種ソーシャルアカウントへのアクセス権限を確認する
:param: id ソーシャルアカウントのID
:returns: アクセス権限
*/
public func accessGrantedWithAccountTypeIdentifier(id: NSString) -> Bool {
let accountType = _store.accountTypeWithAccountTypeIdentifier(id)
return accountType.accessGranted
}
/**
各種ソーシャルアカウントへのアクセスを要求する
:param: id ソーシャルアカウントのID
:param: completion ユーザが返答した際のコールバック
*/
public func requestAccessWithAccountTypeIdentifier(id: NSString, completion: RequestAccessCompletionHandler) {
let accountType = _store.accountTypeWithAccountTypeIdentifier(id)
var options: [NSObject : AnyObject]?
if id.isEqualToString(ACAccountTypeIdentifierFacebook) {
let permissions = ["email", "user_about_me", "user_likes", "user_photos"]
options = [ACFacebookAppIdKey: _fbAppID,
ACFacebookPermissionsKey: permissions,
ACFacebookAudienceKey: ACFacebookAudienceFriends]
} else {
let error = NSError(domain: Error.errorDomain, code: Error.Code.notSupportedType, userInfo: nil)
completion(nil, error)
}
_store.requestAccessToAccountsWithType(accountType, options: options) { (granted: Bool, error:
NSError!) -> Void in
dispatch_async(dispatch_get_main_queue(), { () -> Void in
if error != nil {
completion(nil, error)
return
} else if granted == false {
let userInfo = [NSLocalizedDescriptionKey: NSLocalizedString("errorNotGranted", comment: "")]
let grantError = NSError(domain: Error.errorDomain, code: Error.Code.userNotGranted, userInfo: userInfo)
completion(nil, grantError)
} else {
let accounts = self._store.accountsWithAccountType(accountType)
self._fbAccount = accounts?[0] as? ACAccount
completion(accounts, nil)
}
})
}
}
public func requestAboutMeWithCompletion(completion: RequestAboutUserCompletionHandler) {
let url = NSURL(string: GraphAPIEndPoint.me)
let params = ["fields": "cover,picture.type(large),name",
"locale": "ja_JP"]
let request = SLRequest(forServiceType: SLServiceTypeFacebook, requestMethod: SLRequestMethod.GET, URL: url, parameters: params)
request.account = _fbAccount
request.performRequestWithHandler { (data, response, error) -> Void in
dispatch_async(dispatch_get_main_queue(), { () -> Void in
if error != nil {
completion(nil, error)
} else {
var jsonError: NSError?
if let result = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.AllowFragments, error: &jsonError) as? [String: AnyObject] {
var userModel = FBUserModel(response: result)
completion(userModel, nil)
} else {
completion(nil, jsonError)
}
}
})
}
}
} | apache-2.0 | 1044deed9c1032753e3d7ab74953624e | 36.169014 | 171 | 0.51317 | 5.531447 | false | false | false | false |
JoeLago/MHGDB-iOS | MHGDB/Screens/Weapon/Custom/SharpnessesView.swift | 1 | 1689 | //
// MIT License
// Copyright (c) Gathering Hall Studios
//
import UIKit
class SharpnesesView: UIView {
var sharpnessViews = [SharpnessView]()
var sharpnesses: [Sharpness]? {
didSet {
if sharpnesses == nil {
isHidden = true
return
}
isHidden = false
sharpnessViews[0].sharpness = sharpnesses![0]
sharpnessViews[1].sharpness = sharpnesses![1]
sharpnessViews[2].sharpness = sharpnesses![2]
}
}
init() {
super.init(frame: CGRect.zero)
createViews()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func createViews() {
sharpnessViews.append(SharpnessView())
sharpnessViews.append(SharpnessView())
sharpnessViews.append(SharpnessView())
addSubview(sharpnessViews[0])
addSubview(sharpnessViews[1])
addSubview(sharpnessViews[2])
sharpnessViews[0].paddingBottom = 1
sharpnessViews[1].paddingTop = 1
sharpnessViews[1].paddingBottom = 1
sharpnessViews[2].paddingTop = 1
useConstraintsOnly()
addConstraints(
formatStrings: ["H:|[one]|",
"H:|[two]|",
"H:|[three]|",
"V:|[one(==two)][two(==one)][three(==one)]|"],
views: [
"one": sharpnessViews[0],
"two": sharpnessViews[1],
"three": sharpnessViews[2]
],
metrics: [:])
}
}
| mit | c9d63fa726e86fc67cf5192d3cd09710 | 25.809524 | 74 | 0.502072 | 5.118182 | false | false | false | false |
mozilla-mobile/firefox-ios | Client/Helpers/MenuHelper.swift | 2 | 2452 | // 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
@objc public protocol MenuHelperInterface {
@objc optional func menuHelperCopy()
@objc optional func menuHelperOpenAndFill()
@objc optional func menuHelperReveal()
@objc optional func menuHelperSecure()
@objc optional func menuHelperFindInPage()
@objc optional func menuHelperSearchWithFirefox()
@objc optional func menuHelperPasteAndGo()
}
open class MenuHelper: NSObject {
public static let SelectorCopy: Selector = #selector(MenuHelperInterface.menuHelperCopy)
public static let SelectorHide: Selector = #selector(MenuHelperInterface.menuHelperSecure)
public static let SelectorOpenAndFill: Selector = #selector(MenuHelperInterface.menuHelperOpenAndFill)
public static let SelectorReveal: Selector = #selector(MenuHelperInterface.menuHelperReveal)
public static let SelectorFindInPage: Selector = #selector(MenuHelperInterface.menuHelperFindInPage)
public static let SelectorSearchWithFirefox: Selector = #selector(MenuHelperInterface.menuHelperSearchWithFirefox)
public static let SelectorPasteAndGo: Selector = #selector(MenuHelperInterface.menuHelperPasteAndGo)
open class var defaultHelper: MenuHelper {
struct Singleton {
static let instance = MenuHelper()
}
return Singleton.instance
}
open func setItems() {
let pasteAndGoItem = UIMenuItem(title: .MenuHelperPasteAndGo, action: MenuHelper.SelectorPasteAndGo)
let revealPasswordItem = UIMenuItem(title: .MenuHelperReveal, action: MenuHelper.SelectorReveal)
let hidePasswordItem = UIMenuItem(title: .MenuHelperHide, action: MenuHelper.SelectorHide)
let copyItem = UIMenuItem(title: .MenuHelperCopy, action: MenuHelper.SelectorCopy)
let openAndFillItem = UIMenuItem(title: .MenuHelperOpenAndFill, action: MenuHelper.SelectorOpenAndFill)
let findInPageItem = UIMenuItem(title: .MenuHelperFindInPage, action: MenuHelper.SelectorFindInPage)
let searchItem = UIMenuItem(title: .MenuHelperSearchWithFirefox, action: MenuHelper.SelectorSearchWithFirefox)
UIMenuController.shared.menuItems = [pasteAndGoItem, copyItem, revealPasswordItem, hidePasswordItem, openAndFillItem, findInPageItem, searchItem]
}
}
| mpl-2.0 | 18445c259de501e496ee4a66e14e1c6e | 54.727273 | 153 | 0.774062 | 5.318872 | false | false | false | false |
jngd/advanced-ios10-training | T5E02/T5E02ShareExtension/SizeTableViewController.swift | 1 | 3470 | //
// SizeTableViewController.swift
// T5E02
//
// Created by jngd on 27/02/2017.
// Copyright © 2017 jngd. All rights reserved.
//
import UIKit
@objc(SizeTableViewControllerDelegate)
protocol SizeTableViewControllerDelegate {
@objc optional func sizeSelection(_ sender: SizeTableViewController,
selectedValue: String)
}
class SizeTableViewController: UITableViewController {
var size = ["Small","Medium", "Big"]
let tableviewCellIdentifier = "sizeSelectionCell"
var selectedSize: String = "Small"
var delegate : SizeTableViewControllerDelegate?
override func viewDidLoad() {
super.viewDidLoad()
}
required override init(style: UITableViewStyle) {
super.init(style: style)
tableView.register(UITableViewCell.classForCoder(),
forCellReuseIdentifier: tableviewCellIdentifier)
title = "Choose size"
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
// MARK: - Table view data source
override func numberOfSections(in tableView: UITableView) -> Int {
// #warning Incomplete implementation, return the number of sections
return 1
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// #warning Incomplete implementation, return the number of rows
return 3
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: tableviewCellIdentifier, for: indexPath)
cell.textLabel?.text = self.size[(indexPath as NSIndexPath).row]
return cell
}
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
if let theDelegate = delegate {
selectedSize = self.size[(indexPath as NSIndexPath).row]
theDelegate.sizeSelection!(self, selectedValue: selectedSize)
}
}
/*
// Override to support conditional editing of the table view.
override func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
// Return false if you do not want the specified item to be editable.
return true
}
*/
/*
// Override to support editing the table view.
override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {
if editingStyle == .delete {
// Delete the row from the data source
tableView.deleteRows(at: [indexPath], with: .fade)
} else if editingStyle == .insert {
// Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
}
}
*/
/*
// Override to support rearranging the table view.
override func tableView(_ tableView: UITableView, moveRowAt fromIndexPath: IndexPath, to: IndexPath) {
}
*/
/*
// Override to support conditional rearranging of the table view.
override func tableView(_ tableView: UITableView, canMoveRowAt indexPath: IndexPath) -> Bool {
// Return false if you do not want the item to be re-orderable.
return true
}
*/
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
| apache-2.0 | e429b061b847cff5a65088c667f6a642 | 29.429825 | 133 | 0.738253 | 4.32005 | false | false | false | false |
DoubleSha/BitcoinSwift | BitcoinSwift/ExtendedECKey.swift | 1 | 4992 | //
// DeterministicECKey.swift
// BitcoinSwift
//
// Created by Kevin Greene on 12/20/14.
// Copyright (c) 2014 DoubleSha. All rights reserved.
//
import Foundation
/// An ExtendedECKey represents a key that is part of a DeterministicECKeyChain. It is just an
/// ECKey except an additional chainCode parameter and an index are used to derive the key.
/// Extended keys can be used to derive child keys.
/// BIP 32: https://github.com/bitcoin/bips/blob/master/bip-0032.mediawiki
public class ExtendedECKey : ECKey {
public let chainCode: SecureData
public let index: UInt32
/// Creates a new master extended key (both private and public).
/// Returns the key and the randomly-generated seed used to create the key.
public class func masterKey() -> (key: ExtendedECKey, seed: SecureData) {
var masterKey: ExtendedECKey? = nil
let randomData = SecureData(length: UInt(ECKey.privateKeyLength()))
var tries = 0
while masterKey == nil {
let result = SecRandomCopyBytes(kSecRandomDefault,
size_t(randomData.length),
UnsafeMutablePointer<UInt8>(randomData.mutableBytes))
assert(result == 0)
masterKey = ExtendedECKey.masterKeyWithSeed(randomData)
assert(++tries < 5)
}
return (masterKey!, randomData)
}
/// Can return nil in the (very very very very) unlikely case the randomly generated private key
/// is invalid. If nil is returned, retry.
public class func masterKeyWithSeed(seed: SecureData) -> ExtendedECKey? {
let indexHash = seed.HMACSHA512WithKeyData(ExtendedECKey.masterKeySeed())
let privateKey = indexHash[0..<32]
let chainCode = indexHash[32..<64]
let privateKeyInt = SecureBigInteger(secureData: privateKey)
if privateKeyInt.isEqual(BigInteger(0)) ||
privateKeyInt.greaterThanOrEqual(ECKey.curveOrder()) {
return nil
}
return ExtendedECKey(privateKey: privateKey, chainCode: chainCode)
}
/// Creates a new child key derived from self with index.
public func childKeyWithIndex(index: UInt32) -> ExtendedECKey? {
let data = SecureData()
if indexIsHardened(index) {
data.appendBytes([0] as [UInt8], length: 1)
data.appendSecureData(privateKey)
data.appendUInt32(index, endianness: .BigEndian)
} else {
data.appendData(publicKey)
data.appendUInt32(index, endianness: .BigEndian)
}
let indexHash = data.HMACSHA512WithKey(chainCode)
let indexHashLInt = SecureBigInteger(secureData: indexHash[0..<32])
let curveOrder = ECKey.curveOrder()
if indexHashLInt.greaterThanOrEqual(curveOrder) {
return nil
}
let childPrivateKeyInt = indexHashLInt.add(SecureBigInteger(secureData: privateKey),
modulo:curveOrder)
if childPrivateKeyInt.isEqual(BigInteger(0)) {
return nil
}
// The BigInteger might result in data whose length is less than expected, so we pad with 0's.
let childPrivateKey = SecureData()
let offset = ECKey.privateKeyLength() - Int32(childPrivateKeyInt.secureData.length)
assert(offset >= 0)
if offset > 0 {
let offsetBytes = [UInt8](count: Int(offset), repeatedValue: 0)
childPrivateKey.appendBytes(offsetBytes, length: UInt(offsetBytes.count))
}
childPrivateKey.appendSecureData(childPrivateKeyInt.secureData)
assert(Int32(childPrivateKey.length) == ECKey.privateKeyLength())
let childChainCode = indexHash[32..<64]
return ExtendedECKey(privateKey: childPrivateKey, chainCode: childChainCode, index: index)
}
public func childKeyWithHardenedIndex(index: UInt32) -> ExtendedECKey? {
return childKeyWithIndex(index + ExtendedECKey.hardenedIndexOffset())
}
/// Returns whether or not this key is hardened. A hardened key has more secure properties.
/// In general, you should always use a hardened key as the master key when deriving a
/// deterministic key chain where the keys in that chain will be published to the blockchain.
public var hardened: Bool {
return indexIsHardened(index)
}
/// Returns nil if the index is not hardened.
public var hardenedIndex: UInt32? {
return hardened ? index - ExtendedECKey.hardenedIndexOffset() : nil
}
// MARK: - Private Methods.
// TODO: Make this a class var instead of a func once Swift adds support for that.
private class func masterKeySeed() -> NSData {
return ("Bitcoin seed" as NSString).dataUsingEncoding(NSUTF8StringEncoding)!
}
// TODO: Make this a class var instead of a func once Swift adds support for that.
private class func hardenedIndexOffset() -> UInt32 {
return 0x80000000
}
private init(privateKey: SecureData, chainCode: SecureData, index: UInt32 = 0) {
self.chainCode = chainCode
self.index = index
super.init(privateKey: privateKey)
}
private func indexIsHardened(index: UInt32) -> Bool {
return index >= ExtendedECKey.hardenedIndexOffset()
}
}
| apache-2.0 | c6e2a8aea52cf211d863af07991ee0bd | 39.258065 | 98 | 0.705529 | 4.461126 | false | false | false | false |
avito-tech/Paparazzo | Paparazzo/Core/VIPER/ImageCropping/View/ImageCroppingControlsView.swift | 1 | 6615 | import UIKit
final class ImageCroppingControlsView: UIView, ThemeConfigurable {
typealias ThemeType = ImageCroppingUITheme
// MARK: - Subviews
private let rotationSliderView = RotationSliderView()
private let rotationButton = UIButton()
private let rotationCancelButton = RightIconButton()
private let gridButton = UIButton()
private let discardButton = UIButton()
private let confirmButton = UIButton()
// MARK: - Constants
// MARK: - Init
init() {
super.init(frame: .zero)
backgroundColor = .white
rotationCancelButton.backgroundColor = .RGB(red: 25, green: 25, blue: 25, alpha: 1)
rotationCancelButton.setTitleColor(.white, for: .normal)
rotationCancelButton.contentEdgeInsets = UIEdgeInsets(top: 3, left: 12, bottom: 3, right: 12)
rotationCancelButton.titleEdgeInsets = UIEdgeInsets(top: 0, left: 2, bottom: 0, right: -2)
rotationCancelButton.imageEdgeInsets = UIEdgeInsets(top: 0, left: -2, bottom: 0, right: 2)
rotationCancelButton.addTarget(
self,
action: #selector(onRotationCancelButtonTap(_:)),
for: .touchUpInside
)
rotationButton.addTarget(
self,
action: #selector(onRotationButtonTap(_:)),
for: .touchUpInside
)
gridButton.addTarget(
self,
action: #selector(onGridButtonTap(_:)),
for: .touchUpInside
)
discardButton.addTarget(
self,
action: #selector(onDiscardButtonTap(_:)),
for: .touchUpInside
)
confirmButton.addTarget(
self,
action: #selector(onConfirmButtonTap(_:)),
for: .touchUpInside
)
addSubview(rotationSliderView)
addSubview(rotationButton)
addSubview(gridButton)
addSubview(rotationCancelButton)
addSubview(discardButton)
addSubview(confirmButton)
setUpAccessibilityIdentifiers()
}
private func setUpAccessibilityIdentifiers() {
rotationButton.setAccessibilityId(.rotationButton)
gridButton.setAccessibilityId(.gridButton)
rotationCancelButton.setAccessibilityId(.rotationCancelButton)
discardButton.setAccessibilityId(.discardButton)
confirmButton.setAccessibilityId(.confirmButton)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
// MARK: - UIView
override func layoutSubviews() {
super.layoutSubviews()
rotationSliderView.layout(
left: bounds.left + 50,
right: bounds.right - 50,
top: 19,
height: 44
)
rotationButton.size = CGSize.minimumTapAreaSize
rotationButton.center = CGPoint(x: 31, y: rotationSliderView.centerY)
gridButton.size = CGSize.minimumTapAreaSize
gridButton.center = CGPoint(x: bounds.right - 31, y: rotationSliderView.centerY)
rotationCancelButton.centerX = bounds.centerX
rotationCancelButton.top = rotationSliderView.bottom + 11
discardButton.size = CGSize.minimumTapAreaSize
discardButton.center = CGPoint(
x: bounds.left + bounds.size.width * 0.25,
y: bounds.bottom - paparazzoSafeAreaInsets.bottom - 42
)
confirmButton.size = CGSize.minimumTapAreaSize
confirmButton.center = CGPoint(x: bounds.right - bounds.size.width * 0.25, y: discardButton.centerY)
}
// MARK: - ThemeConfigurable
func setTheme(_ theme: ThemeType) {
rotationButton.setImage(theme.rotationIcon, for: .normal)
gridButton.setImage(theme.gridIcon, for: .normal)
gridButton.setImage(theme.gridSelectedIcon, for: .selected)
discardButton.setImage(theme.cropperDiscardIcon, for: .normal)
confirmButton.setImage(theme.cropperConfirmIcon, for: .normal)
rotationCancelButton.backgroundColor = theme.cancelRotationBackgroundColor
rotationCancelButton.titleLabel?.textColor = theme.cancelRotationTitleColor
rotationCancelButton.titleLabel?.font = theme.cancelRotationTitleFont
rotationCancelButton.setImage(theme.cancelRotationButtonIcon, for: .normal)
}
// MARK: - ImageCroppingControlsView
var onDiscardButtonTap: (() -> ())?
var onConfirmButtonTap: (() -> ())?
var onRotationCancelButtonTap: (() -> ())?
var onRotateButtonTap: (() -> ())?
var onGridButtonTap: (() -> ())?
var onRotationAngleChange: ((Float) -> ())? {
get { return rotationSliderView.onSliderValueChange }
set { rotationSliderView.onSliderValueChange = newValue }
}
func setMinimumRotation(degrees: Float) {
rotationSliderView.setMiminumValue(degrees)
}
func setMaximumRotation(degrees: Float) {
rotationSliderView.setMaximumValue(degrees)
}
func setRotationSliderValue(_ value: Float) {
rotationSliderView.setValue(value)
}
func setControlsEnabled(_ enabled: Bool) {
rotationButton.isEnabled = enabled
gridButton.isEnabled = enabled
rotationSliderView.isUserInteractionEnabled = enabled
rotationCancelButton.isEnabled = enabled
}
func setCancelRotationButtonTitle(_ title: String) {
rotationCancelButton.setTitle(title, for: .normal)
rotationCancelButton.sizeToFit()
rotationCancelButton.layer.cornerRadius = rotationCancelButton.size.height / 2
}
func setCancelRotationButtonVisible(_ visible: Bool) {
rotationCancelButton.isHidden = !visible
}
func setGridButtonSelected(_ selected: Bool) {
gridButton.isSelected = selected
}
// MARK: - Private
@objc private func onDiscardButtonTap(_: UIButton) {
onDiscardButtonTap?()
}
@objc private func onConfirmButtonTap(_: UIButton) {
onConfirmButtonTap?()
}
@objc private func onRotationSliderValueChange(_ sender: UISlider) {
onRotationAngleChange?(sender.value)
}
@objc private func onRotationCancelButtonTap(_: UIButton) {
onRotationCancelButtonTap?()
}
@objc private func onRotationButtonTap(_: UIButton) {
onRotateButtonTap?()
}
@objc private func onGridButtonTap(_: UIButton) {
onGridButtonTap?()
}
}
| mit | fb3f7f05fd13a0717be0cd08ff05b090 | 32.409091 | 108 | 0.637944 | 5.489627 | false | false | false | false |
avito-tech/Paparazzo | Paparazzo/Marshroute/MaskCropper/Assembly/MaskCropperMarshrouteAssemblyImpl.swift | 1 | 1256 | import Marshroute
import UIKit
public final class MaskCropperMarshrouteAssemblyImpl: BasePaparazzoAssembly, MaskCropperMarshrouteAssembly {
public func module(
data: MaskCropperData,
croppingOverlayProvider: CroppingOverlayProvider,
routerSeed: RouterSeed,
configure: (MaskCropperModule) -> ()
) -> UIViewController {
let imageCroppingService = serviceFactory.imageCroppingService(
image: data.imageSource,
canvasSize: data.cropCanvasSize
)
let interactor = MaskCropperInteractorImpl(
imageCroppingService: imageCroppingService
)
let router = MaskCropperMarshrouteRouter(
routerSeed: routerSeed
)
let presenter = MaskCropperPresenter(
interactor: interactor,
router: router
)
let viewController = MaskCropperViewController(
croppingOverlayProvider: croppingOverlayProvider
)
viewController.addDisposable(presenter)
viewController.setTheme(theme)
presenter.view = viewController
configure(presenter)
return viewController
}
}
| mit | 75a34af2460401f55d1addd517859c98 | 27.545455 | 108 | 0.627389 | 6.901099 | false | false | false | false |
spacedrabbit/SRZoomTransition | SRZoomTransition/SRZoomTransition/CatCollectionViewController.swift | 1 | 14250 | //
// CatCollectionViewController.swift
// SRZoomTransition
//
// Created by Louis Tur on 11/1/15.
// Copyright © 2015 Louis Tur. All rights reserved.
//
import Foundation
import UIKit
import Cartography
import Alamofire
public struct CatAPIUrl {
static let BaseUrl: String = "http://thecatapi.com/api"
static let CatRequestUrl: String = CatAPIUrl.BaseUrl + "/images/get"
public struct Params {
static let ImageId: String = "image_id"
static let ResponseFormat: String = "format"
static let NumberOfResults: String = "results_per_page"
static let ImageType: String = "type"
static let ImageSize: String = "size"
}
public struct ElementName {
static let Image: String = "image"
static let Url: String = "url"
static let Id: String = "id"
static let SourceUrl: String = "source_url"
}
enum ResponseFormat: String {
case xml = "xml"
case html = "html"
case src = "src"
}
enum ImageType: String {
case jpg = "jpg"
case png = "png"
case gif = "gif"
}
enum CatImageSize: String {
case Small = "small" // 250
case Medium = "med" // 500
case Full = "full" // original
}
}
public class CatCollectionViewController: UIViewController, UICollectionViewDataSource, UICollectionViewDelegate, UICollectionViewDelegateFlowLayout, NSXMLParserDelegate, CatZoomTransitionCoordinatorDelegate, UIViewControllerTransitioningDelegate {
// MARK: - Variables
public static let CatCellIdentifier: String = "catCell"
public var catArray: [Cat] = []
private var numberOfImagesToFetch: Int = 20
private var selectedCell: UICollectionViewCell?
// MARK: - Lifecycle
public override func viewDidLoad() {
super.viewDidLoad()
}
convenience public init(WithPreloadedCatImages numberOfImages: Int) {
self.init()
if numberOfImages > 0 { self.numberOfImagesToFetch = numberOfImages }
self.view.addSubview(self.catCollectionView)
self.catCollectionView.delegate = self
self.catCollectionView.dataSource = self
self.catCollectionView.backgroundColor = UIColor.redColor()
self.makeCatRequest()
self.configureConstraints()
}
public func makeCatRequest() {
let params: [String : String] = [
CatAPIUrl.Params.ResponseFormat : CatAPIUrl.ResponseFormat.xml.rawValue,
CatAPIUrl.Params.NumberOfResults : String(numberOfImagesToFetch)
]
Alamofire.request(.GET, CatAPIUrl.CatRequestUrl, parameters: params)
.responseData { response in
let xmlParser: NSXMLParser = NSXMLParser(data: response.data!)
xmlParser.delegate = self
xmlParser.shouldProcessNamespaces = true
xmlParser.parse()
}
}
// MARK: - Layout
private func configureConstraints() {
constrain( catCollectionView ) { collectionView in
collectionView.edges == collectionView.superview!.edges
}
}
// MARK: - XML Parser
// XML Parsing is really odd, see http://themainthread.com/blog/2014/04/mapping-xml-to-objects-with-nsxmlparser.html
// Apple Doc was slighty helpful as well https://developer.apple.com/library/ios/samplecode/SeismicXML/Introduction/Intro.html#//apple_ref/doc/uid/DTS40007323-Intro-DontLinkElementID_2
/* Using the NSXMLParserDelegate requires that you handle each state of the XML document parse.
Those states that are of most interest/use, are that of
- element start
- element characters
- element end
In the CatAPI, the xml returned for a single request looks like:
<response>
<data>
<images>
<image>
<url>http://29.media.tumblr.com/tumblr_m2yfbdxze71qjev1to1_250.jpg</url>
<id>3kc</id>
<source_url>http://thecatapi.com/?id=3kc</source_url>
</image>
<image>
<url>http://24.media.tumblr.com/tumblr_m18kwh02Av1r8kxuoo1_250.jpg</url>
<id>b0h</id>
<source_url>http://thecatapi.com/?id=b0h</source_url>
</image>
</images>
</data>
</response>
Each tag is considered an "element" and it's opening tag is the element's start. And, you guessed it, the
closing tag is considered it's end. The characters are considered anything found following the tag, which
ends up being a lot of newline characters + whitespace. Not terribly useful (unless you're looking to draw
out a simple drawing of the xml mapping).
Through the delegate, you must listen for the start of the element, any following string information, and
then the element's closing tag. As shown in the links above, you need to anticipate and add elements/strings
as needed based on the delegate calls.
In the example below, I add each element encountered to an element stack. When I reach a string without a newline
I know it is the relevant text between the tags in a child xml node. So I create a new dictionary element with
the key being the last element on the stack and the value of the string. Because the end of this string will
signal the closing tag of the element I'm currently going through, I know I can pop off this element from the
top of stack.
At the point of the first relevant data node, the stack looks like:
["response", "data", "images", "image", "url"]
At this point I take the string of "http://29.media.tumblr.com/...." and add a dictionary entry
elementDict["url"] = "http://...."
Encountering a closing take for "url" I do a simple comparison of the element's string with the last element
in the element stack, and if they match, that element is popped off the stack. Then on the next loop, the next
element is added, and so on and so forth..
["response", "data", "images", "image", "id"]
"3kc"
pop()
["response", "data", "images", "image", "source_url"]
"http......"
pop()
["response", "data", "images", "image"], pop()
["response", "data", "images"], pop()
*/
var indentationLevel: Int = 0
var elementStack: [String] = []
var encounteredElementValue: String = String()
var elementDictionary: [String : String] = [String : String]()
public func parser(parser: NSXMLParser, didStartElement elementName: String, namespaceURI: String?, qualifiedName qName: String?, attributes attributeDict: [String : String]) {
elementStack.append(elementName)
}
public func parser(parser: NSXMLParser, foundCharacters string: String) {
let newLines: NSCharacterSet = NSCharacterSet.newlineCharacterSet()
if let _: Range = string.rangeOfCharacterFromSet(newLines) {
// ignores newline characters
} else {
encounteredElementValue = string
if let element: String = elementStack.last {
elementDictionary[element] = encounteredElementValue
}
}
}
public func parser(parser: NSXMLParser, didEndElement elementName: String, namespaceURI: String?, qualifiedName qName: String?) {
if let lastElementOnStack: String = elementStack.last {
if lastElementOnStack == elementName {
if let closedTag:String? = elementStack.popLast() {
if closedTag == CatAPIUrl.ElementName.Image {
if let cat: Cat = self.generateCatObject() {
self.catArray.append(cat)
}
}
}
}
}
}
private func generateCatObject() -> Cat? {
if elementDictionary.keys.count == 3 {
guard let catImageId: String = elementDictionary[CatAPIUrl.ElementName.Id],
let catImageUrl: String = elementDictionary[CatAPIUrl.ElementName.Url],
let catSourceURL: String = elementDictionary[CatAPIUrl.ElementName.SourceUrl]
else {
return nil
}
elementDictionary.removeAll()
return Cat(WithId: catImageId, url: catImageUrl, sourceUrl: catSourceURL)
}
return nil
}
// MARK: - UICollectionViewDataSource
public func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
let cell: UICollectionViewCell = collectionView.dequeueReusableCellWithReuseIdentifier(CatCollectionViewController.CatCellIdentifier, forIndexPath: indexPath)
if self.catArray.count > 0 {
let catToDisplay: Cat = self.catArray[indexPath.row]
if let catImageView: UIImageView = UIImageView(image: catToDisplay.catImage) {
catImageView.frame = cell.contentView.frame
cell.contentView.addSubview(catImageView)
}
}
cell.contentView.backgroundColor = UIColor.blueColor()
return cell
}
public func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int {
return 1
}
public func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return numberOfImagesToFetch
}
// MARK: - UICollectionViewDelegate
var transitioningViewRect: CGRect?
var viewToSnapShot: UIView?
public func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
let formatString: String = "%.0f"
if let catCollectionCell: UICollectionViewCell = collectionView.cellForItemAtIndexPath(indexPath) {
let cellX = String(format: formatString, catCollectionCell.frame.origin.x),
cellY = String(format: formatString, catCollectionCell.frame.origin.y),
cellWidth = String(format: formatString, catCollectionCell.frame.size.width),
cellHeight = String(format: formatString, catCollectionCell.frame.size.height)
let cellTranslatedInView: CGRect = catCollectionCell.convertRect(catCollectionCell.bounds, toView: self.view)
print("selectedCell origin: (\(cellX), \(cellY))")
print("selectedCell size: (\(cellWidth), \(cellHeight))")
print("selectedCell in view's coordinate space: \(cellTranslatedInView)")
transitioningViewRect = cellTranslatedInView
viewToSnapShot = catCollectionCell.contentView
}
if let catCollectionCell: UICollectionViewCell = collectionView.cellForItemAtIndexPath(indexPath) {
self.selectedCell = catCollectionCell
}
if let catToDisplay: Cat = self.catArray[indexPath.row] {
if let catToDisplayImage: UIImage = catToDisplay.catImage {
let dtvc: CatFullScreenView = CatFullScreenView()
dtvc.loadViewWithCatImage(catToDisplayImage)
dtvc.transitioningDelegate = self
self.presentViewController(dtvc, animated: true, completion: nil)
//self.navigationController?.pushViewController(dtvc, animated: true)
}
}
}
public func coordinateZoomTransition(withCatZoomCoordinator coordinator: CatZoomTransitionCoordinator,
forView view: UIView,
relativeToView relativeView: UIView,
fromViewController sourceVC: UIViewController,
toViewController destinationVC: UIViewController) -> CGRect {
if sourceVC == self { // collection view is presenting
if let selectedCatCell: UICollectionViewCell = self.selectedCell {
return selectedCatCell.convertRect(selectedCatCell.bounds, toView: relativeView)
}
} else { // collection view is ending vc
if sourceVC is CatFullScreenView {
let sourceCatZoomView: CatFullScreenView = sourceVC as! CatFullScreenView
return sourceCatZoomView.imageView.convertRect(sourceCatZoomView.imageView.bounds, toView: relativeView)
}
}
return CGRectZero
}
public func coordinateZoomReverseTransition(withCatCoordinator coordinator: CatZoomTransitionCoordinator,
forView view: UIView,
relativeToView relativeView: UIView,
fromViewController sourceVC: UIViewController,
toViewController destinationVC: UIViewController) -> CGRect {
if sourceVC == self {
if destinationVC is CatFullScreenView {
let destinationCatVC: CatFullScreenView = destinationVC as! CatFullScreenView
return destinationCatVC.imageView.convertRect(destinationCatVC.imageView.bounds, toView: relativeView)
}
}
else if sourceVC is CatFullScreenView {
if let selectedCatCell: UICollectionViewCell = self.selectedCell {
return selectedCatCell.convertRect(selectedCatCell.bounds, toView: relativeView)
}
}
return CGRectZero
}
public func animationControllerForPresentedController(
presented: UIViewController,
presentingController presenting: UIViewController,
sourceController source: UIViewController) -> UIViewControllerAnimatedTransitioning? {
var animationController: CatZoomTransitionCoordinator?
if let selectedCatCell: UICollectionViewCell = self.selectedCell {
let transitionType: CatTransitionType = (source == self) ? .CatTransitionPresentating : .CatTransitionDismissing
animationController = CatZoomTransitionCoordinator(withTargetView: selectedCatCell, transitionType: transitionType, duration: 2.00, delegate: self)
animationController!.delegate = self
}
return animationController
}
// MARK: - UICollectionViewDelegateFlowLayout
public func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize {
return CGSizeMake(100.0, 100.0)
}
private func reloadCatCollection() {
self.catCollectionView.reloadData()
}
// MARK: - Lazy UI Loaders
public lazy var catCollectionView: UICollectionView = {
let flowLayout: UICollectionViewFlowLayout = UICollectionViewFlowLayout()
flowLayout.sectionInset = UIEdgeInsetsMake(8.0, 8.0, 8.0, 8.0)
flowLayout.estimatedItemSize = CGSizeZero // use this to implement autolayout
flowLayout.minimumLineSpacing = 10.0
flowLayout.minimumInteritemSpacing = 10.0
let collectionView: UICollectionView = UICollectionView(frame: CGRectZero, collectionViewLayout: flowLayout)
collectionView.registerClass(UICollectionViewCell.self, forCellWithReuseIdentifier: CatCollectionViewController.CatCellIdentifier)
return collectionView
}()
} | mit | a4ea18109295ca0c78dc44fb8c6223a6 | 38.364641 | 248 | 0.704541 | 4.970003 | false | false | false | false |
Ezfen/iOS.Apprentice.1-4 | MyLocations/MyLocations/CurrentLocationViewController.swift | 1 | 14007 | //
// FirstViewController.swift
// MyLocations
//
// Created by ezfen on 16/8/15.
// Copyright © 2016年 Ezfen Inc. All rights reserved.
//
import UIKit
import CoreLocation
import CoreData
import QuartzCore
import AudioToolbox
class CurrentLocationViewController: UIViewController, CLLocationManagerDelegate {
@IBOutlet weak var messageLabel: UILabel!
@IBOutlet weak var latitudeLabel: UILabel!
@IBOutlet weak var longitudeLabel: UILabel!
@IBOutlet weak var addressLabel: UILabel!
@IBOutlet weak var tagButton: UIButton!
@IBOutlet weak var getButton: UIButton!
@IBOutlet weak var latitudeTextLabel: UILabel!
@IBOutlet weak var longitudeTextLabel: UILabel!
@IBOutlet weak var containerView: UIView!
var managedObjectContext: NSManagedObjectContext!
let locationManager = CLLocationManager()
var location: CLLocation?
var updatingLocation = false
var lastLocationError: NSError?
let geocoder = CLGeocoder()
var placemark: CLPlacemark?
var performingReverseGeocoding = false
var lastGeocodingError: NSError?
var timer: NSTimer?
var soundID: SystemSoundID = 0
var logoVisible = false
lazy var logoButton: UIButton = {
let button = UIButton(type: .Custom)
button.setBackgroundImage(UIImage(named: "Logo"), forState: .Normal)
button.sizeToFit()
button.addTarget(self, action: #selector(CurrentLocationViewController.getLocation), forControlEvents: .TouchUpInside)
button.center.x = CGRectGetMidX(self.view.bounds)
button.center.y = 220
return button
}()
// MARK: - Logo View
func showLogoView() {
if !logoVisible {
logoVisible = true
containerView.hidden = true
view.addSubview(logoButton)
}
}
func hideLogoView() {
if !logoVisible { return }
logoVisible = false
containerView.hidden = false
containerView.center.x = view.bounds.size.width * 2
containerView.center.y = 40 + containerView.bounds.size.height / 2
let centerX = CGRectGetMidX(view.bounds)
let panelMover = CABasicAnimation(keyPath: "position")
panelMover.removedOnCompletion = false
panelMover.fillMode = kCAFillModeForwards
panelMover.duration = 0.6
panelMover.fromValue = NSValue(CGPoint: containerView.center)
panelMover.toValue = NSValue(CGPoint: CGPoint(x: centerX, y: containerView.center.y))
panelMover.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseOut)
panelMover.delegate = self
containerView.layer.addAnimation(panelMover, forKey: "panelMover")
let logoMover = CABasicAnimation(keyPath: "position")
logoMover.removedOnCompletion = false
logoMover.fillMode = kCAFillModeForwards
logoMover.duration = 0.5
logoMover.fromValue = NSValue(CGPoint: logoButton.center)
logoMover.toValue = NSValue(CGPoint: CGPoint(x: -centerX, y: logoButton.center.y))
logoMover.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseIn)
logoButton.layer.addAnimation(logoMover, forKey: "logoMover")
let logoRotator = CABasicAnimation(keyPath: "transform.rotation.z")
logoRotator.removedOnCompletion = false
logoRotator.fillMode = kCAFillModeForwards
logoRotator.duration = 0.5
logoRotator.fromValue = 0.0
logoRotator.toValue = -2 * M_PI
logoRotator.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseIn)
logoButton.layer.addAnimation(logoRotator, forKey: "logoRotator")
}
override func animationDidStop(anim: CAAnimation, finished flag: Bool) {
containerView.layer.removeAllAnimations()
containerView.center.x = view.bounds.size.width / 2
containerView.center.y = 40 + containerView.bounds.size.height / 2
logoButton.layer.removeAllAnimations()
logoButton.removeFromSuperview()
}
// MARK: -Sound Effect
func loadSoundEffect(name: String) {
if let path = NSBundle.mainBundle().pathForResource(name, ofType: nil) {
let fileURL = NSURL.fileURLWithPath(path, isDirectory: false)
let error = AudioServicesCreateSystemSoundID(fileURL, &soundID)
if error != kAudioServicesNoError {
print("Error code \(error) loading sound at path: \(path)")
}
}
}
func unloadSoundEffect() {
AudioServicesDisposeSystemSoundID(soundID)
soundID = 0
}
func playSoundEffect() {
AudioServicesPlaySystemSound(soundID)
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
updateLabels()
configureGetButton()
loadSoundEffect("Sound.caf")
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func getLocation() {
let authStatus = CLLocationManager.authorizationStatus()
if authStatus == .NotDetermined {
locationManager.requestWhenInUseAuthorization()
return
}
if authStatus == .Denied || authStatus == .Restricted {
showLocationServicesDeniedAlert()
return
}
if updatingLocation {
stopLocationManager()
} else {
location = nil
lastLocationError = nil
placemark = nil
lastGeocodingError = nil
startLocationManager()
}
if logoVisible {
hideLogoView()
}
updateLabels()
configureGetButton()
}
func showLocationServicesDeniedAlert() {
let alert = UIAlertController(title: "Location Services Disabled", message: "Please enable location services for this app in Settings", preferredStyle: .Alert)
let okAction = UIAlertAction(title: "OK", style: .Default, handler: nil)
alert.addAction(okAction)
presentViewController(alert, animated: true, completion: nil)
}
// MARK: - CLLocationManagerDelegate
func locationManager(manager: CLLocationManager, didFailWithError error: NSError) {
print("didFailWithError \(error)")
if error.code == CLError.LocationUnknown.rawValue {
return
}
lastLocationError = error
stopLocationManager()
updateLabels()
configureGetButton()
}
func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
let newLocation = locations.last!
print("didUpdateLocations \(newLocation)")
// ignore these cached locations
if newLocation.timestamp.timeIntervalSinceNow < -5 {
return
}
// these measurements are invalid
if newLocation.horizontalAccuracy < 0 {
return
}
var distance = CLLocationDistance(DBL_MAX)
if let location = location {
distance = newLocation.distanceFromLocation(location)
}
if location == nil || location!.horizontalAccuracy > newLocation.horizontalAccuracy {
lastLocationError = nil
location = newLocation
updateLabels()
if newLocation.horizontalAccuracy <= locationManager.desiredAccuracy {
print("*** We're done")
stopLocationManager()
configureGetButton()
if distance > 0 {
performingReverseGeocoding = false
}
}
if !performingReverseGeocoding {
print("*** Going to geocode")
performingReverseGeocoding = true
geocoder.reverseGeocodeLocation(newLocation, completionHandler: {
placemarks, error in
print("*** Found placemarks: \(placemarks), error: \(error)")
self.lastGeocodingError = error
if error == nil, let p = placemarks where !p.isEmpty {
if self.placemark == nil {
print("First Time!")
self.playSoundEffect()
}
self.placemark = p.last!
} else {
self.placemark = nil
}
self.performingReverseGeocoding = false
self.updateLabels()
})
}
} else if distance < 1.0 {
let timeInterval = newLocation.timestamp.timeIntervalSinceDate(location!.timestamp)
if timeInterval > 10 {
print("*** Force done!")
stopLocationManager()
updateLabels()
configureGetButton()
}
}
}
func updateLabels() {
if let location = location {
latitudeLabel.text = String(format: "%.8f", location.coordinate.latitude)
longitudeLabel.text = String(format: "%.8f", location.coordinate.longitude)
tagButton.hidden = false
messageLabel.text = ""
if let placemark = placemark {
addressLabel.text = stringFromPlacemark(placemark)
} else if performingReverseGeocoding {
addressLabel.text = "Searching for Address..."
} else if lastGeocodingError != nil {
addressLabel.text = "Error Finding Address"
} else {
addressLabel.text = "No Address Found"
}
latitudeTextLabel.hidden = false
longitudeTextLabel.hidden = false
} else {
latitudeLabel.text = ""
longitudeLabel.text = ""
addressLabel.text = ""
tagButton.hidden = true
let statusMessage: String
if let error = lastLocationError {
if error.domain == kCLErrorDomain && error.code == CLError.Denied.rawValue {
statusMessage = "Location Services Disabled"
} else {
statusMessage = "Error Getting Location"
}
} else if !CLLocationManager.locationServicesEnabled() {
statusMessage = "Location Servics Disabled"
} else if updatingLocation {
statusMessage = "Searching..."
} else {
statusMessage = ""
showLogoView()
}
messageLabel.text = statusMessage
latitudeTextLabel.hidden = true
longitudeTextLabel.hidden = true
}
}
func startLocationManager() {
if CLLocationManager.locationServicesEnabled() {
locationManager.delegate = self
locationManager.desiredAccuracy = kCLLocationAccuracyNearestTenMeters
locationManager.startUpdatingLocation()
updatingLocation = true
timer = NSTimer.scheduledTimerWithTimeInterval(60, target: self, selector: #selector(CurrentLocationViewController.didTimeOut), userInfo: nil, repeats: false)
}
}
func stopLocationManager() {
if updatingLocation {
if let timer = timer {
timer.invalidate()
}
locationManager.stopUpdatingLocation()
locationManager.delegate = nil
updatingLocation = false
}
}
func configureGetButton() {
let spinnerTag = 1000
if updatingLocation {
getButton.setTitle("Stop", forState: .Normal)
if view.viewWithTag(spinnerTag) == nil {
let spinner = UIActivityIndicatorView(activityIndicatorStyle: .White)
spinner.center = messageLabel.center
spinner.center.y += spinner.bounds.size.height/2 + 15
spinner.stopAnimating()
spinner.tag = spinnerTag
containerView.addSubview(spinner)
}
} else {
getButton.setTitle("Get My Location", forState: .Normal)
if let spinner = view.viewWithTag(spinnerTag) {
spinner.removeFromSuperview()
}
}
}
func stringFromPlacemark(placemark: CLPlacemark) -> String {
var line1 = ""
if let s = placemark.subThoroughfare {
line1 += s + " "
}
if let s = placemark.thoroughfare {
line1 += s
}
var line2 = ""
if let s = placemark.locality {
line2 += s + " "
}
if let s = placemark.administrativeArea {
line2 += s + " "
}
if let s = placemark.postalCode {
line2 += s
}
return line1 + "\n" + line2
}
func didTimeOut() {
print("*** Time out")
if location == nil {
stopLocationManager()
lastLocationError = NSError(domain: "MyLocationErrorDomain", code: 1, userInfo: nil)
updateLabels()
configureGetButton()
}
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if segue.identifier == "TagLocation" {
let navigationController = segue.destinationViewController as! UINavigationController
let controller = navigationController.topViewController as! LocationDetailsViewController
controller.coordinate = location!.coordinate
controller.placemark = placemark
controller.managedObjectContext = managedObjectContext
}
}
}
| mit | 3de508cbe2a9f9a6b72ff69d9ebbb822 | 35.659686 | 170 | 0.592831 | 5.994863 | false | false | false | false |
kArTeL/News-YC---iPhone | HN/CustomViews/Cells/Navigation/HNNavThemeTableViewCell.swift | 5 | 1307 | //
// HNNavThemeTableViewCell.swift
// HN
//
// Created by Ben Gordon on 9/30/14.
// Copyright (c) 2014 bennyguitar. All rights reserved.
//
import UIKit
let HNNavThemeTableViewCellIdentifier = "HNNavThemeTableViewCellIdentifier"
class HNNavThemeTableViewCell: UITableViewCell {
var currentThemeType: Int? = HNTheme.currentTheme().themeType.rawValue
// TableView Lifecycle
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
updateUI()
}
override func setSelected(selected: Bool, animated: Bool) {
super.setSelected(false, animated: false)
}
override func setHighlighted(highlighted: Bool, animated: Bool) {
super.setHighlighted(false, animated: false)
}
func didSelectThemeButton(sender: UIButton) {
HNTheme.currentTheme().changeTheme(HNTheme.ThemeType(rawValue: sender.tag)!)
currentThemeType = sender.tag
updateUI()
}
func updateUI() {
for (view) in subviews[0].subviews {
if (view.isKindOfClass(UIButton.self)) {
var b = view as! UIButton
b.setTitleColor((b.tag == currentThemeType ? HNOrangeColor : UIColor.whiteColor()), forState: UIControlState.Normal)
}
}
}
}
| mit | df09add13fe0b0604b9627a6825ed30e | 28.044444 | 132 | 0.648049 | 4.602113 | false | false | false | false |
pavelpark/RoundMedia | roundMedia/roundMedia/CleanButton.swift | 1 | 540 | //
// CleanButton.swift
// roundMedia
//
// Created by Pavel Parkhomey on 7/16/17.
// Copyright © 2017 Pavel Parkhomey. All rights reserved.
//
import UIKit
class CleanButton: UIButton {
override func awakeFromNib() {
super.awakeFromNib()
layer.shadowColor = UIColor(red: SHADOW_GRAY, green: SHADOW_GRAY, blue: SHADOW_GRAY, alpha: 0.6).cgColor
layer.shadowOpacity = 0.8
layer.shadowRadius = 5.0
layer.shadowOffset = CGSize(width: 1.0, height: 1.0)
layer.cornerRadius = 2.0
}
}
| mit | e337e0292076a212e0c802e79a0bc6ed | 21.458333 | 108 | 0.651206 | 3.546053 | false | false | false | false |
overtake/TelegramSwift | Telegram-Mac/ChatListController.swift | 1 | 52898 | //
// TGDialogsViewController.swift
// Telegram-Mac
//
// Created by keepcoder on 07/09/16.
// Copyright © 2016 Telegram. All rights reserved.
//
import Cocoa
import TGUIKit
import SwiftSignalKit
import Postbox
import TelegramCore
import InAppSettings
import FetchManager
private final class Arguments {
let context: AccountContext
let setupFilter: (ChatListFilter)->Void
let openFilterSettings: (ChatListFilter)->Void
let tabsMenuItems: (ChatListFilter)->[ContextMenuItem]
let createTopic: ()->Void
let switchOffForum: ()->Void
init(context: AccountContext, setupFilter: @escaping(ChatListFilter)->Void, openFilterSettings: @escaping(ChatListFilter)->Void, tabsMenuItems: @escaping(ChatListFilter)->[ContextMenuItem], createTopic: @escaping()->Void, switchOffForum: @escaping()->Void) {
self.context = context
self.setupFilter = setupFilter
self.openFilterSettings = openFilterSettings
self.tabsMenuItems = tabsMenuItems
self.createTopic = createTopic
self.switchOffForum = switchOffForum
}
}
enum UIChatListEntryId : Hashable {
case chatId(EngineChatList.Item.Id, PeerId, Int32)
case groupId(EngineChatList.Group)
case forum(PeerId)
case reveal
case empty
case loading
}
struct UIChatAdditionalItem : Equatable {
static func == (lhs: UIChatAdditionalItem, rhs: UIChatAdditionalItem) -> Bool {
return lhs.item == rhs.item && lhs.index == rhs.index
}
let item: EngineChatList.AdditionalItem
let index: Int
}
enum UIChatListEntry : Identifiable, Comparable {
case chat(EngineChatList.Item, [PeerListState.InputActivities.Activity], UIChatAdditionalItem?, filter: ChatListFilter)
case group(Int, EngineChatList.GroupItem, Bool, HiddenArchiveStatus)
case reveal([ChatListFilter], ChatListFilter, ChatListFilterBadges)
case empty(ChatListFilter, PeerListMode, SplitViewState, PeerEquatable?)
case loading(ChatListFilter)
static func == (lhs: UIChatListEntry, rhs: UIChatListEntry) -> Bool {
switch lhs {
case let .chat(entry, activity, additionItem, filter):
if case .chat(entry, activity, additionItem, filter) = rhs {
return true
} else {
return false
}
case let .group(index, item, animated, isHidden):
if case .group(index, item, animated, isHidden) = rhs {
return true
} else {
return false
}
case let .reveal(filters, current, counters):
if case .reveal(filters, current, counters) = rhs {
return true
} else {
return false
}
case let .empty(filter, mode, state, peer):
if case .empty(filter, mode, state, peer) = rhs {
return true
} else {
return false
}
case let .loading(filter):
if case .loading(filter) = rhs {
return true
} else {
return false
}
}
}
var index: ChatListIndex {
switch self {
case let .chat(entry, _, additionItem, _):
if let additionItem = additionItem {
var current = MessageIndex.absoluteUpperBound().globalPredecessor()
for _ in 0 ..< additionItem.index {
current = current.globalPredecessor()
}
return ChatListIndex(pinningIndex: 0, messageIndex: current)
}
switch entry.index {
case let .chatList(index):
return index
case let .forum(pinnedIndex, timestamp, _, namespace, id):
let index: UInt16?
switch pinnedIndex {
case .none:
index = nil
case let .index(value):
index = UInt16(value)
}
return ChatListIndex(pinningIndex: index, messageIndex: .init(id: MessageId(peerId: entry.renderedPeer.peerId, namespace: namespace, id: id), timestamp: timestamp))
}
case .reveal:
return ChatListIndex(pinningIndex: 0, messageIndex: MessageIndex.absoluteUpperBound())
case let .group(id, _, _, _):
var index = MessageIndex.absoluteUpperBound().globalPredecessor()
for _ in 0 ..< id {
index = index.peerLocalPredecessor()
}
return ChatListIndex(pinningIndex: 0, messageIndex: index)
case .empty:
return ChatListIndex(pinningIndex: 0, messageIndex: MessageIndex.absoluteUpperBound().globalPredecessor())
case .loading:
return ChatListIndex(pinningIndex: 0, messageIndex: MessageIndex.absoluteUpperBound().globalPredecessor())
}
}
static func < (lhs: UIChatListEntry, rhs: UIChatListEntry) -> Bool {
return lhs.index < rhs.index
}
var stableId: UIChatListEntryId {
switch self {
case let .chat(entry, _, _, filterId):
if entry.renderedPeer.peer?._asPeer().isForum == true, entry.threadData == nil {
return .forum(entry.renderedPeer.peerId)
} else {
return .chatId(entry.id, entry.renderedPeer.peerId, filterId.id)
}
case let .group(_, group, _, _):
return .groupId(group.id)
case .reveal:
return .reveal
case .empty:
return .empty
case .loading:
return .loading
}
}
}
fileprivate func prepareEntries(from:[AppearanceWrapperEntry<UIChatListEntry>]?, to:[AppearanceWrapperEntry<UIChatListEntry>], adIndex: UInt16?, arguments: Arguments, initialSize:NSSize, animated:Bool, scrollState:TableScrollState? = nil, groupId: EngineChatList.Group) -> Signal<TableUpdateTransition, NoError> {
return Signal { subscriber in
func makeItem(_ entry: AppearanceWrapperEntry<UIChatListEntry>) -> TableRowItem {
switch entry.entry {
case let .chat(item, activities, addition, filter):
var pinnedType: ChatListPinnedType = .some
if let addition = addition {
pinnedType = .ad(addition.item)
} else if entry.entry.index.pinningIndex == nil {
pinnedType = .none
}
let messages = item.messages.map {
$0._asMessage()
}
let mode: ChatListRowItem.Mode
if let data = item.threadData, case let .forum(id) = item.id {
mode = .topic(id, data)
} else {
mode = .chat
}
return ChatListRowItem(initialSize, context: arguments.context, stableId: entry.entry.stableId, mode: mode, messages: messages, index: entry.entry.index, readState: item.readCounters, draft: item.draft, pinnedType: pinnedType, renderedPeer: item.renderedPeer, peerPresence: item.presence, forumTopicData: item.forumTopicData, activities: activities, associatedGroupId: groupId, isMuted: item.isMuted, hasFailed: item.hasFailed, hasUnreadMentions: item.hasUnseenMentions, hasUnreadReactions: item.hasUnseenReactions, filter: filter)
case let .group(_, item, animated, archiveStatus):
var messages:[Message] = []
if let message = item.topMessage {
messages.append(message._asMessage())
}
return ChatListRowItem(initialSize, context: arguments.context, stableId: entry.entry.stableId, pinnedType: .none, groupId: item.id, groupItems: item.items, messages: messages, unreadCount: item.unreadCount, animateGroup: animated, archiveStatus: archiveStatus)
case let .reveal(tabs, selected, counters):
return ChatListRevealItem(initialSize, context: arguments.context, tabs: tabs, selected: selected, counters: counters, action: arguments.setupFilter, openSettings: {
arguments.openFilterSettings(.allChats)
}, menuItems: arguments.tabsMenuItems)
case let .empty(filter, mode, state, peer):
return ChatListEmptyRowItem(initialSize, stableId: entry.stableId, filter: filter, mode: mode, peer: peer?.peer, layoutState: state, context: arguments.context, openFilterSettings: arguments.openFilterSettings, createTopic: arguments.createTopic, switchOffForum: arguments.switchOffForum)
case let .loading(filter):
return ChatListLoadingRowItem(initialSize, stableId: entry.stableId, filter: filter, context: arguments.context)
}
}
let (deleted,inserted,updated) = proccessEntries(from, right: to, { entry -> TableRowItem in
return makeItem(entry)
})
let nState = scrollState ?? (animated ? .none(nil) : .saveVisible(.lower))
let transition = TableUpdateTransition(deleted: deleted, inserted: inserted, updated:updated, animated: animated, state: nState, animateVisibleOnly: false)
subscriber.putNext(transition)
subscriber.putCompletion()
return ActionDisposable {
}
}
}
enum HiddenArchiveStatus : Equatable {
case normal
case collapsed
case hidden(Bool)
var rawValue: Int {
switch self {
case .normal:
return 0
case .collapsed:
return 1
case .hidden:
return 2
}
}
var isHidden: Bool {
switch self {
case .hidden:
return true
default:
return false
}
}
init?(rawValue: Int) {
switch rawValue {
case 0:
self = .normal
case 1:
self = .collapsed
case 2:
self = .hidden(true)
default:
return nil
}
}
}
struct FilterData : Equatable {
let filter: ChatListFilter
let tabs: [ChatListFilter]
let sidebar: Bool
let request: ChatListIndexRequest
init(filter: ChatListFilter, tabs: [ChatListFilter], sidebar: Bool, request: ChatListIndexRequest) {
self.filter = filter
self.tabs = tabs
self.sidebar = sidebar
self.request = request
}
var isEmpty: Bool {
return self.tabs.isEmpty || (self.tabs.count == 1 && self.tabs[0] == .allChats)
}
var isFirst: Bool {
return self.tabs.firstIndex(of: filter) == 0
}
func withUpdatedFilter(_ filter: ChatListFilter?) -> FilterData {
let filter = filter ?? self.tabs.first ?? .allChats
return FilterData(filter: filter, tabs: self.tabs, sidebar: self.sidebar, request: self.request)
}
func withUpdatedTabs(_ tabs: [ChatListFilter]) -> FilterData {
return FilterData(filter: self.filter, tabs: tabs, sidebar: self.sidebar, request: self.request)
}
func withUpdatedSidebar(_ sidebar: Bool) -> FilterData {
return FilterData(filter: self.filter, tabs: self.tabs, sidebar: sidebar, request: self.request)
}
func withUpdatedRequest(_ request: ChatListIndexRequest) -> FilterData {
return FilterData(filter: self.filter, tabs: self.tabs, sidebar: sidebar, request: request)
}
}
private struct HiddenItems : Equatable {
let archive: HiddenArchiveStatus
let promo: Set<PeerId>
}
class ChatListController : PeersListController {
private let filter = ValuePromise<FilterData>(ignoreRepeated: true)
private let _filterValue = Atomic<FilterData>(value: FilterData(filter: .allChats, tabs: [], sidebar: false, request: .Initial(50, nil)))
private var filterValue: FilterData? {
return _filterValue.with { $0 }
}
var filterSignal : Signal<FilterData, NoError> {
return self.filter.get()
}
func updateFilter(_ f:(FilterData)->FilterData) {
let data = f(_filterValue.with { $0 })
if !context.isPremium {
if let index = data.tabs.firstIndex(of: data.filter) {
if index > context.premiumLimits.dialog_filters_limit_default {
showPremiumLimit(context: context, type: .folders)
return
}
}
}
var changedFolder = false
filter.set(_filterValue.modify { previous in
var current = f(previous)
if previous.filter.id != current.filter.id {
current = current.withUpdatedRequest(.Initial(max(Int(context.window.frame.height / 70) + 3, 12), nil))
changedFolder = true
}
return current
})
if changedFolder {
self.removeRevealStateIfNeeded(nil)
}
self.genericView.searchView.change(state: .None, true)
setCenterTitle(self.defaultBarTitle)
}
private let previousChatList:Atomic<EngineChatList?> = Atomic(value: nil)
private let first = Atomic(value:true)
private let animated = Atomic(value: false)
private let removePeerIdGroupDisposable = MetaDisposable()
private let downloadsDisposable = MetaDisposable()
private let disposable = MetaDisposable()
private let scrollDisposable = MetaDisposable()
private let reorderDisposable = MetaDisposable()
private let globalPeerDisposable = MetaDisposable()
private let archivationTooltipDisposable = MetaDisposable()
private let animateGroupNextTransition:Atomic<EngineChatList.Group?> = Atomic(value: nil)
private var activityStatusesDisposable:Disposable?
private let downloadsSummary: DownloadsSummary
private let suggestAutoarchiveDisposable = MetaDisposable()
private var didSuggestAutoarchive: Bool = false
private let hiddenItemsValue: Atomic<HiddenItems> = Atomic(value: HiddenItems(archive: FastSettings.archiveStatus, promo: Set()))
private let hiddenItemsState: ValuePromise<HiddenItems> = ValuePromise(HiddenItems(archive: FastSettings.archiveStatus, promo: Set()), ignoreRepeated: true)
private let filterDisposable = MetaDisposable()
private func updateHiddenStateState(_ f:(HiddenItems)->HiddenItems) {
let result = hiddenItemsValue.modify(f)
FastSettings.archiveStatus = result.archive
hiddenItemsState.set(result)
}
override func viewDidResized(_ size: NSSize) {
super.viewDidResized(size)
}
override func viewDidLoad() {
super.viewDidLoad()
let initialSize = self.atomicSize
let context = self.context
let previousChatList = self.previousChatList
let first = Atomic<(hasEarlier: Bool, hasLater: Bool)>(value: (hasEarlier: false, hasLater: false))
let scrollUp:Atomic<Bool> = self.first
let groupId = self.mode.groupId
let mode = self.mode
let previousEntries:Atomic<[AppearanceWrapperEntry<UIChatListEntry>]?> = Atomic(value: nil)
let animated: Atomic<Bool> = self.animated
let animateGroupNextTransition = self.animateGroupNextTransition
var scroll:TableScrollState? = nil
let arguments = Arguments(context: context, setupFilter: { [weak self] filter in
self?.updateFilter {
$0.withUpdatedFilter(filter)
}
self?.scrollup(force: true)
}, openFilterSettings: { filter in
if case .filter = filter {
context.bindings.rootNavigation().push(ChatListFilterController(context: context, filter: filter))
} else {
context.bindings.rootNavigation().push(ChatListFiltersListController(context: context))
}
}, tabsMenuItems: { filter in
return filterContextMenuItems(filter, context: context)
}, createTopic: {
switch mode {
case let .forum(peerId):
ForumUI.createTopic(peerId, context: context)
default:
break
}
}, switchOffForum: {
switch mode {
case let .forum(peerId):
_ = context.engine.peers.setChannelForumMode(id: peerId, isForum: false).start()
default:
break
}
})
let previousLocation: Atomic<ChatLocation?> = Atomic(value: nil)
globalPeerDisposable.set(context.globalPeerHandler.get().start(next: { [weak self] location in
if previousLocation.swap(location) != location {
self?.removeRevealStateIfNeeded(nil)
}
self?.removeHighlightEvents()
if let searchController = self?.searchController {
searchController.updateHighlightEvents(location != nil)
}
if location == nil {
self?.setHighlightEvents()
}
}))
let signal = filter.get()
let previousfilter = Atomic<FilterData?>(value: self.filterValue)
let chatHistoryView: Signal<(ChatListViewUpdate, FilterData, Bool), NoError> = signal |> mapToSignal { data -> Signal<(ChatListViewUpdate, FilterData, Bool), NoError> in
return chatListViewForLocation(chatListLocation: mode.location, location: data.request, filter: data.filter, account: context.account) |> map {
return ($0, data, previousfilter.swap(data)?.filter.id != data.filter.id)
}
}
let previousLayout: Atomic<SplitViewState> = Atomic(value: context.layout)
let list:Signal<TableUpdateTransition,NoError> = combineLatest(queue: prepareQueue, chatHistoryView, appearanceSignal, stateUpdater, hiddenItemsState.get(), appNotificationSettings(accountManager: context.sharedContext.accountManager), chatListFilterItems(engine: context.engine, accountManager: context.sharedContext.accountManager)) |> mapToQueue { value, appearance, state, hiddenItems, inAppSettings, filtersCounter -> Signal<TableUpdateTransition, NoError> in
let filterData = value.1
let update = value.0
let removeNextAnimation = update.removeNextAnimation
let previous = first.swap((hasEarlier: update.list.hasEarlier,
hasLater: update.list.hasLater))
let ignoreFlags = scrollUp.swap(false)
if !ignoreFlags || (!ignoreFlags && (previous.hasEarlier != update.list.hasEarlier || previous.hasLater != update.list.hasLater) && !removeNextAnimation) {
scroll = nil
}
_ = previousChatList.swap(update.list)
var prepare:[(EngineChatList.Item, UIChatAdditionalItem?)] = []
for value in update.list.items {
prepare.append((value, nil))
}
if !update.list.hasLater, case .allChats = filterData.filter {
let items = update.list.additionalItems.filter {
!hiddenItems.promo.contains($0.item.renderedPeer.peerId)
}
for (i, current) in items.enumerated() {
prepare.append((current.item, UIChatAdditionalItem(item: current, index: i + update.list.groupItems.count)))
}
}
var mapped: [UIChatListEntry] = prepare.map { item in
let space: PeerActivitySpace
switch item.0.id {
case let .forum(threadId):
space = .init(peerId: item.0.renderedPeer.peerId, category: .thread(threadId))
case let .chatList(peerId):
space = .init(peerId: peerId, category: .global)
}
return .chat(item.0, state?.activities.activities[space] ?? [], item.1, filter: filterData.filter)
}
if case .filter = filterData.filter, mapped.isEmpty {} else {
if !update.list.hasLater {
for (i, group) in update.list.groupItems.reversed().enumerated() {
mapped.append(.group(i, group, animateGroupNextTransition.swap(nil) == group.id, hiddenItems.archive))
}
}
}
if mapped.isEmpty {
if !update.list.isLoading {
mapped.append(.empty(filterData.filter, mode, state?.splitState ?? .none, .init(state?.forumPeer?.peer)))
} else {
mapped.append(.loading(filterData.filter))
}
} else {
if update.list.isLoading {
mapped.append(.loading(filterData.filter))
}
}
if !filterData.isEmpty && !filterData.sidebar {
mapped.append(.reveal(filterData.tabs, filterData.filter, filtersCounter))
}
let entries = mapped.sorted().compactMap { entry -> AppearanceWrapperEntry<UIChatListEntry>? in
return AppearanceWrapperEntry(entry: entry, appearance: appearance)
}
let prev = previousEntries.swap(entries)
var animated = animated.swap(true)
if value.2 {
animated = false
scroll = .up(true)
}
let layoutUpdated = previousLayout.swap(context.layout) != context.layout
if layoutUpdated {
scroll = .up(false)
animated = false
}
return prepareEntries(from: prev, to: entries, adIndex: nil, arguments: arguments, initialSize: initialSize.with { $0 }, animated: animated, scrollState: scroll, groupId: groupId)
}
let appliedTransition = list |> deliverOnMainQueue |> mapToQueue { [weak self] transition -> Signal<Void, NoError> in
self?.enqueueTransition(transition)
return .complete()
}
disposable.set(appliedTransition.start())
var pinnedCount: Int = 0
self.genericView.tableView.enumerateItems { item -> Bool in
guard let item = item as? ChatListRowItem, item.isFixedItem else {return false}
pinnedCount += 1
return item.isFixedItem
}
genericView.tableView.resortController = TableResortController(resortRange: NSMakeRange(0, pinnedCount), start: { row in
}, resort: { row in
}, complete: { [weak self] from, to in
self?.resortPinned(from, to)
})
genericView.tableView.addScroll(listener: TableScrollListener(dispatchWhenVisibleRangeUpdated: false, { [weak self] scroll in
guard let `self` = self else {
return
}
self.removeRevealStateIfNeeded(nil)
}))
genericView.tableView.set(stickClass: ChatListRevealItem.self, handler: { _ in
})
genericView.tableView.emptyChecker = { items in
let filter = items.filter { !($0 is ChatListEmptyRowItem) }
return filter.isEmpty
}
genericView.tableView.setScrollHandler({ [weak self] scroll in
let view = previousChatList.modify({$0})
self?.removeRevealStateIfNeeded(nil)
if let strongSelf = self, let view = view {
var messageIndex:EngineChatList.Item.Index?
switch scroll.direction {
case .bottom:
if view.hasEarlier {
messageIndex = view.items.first?.index
}
case .top:
if view.hasLater {
messageIndex = view.items.last?.index
}
case .none:
break
}
if let messageIndex = messageIndex {
_ = animated.swap(false)
strongSelf.updateFilter {
$0.withUpdatedRequest(.Index(messageIndex, nil))
}
}
}
})
let filterView = chatListFilterPreferences(engine: context.engine) |> deliverOnMainQueue
switch mode {
case .folder, .forum:
self.updateFilter( {
$0.withUpdatedTabs([]).withUpdatedFilter(nil)
} )
case let .filter(filterId):
filterDisposable.set(filterView.start(next: { [weak self] filters in
var shouldBack: Bool = false
self?.updateFilter { current in
var current = current
if let updated = filters.list.first(where: { $0.id == filterId }) {
current = current.withUpdatedFilter(updated)
} else {
shouldBack = true
current = current.withUpdatedFilter(nil)
}
current = current.withUpdatedTabs([])
return current
}
if shouldBack {
self?.navigationController?.back()
}
}))
default:
var first: Bool = true
filterDisposable.set(combineLatest(filterView, context.layoutValue).start(next: { [weak self] filters, layout in
self?.updateFilter( { current in
var current = current
current = current.withUpdatedTabs(filters.list).withUpdatedSidebar(filters.sidebar || layout == .minimisize)
if !first, let updated = filters.list.first(where: { $0.id == current.filter.id }) {
current = current.withUpdatedFilter(updated)
} else {
current = current.withUpdatedFilter(nil)
}
return current
} )
first = false
}))
}
let downloadArguments: DownloadsControlArguments = DownloadsControlArguments(open: { [weak self] in
self?.showDownloads(animated: true)
}, navigate: { [weak self] messageId in
self?.open(with: .chatId(.chatList(messageId.peerId), messageId.peerId, -1), messageId: messageId, initialAction: nil, close: false, forceAnimated: true)
})
downloadsDisposable.set(self.downloadsSummary.state.start(next: { [weak self] state in
self?.genericView.updateDownloads(state, context: context, arguments: downloadArguments, animated: true)
}))
}
func collapseOrExpandArchive() {
updateHiddenStateState { current in
switch current.archive {
case .collapsed:
return HiddenItems(archive: .normal, promo: current.promo)
default:
return HiddenItems(archive: .collapsed, promo: current.promo)
}
}
}
func hidePromoItem(_ peerId: PeerId) {
updateHiddenStateState { current in
var promo = current.promo
promo.insert(peerId)
return HiddenItems(archive: current.archive, promo: promo)
}
_ = hideAccountPromoInfoChat(account: self.context.account, peerId: peerId).start()
}
func toggleHideArchive() {
updateHiddenStateState { current in
switch current.archive {
case .hidden:
return HiddenItems(archive: .normal, promo: current.promo)
default:
return HiddenItems(archive: .hidden(true), promo: current.promo)
}
}
}
func setAnimateGroupNextTransition(_ groupId: EngineChatList.Group) {
_ = self.animateGroupNextTransition.swap(groupId)
}
private func enqueueTransition(_ transition: TableUpdateTransition) {
self.genericView.tableView.merge(with: transition)
self.readyOnce()
switch self.mode {
case .folder:
if self.genericView.tableView.isEmpty {
self.navigationController?.close()
}
default:
break
}
var first: ChatListRowItem?
self.genericView.tableView.enumerateItems { item -> Bool in
if let item = item as? ChatListRowItem, item.archiveStatus != nil {
first = item
}
return first == nil
}
if let first = first, let archiveStatus = first.archiveStatus {
self.genericView.tableView.autohide = TableAutohide(item: first, hideUntilOverscroll: archiveStatus.isHidden, hideHandler: { [weak self] hidden in
self?.updateHiddenStateState { current in
return HiddenItems(archive: .hidden(hidden), promo: current.promo)
}
})
} else {
self.genericView.tableView.autohide = nil
}
var pinnedRange: NSRange = NSMakeRange(NSNotFound, 0)
self.genericView.tableView.enumerateItems { item -> Bool in
guard let item = item as? ChatListRowItem else {return true}
switch item.pinnedType {
case .some, .last:
if pinnedRange.location == NSNotFound {
pinnedRange.location = item.index
}
pinnedRange.length += 1
default:
break
}
return item.isFixedItem || item.groupId != .root
}
self.searchController?.pinnedItems = self.collectPinnedItems
self.genericView.tableView.resortController?.resortRange = pinnedRange
let needPreload = previousChatList.with { $0?.hasLater == false }
if needPreload {
var preloadItems:[ChatHistoryPreloadItem] = []
self.genericView.tableView.enumerateItems(with: { item -> Bool in
guard let item = item as? ChatListRowItem, let index = item.chatListIndex else {return true}
preloadItems.append(.init(index: index, threadId: item.mode.threadId, isMuted: item.isMuted, hasUnread: item.hasUnread))
return preloadItems.count < 30
})
context.account.viewTracker.chatListPreloadItems.set(.single(preloadItems) |> delay(0.2, queue: prepareQueue))
} else {
context.account.viewTracker.chatListPreloadItems.set(.single([]))
}
}
private func resortPinned(_ from: Int, _ to: Int) {
var items:[PinnedItemId] = []
var offset: Int = 0
let groupId: EngineChatList.Group = self.mode.groupId
let location: TogglePeerChatPinnedLocation
if let filter = self.filterValue?.filter {
switch filter {
case .allChats:
location = .group(groupId._asGroup())
case let .filter(id, _, _, _):
location = .filter(id)
}
} else {
location = .group(groupId._asGroup())
}
self.genericView.tableView.enumerateItems { item -> Bool in
guard let item = item as? ChatListRowItem else {
offset += 1
return true
}
if item.groupId != .root || item.isAd {
offset += 1
}
if let location = item.chatLocation {
switch item.pinnedType {
case .some, .last:
items.append(location.pinnedItemId)
default:
break
}
}
return item.isFixedItem || item.groupId != .root
}
items.move(at: from - offset, to: to - offset)
reorderDisposable.set(context.engine.peers.reorderPinnedItemIds(location: location, itemIds: items).start())
}
override var collectPinnedItems:[PinnedItemId] {
var items:[PinnedItemId] = []
self.genericView.tableView.enumerateItems { item -> Bool in
guard let item = item as? ChatListRowItem else {return false}
if let location = item.chatLocation {
switch item.pinnedType {
case .some, .last:
items.append(location.pinnedItemId)
default:
break
}
}
return item.isFixedItem || item.groupId != .root
}
return items
}
private var lastScrolledIndex: ChatListIndex? = nil
override func scrollup(force: Bool = false) {
if force {
self.genericView.tableView.scroll(to: .up(true), ignoreLayerAnimation: true)
return
}
if searchController != nil {
self.genericView.searchView.change(state: .None, true)
return
}
let view = self.previousChatList.with { $0 }
if self.genericView.tableView.contentOffset.y == 0, view?.hasLater == false {
switch mode {
case .folder:
navigationController?.back()
return
case .filter:
navigationController?.back()
return
case .plain:
break
case .forum:
navigationController?.back()
return
}
}
let scrollToTop:()->Void = { [weak self] in
guard let `self` = self else {return}
let view = self.previousChatList.modify({$0})
if view?.hasLater == true {
_ = self.first.swap(true)
self.updateFilter {
$0.withUpdatedRequest(.Initial(50, .up(true)))
}
} else {
if self.genericView.tableView.documentOffset.y == 0 {
if self.filterValue?.filter == .allChats {
self.context.bindings.mainController().showFastChatSettings()
} else {
self.updateFilter {
$0.withUpdatedFilter(nil)
}
}
} else {
self.genericView.tableView.scroll(to: .up(true), ignoreLayerAnimation: true)
}
}
}
scrollToTop()
}
func globalSearch(_ query: String) {
let invoke = { [weak self] in
self?.genericView.searchView.change(state: .Focus, false)
self?.genericView.searchView.setString(query)
}
switch context.layout {
case .single:
context.bindings.rootNavigation().back()
Queue.mainQueue().justDispatch(invoke)
case .minimisize:
context.bindings.needFullsize()
Queue.mainQueue().justDispatch(invoke)
default:
invoke()
}
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
let isLocked = (NSApp.delegate as? AppDelegate)?.passlock ?? .single(false)
self.suggestAutoarchiveDisposable.set(combineLatest(queue: .mainQueue(), isLocked, context.isKeyWindow, getServerProvidedSuggestions(account: self.context.account)).start(next: { [weak self] locked, isKeyWindow, values in
guard let strongSelf = self, let navigation = strongSelf.navigationController else {
return
}
if strongSelf.didSuggestAutoarchive {
return
}
if !values.contains(.autoarchivePopular) {
return
}
if !isKeyWindow {
return
}
if navigation.stackCount > 1 {
return
}
if locked {
return
}
strongSelf.didSuggestAutoarchive = true
let context = strongSelf.context
_ = dismissServerProvidedSuggestion(account: strongSelf.context.account, suggestion: .autoarchivePopular).start()
confirm(for: context.window, header: strings().alertHideNewChatsHeader, information: strings().alertHideNewChatsText, okTitle: strings().alertHideNewChatsOK, cancelTitle: strings().alertHideNewChatsCancel, successHandler: { _ in
execute(inapp: .settings(link: "tg://settings/privacy", context: context, section: .privacy))
})
}))
context.window.set(mouseHandler: { [weak self] event -> KeyHandlerResult in
guard let `self` = self else {return .rejected}
if event.modifierFlags.contains(.control) {
if self.genericView.tableView._mouseInside() {
let row = self.genericView.tableView.row(at: self.genericView.tableView.clipView.convert(event.locationInWindow, from: nil))
if row >= 0 {
let view = self.genericView.hitTest(self.genericView.convert(event.locationInWindow, from: nil))
if view?.className.contains("Segment") == false {
self.genericView.tableView.item(at: row).view?.mouseDown(with: event)
return .invoked
} else {
return .rejected
}
}
}
}
return .rejected
}, with: self, for: .leftMouseDown, priority: .high)
context.window.add(swipe: { [weak self] direction, _ -> SwipeHandlerResult in
guard let `self` = self, let window = self.window else {return .failed}
let swipeState: SwipeState?
var checkFolder: Bool = true
let row = self.genericView.tableView.row(at: self.genericView.tableView.clipView.convert(window.mouseLocationOutsideOfEventStream, from: nil))
if row != -1 {
let hitTestView = self.genericView.hitTest(self.genericView.convert(window.mouseLocationOutsideOfEventStream, from: nil))
if let view = hitTestView, view.isInSuperclassView(ChatListRevealView.self) {
return .failed
}
let item = self.genericView.tableView.item(at: row) as? ChatListRowItem
if let item = item {
let view = item.view as? ChatListRowView
if view?.endRevealState != nil {
checkFolder = false
}
if !item.hasRevealState {
return .failed
}
} else {
return .failed
}
}
switch direction {
case let .left(_state):
if !self.mode.isPlain && checkFolder {
swipeState = nil
} else {
swipeState = _state
}
case let .right(_state):
swipeState = _state
case .none:
swipeState = nil
}
guard let state = swipeState, self.context.layout != .minimisize else {return .failed}
switch state {
case .start:
let row = self.genericView.tableView.row(at: self.genericView.tableView.clipView.convert(window.mouseLocationOutsideOfEventStream, from: nil))
if row != -1 {
let item = self.genericView.tableView.item(at: row) as! ChatListRowItem
guard !item.isAd else {return .failed}
self.removeRevealStateIfNeeded(item.peerId)
(item.view as? RevealTableView)?.initRevealState()
return .success(RevealTableItemController(item: item))
} else {
return .failed
}
case let .swiping(_delta, controller):
let controller = controller as! RevealTableItemController
guard let view = controller.item.view as? RevealTableView else {return .nothing}
var delta:CGFloat
switch direction {
case .left:
delta = _delta//max(0, _delta)
case .right:
delta = -_delta//min(-_delta, 0)
default:
delta = _delta
}
delta -= view.additionalRevealDelta
let newDelta = min(view.width * log2(abs(delta) + 1) * log2(delta < 0 ? view.width * 8 : view.width) / 100.0, abs(delta))
if delta < 0 {
delta = -newDelta
} else {
delta = newDelta
}
view.moveReveal(delta: delta)
case let .success(_, controller), let .failed(_, controller):
let controller = controller as! RevealTableItemController
guard let view = (controller.item.view as? RevealTableView) else {return .nothing}
var direction = direction
switch direction {
case let .left(state):
if view.containerX < 0 && abs(view.containerX) > view.rightRevealWidth / 2 {
direction = .right(state.withAlwaysSuccess())
} else if abs(view.containerX) < view.rightRevealWidth / 2 && view.containerX < view.leftRevealWidth / 2 {
direction = .left(state.withAlwaysFailed())
} else {
direction = .left(state.withAlwaysSuccess())
}
case .right:
if view.containerX > 0 && view.containerX > view.leftRevealWidth / 2 {
direction = .left(state.withAlwaysSuccess())
} else if abs(view.containerX) < view.rightRevealWidth / 2 && view.containerX < view.leftRevealWidth / 2 {
direction = .right(state.withAlwaysFailed())
} else {
direction = .right(state.withAlwaysSuccess())
}
default:
break
}
view.completeReveal(direction: direction)
}
// return .success()
return .nothing
}, with: self.genericView.tableView, identifier: "chat-list", priority: .high)
if context.bindings.rootNavigation().stackCount == 1 {
setHighlightEvents()
}
}
private func setHighlightEvents() {
removeHighlightEvents()
context.window.set(handler: { [weak self] _ -> KeyHandlerResult in
if let item = self?.genericView.tableView.highlightedItem(), item.index > 0 {
self?.genericView.tableView.highlightPrev(turnDirection: false)
while self?.genericView.tableView.highlightedItem() is PopularPeersRowItem || self?.genericView.tableView.highlightedItem() is SeparatorRowItem {
self?.genericView.tableView.highlightNext(turnDirection: false)
}
}
return .invoked
}, with: self, for: .UpArrow, priority: .low)
context.window.set(handler: { [weak self] _ -> KeyHandlerResult in
self?.genericView.tableView.highlightNext(turnDirection: false)
while self?.genericView.tableView.highlightedItem() is PopularPeersRowItem || self?.genericView.tableView.highlightedItem() is SeparatorRowItem {
self?.genericView.tableView.highlightNext(turnDirection: false)
}
return .invoked
}, with: self, for: .DownArrow, priority: .low)
}
private func removeHighlightEvents() {
genericView.tableView.cancelHighlight()
context.window.remove(object: self, for: .DownArrow, forceCheckFlags: true)
context.window.remove(object: self, for: .UpArrow, forceCheckFlags: true)
}
private func removeRevealStateIfNeeded(_ ignoreId: PeerId?) {
genericView.tableView.enumerateItems { item -> Bool in
if let item = item as? ChatListRowItem, item.peerId != ignoreId {
(item.view as? ChatListRowView)?.endRevealState = nil
}
return true
}
}
private func _openChat(_ index: Int) {
if !genericView.tableView.isEmpty {
let archiveItem = genericView.tableView.item(at: 0) as? ChatListRowItem
var index: Int = index
if let item = archiveItem, item.isAutohidden || item.archiveStatus == .collapsed {
index += 1
}
if archiveItem == nil {
index += 1
if genericView.tableView.count > 1 {
let archiveItem = genericView.tableView.item(at: 1) as? ChatListRowItem
if let item = archiveItem, item.isAutohidden || item.archiveStatus == .collapsed {
index += 1
}
}
}
if genericView.tableView.count > index {
_ = genericView.tableView.select(item: genericView.tableView.item(at: index), notify: true, byClick: true)
}
}
}
func openChat(_ index: Int, force: Bool = false) {
if case .forum = self.mode {
_openChat(index)
} else if case .folder = self.mode {
_openChat(index)
} else if force {
_openChat(index)
} else {
let prefs = chatListFilterPreferences(engine: context.engine) |> deliverOnMainQueue |> take(1)
_ = prefs.start(next: { [weak self] filters in
if filters.isEmpty {
self?._openChat(index)
} else if filters.list.count > index {
self?.updateFilter {
$0.withUpdatedFilter(filters.list[index])
}
self?.scrollup(force: true)
} else {
self?._openChat(index)
}
})
}
}
override var removeAfterDisapper: Bool {
return false
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
context.window.removeAllHandlers(for: self)
context.window.removeAllHandlers(for: genericView.tableView)
removeRevealStateIfNeeded(nil)
suggestAutoarchiveDisposable.set(nil)
}
// override func getLeftBarViewOnce() -> BarView {
// return MajorBackNavigationBar(self, context: context, excludePeerId: context.peerId)
// }
deinit {
removePeerIdGroupDisposable.dispose()
disposable.dispose()
scrollDisposable.dispose()
reorderDisposable.dispose()
globalPeerDisposable.dispose()
archivationTooltipDisposable.dispose()
activityStatusesDisposable?.dispose()
filterDisposable.dispose()
suggestAutoarchiveDisposable.dispose()
downloadsDisposable.dispose()
}
override var enableBack: Bool {
switch mode {
case .folder, .filter:
return true
default:
return false
}
}
override var defaultBarTitle: String {
switch mode {
case .filter:
return _filterValue.with { $0.filter.title }
default:
return super.defaultBarTitle
}
}
override func escapeKeyAction() -> KeyHandlerResult {
if !mode.isPlain, let navigation = navigationController {
navigation.back()
return .invoked
}
if let filter = self.filterValue, !filter.isFirst {
updateFilter {
$0.withUpdatedFilter(nil)
}
return .invoked
}
return super.escapeKeyAction()
}
init(_ context: AccountContext, modal:Bool = false, mode: PeerListMode = .plain) {
self.downloadsSummary = DownloadsSummary(context.fetchManager as! FetchManagerImpl, context: context)
let searchOptions:AppSearchOptions
searchOptions = [.messages, .chats]
super.init(context, followGlobal: !modal, mode: mode, searchOptions: searchOptions)
if mode.filterId != nil {
context.closeFolderFirst = true
}
}
override func selectionWillChange(row:Int, item:TableRowItem, byClick: Bool) -> Bool {
if let item = item as? ChatListRowItem, let peer = item.peer, let modalAction = context.bindings.rootNavigation().modalAction {
if !modalAction.isInvokable(for: peer) {
modalAction.alertError(for: peer, with: item.context.window)
return false
}
modalAction.afterInvoke()
if let modalAction = modalAction as? FWDNavigationAction {
if item.peerId == context.peerId {
_ = Sender.forwardMessages(messageIds: modalAction.messages.map{$0.id}, context: context, peerId: context.peerId, replyId: nil).start()
_ = showModalSuccess(for: item.context.window, icon: theme.icons.successModalProgress, delay: 1.0).start()
navigationController?.removeModalAction()
return false
}
}
}
if let item = item as? ChatListRowItem {
if item.groupId != .root {
if byClick {
item.view?.focusAnimation(nil)
open(with: item.entryId, initialAction: nil, addition: false)
}
return false
} else if item.isForum && !item.isTopic {
item.view?.focusAnimation(nil)
}
}
if item is ChatListRevealItem {
return false
}
return true
}
override func selectionDidChange(row:Int, item:TableRowItem, byClick:Bool, isNew:Bool) -> Void {
let navigation = context.bindings.rootNavigation()
if let item = item as? ChatListRowItem {
if !isNew, let controller = navigation.controller as? ChatController, !(item.isForum && !item.isTopic) {
switch controller.mode {
case .history, .thread:
if let modalAction = navigation.modalAction {
navigation.controller.invokeNavigation(action: modalAction)
}
controller.clearReplyStack()
controller.scrollUpOrToUnread()
case .scheduled, .pinned:
navigation.back()
}
} else {
let context = self.context
_ = (context.globalPeerHandler.get() |> take(1)).start(next: { location in
context.globalPeerHandler.set(.single(location))
})
let initialAction: ChatInitialAction?
switch item.pinnedType {
case let .ad(info):
initialAction = .ad(info.promoInfo.content)
default:
initialAction = nil
}
open(with: item.entryId, initialAction: initialAction, addition: false)
}
}
}
}
| gpl-2.0 | 94750daee3863d52ca7f5e7d82d88a9d | 38.299406 | 547 | 0.553113 | 5.338817 | false | false | false | false |
Antondomashnev/ADMozaicCollectionViewLayout | Pods/Nimble/Sources/Nimble/Matchers/RaisesException.swift | 1 | 7369 | import Foundation
// This matcher requires the Objective-C, and being built by Xcode rather than the Swift Package Manager
#if (os(macOS) || os(iOS) || os(tvOS) || os(watchOS)) && !SWIFT_PACKAGE
/// A Nimble matcher that succeeds when the actual expression raises an
/// exception with the specified name, reason, and/or userInfo.
///
/// Alternatively, you can pass a closure to do any arbitrary custom matching
/// to the raised exception. The closure only gets called when an exception
/// is raised.
///
/// nil arguments indicates that the matcher should not attempt to match against
/// that parameter.
public func raiseException(
named: String? = nil,
reason: String? = nil,
userInfo: NSDictionary? = nil,
closure: ((NSException) -> Void)? = nil) -> Predicate<Any> {
return Predicate { actualExpression in
var exception: NSException?
let capture = NMBExceptionCapture(handler: ({ e in
exception = e
}), finally: nil)
do {
try capture.tryBlockThrows {
_ = try actualExpression.evaluate()
}
} catch {
return PredicateResult(status: .fail, message: .fail("unexpected error thrown: <\(error)>"))
}
let failureMessage = FailureMessage()
setFailureMessageForException(
failureMessage,
exception: exception,
named: named,
reason: reason,
userInfo: userInfo,
closure: closure
)
let matches = exceptionMatchesNonNilFieldsOrClosure(
exception,
named: named,
reason: reason,
userInfo: userInfo,
closure: closure
)
return PredicateResult(bool: matches, message: failureMessage.toExpectationMessage())
}
}
// swiftlint:disable:next function_parameter_count
internal func setFailureMessageForException(
_ failureMessage: FailureMessage,
exception: NSException?,
named: String?,
reason: String?,
userInfo: NSDictionary?,
closure: ((NSException) -> Void)?) {
failureMessage.postfixMessage = "raise exception"
if let named = named {
failureMessage.postfixMessage += " with name <\(named)>"
}
if let reason = reason {
failureMessage.postfixMessage += " with reason <\(reason)>"
}
if let userInfo = userInfo {
failureMessage.postfixMessage += " with userInfo <\(userInfo)>"
}
if closure != nil {
failureMessage.postfixMessage += " that satisfies block"
}
if named == nil && reason == nil && userInfo == nil && closure == nil {
failureMessage.postfixMessage = "raise any exception"
}
if let exception = exception {
// swiftlint:disable:next line_length
failureMessage.actualValue = "\(String(describing: type(of: exception))) { name=\(exception.name), reason='\(stringify(exception.reason))', userInfo=\(stringify(exception.userInfo)) }"
} else {
failureMessage.actualValue = "no exception"
}
}
internal func exceptionMatchesNonNilFieldsOrClosure(
_ exception: NSException?,
named: String?,
reason: String?,
userInfo: NSDictionary?,
closure: ((NSException) -> Void)?) -> Bool {
var matches = false
if let exception = exception {
matches = true
if let named = named, exception.name.rawValue != named {
matches = false
}
if reason != nil && exception.reason != reason {
matches = false
}
if let userInfo = userInfo, let exceptionUserInfo = exception.userInfo,
(exceptionUserInfo as NSDictionary) != userInfo {
matches = false
}
if let closure = closure {
let assertions = gatherFailingExpectations {
closure(exception)
}
let messages = assertions.map { $0.message }
if messages.count > 0 {
matches = false
}
}
}
return matches
}
public class NMBObjCRaiseExceptionMatcher: NSObject, NMBMatcher {
// swiftlint:disable identifier_name
internal var _name: String?
internal var _reason: String?
internal var _userInfo: NSDictionary?
internal var _block: ((NSException) -> Void)?
// swiftlint:enable identifier_name
internal init(name: String?, reason: String?, userInfo: NSDictionary?, block: ((NSException) -> Void)?) {
_name = name
_reason = reason
_userInfo = userInfo
_block = block
}
@objc public func matches(_ actualBlock: @escaping () -> NSObject?, failureMessage: FailureMessage, location: SourceLocation) -> Bool {
let block: () -> Any? = ({ _ = actualBlock(); return nil })
let expr = Expression(expression: block, location: location)
do {
return try raiseException(
named: _name,
reason: _reason,
userInfo: _userInfo,
closure: _block
).matches(expr, failureMessage: failureMessage)
} catch let error {
failureMessage.stringValue = "unexpected error thrown: <\(error)>"
return false
}
}
@objc public func doesNotMatch(_ actualBlock: @escaping () -> NSObject?, failureMessage: FailureMessage, location: SourceLocation) -> Bool {
return !matches(actualBlock, failureMessage: failureMessage, location: location)
}
@objc public var named: (_ name: String) -> NMBObjCRaiseExceptionMatcher {
return ({ name in
return NMBObjCRaiseExceptionMatcher(
name: name,
reason: self._reason,
userInfo: self._userInfo,
block: self._block
)
})
}
@objc public var reason: (_ reason: String?) -> NMBObjCRaiseExceptionMatcher {
return ({ reason in
return NMBObjCRaiseExceptionMatcher(
name: self._name,
reason: reason,
userInfo: self._userInfo,
block: self._block
)
})
}
@objc public var userInfo: (_ userInfo: NSDictionary?) -> NMBObjCRaiseExceptionMatcher {
return ({ userInfo in
return NMBObjCRaiseExceptionMatcher(
name: self._name,
reason: self._reason,
userInfo: userInfo,
block: self._block
)
})
}
@objc public var satisfyingBlock: (_ block: ((NSException) -> Void)?) -> NMBObjCRaiseExceptionMatcher {
return ({ block in
return NMBObjCRaiseExceptionMatcher(
name: self._name,
reason: self._reason,
userInfo: self._userInfo,
block: block
)
})
}
}
extension NMBObjCMatcher {
@objc public class func raiseExceptionMatcher() -> NMBObjCRaiseExceptionMatcher {
return NMBObjCRaiseExceptionMatcher(name: nil, reason: nil, userInfo: nil, block: nil)
}
}
#endif
| mit | 5ac2620c5e4be5e72a51e78b3342e15b | 34.090476 | 196 | 0.570091 | 5.450444 | false | false | false | false |
turingcorp/gattaca | gattaca/View/ProfileEdit/VProfileEditListHeader.swift | 1 | 1442 | import UIKit
class VProfileEditListHeader:UICollectionReusableView
{
private weak var labelTitle:UILabel!
private let kTitleHeight:CGFloat = 40
private let kTitleMarginLeft:CGFloat = 10
private let kTitleWidth:CGFloat = 200
override init(frame:CGRect)
{
super.init(frame:frame)
clipsToBounds = true
backgroundColor = UIColor.clear
let labelTitle:UILabel = UILabel()
labelTitle.translatesAutoresizingMaskIntoConstraints = false
labelTitle.backgroundColor = UIColor.clear
labelTitle.isUserInteractionEnabled = false
labelTitle.font = UIFont.medium(size:15)
labelTitle.textColor = UIColor.colourBackgroundDark
self.labelTitle = labelTitle
addSubview(labelTitle)
NSLayoutConstraint.bottomToBottom(
view:labelTitle,
toView:self)
NSLayoutConstraint.height(
view:labelTitle,
constant:kTitleHeight)
NSLayoutConstraint.leftToLeft(
view:labelTitle,
toView:self,
constant:kTitleMarginLeft)
NSLayoutConstraint.width(
view:labelTitle,
constant:kTitleWidth)
}
required init?(coder:NSCoder)
{
return nil
}
//MARK: internal
func config(model:MProfileEditItemProtocol)
{
labelTitle.text = model.headerTitle
}
}
| mit | 3c45a28d806c59336a05729555a324f4 | 26.730769 | 68 | 0.635922 | 5.654902 | false | false | false | false |
moniqwerty/OpenWeatherApp | OpenWeatherApp/OpenWeatherApp/MasterViewController.swift | 1 | 6425 | //
// MasterViewController.swift
// OpenWeatherApp
//
// Created by Monika Markovska on 3/18/16.
// Copyright © 2016 Monika Markovska. All rights reserved.
//
import UIKit
class MasterViewController: UITableViewController {
var detailViewController: DetailViewController? = nil
var cities = [City]()
var weatherService: WeatherService?
{
//Get the weather service object from app delegate
get {
let delegate = UIApplication.sharedApplication().delegate as? AppDelegate
return delegate?.weatherService
}
}
var cityRepository: CityRepository?
{
//Get the repository object from app delegate
get {
let delegate = UIApplication.sharedApplication().delegate as? AppDelegate
return delegate?.cityRepository
}
}
// MARK: - ViewController
override func viewDidLoad() {
super.viewDidLoad()
self.navigationItem.leftBarButtonItem = self.editButtonItem()
let addButton = UIBarButtonItem(barButtonSystemItem: .Add, target: self, action: "insertNewObject:")
self.navigationItem.rightBarButtonItem = addButton
if let split = self.splitViewController {
let controllers = split.viewControllers
self.detailViewController = (controllers[controllers.count-1] as! UINavigationController).topViewController as? DetailViewController
}
//initialize cities array
self.cities = (self.cityRepository?.fetchCities())!
//fetch fresh data for each city
for cityIteration in self.cities
{
self.weatherService?.weatherForCityName(cityIteration.cityName, completionClosure: {(city: City) in
cityIteration.cityName = city.cityName
cityIteration.temperature = city.temperature
cityIteration.weatherDescription = city.weatherDescription
cityIteration.humidity = city.humidity
})
}
self.title = "Cities"
self.refreshControl?.addTarget(self, action: "handleRefresh:", forControlEvents: UIControlEvents.ValueChanged)
}
override func viewWillAppear(animated: Bool) {
self.clearsSelectionOnViewWillAppear = self.splitViewController!.collapsed
super.viewWillAppear(animated)
}
//save current cities list
override func viewWillDisappear(animated: Bool) {
self.cityRepository?.persistCities(cities)
super.viewWillDisappear(animated)
}
// MARK: - Refresh
//fetch fresh data for each city
func handleRefresh(refreshControl: UIRefreshControl) {
for cityIteration in self.cities
{
self.weatherService?.weatherForCityName(cityIteration.cityName, completionClosure: {(city: City) in
cityIteration.cityName = city.cityName
cityIteration.temperature = city.temperature
cityIteration.weatherDescription = city.weatherDescription
cityIteration.humidity = city.humidity
})
}
self.tableView.reloadData()
refreshControl.endRefreshing()
}
// MARK: - Segues
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if segue.identifier == "showDetail" {
if let indexPath = self.tableView.indexPathForSelectedRow {
let object = cities[indexPath.row]
let controller = (segue.destinationViewController as! UINavigationController).topViewController as! DetailViewController
controller.detailItem = object
controller.navigationItem.leftBarButtonItem = self.splitViewController?.displayModeButtonItem()
controller.navigationItem.leftItemsSupplementBackButton = true
}
}
if segue.identifier == "addNewCity" {
let controller = (segue.destinationViewController) as! AddNewCityViewController
controller.parent = self
}
}
func insertNewObject(sender: AnyObject) {
performSegueWithIdentifier("addNewCity", sender: self)
}
//add a new city to the list and fetch weather data
func addNewCity(cityName: String){
let city = City()
city.cityName = cityName
city.temperature = 0
self.weatherService?.weatherForCityName(city.cityName, completionClosure: {(updatedCity: City) in
city.cityName = updatedCity.cityName
city.temperature = updatedCity.temperature
city.weatherDescription = updatedCity.weatherDescription
city.humidity = updatedCity.humidity
dispatch_async(dispatch_get_main_queue()) {
self.tableView.reloadData()
}
})
self.cities.append(city)
self.cityRepository!.cities = self.cities
self.tableView.reloadData()
}
// MARK: - Table View
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return cities.count
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath)
let object = cities[indexPath.row]
cell.textLabel!.text = String(format: "%@ %.0f°C",object.cityName, object.temperature!)
cell.accessoryType = UITableViewCellAccessoryType.DisclosureIndicator
return cell
}
override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool {
// Return false if you do not want the specified item to be editable.
return true
}
override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
if editingStyle == .Delete {
cities.removeAtIndex(indexPath.row)
tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade)
} else if editingStyle == .Insert {
// Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view.
}
}
}
| mit | 5b43875b1e97c0f9ffa90aea8186b8dd | 37.927273 | 157 | 0.660439 | 5.760538 | false | false | false | false |
grpc/grpc-swift | Tests/GRPCTests/EchoHelpers/Interceptors/DelegatingClientInterceptor.swift | 1 | 2824 | /*
* Copyright 2021, gRPC Authors All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import EchoModel
import GRPC
import NIOCore
import SwiftProtobuf
/// A client interceptor which delegates the implementation of `send` and `receive` to callbacks.
final class DelegatingClientInterceptor<
Request: Message,
Response: Message
>: ClientInterceptor<Request, Response> {
typealias RequestPart = GRPCClientRequestPart<Request>
typealias ResponsePart = GRPCClientResponsePart<Response>
typealias Context = ClientInterceptorContext<Request, Response>
typealias OnSend = (RequestPart, EventLoopPromise<Void>?, Context) -> Void
typealias OnReceive = (ResponsePart, Context) -> Void
private let onSend: OnSend
private let onReceive: OnReceive
init(
onSend: @escaping OnSend = { part, promise, context in context.send(part, promise: promise) },
onReceive: @escaping OnReceive = { part, context in context.receive(part) }
) {
self.onSend = onSend
self.onReceive = onReceive
}
override func send(
_ part: GRPCClientRequestPart<Request>,
promise: EventLoopPromise<Void>?,
context: ClientInterceptorContext<Request, Response>
) {
self.onSend(part, promise, context)
}
override func receive(
_ part: GRPCClientResponsePart<Response>,
context: ClientInterceptorContext<Request, Response>
) {
self.onReceive(part, context)
}
}
final class DelegatingEchoClientInterceptorFactory: Echo_EchoClientInterceptorFactoryProtocol {
typealias OnSend = DelegatingClientInterceptor<Echo_EchoRequest, Echo_EchoResponse>.OnSend
let interceptor: DelegatingClientInterceptor<Echo_EchoRequest, Echo_EchoResponse>
init(onSend: @escaping OnSend) {
self.interceptor = DelegatingClientInterceptor(onSend: onSend)
}
func makeGetInterceptors() -> [ClientInterceptor<Echo_EchoRequest, Echo_EchoResponse>] {
return [self.interceptor]
}
func makeExpandInterceptors() -> [ClientInterceptor<Echo_EchoRequest, Echo_EchoResponse>] {
return [self.interceptor]
}
func makeCollectInterceptors() -> [ClientInterceptor<Echo_EchoRequest, Echo_EchoResponse>] {
return [self.interceptor]
}
func makeUpdateInterceptors() -> [ClientInterceptor<Echo_EchoRequest, Echo_EchoResponse>] {
return [self.interceptor]
}
}
| apache-2.0 | 1c45af976b6f767576cd66409fec1068 | 33.439024 | 98 | 0.752479 | 4.511182 | false | false | false | false |
btanner/Eureka | Source/Rows/PickerRow.swift | 7 | 4958 | // PickerRow.swift
// Eureka ( https://github.com/xmartlabs/Eureka )
//
// Copyright (c) 2016 Xmartlabs SRL ( http://xmartlabs.com )
//
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import Foundation
import UIKit
// MARK: PickerCell
open class _PickerCell<T> : Cell<T>, CellType, UIPickerViewDataSource, UIPickerViewDelegate where T: Equatable {
@IBOutlet public weak var picker: UIPickerView!
fileprivate var pickerRow: _PickerRow<T>? { return row as? _PickerRow<T> }
public required init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
let pickerView = UIPickerView()
self.picker = pickerView
self.picker?.translatesAutoresizingMaskIntoConstraints = false
super.init(style: style, reuseIdentifier: reuseIdentifier)
self.contentView.addSubview(pickerView)
self.contentView.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "V:|-0-[picker]-0-|", options: [], metrics: nil, views: ["picker": pickerView]))
self.contentView.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "H:|-0-[picker]-0-|", options: [], metrics: nil, views: ["picker": pickerView]))
}
required public init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
open override func setup() {
super.setup()
accessoryType = .none
editingAccessoryType = .none
height = { UITableView.automaticDimension }
picker.delegate = self
picker.dataSource = self
}
open override func update() {
super.update()
textLabel?.text = nil
detailTextLabel?.text = nil
picker.reloadAllComponents()
}
deinit {
picker?.delegate = nil
picker?.dataSource = nil
}
open var pickerTextAttributes: [NSAttributedString.Key: Any]?
open func numberOfComponents(in pickerView: UIPickerView) -> Int {
return 1
}
open func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
return pickerRow?.options.count ?? 0
}
open func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
return pickerRow?.displayValueFor?(pickerRow?.options[row])
}
open func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
if let picker = pickerRow, !picker.options.isEmpty {
picker.value = picker.options[row]
}
}
open func pickerView(_ pickerView: UIPickerView, attributedTitleForRow row: Int, forComponent component: Int) -> NSAttributedString? {
guard let pickerTextAttributes = pickerTextAttributes, let text = self.pickerView(pickerView, titleForRow: row, forComponent: component) else {
return nil
}
return NSAttributedString(string: text, attributes: pickerTextAttributes)
}
}
open class PickerCell<T> : _PickerCell<T> where T: Equatable {
required public init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
public required init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
}
open override func update() {
super.update()
if let selectedValue = pickerRow?.value, let index = pickerRow?.options.firstIndex(of: selectedValue) {
picker.selectRow(index, inComponent: 0, animated: true)
}
}
}
// MARK: PickerRow
open class _PickerRow<T> : Row<PickerCell<T>> where T: Equatable {
open var options = [T]()
required public init(tag: String?) {
super.init(tag: tag)
}
}
/// A generic row where the user can pick an option from a picker view
public final class PickerRow<T>: _PickerRow<T>, RowType where T: Equatable {
required public init(tag: String?) {
super.init(tag: tag)
}
}
| mit | a2be709bf924915711783bae4a2770ca | 35.189781 | 169 | 0.692215 | 4.726406 | false | false | false | false |
breckinloggins/Swell | Swell/Swell/HTML.swift | 1 | 2690 | //
// HTML.swift
// Swell
//
// Created by Breckin Loggins on 6/16/14.
// Copyright (c) 2014 Breckin Loggins. All rights reserved.
//
import Foundation
let kHTMLContextKey = "HTMLContext"
class HTMLContext {
class var currentContext : HTMLContext {
objc_sync_enter(kHTMLContextKey)
var ctx = NSThread.currentThread().threadDictionary[kHTMLContextKey] as? HTMLContext
if !ctx {
ctx = HTMLContext()
NSThread.currentThread().threadDictionary[kHTMLContextKey] = ctx
}
objc_sync_exit(kHTMLContextKey)
return ctx!
}
var htmlLines : String[] = []
func addLine(line : String) {
htmlLines.append(line)
}
}
func render(content : () -> ()) -> String {
content()
return HTMLContext.currentContext.htmlLines.reduce("", combine: {$0 + "\n" + $1})
}
func text(text : String) {
HTMLContext.currentContext.addLine(text)
}
func html(inner : () -> ()) {
let h = HTMLContext.currentContext
h.htmlLines = []
h.addLine("<!doctype html>")
h.addLine("<html lang=\"en\">")
inner()
h.addLine("</html>")
}
func body(inner : () -> ()) {
let h = HTMLContext.currentContext
h.addLine("<body>")
inner()
h.addLine("</body>")
}
func p(text : String) {
let h = HTMLContext.currentContext
h.addLine("<p>")
h.addLine(text)
}
func br() {
HTMLContext.currentContext.addLine("<br>")
}
func ul(inner : () -> ()) {
let h = HTMLContext.currentContext
h.addLine("<ul>")
inner()
h.addLine("</ul")
}
func li(inner : () -> ()) {
let h = HTMLContext.currentContext
h.addLine("<li>")
inner()
h.addLine("</li>")
}
func a(#href: String, inner : () -> ()) {
let h = HTMLContext.currentContext
h.addLine("<a href=\"\(href)\">")
inner()
h.addLine("</a>")
}
func form(id:String="", method:String="GET", action:String="", inner : () -> ()) {
let h = HTMLContext.currentContext
h.addLine("<form id=\"\(id)\" method=\"\(method)\" action=\"\(action)\">")
inner()
h.addLine("</form>")
}
func fieldset(inner : () -> ()) {
let h = HTMLContext.currentContext
h.addLine("<fieldset>")
inner()
h.addLine("</fieldset>")
}
func label(#`for`:String, inner : () -> ()) {
let h = HTMLContext.currentContext
h.addLine("<label for=\"\(`for`)\">")
inner()
h.addLine("</label>")
}
func input(id:String="", type:String="", name:String="", value:String="") {
HTMLContext.currentContext.addLine("<input id=\"\(id)\" type=\"\(type)\" name=\"\(name)\" value=\"\(value)\">")
}
| bsd-3-clause | 7b144db4f641ae5aef0418e6adb84d9e | 19.692308 | 115 | 0.558736 | 3.826458 | false | false | false | false |
QuarkWorks/RealmModelGenerator | RealmModelGenerator/RelationshipsView.swift | 1 | 9179 | //
// RelationshipsView.swift
// RealmModelGenerator
//
// Created by Zhaolong Zhong on 4/12/16.
// Copyright © 2016 QuarkWorks. All rights reserved.
//
import Cocoa
protocol RelationshipsViewDataSource: AnyObject {
func numberOfRowsInRelationshipsView(relationshipsView:RelationshipsView) -> Int
func relationshipsView(relationshipsView:RelationshipsView, titleForRelationshipAtIndex index:Int) -> String
func relationshipsView(relationshipsView:RelationshipsView, destinationForRelationshipAtIndex index:Int) -> String
}
protocol RelationshipsViewDelegate: AnyObject {
func addRelationshipInRelationshipsView(relationshipsView:RelationshipsView)
func relationshipsView(relationshipsView:RelationshipsView, removeRelationshipAtIndex index:Int)
func relationshipsView(relationshipsView:RelationshipsView, selectedIndexDidChange index:Int?)
func relationshipsView(relationshipsView:RelationshipsView, shouldChangeRelationshipName name:String,
atIndex index:Int) -> Bool
func relationshipsView(relationshipsView:RelationshipsView, atIndex index:Int, changeDestination destinationName:String)
func relationshipsView(relationshipsView:RelationshipsView, sortByColumnName name:String, ascending:Bool)
func relationshipsView(relationshipsView:RelationshipsView, dragFromIndex:Int, dropToIndex:Int)
}
@IBDesignable
class RelationshipsView: NibDesignableView, NSTableViewDelegate, NSTableViewDataSource, TitleCellDelegate, PopupCellDelegate {
// -- MARK UNCERTAIN -- backwardsCompatibleFileURL
static let backwardsCompatibleFileURL: NSPasteboard.PasteboardType = {
if #available(OSX 10.13, *) {
return NSPasteboard.PasteboardType.fileURL
} else {
return NSPasteboard.PasteboardType(kUTTypeFileURL as String)
}
} ()
static let TAG = NSStringFromClass(RelationshipsView.self)
static let RELATIONSHIP_COLUMN = NSUserInterfaceItemIdentifier("relationship")
static let DESTINATION_COLUMN = "destination"
let ROW_TYPE = NSPasteboard.PasteboardType("rowType")
@IBOutlet weak var tableView: NSTableView!
@IBOutlet weak var addButton: NSButton!
@IBOutlet weak var removeButton: NSButton!
weak var dataSource:RelationshipsViewDataSource? {
didSet { self.reloadData() }
}
weak var delegate:RelationshipsViewDelegate?
var selectedIndex:Int? {
get {
return self.tableView.selectedRow != -1 ? self.tableView.selectedRow : nil
}
set {
if self.selectedIndex == newValue || (newValue == nil && self.tableView.selectedRow == -1) {
return
}
if let newValue = newValue {
self.tableView.selectRowIndexes(IndexSet(integer: newValue), byExtendingSelection: false)
} else {
self.tableView.deselectAll(nil)
}
}
}
var destinationNames:[String] = []
// MARK: - Lifecycle
override func nibDidLoad() {
super.nibDidLoad()
removeButton.isEnabled = false
//-- MARK UNCERTAIN -- backwardsCompatibleFileURL
tableView.registerForDraggedTypes([ROW_TYPE, RelationshipsView.backwardsCompatibleFileURL])
setUpDefaultSortDescriptor()
}
func reloadData() {
if !self.nibLoaded { return }
self.tableView.reloadData()
reloadRemoveButtonState()
}
func reloadRemoveButtonState() {
self.removeButton.isEnabled = self.selectedIndex != nil
}
func setUpDefaultSortDescriptor() {
let descriptorAttribute = NSSortDescriptor(key: RelationshipsView.RELATIONSHIP_COLUMN.rawValue, ascending: true)
let descriptorType = NSSortDescriptor(key: RelationshipsView.DESTINATION_COLUMN, ascending: true)
tableView.tableColumns[0].sortDescriptorPrototype = descriptorAttribute
tableView.tableColumns[1].sortDescriptorPrototype = descriptorType
}
// MARK: - NSTableViewDataSource
func numberOfRows(in tableView: NSTableView) -> Int {
if self.isInterfaceBuilder {
return 5
}
if let numberOfItems = self.dataSource?.numberOfRowsInRelationshipsView(relationshipsView: self) {
return numberOfItems
}
return 0
}
// MARK: - NSTableViewDelegate
func tableView(_ tableView: NSTableView, viewFor tableColumn: NSTableColumn?, row: Int) -> NSView? {
if tableColumn?.identifier == RelationshipsView.RELATIONSHIP_COLUMN {
let cell = tableView.makeView(withIdentifier: TitleCell.IDENTIFIER, owner: nil) as! TitleCell
if (self.isInterfaceBuilder) {
cell.title = "Relationship"
return cell
}
cell.delegate = self
if let title = self.dataSource?.relationshipsView(relationshipsView: self, titleForRelationshipAtIndex:row) {
cell.title = title
}
return cell
} else {
let cell = tableView.makeView(withIdentifier: PopUpCell.IDENTIFIER, owner: nil) as! PopUpCell
cell.itemTitles = destinationNames
cell.row = row
if (self.isInterfaceBuilder) {
return cell
}
cell.delegate = self
if let destination = self.dataSource?.relationshipsView(relationshipsView: self, destinationForRelationshipAtIndex: row) {
cell.selectedItemIndex = destinationNames.index(of: destination)!
}
return cell
}
}
func tableView(_ tableView: NSTableView, sortDescriptorsDidChange oldDescriptors: [NSSortDescriptor]) {
let sortDescriptor = tableView.sortDescriptors.first!
self.delegate?.relationshipsView(relationshipsView: self, sortByColumnName: sortDescriptor.key!, ascending: sortDescriptor.ascending)
}
func tableViewSelectionDidChange(_ notification: Notification) {
self.delegate?.relationshipsView(relationshipsView: self, selectedIndexDidChange: self.selectedIndex)
self.reloadRemoveButtonState()
}
// MARK: - Events
@IBAction func addRelationshipOnClick(_ sender: Any) {
self.window!.makeFirstResponder(self.tableView)
self.delegate?.addRelationshipInRelationshipsView(relationshipsView: self)
}
@IBAction func removeRelationshipOnClick(_ sender: Any) {
if let index = selectedIndex {
self.window!.makeFirstResponder(self.tableView)
self.delegate?.relationshipsView(relationshipsView: self, removeRelationshipAtIndex:index)
}
}
// MARK: - TitleCellDelegate
func titleCell(titleCell: TitleCell, shouldChangeTitle title: String) -> Bool {
let index = self.tableView.row(for: titleCell)
if index != -1 {
if let shouldChange = self.delegate?.relationshipsView(relationshipsView: self, shouldChangeRelationshipName: title, atIndex: index) {
return shouldChange
}
}
return true
}
// MARK: - PopUpCellDelegate
func popUpCell(popUpCell: PopUpCell, selectedItemDidChangeIndex index: Int) {
let cellIndex = self.tableView.row(for: popUpCell)
self.delegate?.relationshipsView(relationshipsView: self, atIndex:cellIndex, changeDestination: destinationNames[index])
}
// MARK: - Copy the row to the pasteboard
func tableView(_ tableView: NSTableView, writeRowsWith writeRowsWithIndexes: IndexSet, to toPasteboard: NSPasteboard) -> Bool {
let data = NSKeyedArchiver.archivedData(withRootObject: [writeRowsWithIndexes])
toPasteboard.declareTypes([ROW_TYPE], owner:self)
toPasteboard.setData(data, forType:ROW_TYPE)
return true
}
// MARK: - Validate the drop
func tableView(_ tableView: NSTableView, validateDrop info: NSDraggingInfo, proposedRow row: Int, proposedDropOperation dropOperation: NSTableView.DropOperation) -> NSDragOperation {
tableView.setDropRow(row, dropOperation: NSTableView.DropOperation.above)
return NSDragOperation.move
}
// MARK: - Handle the drop
func tableView(_ tableView: NSTableView, acceptDrop info: NSDraggingInfo, row: Int, dropOperation: NSTableView.DropOperation) -> Bool {
let pasteboard = info.draggingPasteboard()
let rowData = pasteboard.data(forType: ROW_TYPE)
if(rowData != nil) {
var dataArray = NSKeyedUnarchiver.unarchiveObject(with: rowData!) as! Array<NSIndexSet>,
indexSet = dataArray[0]
let movingFromIndex = indexSet.firstIndex
self.delegate?.relationshipsView(relationshipsView: self, dragFromIndex: movingFromIndex, dropToIndex: row)
return true
}
else {
return false
}
}
}
| mit | bd0e141153c2862cf4d43751cc84226d | 38.390558 | 186 | 0.666376 | 5.627223 | false | false | false | false |
RevenueCat/purchases-ios | Examples/MagicWeatherSwiftUI/Shared/Sources/Helpers/SampleData.swift | 1 | 2716 | //
// SampleData.swift
// Magic Weather SwiftUI
//
// Created by Cody Kerns on 12/16/20.
//
import SwiftUI
#if os(macOS)
typealias CompatibilityColor = NSColor
#else
import UIKit
typealias CompatibilityColor = UIColor
#endif
/*
Sample data for Magic Weather.
*/
struct SampleWeatherData {
enum TemperatureUnit: String {
case f
case c
}
enum Environment: String {
case mercury
case venus
case earth
case mars
case jupiter
case saturn
case uranus
case neptune
/*
Pluto is still a planet in my ❤️
*/
case pluto
}
var emoji: String
var temperature: String
var unit: TemperatureUnit = .f
var environment: Environment = .earth
static let testCold = SampleWeatherData.init(emoji: "❄️", temperature: "14")
static let testHot = SampleWeatherData.init(emoji: "☀️", temperature: "85")
static func generateSampleData(for environment: SampleWeatherData.Environment, temperature: Int? = nil) -> SampleWeatherData {
let temperature = temperature ?? Int.random(in: -20...120)
var emoji: String
switch temperature {
case 0...32:
emoji = "❄️"
case 33...60:
emoji = "☁️"
case 61...90:
emoji = "🌤"
case 91...120:
emoji = "🥵"
default:
if temperature < 0 {
emoji = "🥶"
} else {
emoji = "☄️"
}
}
return .init(emoji: emoji, temperature: "\(temperature)", unit: .f, environment: environment)
}
}
extension SampleWeatherData {
var weatherColor: CompatibilityColor? {
switch self.emoji {
case "🥶":
return #colorLiteral(red: 0.012122632, green: 0.2950853705, blue: 0.5183202624, alpha: 1)
case "❄️":
return #colorLiteral(red: 0, green: 0.1543088555, blue: 0.3799687922, alpha: 1)
case "☁️":
return #colorLiteral(red: 0.2000069618, green: 1.306866852e-05, blue: 0.2313408554, alpha: 1)
case "🌤":
return #colorLiteral(red: 0.8323764622, green: 0.277771439, blue: 0.2446353115, alpha: 1)
case "🥵":
return #colorLiteral(red: 0.7131021281, green: 1.25857805e-05, blue: 0.2313565314, alpha: 1)
case "☄️":
return #colorLiteral(red: 0.8000227213, green: 1.210316441e-05, blue: 0.2313722372, alpha: 1)
default:
return #colorLiteral(red: 0.8000227213, green: 1.210316441e-05, blue: 0.2313722372, alpha: 1)
}
}
}
| mit | 20ce3c1d7792df0e50aefaf7a36e73b2 | 26.729167 | 130 | 0.562735 | 3.96131 | false | false | false | false |
mgadda/zig | Sources/zig/CommitView.swift | 1 | 1085 | //
// CommitView.swift
// zig
//
// Created by Matt Gadda on 9/16/17.
// Copyright © 2017 Matt Gadda. All rights reserved.
//
import Foundation
class CommitView : Sequence {
let repository: Repository
init(repository: Repository) {
self.repository = repository
}
func makeIterator() -> CommitIterator {
if case let .commit(headId)? = repository.resolve(.head) {
return CommitIterator(headId.base16DecodedData(), repository: repository)
} else {
print("No commits yet")
return CommitIterator(nil, repository: repository)
}
}
}
struct CommitIterator : IteratorProtocol {
var maybeNextObjectId: Data?
let repository: Repository
init(_ objectId: Data?, repository: Repository) {
self.maybeNextObjectId = objectId
self.repository = repository
}
mutating func next() -> Commit? {
guard
let nextObjectId = maybeNextObjectId,
let commit = repository.readObject(id: nextObjectId, type: Commit.self) else {
return nil
}
maybeNextObjectId = commit.parentId
return commit
}
}
| mit | 02d321a876b1e4bf25980e060f98adaa | 22.06383 | 84 | 0.678044 | 4.185328 | false | false | false | false |
rain2540/Play-with-Algorithms-in-Swift | Basic/01-Sort/01.01-Bucket Sort/Bucket Sort/Bucket Sort/BucketSorter.swift | 1 | 2407 | //
// BucketSorter.swift
// Bucket Sort
//
// Created by RAIN on 16/7/31.
// Copyright © 2016-2017 Smartech. All rights reserved.
//
import Foundation
struct BucketSorter {
/// 为整型数组排序
///
/// - Parameter nums: 未经排序的整型数组
/// - Returns: 完成排序的整型数组
static func sort(nums: [Int]) -> [Int] {
// 整型数组最大值
let maxOfNums = ModelHelper.maxOf(nums)
// 以整型数组最大值和最小值为边界 公差为1的等差数列构成数组的元素个数
let countOfNums = ModelHelper.countOf(nums)
// 取整型数组最大值与新数组个数中的最大的 加1 作为"桶"数组元素个数
let count = max(maxOfNums, countOfNums) + 1
// 记录排序结果的数组
var results = [Int]()
// "桶"数组
var buckets = [Int](repeating: 0, count: count)
// 整型数组元素放入"桶"数组对应位置
for i in 0 ..< nums.count {
if maxOfNums < countOfNums {
// 以整型数组第 i 个元素的值与其最小值的差 作为"桶"数组的索引t
let t = nums[i] - ModelHelper.minOf(nums)
print(i, nums[i])
// "桶"数组第t个元素值加1
buckets[t] += 1
} else {
// 以整型数组第 i 个元素的值 作为"桶"数组的索引t
let t = nums[i]
print(i, t)
// "桶"数组第t个元素值加1
buckets[t] += 1
}
}
// 将"桶"数组元素 依次放入结果数组
for i in 0 ..< buckets.count {
// "桶"数组元素值 为结果数组中 某个值出现的次数
for _ in 0 ..< buckets[i] {
if maxOfNums < countOfNums {
// i 与整型数组最小值的和 作为结果数组元素
let result = i + ModelHelper.minOf(nums)
print(result)
// 结果数组添加元素
results.append(result)
} else {
print(i)
// i 作为结果数组元素 添加进结果数组
results.append(i)
}
}
}
// print("buckets: \n", buckets)
return results
}
}
| mit | 071b708eebf4d48286365ee53f9de279 | 27.636364 | 60 | 0.460847 | 3.648649 | false | false | false | false |
exevil/Keys-For-Sketch | Source/Controller/Outline View/Cell/ItemTableCellView.swift | 1 | 2451 | //
// KeyItemTableCellView.swift
// KeysForSketch
//
// Created by Vyacheslav Dubovitsky on 12/02/2017.
// Copyright © 2017 Vyacheslav Dubovitsky. All rights reserved.
//
class ItemTableCellView: NSTableCellView {
@IBOutlet weak var shortcutView: ShortcutView!
@IBOutlet weak var titleLabel: NSTextField!
@IBOutlet weak var menuButton: NSButton!
// MARK: Init
// Should be assigned during cell initialization process
internal var menuItem: NSMenuItem! {
didSet {
shortcutView.menuItem = menuItem
titleLabel.stringValue = menuItem.title
// Hide shortcut view if now shortcut needed
shortcutView.isHidden = !menuItem.needsShortcut
// Hide menu button if there's no custom shortcut to manage
menuButton.isHidden = !menuItem.hasCustomShortcut
}
}
required init?(coder: NSCoder) {
super.init(coder: coder)
// Draw fake separator
self.layer = {
let layer = CALayer()
let separatorLayer = CAShapeLayer()
separatorLayer.frame = CGRect(x: 0, y: 0, width: self.bounds.width, height: Const.Cell.dividerHeight)
separatorLayer.backgroundColor = NSColor(calibratedRed: 217/255, green: 217/255, blue: 217/255, alpha: 1).cgColor
layer.addSublayer(separatorLayer)
return layer
}()
}
// MARK: Actions
/// Popup context menu on button press.
@IBAction func contextualMenuButtonAction(_ sender: NSButton) {
let contextualMenu = ItemCellContextualMenu(menuItem: menuItem)
contextualMenu.popUp(positioning: nil, at: NSPoint(x: sender.frame.minX, y: sender.frame.minY), in: self)
}
// MARK: Other
/// Blink animation.
func blink(with color: NSColor, forDuration duration: Float) {
let transparentColor = NSColor(calibratedWhite: 1.0, alpha: 0.0).cgColor
let animation = CAKeyframeAnimation(keyPath: "backgroundColor")
animation.values = [color.cgColor, transparentColor]
animation.keyTimes = [0.1, 1.0]
animation.timingFunctions = [
CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseOut),
CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseIn)
]
animation.duration = CFTimeInterval(duration)
layer?.add(animation, forKey: "animation")
}
}
| mit | acf4a426c301f8805a2cc1422c06d7f0 | 35.567164 | 125 | 0.646531 | 4.89022 | false | false | false | false |
abertelrud/swift-package-manager | Sources/PackageGraph/DependencyResolver.swift | 2 | 5541 | //===----------------------------------------------------------------------===//
//
// This source file is part of the Swift 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 http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
import Basics
import Dispatch
import PackageModel
import TSCBasic
public protocol DependencyResolver {
typealias Binding = (package: PackageReference, binding: BoundVersion, products: ProductFilter)
typealias Delegate = DependencyResolverDelegate
}
public enum DependencyResolverError: Error, Equatable {
/// A revision-based dependency contains a local package dependency.
case revisionDependencyContainsLocalPackage(dependency: String, localPackage: String)
}
extension DependencyResolverError: CustomStringConvertible {
public var description: String {
switch self {
case .revisionDependencyContainsLocalPackage(let dependency, let localPackage):
return "package '\(dependency)' is required using a revision-based requirement and it depends on local package '\(localPackage)', which is not supported"
}
}
}
public protocol DependencyResolverDelegate {
func willResolve(term: Term)
func didResolve(term: Term, version: Version, duration: DispatchTimeInterval)
func derived(term: Term)
func conflict(conflict: Incompatibility)
func satisfied(term: Term, by assignment: Assignment, incompatibility: Incompatibility)
func partiallySatisfied(term: Term, by assignment: Assignment, incompatibility: Incompatibility, difference: Term)
func failedToResolve(incompatibility: Incompatibility)
func solved(result: [DependencyResolver.Binding])
}
public struct ObservabilityDependencyResolverDelegate: DependencyResolverDelegate {
private let observabilityScope: ObservabilityScope
public init (observabilityScope: ObservabilityScope) {
self.observabilityScope = observabilityScope.makeChildScope(description: "DependencyResolver")
}
public func willResolve(term: Term) {
self.debug("resolving '\(term.node.package.identity)'")
}
public func didResolve(term: Term, version: Version, duration: DispatchTimeInterval) {
self.debug("resolved '\(term.node.package.identity)' @ '\(version)'")
}
public func derived(term: Term) {
self.debug("derived '\(term.node.package.identity)' requirement '\(term.requirement)'")
}
public func conflict(conflict: Incompatibility) {
self.debug("conflict: \(conflict)")
}
public func failedToResolve(incompatibility: Incompatibility) {
self.debug("failed to resolve '\(incompatibility)'")
}
public func satisfied(term: Term, by assignment: Assignment, incompatibility: Incompatibility) {
self.debug("'\(term)' is satisfied by '\(assignment)', which is caused by '\(assignment.cause?.description ?? "unknown cause")'. new incompatibility: '\(incompatibility)'")
}
public func partiallySatisfied(term: Term, by assignment: Assignment, incompatibility: Incompatibility, difference: Term) {
self.debug("\(term) is partially satisfied by '\(assignment)', which is caused by '\(assignment.cause?.description ?? "unknown cause")'. new incompatibility \(incompatibility)")
}
public func solved(result: [DependencyResolver.Binding]) {
for (package, binding, _) in result {
self.debug("solved '\(package.identity)' (\(package.locationString)) at '\(binding)'")
}
self.debug("dependency resolution complete!")
}
private func debug(_ message: String) {
self.observabilityScope.emit(debug: "[DependencyResolver] \(message)")
}
}
public struct MultiplexResolverDelegate: DependencyResolverDelegate {
private let underlying: [DependencyResolverDelegate]
public init (_ underlying: [DependencyResolverDelegate]) {
self.underlying = underlying
}
public func willResolve(term: Term) {
underlying.forEach { $0.willResolve(term: term) }
}
public func didResolve(term: Term, version: Version, duration: DispatchTimeInterval) {
underlying.forEach { $0.didResolve(term: term, version: version, duration: duration) }
}
public func derived(term: Term) {
underlying.forEach { $0.derived(term: term) }
}
public func conflict(conflict: Incompatibility) {
underlying.forEach { $0.conflict(conflict: conflict) }
}
public func satisfied(term: Term, by assignment: Assignment, incompatibility: Incompatibility) {
underlying.forEach { $0.satisfied(term: term, by: assignment, incompatibility: incompatibility) }
}
public func partiallySatisfied(term: Term, by assignment: Assignment, incompatibility: Incompatibility, difference: Term) {
underlying.forEach { $0.partiallySatisfied(term: term, by: assignment, incompatibility: incompatibility, difference: difference) }
}
public func failedToResolve(incompatibility: Incompatibility) {
underlying.forEach { $0.failedToResolve(incompatibility: incompatibility) }
}
public func solved(result: [(package: PackageReference, binding: BoundVersion, products: ProductFilter)]) {
underlying.forEach { $0.solved(result: result) }
}
}
| apache-2.0 | f5ad5c9f7a373470f7e4c285706978b6 | 40.044444 | 185 | 0.699152 | 5.046448 | false | false | false | false |
tjw/swift | tools/SwiftSyntax/DiagnosticConsumer.swift | 5 | 1019 | //===---------- DiagnosticConsumer.swift - Diagnostic Consumer ------------===//
//
// 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
//
//===----------------------------------------------------------------------===//
// This file provides the DiagnosticConsumer protocol.
//===----------------------------------------------------------------------===//
/// An object that intends to receive notifications when diagnostics are
/// emitted.
public protocol DiagnosticConsumer {
/// Handle the provided diagnostic which has just been registered with the
/// DiagnosticEngine.
func handle(_ diagnostic: Diagnostic)
/// Finalize the consumption of diagnostics, flushing to disk if necessary.
func finalize()
}
| apache-2.0 | 12a04b9ff70ce6021c04b14cf64794bc | 41.458333 | 80 | 0.61629 | 5.568306 | false | false | false | false |
tjw/swift | test/attr/attr_autoclosure.swift | 1 | 6332 | // RUN: %target-typecheck-verify-swift
// Simple case.
var fn : @autoclosure () -> Int = 4 // expected-error {{@autoclosure may only be used on parameters}} expected-error {{cannot convert value of type 'Int' to specified type '() -> Int'}}
@autoclosure func func1() {} // expected-error {{attribute can only be applied to types, not declarations}}
func func1a(_ v1 : @autoclosure Int) {} // expected-error {{@autoclosure attribute only applies to function types}}
func func2(_ fp : @autoclosure () -> Int) { func2(4)}
func func3(fp fpx : @autoclosure () -> Int) {func3(fp: 0)}
func func4(fp : @autoclosure () -> Int) {func4(fp: 0)}
func func6(_: @autoclosure () -> Int) {func6(0)}
// autoclosure + inout doesn't make sense.
func func8(_ x: inout @autoclosure () -> Bool) -> Bool { // expected-error {{@autoclosure may only be used on parameters}}
}
func func9(_ x: @autoclosure (Int) -> Bool) {} // expected-error {{argument type of @autoclosure parameter must be '()'}}
func func10(_ x: @autoclosure (Int, String, Int) -> Void) {} // expected-error {{argument type of @autoclosure parameter must be '()'}}
// <rdar://problem/19707366> QoI: @autoclosure declaration change fixit
let migrate4 : (@autoclosure() -> ()) -> ()
struct SomeStruct {
@autoclosure let property : () -> Int // expected-error {{attribute can only be applied to types, not declarations}}
init() {
}
}
class BaseClass {
@autoclosure var property : () -> Int // expected-error {{attribute can only be applied to types, not declarations}}
init() {}
}
class DerivedClass {
var property : () -> Int { get {} set {} }
}
protocol P1 {
associatedtype Element
}
protocol P2 : P1 {
associatedtype Element
}
func overloadedEach<O: P1>(_ source: O, _ closure: @escaping () -> ()) {
}
func overloadedEach<P: P2>(_ source: P, _ closure: @escaping () -> ()) {
}
struct S : P2 {
typealias Element = Int
func each(_ closure: @autoclosure () -> ()) {
// expected-note@-1{{parameter 'closure' is implicitly non-escaping}}
overloadedEach(self, closure) // expected-error {{passing non-escaping parameter 'closure' to function expecting an @escaping closure}}
}
}
struct AutoclosureEscapeTest {
@autoclosure let delayed: () -> Int // expected-error {{attribute can only be applied to types, not declarations}}
}
// @autoclosure(escaping)
// expected-error @+1 {{attribute can only be applied to types, not declarations}}
func func10(@autoclosure(escaping _: () -> ()) { } // expected-error{{expected parameter name followed by ':'}}
func func11(_: @autoclosure(escaping) @noescape () -> ()) { } // expected-error{{@escaping conflicts with @noescape}}
// expected-warning@-1{{@autoclosure(escaping) is deprecated; use @autoclosure @escaping instead}} {{28-38= @escaping}}
class Super {
func f1(_ x: @autoclosure(escaping) () -> ()) { }
// expected-warning@-1{{@autoclosure(escaping) is deprecated; use @autoclosure @escaping instead}} {{28-38= @escaping}}
func f2(_ x: @autoclosure(escaping) () -> ()) { } // expected-note {{potential overridden instance method 'f2' here}}
// expected-warning@-1{{@autoclosure(escaping) is deprecated; use @autoclosure @escaping instead}} {{28-38= @escaping}}
func f3(x: @autoclosure () -> ()) { }
}
class Sub : Super {
override func f1(_ x: @autoclosure(escaping)() -> ()) { }
// expected-warning@-1{{@autoclosure(escaping) is deprecated; use @autoclosure @escaping instead}} {{37-47= @escaping }}
override func f2(_ x: @autoclosure () -> ()) { } // expected-error{{does not override any method}} // expected-note{{type does not match superclass instance method with type '(@autoclosure @escaping () -> ()) -> ()'}}
override func f3(_ x: @autoclosure(escaping) () -> ()) { } // expected-error{{does not override any method}}
// expected-warning@-1{{@autoclosure(escaping) is deprecated; use @autoclosure @escaping instead}} {{37-47= @escaping}}
}
func func12_sink(_ x: @escaping () -> Int) { }
func func12a(_ x: @autoclosure () -> Int) {
// expected-note@-1{{parameter 'x' is implicitly non-escaping}}
func12_sink(x) // expected-error {{passing non-escaping parameter 'x' to function expecting an @escaping closure}}
}
func func12b(_ x: @autoclosure(escaping) () -> Int) {
// expected-warning@-1{{@autoclosure(escaping) is deprecated; use @autoclosure @escaping instead}} {{31-41= @escaping}}
func12_sink(x) // ok
}
func func12c(_ x: @autoclosure @escaping () -> Int) {
func12_sink(x) // ok
}
func func12d(_ x: @escaping @autoclosure () -> Int) {
func12_sink(x) // ok
}
class TestFunc12 {
var x: Int = 5
func foo() -> Int { return 0 }
func test() {
func12a(x + foo()) // okay
func12b(x + foo())
// expected-error@-1{{reference to property 'x' in closure requires explicit 'self.' to make capture semantics explicit}} {{13-13=self.}}
// expected-error@-2{{call to method 'foo' in closure requires explicit 'self.' to make capture semantics explicit}} {{17-17=self.}}
}
}
enum AutoclosureFailableOf<T> {
case Success(@autoclosure () -> T)
case Failure()
}
let _ : AutoclosureFailableOf<Int> = .Success(42)
let _ : (@autoclosure () -> ()) -> ()
let _ : (@autoclosure(escaping) () -> ()) -> ()
// expected-warning@-1{{@autoclosure(escaping) is deprecated; use @autoclosure @escaping instead}} {{22-32= @escaping}}
// escaping is the name of param type
let _ : (@autoclosure(escaping) -> ()) -> () // expected-error {{use of undeclared type 'escaping'}}
// expected-error@-1 {{argument type of @autoclosure parameter must be '()'}}
// Migration
// expected-error @+1 {{attribute can only be applied to types, not declarations}}
func migrateAC(@autoclosure _: () -> ()) { }
// expected-error @+1 {{attribute can only be applied to types, not declarations}}
func migrateACE(@autoclosure(escaping) _: () -> ()) { }
func takesAutoclosure(_ fn: @autoclosure () -> Int) {}
func callAutoclosureWithNoEscape(_ fn: () -> Int) {
takesAutoclosure(1+1) // ok
}
func callAutoclosureWithNoEscape_2(_ fn: () -> Int) {
takesAutoclosure(fn()) // ok
}
func callAutoclosureWithNoEscape_3(_ fn: @autoclosure () -> Int) {
takesAutoclosure(fn()) // ok
}
// expected-error @+1 {{@autoclosure must not be used on variadic parameters}}
func variadicAutoclosure(_ fn: @autoclosure () -> ()...) {
for _ in fn {}
}
| apache-2.0 | f61c28662540954ce60bdf6219f7eb34 | 37.846626 | 219 | 0.657296 | 3.748964 | false | false | false | false |
alexito4/Baggins | Sources/Baggins/_Brewing.swift | 1 | 3914 | import Foundation
// This file contains candidates to be added to Baggins.
// Exploration to see if a Zip style API is actually more understandable than spread async lets.
/// Still brewing... 🧙♂️
public func asyncZip<Left, Right, Return>(
_ left: () async throws -> Left,
_ right: () async throws -> Right,
combined: (Left, Right) async throws -> Return
) async throws -> Return {
async let leftResult = left()
async let rightResult = right()
return try await combined(leftResult, rightResult)
}
/// Still brewing... 🧙♂️
/// Needs a math library.
public func ilerp<T: FloatingPoint>(_ t: T, min: T, max: T) -> T {
(t - min) / (max - min)
}
public extension String {
/// Still brewing... 🧙♂️
func stringByAddingPercentEncodingForRFC3986() -> String? {
let unreserved = "-._~/?"
let allowedCharacterSet = NSMutableCharacterSet.alphanumeric()
allowedCharacterSet.addCharacters(in: unreserved)
return addingPercentEncoding(withAllowedCharacters: allowedCharacterSet as CharacterSet)
}
}
// MARK: Optional
/// Inspired by Rust Option type
extension Optional {
/// Still brewing... 🧙♂️
var isNone: Bool {
self == nil
}
/// Still brewing... 🧙♂️
var isSome: Bool {
self != nil
}
}
extension Optional {
/// Still brewing... 🧙♂️
/// Rust `pub fn expect(self, msg: &str) -> T`
/// Now we have UnwrapOrThrow library, but I don't really use this so it stayed here.
func unwrap(orDie message: String) -> Wrapped {
if let value = self {
return value
} else {
fatalError(message)
}
}
/// Still brewing... 🧙♂️
/// Swift's `??` operator
/// Rust `pub fn unwrap_or(self, def: T) -> T`
/// Now we have UnwrapOrThrow library, but I don't really use this so it stayed here.
func unwrap(or default: Wrapped) -> Wrapped {
if let value = self {
return value
} else {
return `default`
}
}
/// Still brewing... 🧙♂️
/// Swift's `??` operator
/// Rust `pub fn unwrap_or_else<F>(self, f: F) -> T`
/// Now we have UnwrapOrThrow library, but I don't really use this so it stayed here.
func unwrap(orElse closure: @autoclosure () -> Wrapped) -> Wrapped {
if let value = self {
return value
} else {
return closure()
}
}
/// Still brewing... 🧙♂️
/// Swift's `??` operator
/// Rust `pub fn unwrap_or_else<F>(self, f: F) -> T`
/// Now we have UnwrapOrThrow library, but I don't really use this so it stayed here.
func unwrap(orElse closure: () -> Wrapped) -> Wrapped {
if let value = self {
return value
} else {
return closure()
}
}
}
/// Still brewing... 🧙♂️
// continue with pub fn ok_or<E>(self, err: E) -> Result<T, E> but that will need to conditionally compile only if Result is available, but probably the Result library already has similar functionality?
/// Still brewing... 🧙♂️
// This is not part of the UnwrapOrThrow package because I ended up never using it.
// public extension Optional {
// struct UnwrappingError: Error {
// public let text: String
// }
// }
//
// infix operator -?!: AdditionPrecedence
// public extension Optional {
// static func -?! (lhs: Optional<Wrapped>, rhs: String) throws -> Wrapped {
// switch lhs {
// case .some(let value):
// return value
// case .none:
// throw UnwrappingError(text: rhs)
// }
// }
// }
//
// postfix operator -?!
// public extension Optional {
// static postfix func -?! (lhs: Optional<Wrapped>) throws -> Wrapped {
// return try lhs -?! "Error unwrapping optional"
// }
// }
| mit | e51c1ff12765f27c7da03fbb337095e0 | 29.277778 | 202 | 0.586894 | 4.206174 | false | false | false | false |
vnu/vTweetz | vTweetz/TimelineController.swift | 1 | 6334 | //
// TimelineController.swift
// vTweetz
//
// Created by Vinu Charanya on 2/27/16.
// Copyright © 2016 vnu. All rights reserved.
//
import UIKit
class TimelineController: UIViewController {
var tweetsTableView: TweetzTableView!
override func viewDidLoad() {
super.viewDidLoad()
commonInit()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
func commonInit(){
if let tweetsTblView = NSBundle.mainBundle().loadNibNamed("TweetzTableView", owner: self, options: nil).first as? TweetzTableView {
tweetsTableView = tweetsTblView
tweetsTableView.initView("mentions_timeline.json")
tweetsTableView.translatesAutoresizingMaskIntoConstraints = false
self.view.addSubview(tweetsTableView)
setConstraints()
tweetsTableView.fetchTweets()
}
}
func setConstraints(){
let views = ["superView": self.view, "tableView": self.tweetsTableView]
let horizontalConstraints = NSLayoutConstraint.constraintsWithVisualFormat("H:|-0-[tableView]-0-|", options: NSLayoutFormatOptions.AlignAllCenterY, metrics: nil, views: views)
view.addConstraints(horizontalConstraints)
let verticalConstraints = NSLayoutConstraint.constraintsWithVisualFormat("V:|-0-[tableView]-0-|", options: NSLayoutFormatOptions.AlignAllCenterX, metrics: nil, views: views)
view.addConstraints(verticalConstraints)
}
}
/*
@IBOutlet weak var tweetsTableView: UITableView!
var isMoreDataLoading = false
var reachedAPILimit = false
let tweetCellId = "com.vnu.tweetcell"
let tweetStatus = "home_timeline.json"
let detailSegueId = "com.vnu.tweetDetail"
let refreshControl = UIRefreshControl()
let replySegueId = "com.vnu.ReplySegue"
let homeComposeSegue = "HomeComposeSegue"
private var tweets = [Tweet]()
override func viewDidLoad() {
super.viewDidLoad()
let cellNib = UINib(nibName: "TweetCell", bundle: NSBundle.mainBundle())
tweetsTableView.registerNib(cellNib, forCellReuseIdentifier: tweetCellId)
tweetsTableView.estimatedRowHeight = 200
tweetsTableView.rowHeight = UITableViewAutomaticDimension
setTweetyNavBar() ---------> Not done yet
fetchTweets()
refreshControl.addTarget(self, action: "refreshControlAction:", forControlEvents: UIControlEvents.ValueChanged)
tweetsTableView.insertSubview(refreshControl, atIndex: 0)
}
//Done
//Fetch Tweets
func fetchTweets(){
TwitterAPI.sharedInstance.fetchTweets(tweetStatus, completion: onFetchCompletion)
}
func onFetchCompletion(tweets: [Tweet]?, error: NSError?){
if tweets != nil{
self.tweets = tweets!
tweetsTableView.reloadData()
}else{
print("ERROR OCCURED: \(error?.description)")
}
if refreshControl.refreshing{
refreshControl.endRefreshing()
}
func refreshControlAction(refreshControl: UIRefreshControl) {
self.fetchTweets()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
//Not done
func setTweetyNavBar(){
let logo = UIImage(named: "Twitter_logo_blue_32")
let imageView = UIImageView(image:logo)
self.navigationItem.titleView = imageView
}
@IBAction func onLogout(sender: UIBarButtonItem) {
User.currentUser?.logout()
}
}
//Segue into Detail View
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if segue.identifier == detailSegueId {
if let destination = segue.destinationViewController as? TweetViewController {
if let cell = sender as? TweetCell{
let indexPath = self.tweetsTableView!.indexPathForCell(cell)
let index = indexPath!.row
destination.tweet = tweets[index]
}
destination.hidesBottomBarWhenPushed = true
}
}else if(segue.identifier == replySegueId){
if let destination = segue.destinationViewController as? ComposeViewController {
let cell = sender as! TweetCell
destination.fromTweet = cell.tweet
destination.delegate = self
destination.toScreenNames = ["@\(cell.tweet.user!.screenName!)"]
destination.hidesBottomBarWhenPushed = true
}
}else if(segue.identifier == homeComposeSegue){
if let destination = segue.destinationViewController as? ComposeViewController {
destination.delegate = self
destination.hidesBottomBarWhenPushed = true
}
}
}
func loadMoreTweets(){
if tweets.count > 0{
let maxTweetId = tweets.last?.tweetId!
TwitterAPI.sharedInstance.loadMoreTweets(tweetStatus, maxId: maxTweetId!) { (tweets, error) -> Void in
if tweets != nil{
self.tweets = self.tweets + tweets!
self.tweetsTableView.reloadData()
if(self.isMoreDataLoading){
self.isMoreDataLoading = false
}
}else{
print("ERROR OCCURED: \(error?.description)")
}
}
}
}
}
extension HomeViewController:UIScrollViewDelegate{
func scrollViewDidScroll(scrollView: UIScrollView) {
if (!isMoreDataLoading) {
// Calculate the position of one screen length before the bottom of the results
let scrollViewContentHeight = tweetsTableView.contentSize.height
let scrollOffsetThreshold = scrollViewContentHeight - (tweetsTableView.bounds.size.height)
// When the user has scrolled past the threshold, start requesting
if(scrollView.contentOffset.y > scrollOffsetThreshold && tweetsTableView.dragging && !reachedAPILimit) {
isMoreDataLoading = true
loadMoreTweets()
}
}
}
}
extension HomeViewController: ComposeViewControllerDelegate{
func composeViewController(composeViewController: ComposeViewController, onCreateTweet value: Tweet) {
tweets.insert(value, atIndex: 0)
tweetsTableView.reloadData()
}
}
extension HomeViewController:UITableViewDelegate, UITableViewDataSource, TweetCellDelegate{
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier(tweetCellId) as! TweetCell
cell.tweet = tweets[indexPath.row]
cell.delegate = self
return cell
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return tweets.count
}
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
let selectedCell = tableView.cellForRowAtIndexPath(indexPath) as!TweetCell
self.performSegueWithIdentifier(detailSegueId, sender: selectedCell)
tableView.deselectRowAtIndexPath(indexPath, animated: true)
}
func tweetCell(tweetCell: TweetCell, onTweetReply value: Tweet) {
print ("On reply delegate")
self.performSegueWithIdentifier(replySegueId, sender: tweetCell)
}
}
*/
| apache-2.0 | 0571b683df1de69cc3081ba57c99a132 | 28.184332 | 183 | 0.774041 | 4.602471 | false | false | false | false |
cheeyi/ProjectSora | Pods/ZLSwipeableViewSwift/ZLSwipeableViewSwift/ZLSwipeableView.swift | 1 | 25462 | //
// ZLSwipeableView.swift
// ZLSwipeableViewSwiftDemo
//
// Created by Zhixuan Lai on 4/27/15.
// Copyright (c) 2015 Zhixuan Lai. All rights reserved.
//
import UIKit
// MARK: - Helper classes
public typealias ZLSwipeableViewDirection = Direction
public func ==(lhs: Direction, rhs: Direction) -> Bool {
return lhs.rawValue == rhs.rawValue
}
/**
* Swiped direction.
*/
public struct Direction : OptionSetType, CustomStringConvertible {
public var rawValue: UInt
public init(rawValue: UInt) {
self.rawValue = rawValue
}
public static let None = Direction(rawValue: 0b0000)
public static let Left = Direction(rawValue: 0b0001)
public static let Right = Direction(rawValue: 0b0010)
public static let Up = Direction(rawValue: 0b0100)
public static let Down = Direction(rawValue: 0b1000)
public static let Horizontal: Direction = [Left, Right]
public static let Vertical: Direction = [Up, Down]
public static let All: Direction = [Horizontal, Vertical]
public static func fromPoint(point: CGPoint) -> Direction {
switch (point.x, point.y) {
case let (x, y) where abs(x) >= abs(y) && x > 0:
return .Right
case let (x, y) where abs(x) >= abs(y) && x < 0:
return .Left
case let (x, y) where abs(x) < abs(y) && y < 0:
return .Up
case let (x, y) where abs(x) < abs(y) && y > 0:
return .Down
case (_, _):
return .None
}
}
public var description: String {
switch self {
case Direction.None:
return "None"
case Direction.Left:
return "Left"
case Direction.Right:
return "Right"
case Direction.Up:
return "Up"
case Direction.Down:
return "Down"
case Direction.Horizontal:
return "Horizontal"
case Direction.Vertical:
return "Vertical"
case Direction.All:
return "All"
default:
return "Unknown"
}
}
}
// data source
public typealias NextViewHandler = () -> UIView?
public typealias PreviousViewHandler = () -> UIView?
// customization
public typealias AnimateViewHandler = (view: UIView, index: Int, views: [UIView], swipeableView: ZLSwipeableView) -> ()
public typealias InterpretDirectionHandler = (topView: UIView, direction: Direction, views: [UIView], swipeableView: ZLSwipeableView) -> (CGPoint, CGVector)
public typealias ShouldSwipeHandler = (view: UIView, movement: Movement, swipeableView: ZLSwipeableView) -> Bool
// delegates
public typealias DidStartHandler = (view: UIView, atLocation: CGPoint) -> ()
public typealias SwipingHandler = (view: UIView, atLocation: CGPoint, translation: CGPoint) -> ()
public typealias DidEndHandler = (view: UIView, atLocation: CGPoint) -> ()
public typealias DidSwipeHandler = (view: UIView, inDirection: Direction, directionVector: CGVector) -> ()
public typealias DidCancelHandler = (view: UIView) -> ()
public struct Movement {
let location: CGPoint
let translation: CGPoint
let velocity: CGPoint
}
// MARK: - Main
public class ZLSwipeableView: UIView {
// MARK: Data Source
public var numberOfActiveView = UInt(4)
public var nextView: NextViewHandler? {
didSet {
loadViews()
}
}
public var previousView: PreviousViewHandler?
// Rewinding
public var history = [UIView]()
public var numberOfHistoryItem = UInt(10)
// MARK: Customizable behavior
public var animateView = ZLSwipeableView.defaultAnimateViewHandler()
public var interpretDirection = ZLSwipeableView.defaultInterpretDirectionHandler()
public var shouldSwipeView = ZLSwipeableView.defaultShouldSwipeViewHandler()
public var minTranslationInPercent = CGFloat(0.25)
public var minVelocityInPointPerSecond = CGFloat(750)
public var allowedDirection = Direction.Horizontal
// MARK: Delegate
public var didStart: DidStartHandler?
public var swiping: SwipingHandler?
public var didEnd: DidEndHandler?
public var didSwipe: DidSwipeHandler?
public var didCancel: DidCancelHandler?
// MARK: Private properties
/// Contains subviews added by the user.
private var containerView = UIView()
/// Contains auxiliary subviews.
private var miscContainerView = UIView()
private var animator: UIDynamicAnimator!
private var viewManagers = [UIView: ViewManager]()
private var scheduler = Scheduler()
// MARK: Life cycle
override init(frame: CGRect) {
super.init(frame: frame)
setup()
}
required public init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
setup()
}
private func setup() {
addSubview(containerView)
addSubview(miscContainerView)
animator = UIDynamicAnimator(referenceView: self)
}
deinit {
nextView = nil
didStart = nil
swiping = nil
didEnd = nil
didSwipe = nil
didCancel = nil
}
override public func layoutSubviews() {
super.layoutSubviews()
containerView.frame = bounds
}
// MARK: Public APIs
public func topView() -> UIView? {
return activeViews().first
}
// top view first
public func activeViews() -> [UIView] {
return allViews().filter() {
view in
guard let viewManager = viewManagers[view] else { return false }
if case .Swiping(_) = viewManager.state {
return false
}
return true
}.reverse()
}
public func loadViews() {
for var i = UInt(activeViews().count); i < numberOfActiveView; i++ {
if let nextView = nextView?() {
insert(nextView, atIndex: 0)
}
}
updateViews()
}
public func rewind() {
var viewToBeRewinded: UIView?
if let lastSwipedView = history.popLast() {
viewToBeRewinded = lastSwipedView
} else if let view = previousView?() {
viewToBeRewinded = view
}
guard let view = viewToBeRewinded else { return }
insert(view, atIndex: allViews().count)
updateViews()
}
public func discardViews() {
for view in allViews() {
remove(view)
}
}
public func swipeTopView(inDirection direction: Direction) {
guard let topView = topView() else { return }
let (location, directionVector) = interpretDirection(topView: topView, direction: direction, views: activeViews(), swipeableView: self)
swipeTopView(fromPoint: location, inDirection: directionVector)
}
public func swipeTopView(fromPoint location: CGPoint, inDirection directionVector: CGVector) {
guard let topView = topView(), topViewManager = viewManagers[topView] else { return }
topViewManager.state = .Swiping(location, directionVector)
swipeView(topView, location: location, directionVector: directionVector)
}
// MARK: Private APIs
private func allViews() -> [UIView] {
return containerView.subviews
}
private func insert(view: UIView, atIndex index: Int) {
guard !allViews().contains(view) else {
// this view has been schedule to be removed
guard let viewManager = viewManagers[view] else { return }
viewManager.state = viewManager.snappingStateAtContainerCenter()
return
}
let viewManager = ViewManager(view: view, containerView: containerView, index: index, miscContainerView: miscContainerView, animator: animator, swipeableView: self)
viewManagers[view] = viewManager
}
private func remove(view: UIView) {
guard allViews().contains(view) else { return }
viewManagers.removeValueForKey(view)
}
public func updateViews() {
let activeViews = self.activeViews()
let inactiveViews = allViews().arrayByRemoveObjectsInArray(activeViews)
for view in inactiveViews {
view.userInteractionEnabled = false
}
guard let gestureRecognizers = activeViews.first?.gestureRecognizers where gestureRecognizers.filter({ gestureRecognizer in gestureRecognizer.state != .Possible }).count == 0 else { return }
for i in 0 ..< activeViews.count {
let view = activeViews[i]
view.userInteractionEnabled = true
let shouldBeHidden = i >= Int(numberOfActiveView)
view.hidden = shouldBeHidden
guard !shouldBeHidden else { continue }
animateView(view: view, index: i, views: activeViews, swipeableView: self)
}
}
private func swipeView(view: UIView, location: CGPoint, directionVector: CGVector) {
let direction = Direction.fromPoint(CGPoint(x: directionVector.dx, y: directionVector.dy))
scheduleToBeRemoved(view) { aView in
!CGRectIntersectsRect(self.containerView.convertRect(aView.frame, toView: nil), UIScreen.mainScreen().bounds)
}
didSwipe?(view: view, inDirection: direction, directionVector: directionVector)
loadViews()
}
private func scheduleToBeRemoved(view: UIView, withPredicate predicate: (UIView) -> Bool) {
guard allViews().contains(view) else { return }
history.append(view)
if UInt(history.count) > numberOfHistoryItem {
history.removeFirst()
}
scheduler.scheduleRepeatedly({ () -> Void in
self.allViews().arrayByRemoveObjectsInArray(self.activeViews()).filter({ view in predicate(view) }).forEach({ view in self.remove(view) })
}, interval: 0.3) { () -> Bool in
return self.activeViews().count == self.allViews().count
}
}
}
// MARK: - Default behaviors
extension ZLSwipeableView {
static func defaultAnimateViewHandler() -> AnimateViewHandler {
func toRadian(degree: CGFloat) -> CGFloat {
return degree * CGFloat(M_PI / 180)
}
func rotateView(view: UIView, forDegree degree: CGFloat, duration: NSTimeInterval, offsetFromCenter offset: CGPoint, swipeableView: ZLSwipeableView, completion: ((Bool) -> Void)? = nil) {
UIView.animateWithDuration(duration, delay: 0, options: .AllowUserInteraction, animations: {
view.center = swipeableView.convertPoint(swipeableView.center, fromView: swipeableView.superview)
var transform = CGAffineTransformMakeTranslation(offset.x, offset.y)
transform = CGAffineTransformRotate(transform, toRadian(degree))
transform = CGAffineTransformTranslate(transform, -offset.x, -offset.y)
view.transform = transform
},
completion: completion)
}
return { (view: UIView, index: Int, views: [UIView], swipeableView: ZLSwipeableView) in
let degree = CGFloat(1)
let duration = 0.4
let offset = CGPoint(x: 0, y: CGRectGetHeight(swipeableView.bounds) * 0.3)
switch index {
case 0:
rotateView(view, forDegree: 0, duration: duration, offsetFromCenter: offset, swipeableView: swipeableView)
case 1:
rotateView(view, forDegree: degree, duration: duration, offsetFromCenter: offset, swipeableView: swipeableView)
case 2:
rotateView(view, forDegree: -degree, duration: duration, offsetFromCenter: offset, swipeableView: swipeableView)
default:
rotateView(view, forDegree: 0, duration: duration, offsetFromCenter: offset, swipeableView: swipeableView)
}
}
}
static func defaultInterpretDirectionHandler() -> InterpretDirectionHandler {
return { (topView: UIView, direction: Direction, views: [UIView], swipeableView: ZLSwipeableView) in
let programmaticSwipeVelocity = CGFloat(1000)
let location = CGPoint(x: topView.center.x, y: topView.center.y*0.7)
var directionVector: CGVector!
switch direction {
case Direction.Left:
directionVector = CGVector(dx: -programmaticSwipeVelocity, dy: 0)
case Direction.Right:
directionVector = CGVector(dx: programmaticSwipeVelocity, dy: 0)
case Direction.Up:
directionVector = CGVector(dx: 0, dy: -programmaticSwipeVelocity)
case Direction.Down:
directionVector = CGVector(dx: 0, dy: programmaticSwipeVelocity)
default:
directionVector = CGVector(dx: 0, dy: 0)
}
return (location, directionVector)
}
}
static func defaultShouldSwipeViewHandler() -> ShouldSwipeHandler {
return { (view: UIView, movement: Movement, swipeableView: ZLSwipeableView) -> Bool in
let translation = movement.translation
let velocity = movement.velocity
let bounds = swipeableView.bounds
let minTranslationInPercent = swipeableView.minTranslationInPercent
let minVelocityInPointPerSecond = swipeableView.minVelocityInPointPerSecond
let allowedDirection = swipeableView.allowedDirection
func areTranslationAndVelocityInTheSameDirection() -> Bool {
return CGPoint.areInSameTheDirection(translation, p2: velocity)
}
func isDirectionAllowed() -> Bool {
return Direction.fromPoint(translation).intersect(allowedDirection) != .None
}
func isTranslationLargeEnough() -> Bool {
return abs(translation.x) > minTranslationInPercent * bounds.width || abs(translation.y) > minTranslationInPercent * bounds.height
}
func isVelocityLargeEnough() -> Bool {
return velocity.magnitude > minVelocityInPointPerSecond
}
return isDirectionAllowed() && areTranslationAndVelocityInTheSameDirection() && (isTranslationLargeEnough() || isVelocityLargeEnough())
}
}
}
// MARK: - Deprecated APIs
extension ZLSwipeableView {
@available(*, deprecated=1, message="Use numberOfActiveView")
public var numPrefetchedViews: UInt {
get {
return numberOfActiveView
}
set(newValue){
numberOfActiveView = newValue
}
}
@available(*, deprecated=1, message="Use allowedDirection")
public var direction: Direction {
get {
return allowedDirection
}
set(newValue){
allowedDirection = newValue
}
}
@available(*, deprecated=1, message="Use minTranslationInPercent")
public var translationThreshold: CGFloat {
get {
return minTranslationInPercent
}
set(newValue){
minTranslationInPercent = newValue
}
}
@available(*, deprecated=1, message="Use minVelocityInPointPerSecond")
public var velocityThreshold: CGFloat {
get {
return minVelocityInPointPerSecond
}
set(newValue){
minVelocityInPointPerSecond = newValue
}
}
}
// MARK: - Internal classes
internal class ViewManager : NSObject {
// Snapping -> [Moving]+ -> Snapping
// Snapping -> [Moving]+ -> Swiping -> Snapping
enum State {
case Snapping(CGPoint), Moving(CGPoint), Swiping(CGPoint, CGVector)
}
var state: State {
didSet {
if case .Snapping(_) = oldValue, case let .Moving(point) = state {
unsnapView()
attachView(toPoint: point)
} else if case .Snapping(_) = oldValue, case let .Swiping(origin, direction) = state {
unsnapView()
attachView(toPoint: origin)
pushView(fromPoint: origin, inDirection: direction)
} else if case .Moving(_) = oldValue, case let .Moving(point) = state {
moveView(toPoint: point)
} else if case .Moving(_) = oldValue, case let .Snapping(point) = state {
detachView()
snapView(point)
} else if case .Moving(_) = oldValue, case let .Swiping(origin, direction) = state {
pushView(fromPoint: origin, inDirection: direction)
} else if case .Swiping(_, _) = oldValue, case let .Snapping(point) = state {
unpushView()
detachView()
snapView(point)
}
}
}
/// To be added to view and removed
private class ZLPanGestureRecognizer: UIPanGestureRecognizer { }
static private let anchorViewWidth = CGFloat(1000)
private var anchorView = UIView(frame: CGRect(x: 0, y: 0, width: anchorViewWidth, height: anchorViewWidth))
private var snapBehavior: UISnapBehavior!
private var viewToAnchorViewAttachmentBehavior: UIAttachmentBehavior!
private var anchorViewToPointAttachmentBehavior: UIAttachmentBehavior!
private var pushBehavior: UIPushBehavior!
private let view: UIView
private let containerView: UIView
private let miscContainerView: UIView
private let animator: UIDynamicAnimator
private weak var swipeableView: ZLSwipeableView?
init(view: UIView, containerView: UIView, index: Int, miscContainerView: UIView, animator: UIDynamicAnimator, swipeableView: ZLSwipeableView) {
self.view = view
self.containerView = containerView
self.miscContainerView = miscContainerView
self.animator = animator
self.swipeableView = swipeableView
self.state = ViewManager.defaultSnappingState(view)
super.init()
view.addGestureRecognizer(ZLPanGestureRecognizer(target: self, action: Selector("handlePan:")))
miscContainerView.addSubview(anchorView)
containerView.insertSubview(view, atIndex: index)
}
static func defaultSnappingState(view: UIView) -> State {
return .Snapping(view.convertPoint(view.center, fromView: view.superview))
}
func snappingStateAtContainerCenter() -> State {
guard let swipeableView = swipeableView else { return ViewManager.defaultSnappingState(view) }
return .Snapping(containerView.convertPoint(swipeableView.center, fromView: swipeableView.superview))
}
deinit {
if let snapBehavior = snapBehavior {
removeBehavior(snapBehavior)
}
if let viewToAnchorViewAttachmentBehavior = viewToAnchorViewAttachmentBehavior {
removeBehavior(viewToAnchorViewAttachmentBehavior)
}
if let anchorViewToPointAttachmentBehavior = anchorViewToPointAttachmentBehavior {
removeBehavior(anchorViewToPointAttachmentBehavior)
}
if let pushBehavior = pushBehavior {
removeBehavior(pushBehavior)
}
for gestureRecognizer in view.gestureRecognizers! {
if gestureRecognizer.isKindOfClass(ZLPanGestureRecognizer.classForCoder()) {
view.removeGestureRecognizer(gestureRecognizer)
}
}
anchorView.removeFromSuperview()
view.removeFromSuperview()
}
func handlePan(recognizer: UIPanGestureRecognizer) {
guard let swipeableView = swipeableView else { return }
let translation = recognizer.translationInView(containerView)
let location = recognizer.locationInView(containerView)
let velocity = recognizer.velocityInView(containerView)
let movement = Movement(location: location, translation: translation, velocity: velocity)
switch recognizer.state {
case .Began:
guard case .Snapping(_) = state else { return }
state = .Moving(location)
swipeableView.didStart?(view: view, atLocation: location)
case .Changed:
guard case .Moving(_) = state else { return }
state = .Moving(location)
swipeableView.swiping?(view: view, atLocation: location, translation: translation)
case .Ended, .Cancelled:
guard case .Moving(_) = state else { return }
if swipeableView.shouldSwipeView(view: view, movement: movement, swipeableView: swipeableView) {
let directionVector = CGVector(point: translation.normalized * max(velocity.magnitude, swipeableView.minVelocityInPointPerSecond))
state = .Swiping(location, directionVector)
swipeableView.swipeView(view, location: location, directionVector: directionVector)
} else {
state = snappingStateAtContainerCenter()
swipeableView.didCancel?(view: view)
}
swipeableView.didEnd?(view: view, atLocation: location)
default:
break
}
}
private func snapView(point: CGPoint) {
snapBehavior = UISnapBehavior(item: view, snapToPoint: point)
snapBehavior!.damping = 0.75
addBehavior(snapBehavior)
}
private func unsnapView() {
guard let snapBehavior = snapBehavior else { return }
removeBehavior(snapBehavior)
}
private func attachView(toPoint point: CGPoint) {
anchorView.center = point
anchorView.backgroundColor = UIColor.blueColor()
anchorView.hidden = true
// attach aView to anchorView
let p = view.center
viewToAnchorViewAttachmentBehavior = UIAttachmentBehavior(item: view, offsetFromCenter: UIOffset(horizontal: -(p.x - point.x), vertical: -(p.y - point.y)), attachedToItem: anchorView, offsetFromCenter: UIOffsetZero)
viewToAnchorViewAttachmentBehavior!.length = 0
// attach anchorView to point
anchorViewToPointAttachmentBehavior = UIAttachmentBehavior(item: anchorView, offsetFromCenter: UIOffsetZero, attachedToAnchor: point)
anchorViewToPointAttachmentBehavior!.damping = 100
anchorViewToPointAttachmentBehavior!.length = 0
addBehavior(viewToAnchorViewAttachmentBehavior!)
addBehavior(anchorViewToPointAttachmentBehavior!)
}
private func moveView(toPoint point: CGPoint) {
guard let _ = viewToAnchorViewAttachmentBehavior, let toPoint = anchorViewToPointAttachmentBehavior else { return }
toPoint.anchorPoint = point
}
private func detachView() {
guard let viewToAnchorViewAttachmentBehavior = viewToAnchorViewAttachmentBehavior, let anchorViewToPointAttachmentBehavior = anchorViewToPointAttachmentBehavior else { return }
removeBehavior(viewToAnchorViewAttachmentBehavior)
removeBehavior(anchorViewToPointAttachmentBehavior)
}
private func pushView(fromPoint point: CGPoint, inDirection direction: CGVector) {
guard let _ = viewToAnchorViewAttachmentBehavior, let anchorViewToPointAttachmentBehavior = anchorViewToPointAttachmentBehavior else { return }
removeBehavior(anchorViewToPointAttachmentBehavior)
pushBehavior = UIPushBehavior(items: [anchorView], mode: .Instantaneous)
pushBehavior.pushDirection = direction
addBehavior(pushBehavior)
}
private func unpushView() {
guard let pushBehavior = pushBehavior else { return }
removeBehavior(pushBehavior)
}
private func addBehavior(behavior: UIDynamicBehavior) {
animator.addBehavior(behavior)
}
private func removeBehavior(behavior: UIDynamicBehavior) {
animator.removeBehavior(behavior)
}
}
internal class Scheduler : NSObject {
typealias Action = () -> Void
typealias EndCondition = () -> Bool
var timer: NSTimer?
var action: Action?
var endCondition: EndCondition?
func scheduleRepeatedly(action: Action, interval: NSTimeInterval, endCondition: EndCondition) {
guard timer == nil && interval > 0 else { return }
self.action = action
self.endCondition = endCondition
timer = NSTimer.scheduledTimerWithTimeInterval(interval, target: self, selector: Selector("doAction:"), userInfo: nil, repeats: true)
}
func doAction(timer: NSTimer) {
guard let action = action, let endCondition = endCondition where !endCondition() else {
timer.invalidate()
self.timer = nil
return
}
action()
}
}
// MARK: - Helper extensions
public func *(lhs: CGPoint, rhs: CGFloat) -> CGPoint {
return CGPoint(x: lhs.x * rhs, y: lhs.y * rhs)
}
extension CGPoint {
init(vector: CGVector) {
self.init(x: vector.dx, y: vector.dy)
}
var normalized: CGPoint {
return CGPoint(x: x / magnitude, y: y / magnitude)
}
var magnitude: CGFloat {
return CGFloat(sqrtf(powf(Float(x), 2) + powf(Float(y), 2)))
}
static func areInSameTheDirection(p1: CGPoint, p2: CGPoint) -> Bool {
func signNum(n: CGFloat) -> Int {
return (n < 0.0) ? -1 : (n > 0.0) ? +1 : 0
}
return signNum(p1.x) == signNum(p2.x) && signNum(p1.y) == signNum(p2.y)
}
}
extension CGVector {
init(point: CGPoint) {
self.init(dx: point.x, dy: point.y)
}
}
extension Array where Element: Equatable {
func arrayByRemoveObjectsInArray(array: [Element]) -> [Element] {
return Array(self).filter() { element in !array.contains(element) }
}
}
| mit | f451dc6c5ca55d076d1e0776b5d1e623 | 35.116312 | 223 | 0.646257 | 5.22619 | false | false | false | false |
robin24/bagtrack | BagTrack/View Controllers/BagsTableViewController.swift | 1 | 7772 | //
// BagsTableViewController.swift
// BagTrack
//
// Created by Robin Kipp on 14.09.17.
// Copyright © 2017 Robin Kipp. All rights reserved.
//
import UIKit
import CoreLocation
class BagsTableViewController: UITableViewController {
// MARK: - Properties
var dataModel:DataModel!
var manager:CLLocationManager!
// MARK: - Methods
override func viewDidLoad() {
super.viewDidLoad()
if !UserDefaults.standard.bool(forKey: "hasCompletedOnboarding") {
performSegue(withIdentifier: "onboardingSegue", sender: nil)
}
self.navigationItem.leftBarButtonItem = self.editButtonItem
dataModel = DataModel.sharedInstance
manager = CLLocationManager()
manager.delegate = self
for bag in dataModel.bags {
if bag.isTrackingEnabled {
startMonitoring(for: bag)
}
}
}
func startMonitoring(for bag:Bag) {
manager.startMonitoring(for: bag.region)
print("Region monitoring started.")
manager.startRangingBeacons(in: bag.region)
print("Beacon ranging started.")
}
func stopMonitoring(for bag:Bag) {
manager.stopMonitoring(for: bag.region)
print("Region monitoring stopped.")
manager.stopRangingBeacons(in: bag.region)
print("Beacon ranging stopped.")
}
@IBAction func onAddButtonTapped(_ sender: UIBarButtonItem) {
performSegue(withIdentifier: "addBag", sender: nil)
}
// MARK: - Table view data source
override func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return dataModel.bags.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "bagCell", for: indexPath) as! BagCell
let bag = dataModel.bags[indexPath.row]
cell.bag = bag
cell.delegate = self
return cell
}
override func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
// Return false if you do not want the specified item to be editable.
return true
}
// Override to disable "swipe to delete" action unless in edit mode
override func tableView(_ tableView: UITableView, editingStyleForRowAt indexPath: IndexPath) -> UITableViewCellEditingStyle {
if tableView.isEditing {
return .delete
}
return .none
}
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
performSegue(withIdentifier: "editBag", sender: indexPath)
}
// Override to support editing the table view.
override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {
if editingStyle == .delete {
let bag = dataModel.bags[indexPath.row]
stopMonitoring(for: bag)
dataModel.bags.remove(at: indexPath.row)
tableView.deleteRows(at: [indexPath], with: .fade)
}
}
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
if segue.identifier == "onboardingSegue" {
return
}
guard let navController = segue.destination as? UINavigationController else {
fatalError("Error: segue to unexpected view controller.")
}
guard let controller = navController.topViewController as? BagDetailTableViewController else {
fatalError("Error: navigation controller contains unexpected top view controller.")
}
controller.delegate = self
if segue.identifier == "editBag" {
controller.title = NSLocalizedString("Edit Bag", comment: "Window title shown when editing a bag.")
let indexPath = sender as! IndexPath
controller.bag = dataModel.bags[indexPath.row]
controller.indexPath = indexPath
}
}
}
// MARK: - NewBagDelegate
extension BagsTableViewController:BagDetailDelegate {
func bagDetailController(_ controller: BagDetailTableViewController, didFinishAdding bag: Bag) {
dataModel.bags.append(bag)
startMonitoring(for: bag)
let indexPath = IndexPath(row: dataModel.bags.count - 1, section: 0)
tableView.beginUpdates()
tableView.insertRows(at: [indexPath], with: .automatic)
tableView.endUpdates()
}
func bagDetailController(_ controller: BagDetailTableViewController, didFinishEditing bag: Bag, at indexPath: IndexPath) {
bag.isTrackingEnabled = dataModel.bags[indexPath.row].isTrackingEnabled
bag.proximity = dataModel.bags[indexPath.row].proximity
dataModel.bags.remove(at: indexPath.row)
dataModel.bags.insert(bag, at: indexPath.row)
let cell = tableView.cellForRow(at: indexPath) as! BagCell
cell.bag = bag
cell.configureCell(for: bag)
}
}
// MARK: - BagCellDelegate
extension BagsTableViewController:BagCellDelegate {
func bagCell(_ cell: BagCell, didToggleTrackingFor bag: Bag) {
if bag.isTrackingEnabled {
stopMonitoring(for: bag)
bag.isTrackingEnabled = false
bag.proximity = .unknown
cell.proximityLabel.text = bag.proximityForDisplay()
} else {
bag.isTrackingEnabled = true
startMonitoring(for: bag)
cell.proximityLabel.text = NSLocalizedString("Searching...", comment: "Searching after tracking is enabled.")
}
}
}
// MARK: - CLLocationManagerDelegate
extension BagsTableViewController:CLLocationManagerDelegate {
func locationManager(_ manager: CLLocationManager, didRangeBeacons beacons: [CLBeacon], in region: CLBeaconRegion) {
for index in 0 ..< dataModel.bags.count {
let bag = dataModel.bags[index]
for beacon in beacons {
if bag == beacon {
if bag.proximity == beacon.proximity {
return
}
bag.proximity = beacon.proximity
let indexPath = IndexPath(row: index, section: 0)
guard let cell = tableView.cellForRow(at: indexPath) as? BagCell else {
fatalError("No cell at requested IndexPath.")
}
cell.proximityLabel.text = bag.proximityForDisplay()
if cell.accessibilityElementIsFocused() {
UIAccessibilityPostNotification(UIAccessibilityAnnouncementNotification, bag.proximityForDisplay() as NSString)
}
}
}
}
}
func locationManager(_ manager: CLLocationManager, didFailWithError error: Error) {
present(Helpers.showAlert(.locationError, error: error), animated: true, completion: nil)
}
func locationManager(_ manager: CLLocationManager, monitoringDidFailFor region: CLRegion?, withError error: Error) {
present(Helpers.showAlert(.locationError, error: error), animated: true, completion: nil)
}
func locationManager(_ manager: CLLocationManager, rangingBeaconsDidFailFor region: CLBeaconRegion, withError error: Error) {
present(Helpers.showAlert(.locationError, error: error), animated: true, completion: nil)
}
}
| mit | 634e9803fb37495346d13201c7a0b373 | 39.056701 | 136 | 0.655257 | 5.279212 | false | false | false | false |
jhurray/SQLiteModel | SQLiteModel/Relationship.swift | 1 | 1904 | //
// Relationship.swift
// SQLiteModel
//
// Created by Jeff Hurray on 1/17/16.
// Copyright © 2016 jhurray. All rights reserved.
//
import Foundation
import SQLite
public struct Relationship<DataType> {
internal typealias UnderlyingType = DataType
internal var template: String
internal var unique: Bool
internal var reference: Int = -1
}
extension Relationship where DataType : SQLiteModel {
public init(_ template: String, unique: Bool = false) {
self.template = template
self.unique = unique
}
}
extension Relationship where DataType : CollectionType, DataType.Generator.Element : SQLiteModel {
public init(_ template: String, unique: Bool = false) {
self.template = template
self.unique = unique
}
}
extension Relationship where DataType : _OptionalType{
internal init(_ relationship: Relationship<DataType.WrappedType>) {
self.template = relationship.template
self.unique = relationship.unique
}
public init(_ template: String, unique: Bool = false) {
self.template = template
self.unique = unique
}
}
public struct RelationshipSetter {
internal let action: (SQLiteSettable) -> Void
}
internal struct RelationshipReferenceTracker {
private static var sharedInstance = RelationshipReferenceTracker()
private var tracker = [String : String]()
static func currentTemplate<U: SQLiteModel, V: SQLiteModel>(key: (U.Type, V.Type)) -> String {
guard let value = self.sharedInstance.tracker["\(key.0)_\(key.1)"] else {
fatalError("SQLiteModel Error: Improper table access for a relationship.")
}
return value
}
static func setTemplate<U: SQLiteModel, V: SQLiteModel>(key: (U.Type, V.Type), template: String) {
self.sharedInstance.tracker["\(key.0)_\(key.1)"] = template
}
}
| mit | 569fa9b8d9420ae7c8f8dfa7eb2ab118 | 27.402985 | 102 | 0.667893 | 4.52019 | false | false | false | false |
daniele-pizziconi/AlamofireImage | Carthage/Checkouts/YLGIFImage-Swift/YLGIFImage-Swift/YLImageView.swift | 1 | 4699 | //
// YLImageView.swift
// YLGIFImage
//
// Created by Yong Li on 6/8/14.
// Copyright (c) 2014 Yong Li. All rights reserved.
//
import UIKit
import QuartzCore
public class YLImageView : UIImageView {
private lazy var displayLink:CADisplayLink = CADisplayLink(target: self, selector: #selector(self.changeKeyFrame(_:)))
private var accumulator: TimeInterval = 0.0
private var currentFrameIndex: Int = 0
private var currentFrame: UIImage? = nil
private var loopCountdown: Int = Int.max
private var animatedImage: YLGIFImage? = nil
required public init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
self.displayLink.add(to: RunLoop.main, forMode: RunLoopMode.commonModes)
self.displayLink.isPaused = true
}
override init(frame: CGRect) {
super.init(frame: frame)
self.displayLink.add(to: RunLoop.main, forMode: RunLoopMode.commonModes)
self.displayLink.isPaused = true
}
override init(image: UIImage?) {
super.init(image: image)
self.displayLink.add(to: RunLoop.main, forMode: RunLoopMode.commonModes)
self.displayLink.isPaused = true
}
override init(image: UIImage?, highlightedImage: UIImage!) {
super.init(image: image, highlightedImage: highlightedImage)
self.displayLink.add(to: RunLoop.main, forMode: RunLoopMode.commonModes)
self.displayLink.isPaused = true
}
override public var image: UIImage! {
get {
if (self.animatedImage != nil) {
return self.animatedImage
} else {
return super.image
}
}
set{
if image === newValue {
return
}
self.stopAnimating()
self.currentFrameIndex = 0
self.accumulator = 0.0
if newValue is YLGIFImage {
self.animatedImage = newValue as? YLGIFImage
if let Img = self.animatedImage!.getFrame(0) {
super.image = Img
self.currentFrame = super.image
}
self.startAnimating()
} else {
super.image = newValue
self.animatedImage = nil
}
self.layer.setNeedsDisplay()
}
}
override public var isHighlighted: Bool {
get{
return super.isHighlighted
}
set {
if (self.animatedImage != nil) {
return
} else {
return super.isHighlighted = newValue
}
}
}
override public var isAnimating: Bool {
if (self.animatedImage != nil) {
return !self.displayLink.isPaused
} else {
return super.isAnimating
}
}
override public func startAnimating() {
if (self.animatedImage != nil) {
self.displayLink.isPaused = false
} else {
super.startAnimating()
}
}
override public func stopAnimating() {
if (self.animatedImage != nil) {
self.displayLink.isPaused = true
} else {
super.stopAnimating()
}
}
override public func display(_ layer: CALayer) {
if (self.animatedImage != nil) {
if let frame = self.currentFrame {
layer.contents = frame.cgImage
}
} else {
return
}
}
dynamic func changeKeyFrame(_ dpLink: CADisplayLink!) -> Void {
if let animatedImg = self.animatedImage {
if self.currentFrameIndex < animatedImg.frameImages.count {
self.accumulator += fmin(1.0, dpLink.duration)
var frameDura = animatedImg.frameDurations[self.currentFrameIndex] as! NSNumber
while self.accumulator >= frameDura.doubleValue
{
self.accumulator = self.accumulator - frameDura.doubleValue//animatedImg.frameDurations[self.currentFrameIndex]
self.currentFrameIndex += 1
if Int(self.currentFrameIndex) >= animatedImg.frameImages.count {
self.currentFrameIndex = 0
}
if let Img = animatedImg.getFrame(UInt(self.currentFrameIndex)) {
self.currentFrame = Img
}
self.layer.setNeedsDisplay()
frameDura = animatedImg.frameDurations[self.currentFrameIndex] as! NSNumber
}
}
} else {
self.stopAnimating()
}
}
}
| mit | 51697bd290b2f3198332a4f6469585e6 | 30.965986 | 131 | 0.553522 | 5.141138 | false | false | false | false |
riehs/on-the-map | On the Map/On the Map/LoginViewController.swift | 1 | 2652 | //
// LoginViewController.swift
// On the Map
//
// Created by Daniel Riehs on 3/22/15.
// Copyright (c) 2015 Daniel Riehs. All rights reserved.
//
import UIKit
class LoginViewController: UIViewController {
@IBOutlet weak var usernameTextField: UITextField!
@IBOutlet weak var passwordTextField: UITextField!
//This label displays user instructions, errors, and a "Connecting..." message.
@IBOutlet weak var errorLabel: UILabel!
@IBOutlet weak var loginButton: UIButton!
@IBAction func tapSignUpButton(_ sender: AnyObject) {
UIApplication.shared.openURL(URL(string: "https://www.udacity.com/account/auth#!/signup")!)
}
//Tapping the loginButton fetches a userKey from Udacity, fetches a firstName and a lastName from Udacity, and then fetches student information from Parse. Only when all three steps are complete is the completeLogin function called to segue to the map.
@IBAction func tapLoginButton(_ sender: AnyObject) {
loginButton.isEnabled = false
errorLabel.text = "Connecting..."
//Basic error check before sending the credentials to Udacity.
if (usernameTextField.text == "" || passwordTextField.text == "") {
displayError("Enter a username and password.")
//Fetching userKey from Udacity.
} else {
UdacityLogin.sharedInstance().loginToUdacity(username: usernameTextField.text!, password: passwordTextField.text!) { (success, errorString) in
if success {
//Fetching first and last name from Udacity.
UdacityLogin.sharedInstance().setFirstNameLastName() { (success, errorString) in
if success {
//Fetching student information from Parse.
MapPoints.sharedInstance().fetchData() { (success, errorString) in
if success {
self.completeLogin()
} else {
self.displayError(errorString)
}
}
} else {
self.displayError(errorString)
}
}
} else {
self.displayError(errorString)
}
}
}
}
//Complete the login and present the first navigation controller.
func completeLogin() {
DispatchQueue.main.async(execute: {
let controller = self.storyboard!.instantiateViewController(withIdentifier: "StudentsNavigationController") as! UINavigationController
self.present(controller, animated: true, completion: nil)
})
}
//Display error messages returned from any of the completion handlers.
func displayError(_ errorString: String?) {
DispatchQueue.main.async(execute: {
if let errorString = errorString {
self.errorLabel.text = errorString
//The login button in re-enabled so that the user can try again.
self.loginButton.isEnabled = true
}
})
}
}
| mit | 29408fc63528f6043f3492825512ba13 | 29.837209 | 253 | 0.714555 | 4.277419 | false | false | false | false |
urdnot-ios/ShepardAppearanceConverter | ShepardAppearanceConverter/ShepardAppearanceConverter/Library/HideAutolayoutUtility.swift | 1 | 1889 | //
// HideAutolayoutUtility.swift
//
// Created by Emily Ivie on 6/11/15.
//
import UIKit
/**
Hides a view and removes any constraints tied to it, which can allow for space to collapse when view is gone.
Allows for all autolayout to be defined in Interface Builder. Just provide two constraints, a strong one for when the item is visible, and a weaker one for when it is hidden (so, 8 to itemToBeHidden at priority 1000, 8 to previousItem at priority 100), and the weaker one will kick in when the item is hidden. DO NOT USE >= weaker constraints, because then it will just stick with the previous layout and not collapse the space.
Derived from https://gist.github.com/albertbori/9716fd25b424950264eb
*/
public class HideAutolayoutUtility {
var savedConstraints = [String: [NSLayoutConstraint]]()
init() {}
public func hide(view: UIView!, key: String) {
// println("\(key) HIDE")
if view == nil { return }
view.hidden = true
if let parent = view.superview {
let constraints = parent.constraints
var removeConstraints = [NSLayoutConstraint]()
for constraint in constraints {
if constraint.firstItem === view || constraint.secondItem === view {
// println("\(key) \(constraint)")
removeConstraints.append(constraint)
}
}
savedConstraints[key] = removeConstraints
parent.removeConstraints(removeConstraints)
}
}
public func show(view: UIView!, key: String) {
// println("\(key) SHOW")
if view == nil { return }
view.hidden = false
if let constraints = savedConstraints[key], let parent = view.superview {
parent.addConstraints(constraints)
savedConstraints.removeValueForKey(key)
}
}
}
| mit | 97905353cf3c812c8b002851a1ba07e8 | 36.78 | 432 | 0.634727 | 4.758186 | false | false | false | false |
xcodeswift/xcproj | Sources/XcodeProj/Objects/Project/PBXProject.swift | 1 | 22567 | import Foundation
import PathKit
public final class PBXProject: PBXObject {
// MARK: - Attributes
/// Project name
public var name: String
/// Build configuration list reference.
var buildConfigurationListReference: PBXObjectReference
/// Build configuration list.
public var buildConfigurationList: XCConfigurationList! {
set {
buildConfigurationListReference = newValue.reference
}
get {
buildConfigurationListReference.getObject()
}
}
/// A string representation of the XcodeCompatibilityVersion.
public var compatibilityVersion: String
/// The region of development.
public var developmentRegion: String?
/// Whether file encodings have been scanned.
public var hasScannedForEncodings: Int
/// The known regions for localized files.
public var knownRegions: [String]
/// The object is a reference to a PBXGroup element.
var mainGroupReference: PBXObjectReference
/// Project main group.
public var mainGroup: PBXGroup! {
set {
mainGroupReference = newValue.reference
}
get {
mainGroupReference.getObject()
}
}
/// The object is a reference to a PBXGroup element.
var productsGroupReference: PBXObjectReference?
/// Products group.
public var productsGroup: PBXGroup? {
set {
productsGroupReference = newValue?.reference
}
get {
productsGroupReference?.getObject()
}
}
/// The relative path of the project.
public var projectDirPath: String
/// Project references.
var projectReferences: [[String: PBXObjectReference]]
/// Project projects.
// {
// ProductGroup = B900DB69213936CC004AEC3E /* Products group reference */;
// ProjectRef = B900DB68213936CC004AEC3E /* Project file reference */;
// },
public var projects: [[String: PBXFileElement]] {
set {
projectReferences = newValue.map { project in
project.mapValues { $0.reference }
}
}
get {
projectReferences.map { project in
project.mapValues { $0.getObject()! }
}
}
}
private static let targetAttributesKey = "TargetAttributes"
/// The relative root paths of the project.
public var projectRoots: [String]
/// The objects are a reference to a PBXTarget element.
var targetReferences: [PBXObjectReference]
/// Project targets.
public var targets: [PBXTarget] {
set {
targetReferences = newValue.references()
}
get {
targetReferences.objects()
}
}
/// Project attributes.
/// Target attributes will be merged into this
public var attributes: [String: Any]
/// Target attribute references.
var targetAttributeReferences: [PBXObjectReference: [String: Any]]
/// Target attributes.
public var targetAttributes: [PBXTarget: [String: Any]] {
set {
targetAttributeReferences = [:]
newValue.forEach {
targetAttributeReferences[$0.key.reference] = $0.value
}
} get {
var attributes: [PBXTarget: [String: Any]] = [:]
targetAttributeReferences.forEach {
if let object: PBXTarget = $0.key.getObject() {
attributes[object] = $0.value
}
}
return attributes
}
}
/// Package references.
var packageReferences: [PBXObjectReference]?
/// Swift packages.
public var packages: [XCRemoteSwiftPackageReference] {
set {
packageReferences = newValue.references()
}
get {
packageReferences?.objects() ?? []
}
}
/// Sets the attributes for the given target.
///
/// - Parameters:
/// - attributes: attributes that will be set.
/// - target: target.
public func setTargetAttributes(_ attributes: [String: Any], target: PBXTarget) {
targetAttributeReferences[target.reference] = attributes
}
/// Removes the attributes for the given target.
///
/// - Parameter target: target whose attributes will be removed.
public func removeTargetAttributes(target: PBXTarget) {
targetAttributeReferences.removeValue(forKey: target.reference)
}
/// Removes the all the target attributes
public func clearAllTargetAttributes() {
targetAttributeReferences.removeAll()
}
/// Returns the attributes of a given target.
///
/// - Parameter for: target whose attributes will be returned.
/// - Returns: target attributes.
public func attributes(for target: PBXTarget) -> [String: Any]? {
targetAttributeReferences[target.reference]
}
/// Adds a remote swift package
///
/// - Parameters:
/// - repositoryURL: URL in String pointing to the location of remote Swift package
/// - productName: The product to depend on without the extension
/// - versionRequirement: Describes the rules of the version to use
/// - targetName: Target's name to link package product to
public func addSwiftPackage(repositoryURL: String,
productName: String,
versionRequirement: XCRemoteSwiftPackageReference.VersionRequirement,
targetName: String) throws -> XCRemoteSwiftPackageReference {
let objects = try self.objects()
guard let target = targets.first(where: { $0.name == targetName }) else { throw PBXProjError.targetNotFound(targetName: targetName) }
// Reference
let reference = try addSwiftPackageReference(repositoryURL: repositoryURL,
productName: productName,
versionRequirement: versionRequirement)
// Product
let productDependency = try addSwiftPackageProduct(reference: reference,
productName: productName,
target: target)
// Build file
let buildFile = PBXBuildFile(product: productDependency)
objects.add(object: buildFile)
// Link the product
guard let frameworksBuildPhase = try target.frameworksBuildPhase() else { throw PBXProjError.frameworksBuildPhaseNotFound(targetName: targetName) }
frameworksBuildPhase.files?.append(buildFile)
return reference
}
/// Adds a local swift package
///
/// - Parameters:
/// - path: Relative path to the swift package (throws an error if the path is absolute)
/// - productName: The product to depend on without the extension
/// - targetName: Target's name to link package product to
/// - addFileReference: Include a file reference to the package (defaults to main group)
public func addLocalSwiftPackage(path: Path,
productName: String,
targetName: String,
addFileReference: Bool = true) throws -> XCSwiftPackageProductDependency {
guard path.isRelative else { throw PBXProjError.pathIsAbsolute(path) }
let objects = try self.objects()
guard let target = targets.first(where: { $0.name == targetName }) else { throw PBXProjError.targetNotFound(targetName: targetName) }
// Product
let productDependency = try addLocalSwiftPackageProduct(path: path,
productName: productName,
target: target)
// Build file
let buildFile = PBXBuildFile(product: productDependency)
objects.add(object: buildFile)
// Link the product
guard let frameworksBuildPhase = try target.frameworksBuildPhase() else {
throw PBXProjError.frameworksBuildPhaseNotFound(targetName: targetName)
}
frameworksBuildPhase.files?.append(buildFile)
// File reference
// The user might want to control adding the file's reference (to be exact when the reference is added)
// to achieve desired hierarchy of the group's children
if addFileReference {
let reference = PBXFileReference(sourceTree: .group,
name: productName,
lastKnownFileType: "folder",
path: path.string)
objects.add(object: reference)
mainGroup.children.append(reference)
}
return productDependency
}
// MARK: - Init
/// Initializes the project with its attributes
///
/// - Parameters:
/// - name: xcodeproj's name.
/// - buildConfigurationList: project build configuration list.
/// - compatibilityVersion: project compatibility version.
/// - mainGroup: project main group.
/// - developmentRegion: project has development region.
/// - hasScannedForEncodings: project has scanned for encodings.
/// - knownRegions: project known regions.
/// - productsGroup: products group.
/// - projectDirPath: project dir path.
/// - projects: projects.
/// - projectRoots: project roots.
/// - targets: project targets.
public init(name: String,
buildConfigurationList: XCConfigurationList,
compatibilityVersion: String,
mainGroup: PBXGroup,
developmentRegion: String? = nil,
hasScannedForEncodings: Int = 0,
knownRegions: [String] = [],
productsGroup: PBXGroup? = nil,
projectDirPath: String = "",
projects: [[String: PBXFileElement]] = [],
projectRoots: [String] = [],
targets: [PBXTarget] = [],
packages: [XCRemoteSwiftPackageReference] = [],
attributes: [String: Any] = [:],
targetAttributes: [PBXTarget: [String: Any]] = [:]) {
self.name = name
buildConfigurationListReference = buildConfigurationList.reference
self.compatibilityVersion = compatibilityVersion
mainGroupReference = mainGroup.reference
self.developmentRegion = developmentRegion
self.hasScannedForEncodings = hasScannedForEncodings
self.knownRegions = knownRegions
productsGroupReference = productsGroup?.reference
self.projectDirPath = projectDirPath
projectReferences = projects.map { project in project.mapValues { $0.reference } }
self.projectRoots = projectRoots
targetReferences = targets.references()
packageReferences = packages.references()
self.attributes = attributes
targetAttributeReferences = [:]
super.init()
self.targetAttributes = targetAttributes
}
// MARK: - Decodable
fileprivate enum CodingKeys: String, CodingKey {
case name
case buildConfigurationList
case compatibilityVersion
case developmentRegion
case hasScannedForEncodings
case knownRegions
case mainGroup
case productRefGroup
case projectDirPath
case projectReferences
case projectRoot
case projectRoots
case targets
case attributes
case packageReferences
}
public required init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
let referenceRepository = decoder.context.objectReferenceRepository
let objects = decoder.context.objects
name = (try container.decodeIfPresent(.name)) ?? ""
let buildConfigurationListReference: String = try container.decode(.buildConfigurationList)
self.buildConfigurationListReference = referenceRepository.getOrCreate(reference: buildConfigurationListReference, objects: objects)
compatibilityVersion = try container.decode(.compatibilityVersion)
developmentRegion = try container.decodeIfPresent(.developmentRegion)
let hasScannedForEncodingsString: String? = try container.decodeIfPresent(.hasScannedForEncodings)
hasScannedForEncodings = hasScannedForEncodingsString.flatMap { Int($0) } ?? 0
knownRegions = (try container.decodeIfPresent(.knownRegions)) ?? []
let mainGroupReference: String = try container.decode(.mainGroup)
self.mainGroupReference = referenceRepository.getOrCreate(reference: mainGroupReference, objects: objects)
if let productRefGroupReference: String = try container.decodeIfPresent(.productRefGroup) {
productsGroupReference = referenceRepository.getOrCreate(reference: productRefGroupReference, objects: objects)
} else {
productsGroupReference = nil
}
projectDirPath = try container.decodeIfPresent(.projectDirPath) ?? ""
let projectReferences: [[String: String]] = (try container.decodeIfPresent(.projectReferences)) ?? []
self.projectReferences = projectReferences.map { references in
references.mapValues { referenceRepository.getOrCreate(reference: $0, objects: objects) }
}
if let projectRoots: [String] = try container.decodeIfPresent(.projectRoots) {
self.projectRoots = projectRoots
} else if let projectRoot: String = try container.decodeIfPresent(.projectRoot) {
projectRoots = [projectRoot]
} else {
projectRoots = []
}
let targetReferences: [String] = (try container.decodeIfPresent(.targets)) ?? []
self.targetReferences = targetReferences.map { referenceRepository.getOrCreate(reference: $0, objects: objects) }
let packageRefeferenceStrings: [String] = try container.decodeIfPresent(.packageReferences) ?? []
packageReferences = packageRefeferenceStrings.map { referenceRepository.getOrCreate(reference: $0, objects: objects) }
var attributes = (try container.decodeIfPresent([String: Any].self, forKey: .attributes) ?? [:])
var targetAttributeReferences: [PBXObjectReference: [String: Any]] = [:]
if let targetAttributes = attributes[PBXProject.targetAttributesKey] as? [String: [String: Any]] {
targetAttributes.forEach { targetAttributeReferences[referenceRepository.getOrCreate(reference: $0.key, objects: objects)] = $0.value }
attributes[PBXProject.targetAttributesKey] = nil
}
self.attributes = attributes
self.targetAttributeReferences = targetAttributeReferences
try super.init(from: decoder)
}
}
// MARK: - Helpers
extension PBXProject {
/// Adds reference for remote Swift package
private func addSwiftPackageReference(repositoryURL: String,
productName: String,
versionRequirement: XCRemoteSwiftPackageReference.VersionRequirement) throws -> XCRemoteSwiftPackageReference {
let reference: XCRemoteSwiftPackageReference
if let package = packages.first(where: { $0.repositoryURL == repositoryURL }) {
guard package.versionRequirement == versionRequirement else {
throw PBXProjError.multipleRemotePackages(productName: productName)
}
reference = package
} else {
reference = XCRemoteSwiftPackageReference(repositoryURL: repositoryURL, versionRequirement: versionRequirement)
try objects().add(object: reference)
packages.append(reference)
}
return reference
}
/// Adds package product for remote Swift package
private func addSwiftPackageProduct(reference: XCRemoteSwiftPackageReference,
productName: String,
target: PBXTarget) throws -> XCSwiftPackageProductDependency {
let objects = try self.objects()
let productDependency: XCSwiftPackageProductDependency
// Avoid duplication
if let product = objects.swiftPackageProductDependencies.first(where: { $0.value.package == reference })?.value {
productDependency = product
} else {
productDependency = XCSwiftPackageProductDependency(productName: productName, package: reference)
objects.add(object: productDependency)
}
target.packageProductDependencies.append(productDependency)
return productDependency
}
/// Adds package product for local Swift package
private func addLocalSwiftPackageProduct(path: Path,
productName: String,
target: PBXTarget) throws -> XCSwiftPackageProductDependency {
let objects = try self.objects()
let productDependency: XCSwiftPackageProductDependency
// Avoid duplication
if let product = objects.swiftPackageProductDependencies.first(where: { $0.value.productName == productName }) {
guard objects.fileReferences.first(where: { $0.value.name == productName })?.value.path == path.string else {
throw PBXProjError.multipleLocalPackages(productName: productName)
}
productDependency = product.value
} else {
productDependency = XCSwiftPackageProductDependency(productName: productName)
objects.add(object: productDependency)
}
target.packageProductDependencies.append(productDependency)
return productDependency
}
}
// MARK: - PlistSerializable
extension PBXProject: PlistSerializable {
// swiftlint:disable:next function_body_length
func plistKeyAndValue(proj: PBXProj, reference: String) throws -> (key: CommentedString, value: PlistValue) {
var dictionary: [CommentedString: PlistValue] = [:]
dictionary["isa"] = .string(CommentedString(PBXProject.isa))
let buildConfigurationListComment = "Build configuration list for PBXProject \"\(name)\""
let buildConfigurationListCommentedString = CommentedString(buildConfigurationListReference.value,
comment: buildConfigurationListComment)
dictionary["buildConfigurationList"] = .string(buildConfigurationListCommentedString)
dictionary["compatibilityVersion"] = .string(CommentedString(compatibilityVersion))
if let developmentRegion = developmentRegion {
dictionary["developmentRegion"] = .string(CommentedString(developmentRegion))
}
dictionary["hasScannedForEncodings"] = .string(CommentedString("\(hasScannedForEncodings)"))
if !knownRegions.isEmpty {
dictionary["knownRegions"] = PlistValue.array(knownRegions
.map { .string(CommentedString("\($0)")) })
}
let mainGroupObject: PBXGroup? = mainGroupReference.getObject()
dictionary["mainGroup"] = .string(CommentedString(mainGroupReference.value, comment: mainGroupObject?.fileName()))
if let productsGroupReference = productsGroupReference {
let productRefGroupObject: PBXGroup? = productsGroupReference.getObject()
dictionary["productRefGroup"] = .string(CommentedString(productsGroupReference.value,
comment: productRefGroupObject?.fileName()))
}
dictionary["projectDirPath"] = .string(CommentedString(projectDirPath))
if projectRoots.count > 1 {
dictionary["projectRoots"] = projectRoots.plist()
} else {
dictionary["projectRoot"] = .string(CommentedString(projectRoots.first ?? ""))
}
if let projectReferences = try projectReferencesPlistValue(proj: proj) {
dictionary["projectReferences"] = projectReferences
}
dictionary["targets"] = PlistValue.array(targetReferences
.map { targetReference in
let target: PBXTarget? = targetReference.getObject()
return .string(CommentedString(targetReference.value, comment: target?.name))
})
if !packages.isEmpty {
dictionary["packageReferences"] = PlistValue.array(packages.map {
.string(CommentedString($0.reference.value, comment: "XCRemoteSwiftPackageReference \"\($0.name ?? "")\""))
})
}
var plistAttributes: [String: Any] = attributes
// merge target attributes
var plistTargetAttributes: [String: Any] = [:]
for (reference, value) in targetAttributeReferences {
plistTargetAttributes[reference.value] = value.mapValues { value in
(value as? PBXObject)?.reference.value ?? value
}
}
plistAttributes[PBXProject.targetAttributesKey] = plistTargetAttributes
dictionary["attributes"] = plistAttributes.plist()
return (key: CommentedString(reference,
comment: "Project object"),
value: .dictionary(dictionary))
}
private func projectReferencesPlistValue(proj _: PBXProj) throws -> PlistValue? {
guard !projectReferences.isEmpty else {
return nil
}
return .array(projectReferences.compactMap { reference in
guard let productGroupReference = reference[Xcode.ProjectReference.productGroupKey],
let projectRef = reference[Xcode.ProjectReference.projectReferenceKey] else {
return nil
}
let producGroup: PBXGroup? = productGroupReference.getObject()
let groupName = producGroup?.fileName()
let project: PBXFileElement? = projectRef.getObject()
let fileRefName = project?.fileName()
return [
CommentedString(Xcode.ProjectReference.productGroupKey): PlistValue.string(CommentedString(productGroupReference.value, comment: groupName)),
CommentedString(Xcode.ProjectReference.projectReferenceKey): PlistValue.string(CommentedString(projectRef.value, comment: fileRefName)),
]
})
}
}
| mit | 77cf37f46a08a36abbc9474ea8e0b0aa | 41.903042 | 157 | 0.632029 | 6.008253 | false | false | false | false |
orangeloops/OLSDynamicHeaderViewController | Example/OLSDynamicHeaderViewController/SampleHeaderView.swift | 1 | 3889 | //
// SampleHeaderView.swift
// OLSDynamicHeader
//
// Created by Omar Hagopian on 9/7/16.
// Copyright © 2017 OrangeLoops. All rights reserved.
//
import UIKit
import OLSDynamicHeaderViewController
class SampleHeaderView: OLSDynamicHeaderView {
let minHeaderHeight: CGFloat = 64 //navigation bar + status
let maxHeaderHeight: CGFloat = 260
let minLabelSpacing: CGFloat = 0
let maxLabelSpacing: CGFloat = 0
let minTitleFontSize: CGFloat = 18
let maxTitleFontSize: CGFloat = 35
let minBottomSpacing: CGFloat = 5
let maxBottomSpacing: CGFloat = 16
let minImageAlpha: CGFloat = 0
let maxImageAlpha: CGFloat = 1.6
let minBackgroundAlpha: CGFloat = 0.3
let maxBackgroundAlpha: CGFloat = 2.0
@IBOutlet weak var profileImageView: UIImageView!
@IBOutlet weak var backgroundImageView: UIImageView!
@IBOutlet weak var titleLabel: UILabel!
@IBOutlet weak var subtitleLabel: UILabel!
@IBOutlet weak var bottomSpacingLayoutConstraint: NSLayoutConstraint!
@IBOutlet weak var labelSpacingLayoutConstraint: NSLayoutConstraint!
override func awakeFromNib() {
super.awakeFromNib()
translatesAutoresizingMaskIntoConstraints = false
profileImageView.layer.cornerRadius = 12
}
class func viewInstance() -> SampleHeaderView {
let defaultNib = UINib(nibName: "SampleHeaderView", bundle: nil)
let view = defaultNib.instantiate(withOwner: nil, options: nil)[0] as? SampleHeaderView
return view!
}
override func maxHeight() -> CGFloat {
return maxHeaderHeight
}
override func minHeight() -> CGFloat {
return minHeaderHeight
}
override func resize(withProgress progress: CGFloat) {
//Some boring math =S
let minHeight = self.minHeight()
let maxHeight = self.maxHeight()
let headerDistance = maxHeight - minHeight
let progressConstantValue = headerDistance - (headerDistance * progress)
let bottomValue = progressValue(minBottomSpacing, maxBottomSpacing, progress: progress)
bottomSpacingLayoutConstraint.constant = progressConstantValue + bottomValue
labelSpacingLayoutConstraint.constant = progressValue(minLabelSpacing, maxLabelSpacing, progress: progress)
let fontFinalValue = progressValue(minTitleFontSize, maxTitleFontSize, progress: progress)
titleLabel.font = UIFont(name: titleLabel.font!.familyName, size: fontFinalValue)
profileImageView.alpha = progressValue(minImageAlpha, maxImageAlpha, progress: progress)
backgroundImageView.alpha = progressValue(minBackgroundAlpha, maxBackgroundAlpha, progress: progress)
}
override func overflow(withPoints points: CGFloat) {
//Reset everything
bottomSpacingLayoutConstraint.constant = maxBottomSpacing - points
labelSpacingLayoutConstraint.constant = maxLabelSpacing
titleLabel.font = UIFont(name: titleLabel.font!.familyName, size: maxTitleFontSize)
profileImageView.alpha = maxImageAlpha;
backgroundImageView.alpha = maxBackgroundAlpha;
//Fun image transformation =D
var headerTransform = CATransform3DIdentity
let headerScaleFactor:CGFloat = points / self.bounds.height
let headerSizevariation = ((self.bounds.height * (1.0 + headerScaleFactor)) - self.bounds.height)/2.0
headerTransform = CATransform3DTranslate(headerTransform, 0, headerSizevariation, 0)
headerTransform = CATransform3DScale(headerTransform, 1.0 + headerScaleFactor, 1.0 + headerScaleFactor, 0)
backgroundImageView.layer.transform = headerTransform
}
private func progressValue(_ min: CGFloat, _ max: CGFloat, progress: CGFloat) -> CGFloat { //Assuming progress 0..1
let range = max - min
let value = range * progress
return min + value
}
}
| mit | 28d64d694cef282221b069a58f84b096 | 36.384615 | 119 | 0.718621 | 5.318741 | false | false | false | false |
zaneswafford/ProjectEulerSwift | ProjectEuler/Problem10.swift | 1 | 733 | //
// Problem10.swift
// ProjectEuler
//
// Created by Zane Swafford on 6/25/15.
// Copyright (c) 2015 Zane Swafford. All rights reserved.
//
import Foundation
func problem10() -> Int {
//return ZSMath.generatePrimes(upToNumber: 2_000_000).reduce(0, combine: +)
// This method using the Sieve of Eratosthenes is nearly 10x faster than
// using the built-in reduce.
var sieve = [Bool](count: 2_000_000, repeatedValue: true)
var sum = 0
for i in 2..<2_000_000 {
if sieve[i] {
sum += i
for var multiple = i + i; multiple < 2_000_000; multiple += i {
sieve[multiple] = false
}
}
}
return sum
} | bsd-2-clause | 07711bd27d442c952de2163618c1c22f | 21.9375 | 79 | 0.553888 | 3.739796 | false | false | false | false |
laurentVeliscek/AudioKit | AudioKit/Common/Tests/AKPWMOscillatorTests.swift | 2 | 1128 | //
// AKPWMOscillatorTests.swift
// AudioKit for iOS
//
// Created by Aurelius Prochazka on 8/6/16.
// Copyright © 2016 AudioKit. All rights reserved.
//
import XCTest
import AudioKit
class AKPWMOscillatorTests: AKTestCase {
func testDefault() {
output = AKPWMOscillator()
AKTestMD5("32911323b68d88bd7d47ed97c1e953b4")
}
func testParametersSetOnInit() {
output = AKPWMOscillator(frequency: 1234,
amplitude: 0.5,
pulseWidth: 0.75,
detuningOffset: 1.234,
detuningMultiplier: 1.234)
AKTestMD5("c6900108acaf6ecba12409938715ea75")
}
func testParametersSetAfterInit() {
let oscillator = AKPWMOscillator()
oscillator.frequency = 1234
oscillator.amplitude = 0.5
oscillator.pulseWidth = 0.75
oscillator.detuningOffset = 1.234
oscillator.detuningMultiplier = 1.234
output = oscillator
AKTestMD5("c6900108acaf6ecba12409938715ea75")
}}
| mit | ca6a27a608b86542b64d8bf691939983 | 29.459459 | 59 | 0.581189 | 4.581301 | false | true | false | false |
ouch1985/IQuery | IQuery/utils/SessionBiz.swift | 1 | 1556 | //
// SessionBridge.swift
// IQuery
//
// Created by ouchuanyu on 15/12/27.
// Copyright © 2015年 ouchuanyu.com. All rights reserved.
//
import Foundation
class SessionBiz : JSInterface {
// 单例
class var sharedInstance : SessionBiz {
struct Static {
static var instance : SessionBiz?
static var token : dispatch_once_t = 0
}
dispatch_once(&Static.token) {
Static.instance = SessionBiz()
}
return Static.instance!
}
func call (service : String, action : String?, params : NSDictionary?, ctx : NSDictionary, callback : ((result : NSMutableDictionary?) -> ())) {
let iapp : IApp = ctx.objectForKey("iapp") as! IApp
let result = NSMutableDictionary()
// webview ready, 把app的setting信息传过去
if action == "ready" {
if let settings = IAppBiz.sharedInstance.getSettings(iapp) {
result.setValue(settings, forKey: "settings")
}
let infoDictionary = NSBundle.mainBundle().infoDictionary
let version : String = infoDictionary! ["CFBundleShortVersionString"] as! String
result.setValue(version, forKey: "version")
// 保存设置
} else if action == "setting" {
if let settings = params?.objectForKey("settings") as? String{
IAppBiz.sharedInstance.saveSettings(iapp, settings: settings)
}
}
callback(result: result)
}
} | mit | 48d09a015103d4b2a1505aec677b28af | 30.183673 | 148 | 0.578258 | 4.627273 | false | false | false | false |
wireapp/wire-ios | Wire-iOS/Sources/UserInterface/Conversation/Content/Cells/FileTransfer/FileMessageViewState.swift | 1 | 5494 | //
// Wire
// Copyright (C) 2016 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 WireCommonComponents
import WireDataModel
enum ProgressViewType {
case determ // stands for deterministic
case infinite
}
typealias FileMessageViewViewsState = (progressViewType: ProgressViewType?, playButtonIcon: StyleKitIcon?, playButtonBackgroundColor: UIColor?)
public enum FileMessageViewState {
case unavailable
case uploading /// only for sender
case uploaded
case downloading
case downloaded
case failedUpload /// only for sender
case cancelledUpload /// only for sender
case failedDownload
case obfuscated
// Value mapping from message consolidated state (transfer state, previewData, fileURL) to FileMessageViewState
static func fromConversationMessage(_ message: ZMConversationMessage) -> FileMessageViewState? {
guard let fileMessageData = message.fileMessageData, message.isFile else {
return .none
}
guard !message.isObfuscated else { return .obfuscated }
switch fileMessageData.transferState {
case .uploaded:
switch fileMessageData.downloadState {
case .downloaded: return .downloaded
case .downloading: return .downloading
default: return .uploaded
}
case .uploading:
if fileMessageData.fileURL != nil {
return .uploading
} else if fileMessageData.size == 0 {
return .downloaded
} else {
return .unavailable
}
case .uploadingFailed:
if fileMessageData.fileURL != nil {
return .failedUpload
} else {
return .unavailable
}
case .uploadingCancelled:
if fileMessageData.fileURL != nil {
return .cancelledUpload
} else {
return .unavailable
}
}
}
static let clearColor = UIColor.clear
static let normalColor = UIColor.black.withAlphaComponent(0.4)
static let failureColor = UIColor.red.withAlphaComponent(0.24)
typealias ViewsStateMapping = [FileMessageViewState: FileMessageViewViewsState]
/// Mapping of cell state to it's views state for media message:
/// # Cell state ======> #progressViewType
/// ======> | #playButtonIcon
/// ======> | | #playButtonBackgroundColor
static let viewsStateForCellStateForVideoMessage: ViewsStateMapping =
[.uploading: (.determ, .cross, normalColor),
.uploaded: (.none, .play, normalColor),
.downloading: (.determ, .cross, normalColor),
.downloaded: (.none, .play, normalColor),
.failedUpload: (.none, .redo, failureColor),
.cancelledUpload: (.none, .redo, normalColor),
.failedDownload: (.none, .redo, failureColor) ]
/// Mapping of cell state to it's views state for media message:
/// # Cell state ======> #progressViewType
/// ======> | #playButtonIcon
/// ======> | | #playButtonBackgroundColor
static let viewsStateForCellStateForAudioMessage: ViewsStateMapping =
[.uploading: (.determ, .cross, normalColor),
.uploaded: (.none, .play, normalColor),
.downloading: (.determ, .cross, normalColor),
.downloaded: (.none, .play, normalColor),
.failedUpload: (.none, .redo, failureColor),
.cancelledUpload: (.none, .redo, normalColor),
.failedDownload: (.none, .redo, failureColor) ]
/// Mapping of cell state to it's views state for normal file message:
/// # Cell state ======> #progressViewType
/// ======> | #actionButtonIcon
/// ======> | | #actionButtonBackgroundColor
static let viewsStateForCellStateForFileMessage: ViewsStateMapping =
[.uploading: (.determ, .cross, normalColor),
.downloading: (.determ, .cross, normalColor),
.downloaded: (.none, .none, clearColor),
.uploaded: (.none, .none, clearColor),
.failedUpload: (.none, .redo, failureColor),
.cancelledUpload: (.none, .redo, normalColor),
.failedDownload: (.none, .save, failureColor) ]
func viewsStateForVideo() -> FileMessageViewViewsState? {
return type(of: self).viewsStateForCellStateForVideoMessage[self]
}
func viewsStateForAudio() -> FileMessageViewViewsState? {
return type(of: self).viewsStateForCellStateForAudioMessage[self]
}
func viewsStateForFile() -> FileMessageViewViewsState? {
return type(of: self).viewsStateForCellStateForFileMessage[self]
}
}
| gpl-3.0 | 02e7033723fba7e0ab816fd9eba30626 | 37.152778 | 143 | 0.623407 | 5.096475 | false | false | false | false |
loudnate/LoopKit | LoopKitUI/View Controllers/SingleValueScheduleTableViewController.swift | 1 | 11383 | //
// SingleValueScheduleTableViewController.swift
// Naterade
//
// Created by Nathan Racklyeft on 2/13/16.
// Copyright © 2016 Nathan Racklyeft. All rights reserved.
//
import UIKit
import LoopKit
public enum RepeatingScheduleValueResult<T: RawRepresentable> {
case success(scheduleItems: [RepeatingScheduleValue<T>], timeZone: TimeZone)
case failure(Error)
}
public protocol SingleValueScheduleTableViewControllerSyncSource: class {
func syncScheduleValues(for viewController: SingleValueScheduleTableViewController, completion: @escaping (_ result: RepeatingScheduleValueResult<Double>) -> Void)
func syncButtonTitle(for viewController: SingleValueScheduleTableViewController) -> String
func syncButtonDetailText(for viewController: SingleValueScheduleTableViewController) -> String?
func singleValueScheduleTableViewControllerIsReadOnly(_ viewController: SingleValueScheduleTableViewController) -> Bool
}
open class SingleValueScheduleTableViewController: DailyValueScheduleTableViewController, RepeatingScheduleValueTableViewCellDelegate {
open override func viewDidLoad() {
super.viewDidLoad()
tableView.register(RepeatingScheduleValueTableViewCell.nib(), forCellReuseIdentifier: RepeatingScheduleValueTableViewCell.className)
tableView.register(TextButtonTableViewCell.self, forCellReuseIdentifier: TextButtonTableViewCell.className)
}
open override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
if syncSource == nil {
delegate?.dailyValueScheduleTableViewControllerWillFinishUpdating(self)
}
}
// MARK: - State
public var scheduleItems: [RepeatingScheduleValue<Double>] = []
override func addScheduleItem(_ sender: Any?) {
guard !isReadOnly && !isSyncInProgress else {
return
}
tableView.endEditing(false)
var startTime = TimeInterval(0)
var value = 0.0
if scheduleItems.count > 0, let cell = tableView.cellForRow(at: IndexPath(row: scheduleItems.count - 1, section: 0)) as? RepeatingScheduleValueTableViewCell {
let lastItem = scheduleItems.last!
let interval = cell.datePickerInterval
startTime = lastItem.startTime + interval
value = lastItem.value
if startTime >= TimeInterval(hours: 24) {
return
}
}
scheduleItems.append(
RepeatingScheduleValue(
startTime: min(TimeInterval(hours: 23.5), startTime),
value: value
)
)
super.addScheduleItem(sender)
}
override func insertableIndiciesByRemovingRow(_ row: Int, withInterval timeInterval: TimeInterval) -> [Bool] {
return insertableIndices(for: scheduleItems, removing: row, with: timeInterval)
}
var preferredValueFractionDigits: Int {
return 1
}
public weak var syncSource: SingleValueScheduleTableViewControllerSyncSource? {
didSet {
isReadOnly = syncSource?.singleValueScheduleTableViewControllerIsReadOnly(self) ?? false
if isViewLoaded {
tableView.reloadData()
}
}
}
private var isSyncInProgress = false {
didSet {
for cell in tableView.visibleCells {
switch cell {
case let cell as TextButtonTableViewCell:
cell.isEnabled = !isSyncInProgress
cell.isLoading = isSyncInProgress
case let cell as RepeatingScheduleValueTableViewCell:
cell.isReadOnly = isReadOnly || isSyncInProgress
default:
break
}
}
for item in navigationItem.rightBarButtonItems ?? [] {
item.isEnabled = !isSyncInProgress
}
navigationItem.hidesBackButton = isSyncInProgress
}
}
// MARK: - UITableViewDataSource
private enum Section: Int {
case schedule
case sync
}
open override func numberOfSections(in tableView: UITableView) -> Int {
if syncSource != nil {
return 2
}
return 1
}
open override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
switch Section(rawValue: section)! {
case .schedule:
return scheduleItems.count
case .sync:
return 1
}
}
open override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
switch Section(rawValue: indexPath.section)! {
case .schedule:
let cell = tableView.dequeueReusableCell(withIdentifier: RepeatingScheduleValueTableViewCell.className, for: indexPath) as! RepeatingScheduleValueTableViewCell
let item = scheduleItems[indexPath.row]
let interval = cell.datePickerInterval
cell.timeZone = timeZone
cell.date = midnight.addingTimeInterval(item.startTime)
cell.valueNumberFormatter.minimumFractionDigits = preferredValueFractionDigits
cell.value = item.value
cell.unitString = unitDisplayString
cell.isReadOnly = isReadOnly || isSyncInProgress
cell.delegate = self
if indexPath.row > 0 {
let lastItem = scheduleItems[indexPath.row - 1]
cell.datePicker.minimumDate = midnight.addingTimeInterval(lastItem.startTime).addingTimeInterval(interval)
}
if indexPath.row < scheduleItems.endIndex - 1 {
let nextItem = scheduleItems[indexPath.row + 1]
cell.datePicker.maximumDate = midnight.addingTimeInterval(nextItem.startTime).addingTimeInterval(-interval)
} else {
cell.datePicker.maximumDate = midnight.addingTimeInterval(TimeInterval(hours: 24) - interval)
}
return cell
case .sync:
let cell = tableView.dequeueReusableCell(withIdentifier: TextButtonTableViewCell.className, for: indexPath) as! TextButtonTableViewCell
cell.textLabel?.text = syncSource?.syncButtonTitle(for: self)
cell.isEnabled = !isSyncInProgress
cell.isLoading = isSyncInProgress
return cell
}
}
open override func tableView(_ tableView: UITableView, titleForFooterInSection section: Int) -> String? {
switch Section(rawValue: section)! {
case .schedule:
return nil
case .sync:
return syncSource?.syncButtonDetailText(for: self)
}
}
open override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCell.EditingStyle, forRowAt indexPath: IndexPath) {
if editingStyle == .delete {
scheduleItems.remove(at: indexPath.row)
super.tableView(tableView, commit: editingStyle, forRowAt: indexPath)
}
}
open override func tableView(_ tableView: UITableView, moveRowAt sourceIndexPath: IndexPath, to destinationIndexPath: IndexPath) {
if sourceIndexPath != destinationIndexPath {
let item = scheduleItems.remove(at: sourceIndexPath.row)
scheduleItems.insert(item, at: destinationIndexPath.row)
guard destinationIndexPath.row > 0, let cell = tableView.cellForRow(at: destinationIndexPath) as? RepeatingScheduleValueTableViewCell else {
return
}
let interval = cell.datePickerInterval
let startTime = scheduleItems[destinationIndexPath.row - 1].startTime + interval
scheduleItems[destinationIndexPath.row] = RepeatingScheduleValue(startTime: startTime, value: scheduleItems[destinationIndexPath.row].value)
// Since the valid date ranges of neighboring cells are affected, the lazy solution is to just reload the entire table view
DispatchQueue.main.async {
tableView.reloadData()
}
}
}
// MARK: - UITableViewDelegate
open override func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
return super.tableView(tableView, canEditRowAt: indexPath) && !isSyncInProgress
}
open override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
super.tableView(tableView, didSelectRowAt: indexPath)
switch Section(rawValue: indexPath.section)! {
case .schedule:
break
case .sync:
if let syncSource = syncSource, !isSyncInProgress {
isSyncInProgress = true
syncSource.syncScheduleValues(for: self) { (result) in
DispatchQueue.main.async {
switch result {
case .success(let items, let timeZone):
self.scheduleItems = items
self.timeZone = timeZone
self.tableView.reloadSections([Section.schedule.rawValue], with: .fade)
self.isSyncInProgress = false
self.delegate?.dailyValueScheduleTableViewControllerWillFinishUpdating(self)
case .failure(let error):
self.present(UIAlertController(with: error), animated: true) {
self.isSyncInProgress = false
}
}
}
}
}
}
}
open override func tableView(_ tableView: UITableView, targetIndexPathForMoveFromRowAt sourceIndexPath: IndexPath, toProposedIndexPath proposedDestinationIndexPath: IndexPath) -> IndexPath {
guard sourceIndexPath != proposedDestinationIndexPath, let cell = tableView.cellForRow(at: sourceIndexPath) as? RepeatingScheduleValueTableViewCell else {
return proposedDestinationIndexPath
}
let interval = cell.datePickerInterval
let indices = insertableIndices(for: scheduleItems, removing: sourceIndexPath.row, with: interval)
let closestDestinationRow = indices.insertableIndex(closestTo: proposedDestinationIndexPath.row, from: sourceIndexPath.row)
return IndexPath(row: closestDestinationRow, section: proposedDestinationIndexPath.section)
}
// MARK: - RepeatingScheduleValueTableViewCellDelegate
override public func datePickerTableViewCellDidUpdateDate(_ cell: DatePickerTableViewCell) {
if let indexPath = tableView.indexPath(for: cell) {
let currentItem = scheduleItems[indexPath.row]
scheduleItems[indexPath.row] = RepeatingScheduleValue(
startTime: cell.date.timeIntervalSince(midnight),
value: currentItem.value
)
}
super.datePickerTableViewCellDidUpdateDate(cell)
}
func repeatingScheduleValueTableViewCellDidUpdateValue(_ cell: RepeatingScheduleValueTableViewCell) {
if let indexPath = tableView.indexPath(for: cell) {
let currentItem = scheduleItems[indexPath.row]
scheduleItems[indexPath.row] = RepeatingScheduleValue(startTime: currentItem.startTime, value: cell.value)
}
}
}
| mit | 0b2197550b8995dae638b0514c04ff37 | 36.94 | 194 | 0.651643 | 6.15576 | false | false | false | false |
hakota/Sageru | Sageru-Sample/ViewController+setMenuAndTitle.swift | 1 | 835 | //
// ViewController.swift
// Sageru
//
// Created by ArakiKenta on 2016/11/06.
// Copyright © 2016年 Araki Kenta. All rights reserved.
//
import UIKit
extension UIViewController {
func setMenuAndTitle(titleText: String, color: UIColor, image: UIImage = UIImage(named: "hamburger")!) {
let item = UIBarButtonItem(
image: image,
style: .plain,
target: navigationController,
action: #selector(NavigationController.showMenu)
)
item.tintColor = color
self.navigationItem.rightBarButtonItem = item
let title = UILabel()
title.font = UIFont(name: "HelveticaNeue-Light", size: 16)!
title.textColor = color
title.text = titleText
title.sizeToFit()
self.navigationItem.titleView = title
}
}
| mit | c0cebf649d42c804a5d25d667aa160c5 | 27.689655 | 108 | 0.623798 | 4.473118 | false | false | false | false |
ByteriX/BxInputController | BxInputController/Sources/Rows/Pictures/Item/BxInputPictureLibraryItem.swift | 1 | 2882 | /**
* @file BxInputPictureLibraryItem.swift
* @namespace BxInputController
*
* @details Implementation picture item as PHAsset owner. It may be image from Library
* @date 06.02.2017
* @author Sergey Balalaev
*
* @version last in https://github.com/ByteriX/BxInputController.git
* @copyright The MIT License (MIT) https://opensource.org/licenses/MIT
* Copyright (c) 2017 ByteriX. See http://byterix.com
*/
import UIKit
import AssetsLibrary
import Photos
/// Implementation picture item as PHAsset owner. It may be image from Library
public class BxInputPictureLibraryItem : BxInputPictureItem
{
/// storge of icon
internal var asset: PHAsset
/// From BxInputPictureItem icon size
public var iconSize: CGSize
/// From BxInputPictureItem icon data
public var icon: UIImage {
get { return BxInputPictureLibraryItem.imageFromPHAsset(asset, size: iconSize)! }
}
public init (asset: PHAsset, iconSize: CGSize){
self.asset = asset
self.iconSize = iconSize
}
public init? (asset: ALAsset, iconSize: CGSize){
guard let phAsset = BxInputPictureLibraryItem.converterALAssetToPHAsset(asset) else {
return nil
}
self.asset = phAsset
self.iconSize = iconSize
}
public static func converterALAssetToPHAsset(_ alAsset: ALAsset) -> PHAsset?
{
let fetchOptions = PHFetchOptions()
fetchOptions.includeHiddenAssets = true
let url = alAsset.value(forProperty: ALAssetPropertyAssetURL) as! URL
let result = PHAsset.fetchAssets(withALAssetURLs: [url], options: fetchOptions)
return result.firstObject
}
public static func imageFromPHAsset(_ asset: PHAsset, size: CGSize) -> UIImage? {
var image: UIImage? = nil
let options = PHImageRequestOptions()
options.resizeMode = .exact
options.deliveryMode = .highQualityFormat
options.isSynchronous = true
let imageSize = CGSize(width: size.width * UIScreen.main.scale, height: size.height * UIScreen.main.scale)
PHImageManager.default().requestImage(for: asset, targetSize: imageSize, contentMode: .aspectFit, options: options) { (result, info) in
image = result
}
return image
}
}
/// operator return is equal two BxInputPictureLibraryItem
func == (left: BxInputPictureLibraryItem, right: BxInputPictureLibraryItem) -> Bool {
let result = (left === right)
if !result {
return left.asset.localIdentifier == right.asset.localIdentifier
}
return result
}
/// operator return is equal BxInputPictureLibraryItem and PHAsset
func == (left: BxInputPictureLibraryItem, right: PHAsset) -> Bool {
let result = (left.asset === right)
if !result {
return left.asset.localIdentifier == right.localIdentifier
}
return result
}
| mit | 4d25e2dc8b9a06c1be46664e802b65fb | 33.722892 | 143 | 0.684941 | 4.795341 | false | false | false | false |
SocialObjects-Software/AMSlideMenu | AMSlideMenu/Extensions/UIViewController+AMExtension.swift | 1 | 2876 | //
// UIViewController+AMExtension.swift
// AMSlideMenu
//
// The MIT License (MIT)
//
// Created by : arturdev
// Copyright (c) 2020 arturdev. All rights reserved.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of
// this software and associated documentation files (the "Software"), to deal in
// the Software without restriction, including without limitation the rights to
// use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
// the Software, and to permit persons to whom the Software is furnished to do so,
// subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
// FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
// COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
// IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
// CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE
import UIKit
fileprivate struct AssociationKeys {
static var slideMenuMainVCKey = "slideMenuMainVCKey"
}
public extension UIViewController {
weak var slideMenuMainVC: AMSlideMenuMainViewController? {
get {
let vc = objc_getAssociatedObject(self, &AssociationKeys.slideMenuMainVCKey) as? AMSlideMenuMainViewController
if vc == nil && parent != nil {
return parent?.slideMenuMainVC
}
return vc
}
set {
objc_setAssociatedObject(self, &AssociationKeys.slideMenuMainVCKey, newValue, .OBJC_ASSOCIATION_ASSIGN)
}
}
@objc func showLeftMenu(animated: Bool = true, completion handler: (()->Void)? = nil) {
guard !(self is AMSlideMenuMainViewController) else { return }
slideMenuMainVC?.showLeftMenu(animated: animated, completion: handler)
}
@objc func hideLeftMenu(animated: Bool = true, completion handler: (()->Void)? = nil) {
guard !(self is AMSlideMenuMainViewController) else { return }
slideMenuMainVC?.hideLeftMenu(animated: animated, completion: handler)
}
@objc func showRightMenu(animated: Bool = true, completion handler: (()->Void)? = nil) {
guard !(self is AMSlideMenuMainViewController) else { return }
slideMenuMainVC?.showRightMenu(animated: animated, completion: handler)
}
@objc func hideRightMenu(animated: Bool = true, completion handler: (()->Void)? = nil) {
guard !(self is AMSlideMenuMainViewController) else { return }
slideMenuMainVC?.hideRightMenu(animated: animated, completion: handler)
}
}
| mit | 86340aaf7a3b0eaa14b1d42f0570b569 | 41.925373 | 122 | 0.708275 | 4.809365 | false | false | false | false |
codefellows/sea-c40-iOS | Sample Code/MyPokemonDemo.playground/Contents.swift | 1 | 1273 | //: Playground - noun: a place where people can play
import UIKit
class Car {
var make = "ford"
var model = "mustang"
var year = "1998"
}
let myBFF = "Russell Wilson"
//myBFF = "Someone else"
var myFavoriteFood = "Pizza"
myFavoriteFood = "Tacos"
let myNumber = 21
var myOtherNumber = 34.34534534
class Pokemon {
var level = 1
var health = 100
var type = "None"
func levelUp() {
self.level++
}
init (startingLevel : Int) {
self.level = startingLevel
//level = startingLevel
}
}
class Bulbasaur : Pokemon {
func grassAttack () {
}
}
let myBulby = Bulbasaur(startingLevel: 1)
class Squirtle : Pokemon {
func bubbleWithMultiplier(multiplier : Int,enemyType : String) -> Int {
if self.level < 5 {
return 20
} else {
return 30
}
}
}
class WarTurtle : Squirtle {
func waterBlast() {
}
}
let myWarTurtle = WarTurtle(startingLevel: 30)
myWarTurtle.bubbleWithMultiplier(20, enemyType: "Fire")
myWarTurtle.waterBlast()
let mySquirmy = Squirtle(startingLevel: 20)
let myOtherSquirmy = Squirtle(startingLevel: 1)
let mySuperSquirtle = Squirtle(startingLevel: 100)
let totalDamage = mySquirmy.bubbleWithMultiplier(2, enemyType:"Fire")
func doSomething() {
}
doSomething()
| mit | 30a3246a37b8d212306c4533bde79948 | 14.154762 | 73 | 0.6685 | 3.422043 | false | false | false | false |
martijnwalraven/meteor-ios | Examples/Todos/Todos/AppDelegate.swift | 2 | 2547 | // Copyright (c) 2014-2015 Martijn Walraven
//
// 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 CoreData
import Meteor
let Meteor = METCoreDataDDPClient(serverURL: NSURL(string: "ws://localhost:3000/websocket")!)
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate, UISplitViewControllerDelegate {
var window: UIWindow?
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
Meteor.connect()
let splitViewController = self.window!.rootViewController as! UISplitViewController
splitViewController.preferredDisplayMode = .AllVisible
splitViewController.delegate = self
let masterNavigationController = splitViewController.viewControllers[0] as! UINavigationController
let listViewController = masterNavigationController.topViewController as! ListsViewController
listViewController.managedObjectContext = Meteor.mainQueueManagedObjectContext
return true
}
// MARK: - UISplitViewControllerDelegate
func splitViewController(splitViewController: UISplitViewController, collapseSecondaryViewController secondaryViewController:UIViewController, ontoPrimaryViewController primaryViewController:UIViewController) -> Bool {
if let todosViewController = (secondaryViewController as? UINavigationController)?.topViewController as? TodosViewController {
if todosViewController.listID == nil {
return true
}
}
return false
}
}
| mit | 49e3a97b887bf66208819b75e5551a6e | 44.482143 | 220 | 0.783667 | 5.561135 | false | false | false | false |
breadwallet/breadwallet | BreadWallet/BRGeoLocationPlugin.swift | 5 | 13094 | //
// BRGeoLocationPlugin.swift
// BreadWallet
//
// Created by Samuel Sutch on 2/8/16.
// Copyright (c) 2016 breadwallet LLC
//
// 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 CoreLocation
@available(iOS 8.0, *)
class BRGeoLocationDelegate: NSObject, CLLocationManagerDelegate {
var manager: CLLocationManager? = nil
var response: BRHTTPResponse
var remove: (() -> Void)? = nil
var one = false
var nResponses = 0
// on versions ios < 9.0 we don't have the energy-efficient/convenient requestLocation() method
// so after fetching a good location we should terminate location updates
var shouldCancelUpdatingAfterReceivingLocation = false
init(response: BRHTTPResponse) {
self.response = response
super.init()
DispatchQueue.main.sync { () -> Void in
self.manager = CLLocationManager()
self.manager?.delegate = self
}
}
func getOne() {
one = true
DispatchQueue.main.sync { () -> Void in
self.manager?.desiredAccuracy = kCLLocationAccuracyHundredMeters
if #available(iOS 9.0, *) {
self.manager?.requestLocation()
} else {
// Fallback on earlier versions
self.manager?.startUpdatingLocation()
self.shouldCancelUpdatingAfterReceivingLocation = true
}
}
}
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
if one && nResponses > 0 { return }
var j = [String: Any]()
let l = locations.last!
if (shouldCancelUpdatingAfterReceivingLocation
&& !(l.horizontalAccuracy <= kCLLocationAccuracyHundredMeters
&& l.verticalAccuracy <= kCLLocationAccuracyHundredMeters)) {
// return if location is not the requested accuracy of 100m
return
}
nResponses += 1
if (shouldCancelUpdatingAfterReceivingLocation) {
self.manager?.stopUpdatingLocation()
}
j["timestamp"] = l.timestamp.description as AnyObject?
j["coordinate"] = ["latitude": l.coordinate.latitude, "longitude": l.coordinate.longitude]
j["altitude"] = l.altitude as AnyObject?
j["horizontal_accuracy"] = l.horizontalAccuracy as AnyObject?
j["description"] = l.description as AnyObject?
response.request.queue.async {
self.response.provide(200, json: j)
self.remove?()
}
}
func locationManager(_ manager: CLLocationManager, didFailWithError error: Error) {
var j = [String: AnyObject]()
j["error"] = error.localizedDescription as AnyObject?
response.request.queue.async {
self.response.provide(500, json: j)
self.remove?()
}
}
}
@available(iOS 8.0, *)
@objc open class BRGeoLocationPlugin: NSObject, BRHTTPRouterPlugin, CLLocationManagerDelegate, BRWebSocketClient {
lazy var manager = CLLocationManager()
var outstanding = [BRGeoLocationDelegate]()
var sockets = [String: BRWebSocket]()
override init() {
super.init()
self.manager.delegate = self
}
open func locationManager(_ manager: CLLocationManager, didChangeAuthorization status: CLAuthorizationStatus) {
print("new authorization status: \(status)")
}
open func hook(_ router: BRHTTPRouter) {
// GET /_permissions/geo
//
// Call this method to retrieve the current permission status for geolocation.
// The returned JSON dictionary contains the following keys:
//
// "status" = "denied" | "restricted | "undetermined" | "inuse" | "always"
// "user_queried" = true | false
// "location_enabled" = true | false
//
// The status correspond to those found in the apple CLLocation documentation: http://apple.co/1O0lHFv
//
// "user_queried" indicates whether or not the user has already been asked for geolocation
// "location_enabled" indicates whether or not the user has geo location enabled on their phone
router.get("/_permissions/geo") { (request, match) -> BRHTTPResponse in
let userDefaults = UserDefaults.standard
let authzStatus = CLLocationManager.authorizationStatus()
var retJson = [String: Any]()
switch authzStatus {
case .denied:
retJson["status"] = "denied"
case .restricted:
retJson["status"] = "restricted"
case .notDetermined:
retJson["status"] = "undetermined"
case .authorizedWhenInUse:
retJson["status"] = "inuse"
case .authorizedAlways:
retJson["status"] = "always"
}
retJson["user_queried"] = userDefaults.bool(forKey: "geo_permission_was_queried")
retJson["location_enabled"] = CLLocationManager.locationServicesEnabled()
return try BRHTTPResponse(request: request, code: 200, json: retJson as AnyObject)
}
// POST /_permissions/geo
//
// Call this method to request the geo permission from the user.
// The request body should be a JSON dictionary containing a single key, "style"
// the value of which should be either "inuse" or "always" - these correspond to the
// two ways the user can authorize geo access to the app. "inuse" will request
// geo availability to the app when the app is foregrounded, and "always" will request
// full time geo availability to the app
router.post("/_permissions/geo") { (request, match) -> BRHTTPResponse in
if let j = request.json?(), let dict = j as? NSDictionary, let style = dict["style"] as? String {
switch style {
case "inuse": self.manager.requestWhenInUseAuthorization()
case "always": self.manager.requestAlwaysAuthorization()
default: return BRHTTPResponse(request: request, code: 400)
}
UserDefaults.standard.set(true, forKey: "geo_permission_was_queried")
return BRHTTPResponse(request: request, code: 204)
}
return BRHTTPResponse(request: request, code: 400)
}
// GET /_geo
//
// Calling this method will query CoreLocation for a location object. The returned value may not be returned
// very quick (sometimes getting a geo lock takes some time) so be sure to display to the user some status
// while waiting for a response.
//
// Response Object:
//
// "coordinates" = { "latitude": double, "longitude": double }
// "altitude" = double
// "description" = "a string representation of this object"
// "timestamp" = "ISO-8601 timestamp of when this location was generated"
// "horizontal_accuracy" = double
router.get("/_geo") { (request, match) -> BRHTTPResponse in
if let authzErr = self.getAuthorizationError() {
return try BRHTTPResponse(request: request, code: 400, json: authzErr)
}
let resp = BRHTTPResponse(async: request)
let del = BRGeoLocationDelegate(response: resp)
del.remove = {
objc_sync_enter(self)
if let idx = self.outstanding.index(where: { (d) -> Bool in return d == del }) {
self.outstanding.remove(at: idx)
}
objc_sync_exit(self)
}
objc_sync_enter(self)
self.outstanding.append(del)
objc_sync_exit(self)
print("outstanding delegates: \(self.outstanding)")
// get location only once
del.getOne()
return resp
}
// GET /_geosocket
//
// This opens up a websocket to the location manager. It will return a new location every so often (but with no
// predetermined interval) with the same exact structure that is sent via the GET /_geo call.
//
// It will start the location manager when there is at least one client connected and stop the location manager
// when the last client disconnects.
router.websocket("/_geosocket", client: self)
}
func getAuthorizationError() -> [String: Any]? {
var retJson = [String: Any]()
if !CLLocationManager.locationServicesEnabled() {
retJson["error"] = NSLocalizedString("Location services are disabled", comment: "")
return retJson
}
let authzStatus = CLLocationManager.authorizationStatus()
if authzStatus != .authorizedWhenInUse && authzStatus != .authorizedAlways {
retJson["error"] = NSLocalizedString("Location services are not authorized", comment: "")
return retJson
}
return nil
}
var lastLocation: [String: Any]?
var isUpdatingSockets = false
// location manager for continuous websocket clients
public func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
var j = [String: Any]()
let l = locations.last!
j["timestamp"] = l.timestamp.description as AnyObject?
j["coordinate"] = ["latitude": l.coordinate.latitude, "longitude": l.coordinate.longitude]
j["altitude"] = l.altitude as AnyObject?
j["horizontal_accuracy"] = l.horizontalAccuracy as AnyObject?
j["description"] = l.description as AnyObject?
lastLocation = j
sendToAllSockets(data: j)
}
public func locationManager(_ manager: CLLocationManager, didFailWithError error: Error) {
var j = [String: Any]()
j["error"] = error.localizedDescription as AnyObject?
sendToAllSockets(data: j)
}
func sendTo(socket: BRWebSocket, data: [String: Any]) {
do {
let j = try JSONSerialization.data(withJSONObject: data, options: [])
if let s = String(data: j, encoding: .utf8) {
socket.request.queue.async {
socket.send(s)
}
}
} catch let e {
print("LOCATION SOCKET FAILED ENCODE JSON: \(e)")
}
}
func sendToAllSockets(data: [String: Any]) {
for (_, s) in sockets {
sendTo(socket: s, data: data)
}
}
public func socketDidConnect(_ socket: BRWebSocket) {
print("LOCATION SOCKET CONNECT \(socket.id)")
sockets[socket.id] = socket
// on first socket connect to the manager
if !isUpdatingSockets {
// if not authorized yet send an error
if let authzErr = getAuthorizationError() {
sendTo(socket: socket, data: authzErr)
return
}
// begin updating location
isUpdatingSockets = true
DispatchQueue.main.sync { () -> Void in
self.manager.delegate = self
self.manager.startUpdatingLocation()
}
}
if let loc = lastLocation {
sendTo(socket: socket, data: loc)
}
}
public func socketDidDisconnect(_ socket: BRWebSocket) {
print("LOCATION SOCKET DISCONNECT \(socket.id)")
sockets.removeValue(forKey: socket.id)
// on last socket disconnect stop updating location
if sockets.count == 0 {
isUpdatingSockets = false
lastLocation = nil
self.manager.stopUpdatingLocation()
}
}
public func socket(_ socket: BRWebSocket, didReceiveText text: String) {
print("LOCATION SOCKET RECV \(text)")
// this is unused here but just in case just echo received text back
socket.send(text)
}
}
| mit | b3fb59ecd6913ac8a4d54e0bc2dcdde0 | 41.102894 | 119 | 0.609821 | 5.038092 | false | false | false | false |
PureSwift/GATT | Sources/GATT/CharacteristicProperty.swift | 1 | 1475 | //
// CharacteristicProperty.swift
//
//
// Created by Alsey Coleman Miller on 10/23/20.
//
import Foundation
@_exported import Bluetooth
#if canImport(BluetoothGATT)
@_exported import BluetoothGATT
public typealias CharacteristicProperty = GATTCharacteristicProperty
#else
/// GATT Characteristic Properties Bitfield values
public enum CharacteristicProperty: UInt8, BitMaskOption {
case broadcast = 0x01
case read = 0x02
case writeWithoutResponse = 0x04
case write = 0x08
case notify = 0x10
case indicate = 0x20
/// Characteristic supports write with signature
case signedWrite = 0x40 // BT_GATT_CHRC_PROP_AUTH
case extendedProperties = 0x80
}
// MARK: CustomStringConvertible
extension CharacteristicProperty: CustomStringConvertible {
public var description: String {
switch self {
case .broadcast: return "Broadcast"
case .read: return "Read"
case .write: return "Write"
case .writeWithoutResponse: return "Write without Response"
case .notify: return "Notify"
case .indicate: return "Indicate"
case .signedWrite: return "Signed Write"
case .extendedProperties: return "Extended Properties"
}
}
}
#endif
| mit | 91bf437f4358000c0ad0d5086796372d | 29.729167 | 71 | 0.595254 | 5.068729 | false | false | false | false |
JValderramaN/TestPushNotification | TestPushNotification/Source/AppDelegate.swift | 1 | 3502 | //
// AppDelegate.swift
// TestPushNotification
//
// Created by Momentum Lab 4 on 3/22/17.
// Copyright © 2017 JoseValderrama. All rights reserved.
//
import UIKit
import UserNotifications
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate, UNUserNotificationCenterDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
registerForPushNotifications()
return true
}
}
// MARK: - Push Notifications
extension AppDelegate{
func registerForPushNotifications() {
if #available(iOS 10.0, *){
UNUserNotificationCenter.current().delegate = self
UNUserNotificationCenter.current().requestAuthorization(options: [.badge, .sound, .alert], completionHandler: {(granted, error) in
if (granted)
{
UIApplication.shared.registerForRemoteNotifications()
}
else{
}
})
}else{ //If user is not on iOS 10 use the old methods we've been using
let type: UIUserNotificationType = [.badge, .alert, .sound]
let setting = UIUserNotificationSettings(types: type, categories: nil)
UIApplication.shared.registerUserNotificationSettings(setting)
UIApplication.shared.registerForRemoteNotifications()
}
}
func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data){
let token = String(format: "%@", deviceToken as CVarArg)
print("didRegisterForRemoteNotificationsWithDeviceToken", token)
}
func application(_ application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: Error) {
let message = "didFailToRegisterForRemoteNotificationsWithError: " + error.localizedDescription
print(message)
}
func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable : Any], fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) {
print("didReceiveRemoteNotification fetchCompletionHandler", userInfo)
manageAppBagde()
updateDetail(with: userInfo, completionHandler)
}
func manageAppBagde(){
let defaults = UserDefaults.standard
let newAppBagdeCount = defaults.integer(forKey: kAppBagde) + 1
defaults.set(newAppBagdeCount, forKey: kAppBagde)
defaults.synchronize()
UIApplication.shared.applicationIconBadgeNumber = newAppBagdeCount
}
func updateDetail(with userInfo: [AnyHashable : Any], _ completionHandler: @escaping (UIBackgroundFetchResult) -> Void){
if let data = userInfo["data"] as? [AnyHashable : Any], let value = data["value"] as? String{
if value == kAlamofire{
NetworkManager.shared.alamofireTest(callback: { (apps) in
print("Alamofire Test response in callback:", apps)
completionHandler(UIBackgroundFetchResult.newData)
})
}else{
UserDefaults.standard.updateUserDefault(additionalValue: value)
completionHandler(UIBackgroundFetchResult.newData)
}
}else{
completionHandler(UIBackgroundFetchResult.noData)
}
}
}
| mit | 08eff624ad3203a91ce0c42091f1aa45 | 38.337079 | 199 | 0.665239 | 6.046632 | false | false | false | false |
wwczwt/sdfad | PageController/MenuBar.swift | 1 | 5347 | //
// MenuBar.swift
// PageController
//
// Created by Hirohisa Kawasaki on 6/25/15.
// Copyright (c) 2015 Hirohisa Kawasaki. All rights reserved.
//
import UIKit
public class MenuBar: UIView {
weak var controller: PageController?
public var durationForAnimation: NSTimeInterval = 0.2
public var items: [String] = [] {
didSet {
reloadData()
}
}
var sizes: [CGSize] = []
private var menuCellClass: MenuCell.Type = MenuCell.self
public func registerClass(cellClass: MenuCell.Type) {
menuCellClass = cellClass
}
public var selectedIndex: Int {
if let view = scrollView.viewForCurrentPage() as? MenuCell {
return view.index
}
return -1
}
public override var frame: CGRect {
didSet {
reloadData()
}
}
public override init(frame: CGRect) {
super.init(frame: frame)
configure()
}
public required init(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
configure()
}
public let scrollView = ContainerView(frame: CGRectZero)
private var animating = false
}
public extension MenuBar {
override func hitTest(point: CGPoint, withEvent event: UIEvent?) -> UIView? {
if pointInside(point, withEvent: event) {
return scrollView
}
return super.hitTest(point, withEvent: event)
}
}
public extension MenuBar {
func reloadData() {
if items.count == 0 || frame == CGRectZero {
return
}
scrollView.frame = CGRect(origin: CGPointZero, size: CGSize(width: frame.width / 3, height: frame.height))
scrollView.center = CGPoint(x: frame.width / 2, y: frame.height / 2)
scrollView.contentSize = CGSize(width: frame.width, height: frame.height)
sizes = measureCells()
scrollView.reloadData()
controller?.reloadPages(AtIndex: 0)
}
func measureCells() -> [CGSize] {
return map(enumerate(items)) { index, _ -> CGSize in
let cell = self.createMenuCell(AtIndex: index)
return cell.frame.size
}
}
func createMenuCell(AtIndex index: Int) -> MenuCell {
let cell = menuCellClass(frame: frame)
cell.titleLabel.text = items[index]
cell.index = index
cell.updateData()
cell.updateConstraints()
cell.setNeedsLayout()
cell.layoutIfNeeded()
let size = cell.systemLayoutSizeFittingSize(UILayoutFittingCompressedSize, withHorizontalFittingPriority: 50, verticalFittingPriority: 50)
// => systemLayoutSizeFittingSize(UILayoutFittingCompressedSize)
cell.frame = CGRect(x: 0, y: 0, width: size.width, height: frame.height)
return cell
}
func move(#from: Int, until to: Int) {
if to - from == items.count - 1 {
moveMinus(from: from, until: to)
} else if from - to == items.count - 1 {
movePlus(from: from, until: to)
} else if from > to {
moveMinus(from: from, until: to)
} else if from < to {
movePlus(from: from, until: to)
}
}
func revert(to: Int) {
if let view = scrollView.viewForCurrentPage() as? MenuCell {
if view.index != to {
move(from: view.index, until: to)
}
}
}
private func moveMinus(#from: Int, until to: Int) {
if let view = scrollView.viewForCurrentPage() as? MenuCell {
if view.index == to {
return
}
if animating {
return
}
animating = true
let distance = distanceBetweenCells(from: from, to: to, asc: false)
let diff = (sizes[from].width - sizes[to].width) / 2
let x = scrollView.contentOffset.x - distance - diff
let contentOffset = CGPoint(x: x, y: 0)
UIView.animateWithDuration(durationForAnimation, animations: {
self.scrollView.contentOffset = contentOffset
}, completion: { _ in
self.completion()
})
}
}
private func movePlus(#from: Int, until to: Int) {
if let view = scrollView.viewForCurrentPage() as? MenuCell {
if view.index == to {
return
}
if animating {
return
}
animating = true
let distance = distanceBetweenCells(from: from, to: to, asc: true)
let diff = (sizes[from].width - sizes[to].width) / 2
let x = scrollView.contentOffset.x + distance + diff
let contentOffset = CGPoint(x: x, y: 0)
UIView.animateWithDuration(durationForAnimation, animations: {
self.scrollView.contentOffset = contentOffset
}, completion: { _ in
self.completion()
})
}
}
private func completion() {
animating = false
scrollView.updateSubviews()
}
func contentDidChangePage(AtIndex index: Int) {
controller?.switchPage(AtIndex: index)
}
}
extension MenuBar {
func configure() {
clipsToBounds = true
scrollView.bar = self
addSubview(scrollView)
}
} | mit | 7e6fcccfeef20323394c901e985f85c2 | 26.147208 | 146 | 0.569852 | 4.68624 | false | false | false | false |
iscriptology/swamp | Example/Pods/CryptoSwift/Sources/CryptoSwift/Int+Extension.swift | 2 | 3190 | //
// IntExtension.swift
// CryptoSwift
//
// Created by Marcin Krzyzanowski on 12/08/14.
// Copyright (C) 2014 Marcin Krzyżanowski <[email protected]>
// This software is provided 'as-is', without any express or implied warranty.
//
// In no event will the authors be held liable for any damages arising from the use of this software.
//
// Permission is granted to anyone to use this software for any purpose,including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions:
//
// - The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation is required.
// - Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software.
// - This notice may not be removed or altered from any source or binary distribution.
#if os(Linux)
import Glibc
#else
import Darwin
#endif
/* array of bits */
extension Int {
init(bits: [Bit]) {
self.init(bitPattern: integerFrom(bits) as UInt)
}
}
/* array of bytes */
extension Int {
/** Int with collection of bytes (little-endian) */
init<T: Collection>(bytes: T) where T.Iterator.Element == UInt8, T.Index == Int {
self = bytes.toInteger()
}
/** Array of bytes with optional padding (little-endian) */
func bytes(totalBytes: Int = MemoryLayout<Int>.size) -> Array<UInt8> {
return arrayOfBytes(value: self, length: totalBytes)
}
}
/** Shift bits */
extension Int {
/** Shift bits to the left. All bits are shifted (including sign bit) */
mutating func shiftLeft(by count: Int) {
self = CryptoSwift.shiftLeft(self, by: count) //FIXME: count:
}
/** Shift bits to the right. All bits are shifted (including sign bit) */
mutating func shiftRight(by count: Int) {
if (self == 0) {
return
}
let bitsCount = MemoryLayout<Int>.size * 8
if (count >= bitsCount) {
return
}
let maxBitsForValue = Int(floor(log2(Double(self)) + 1))
let shiftCount = Swift.min(count, maxBitsForValue - 1)
var shiftedValue:Int = 0;
for bitIdx in 0..<bitsCount {
// if bit is set then copy to result and shift left 1
let bit = 1 << bitIdx
if ((self & bit) == bit) {
shiftedValue = shiftedValue | (bit >> shiftCount)
}
}
self = Int(shiftedValue)
}
}
// Left operator
/** shift left and assign with bits truncation */
func &<<= (lhs: inout Int, rhs: Int) {
lhs.shiftLeft(by: rhs)
}
/** shift left with bits truncation */
func &<< (lhs: Int, rhs: Int) -> Int {
var l = lhs;
l.shiftLeft(by: rhs)
return l
}
// Right operator
/** shift right and assign with bits truncation */
func &>>= (lhs: inout Int, rhs: Int) {
lhs.shiftRight(by: rhs)
}
/** shift right and assign with bits truncation */
func &>> (lhs: Int, rhs: Int) -> Int {
var l = lhs;
l.shiftRight(by: rhs)
return l
}
| mit | 2e41bee607c786e6df799907790c5522 | 28.803738 | 217 | 0.632487 | 3.976309 | false | false | false | false |
ahoppen/swift | SwiftCompilerSources/Sources/Optimizer/DataStructures/Stack.swift | 5 | 3972 | //===--- Stack.swift - defines the Stack data structure -------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2022 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
//
//===----------------------------------------------------------------------===//
import OptimizerBridging
import SIL
/// A very efficient implementation of a stack, which can also be iterated over.
///
/// A Stack is the best choice for things like worklists, etc., if no random
/// access is needed.
/// Compared to Array, it does not require any memory allocations, because it
/// uses a recycling bump pointer allocator for allocating the slabs.
/// All operations have (almost) zero cost.
///
/// This type should be a move-only type, but unfortunately we don't have move-only
/// types yet. Therefore it's needed to call `deinitialize()` explicitly to
/// destruct this data structure, e.g. in a `defer {}` block.
struct Stack<Element> : CollectionLikeSequence {
private let context: PassContext
private var firstSlab = BridgedSlab(data: nil)
private var lastSlab = BridgedSlab(data: nil)
private var endIndex: Int = 0
private static var slabCapacity: Int {
BridgedSlabCapacity / MemoryLayout<Element>.stride
}
private static func bind(_ slab: BridgedSlab) -> UnsafeMutablePointer<Element> {
return slab.data!.bindMemory(to: Element.self, capacity: Stack.slabCapacity)
}
struct Iterator : IteratorProtocol {
var slab: BridgedSlab
var index: Int
let lastSlab: BridgedSlab
let endIndex: Int
mutating func next() -> Element? {
let end = (slab.data == lastSlab.data ? endIndex : slabCapacity)
if index < end {
let elem = Stack.bind(slab)[index]
index += 1
if index >= end && slab.data != lastSlab.data {
slab = PassContext_getNextSlab(slab)
index = 0
}
return elem
}
return nil
}
}
init(_ context: PassContext) { self.context = context }
func makeIterator() -> Iterator {
return Iterator(slab: firstSlab, index: 0, lastSlab: lastSlab, endIndex: endIndex)
}
var first: Element? {
isEmpty ? nil : Stack.bind(firstSlab)[0]
}
var last: Element? {
isEmpty ? nil : Stack.bind(lastSlab)[endIndex &- 1]
}
mutating func push(_ element: Element) {
if endIndex >= Stack.slabCapacity {
lastSlab = PassContext_allocSlab(context._bridged, lastSlab)
endIndex = 0
} else if firstSlab.data == nil {
assert(endIndex == 0)
firstSlab = PassContext_allocSlab(context._bridged, lastSlab)
lastSlab = firstSlab
}
(Stack.bind(lastSlab) + endIndex).initialize(to: element)
endIndex += 1
}
/// The same as `push` to provide an Array-like append API.
mutating func append(_ element: Element) { push(element) }
mutating func append<S: Sequence>(contentsOf other: S) where S.Element == Element {
for elem in other {
append(elem)
}
}
var isEmpty: Bool { return endIndex == 0 }
mutating func pop() -> Element? {
if isEmpty {
return nil
}
assert(endIndex > 0)
endIndex -= 1
let elem = (Stack.bind(lastSlab) + endIndex).move()
if endIndex == 0 {
if lastSlab.data == firstSlab.data {
_ = PassContext_freeSlab(context._bridged, lastSlab)
firstSlab.data = nil
lastSlab.data = nil
endIndex = 0
} else {
lastSlab = PassContext_freeSlab(context._bridged, lastSlab)
endIndex = Stack.slabCapacity
}
}
return elem
}
mutating func removeAll() {
while pop() != nil { }
}
/// TODO: once we have move-only types, make this a real deinit.
mutating func deinitialize() { removeAll() }
}
| apache-2.0 | 9a04d4d82676772a9b6d204d2bc52545 | 29.320611 | 86 | 0.63998 | 4.345733 | false | false | false | false |
dreamsxin/swift | test/SILGen/unreachable_code.swift | 4 | 2435 | // RUN: %target-swift-frontend -emit-sil %s -o /dev/null -verify
func testUnreachableAfterReturn() -> Int {
var x: Int = 3
return x
x += 1 //expected-warning {{code after 'return' will never be executed}}
}
func testUnreachableAfterIfReturn(a: Bool) -> Int {
if a {
return 1
} else {
return 0
}
var _: Int = testUnreachableAfterReturn() // expected-warning {{will never be executed}}
}
func testUnreachableForAfterContinue(b: Bool) {
for _ in 0..<10 {
var y: Int = 300
y += 1
if b {
break
y += 1 // expected-warning {{code after 'break' will never be executed}}
}
continue
y -= 1 // expected-warning {{code after 'continue' will never be executed}}
}
}
func testUnreachableWhileAfterContinue(b: Bool) {
var i:Int = 0
while (i<10) {
var y: Int = 300
y += 1
if b {
break
y += 1 // expected-warning {{code after 'break' will never be executed}}
}
continue
i += 1 // expected-warning {{code after 'continue' will never be executed}}
}
}
func testBreakAndContinue() {
var m = 0
for _ in 0 ..< 10 {
m += 1
if m == 15 {
break
} else {
continue
}
m += 1 // expected-warning {{will never be executed}}
}
}
// <rdar://problem/20253447> `case let Case` without bindings incorrectly matches other cases
enum Tree {
case Leaf(Int)
case Branch(Int)
}
func testUnreachableCase1(a : Tree) {
switch a {
case let Leaf:
_ = Leaf
return
case .Branch(_): // expected-warning {{case will never be executed}}
return
}
}
func testUnreachableCase2(a : Tree) {
switch a {
case let Leaf:
_ = Leaf
fallthrough
case .Branch(_):
return
}
}
func testUnreachableCase3(a : Tree) {
switch a {
case _:
break
case .Branch(_): // expected-warning {{case will never be executed}}
return
}
}
func testUnreachableCase4(a : Tree) {
switch a {
case .Leaf(_):
return
case .Branch(_):
return
}
}
func testUnreachableCase5(a : Tree) {
switch a {
case _:
break
default: // expected-warning {{default will never be executed}}
return
}
}
func testUnreachableAfterThrow(e: ErrorProtocol) throws {
throw e
return // expected-warning {{code after 'throw' will never be executed}}
}
class TestThrowInInit {
required init(e: ErrorProtocol) throws {
throw e // no unreachable code diagnostic for the implicit return.
}
}
| apache-2.0 | 82b787ff1a588f022635a4932d87d024 | 18.959016 | 93 | 0.618891 | 3.678248 | false | true | false | false |
dreamsxin/swift | test/Interpreter/SDK/objc_dynamic_lookup.swift | 3 | 987 | // RUN: %target-run-simple-swift | FileCheck %s
// REQUIRES: executable_test
// REQUIRES: objc_interop
import Foundation
// Dynamic subscripting of NSArray, dynamic method dispatch
// CHECK: {{^3$}}
var array : AnyObject = [1, 2, 3, 4, 5]
print(array[2].description)
// Dynamic subscripting on an array using an object (fails)
// CHECK: NSArray subscript with an object fails
var optVal1 = array["Hello"]
if optVal1 != nil {
print((optVal1!)!.description)
} else {
print("NSArray subscript with an object fails")
}
// Dynamic subscripting of NSDictionary, dynamic method dispatch
// CHECK: {{^2$}}
var nsdict : NSDictionary = ["Hello" : 1, "World" : 2]
var dict : AnyObject = nsdict
print((dict["World"]!)!.description)
// Dynamic subscripting on a dictionary using an index (fails)
// CHECK: NSDictionary subscript with an index fails
var optVal2 = dict[1]
if optVal2 != nil {
print(optVal2!.description)
} else {
print("NSDictionary subscript with an index fails")
}
| apache-2.0 | e69cd5b60d244000351d196972e192be | 27.2 | 64 | 0.70618 | 3.710526 | false | false | false | false |
exoplatform/exo-ios | Pods/Kingfisher/Sources/Views/AnimatedImageView.swift | 1 | 23026 | //
// AnimatableImageView.swift
// Kingfisher
//
// Created by bl4ckra1sond3tre on 4/22/16.
//
// The AnimatableImageView, AnimatedFrame and Animator is a modified version of
// some classes from kaishin's Gifu project (https://github.com/kaishin/Gifu)
//
// The MIT License (MIT)
//
// Copyright (c) 2019 Reda Lemeden.
//
// 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.
//
// The name and characters used in the demo of this software are property of their
// respective owners.
#if !os(watchOS)
#if canImport(UIKit)
import UIKit
import ImageIO
/// Protocol of `AnimatedImageView`.
public protocol AnimatedImageViewDelegate: AnyObject {
/// Called after the animatedImageView has finished each animation loop.
///
/// - Parameters:
/// - imageView: The `AnimatedImageView` that is being animated.
/// - count: The looped count.
func animatedImageView(_ imageView: AnimatedImageView, didPlayAnimationLoops count: UInt)
/// Called after the `AnimatedImageView` has reached the max repeat count.
///
/// - Parameter imageView: The `AnimatedImageView` that is being animated.
func animatedImageViewDidFinishAnimating(_ imageView: AnimatedImageView)
}
extension AnimatedImageViewDelegate {
public func animatedImageView(_ imageView: AnimatedImageView, didPlayAnimationLoops count: UInt) {}
public func animatedImageViewDidFinishAnimating(_ imageView: AnimatedImageView) {}
}
let KFRunLoopModeCommon = RunLoop.Mode.common
/// Represents a subclass of `UIImageView` for displaying animated image.
/// Different from showing animated image in a normal `UIImageView` (which load all frames at one time),
/// `AnimatedImageView` only tries to load several frames (defined by `framePreloadCount`) to reduce memory usage.
/// It provides a tradeoff between memory usage and CPU time. If you have a memory issue when using a normal image
/// view to load GIF data, you could give this class a try.
///
/// Kingfisher supports setting GIF animated data to either `UIImageView` and `AnimatedImageView` out of box. So
/// it would be fairly easy to switch between them.
open class AnimatedImageView: UIImageView {
/// Proxy object for preventing a reference cycle between the `CADDisplayLink` and `AnimatedImageView`.
class TargetProxy {
private weak var target: AnimatedImageView?
init(target: AnimatedImageView) {
self.target = target
}
@objc func onScreenUpdate() {
target?.updateFrameIfNeeded()
}
}
/// Enumeration that specifies repeat count of GIF
public enum RepeatCount: Equatable {
case once
case finite(count: UInt)
case infinite
public static func ==(lhs: RepeatCount, rhs: RepeatCount) -> Bool {
switch (lhs, rhs) {
case let (.finite(l), .finite(r)):
return l == r
case (.once, .once),
(.infinite, .infinite):
return true
case (.once, .finite(let count)),
(.finite(let count), .once):
return count == 1
case (.once, _),
(.infinite, _),
(.finite, _):
return false
}
}
}
// MARK: - Public property
/// Whether automatically play the animation when the view become visible. Default is `true`.
public var autoPlayAnimatedImage = true
/// The count of the frames should be preloaded before shown.
public var framePreloadCount = 10
/// Specifies whether the GIF frames should be pre-scaled to the image view's size or not.
/// If the downloaded image is larger than the image view's size, it will help to reduce some memory use.
/// Default is `true`.
public var needsPrescaling = true
/// Decode the GIF frames in background thread before using. It will decode frames data and do a off-screen
/// rendering to extract pixel information in background. This can reduce the main thread CPU usage.
public var backgroundDecode = true
/// The animation timer's run loop mode. Default is `RunLoop.Mode.common`.
/// Set this property to `RunLoop.Mode.default` will make the animation pause during UIScrollView scrolling.
public var runLoopMode = KFRunLoopModeCommon {
willSet {
guard runLoopMode != newValue else { return }
stopAnimating()
displayLink.remove(from: .main, forMode: runLoopMode)
displayLink.add(to: .main, forMode: newValue)
startAnimating()
}
}
/// The repeat count. The animated image will keep animate until it the loop count reaches this value.
/// Setting this value to another one will reset current animation.
///
/// Default is `.infinite`, which means the animation will last forever.
public var repeatCount = RepeatCount.infinite {
didSet {
if oldValue != repeatCount {
reset()
setNeedsDisplay()
layer.setNeedsDisplay()
}
}
}
/// Delegate of this `AnimatedImageView` object. See `AnimatedImageViewDelegate` protocol for more.
public weak var delegate: AnimatedImageViewDelegate?
/// The `Animator` instance that holds the frames of a specific image in memory.
public private(set) var animator: Animator?
// MARK: - Private property
// Dispatch queue used for preloading images.
private lazy var preloadQueue: DispatchQueue = {
return DispatchQueue(label: "com.onevcat.Kingfisher.Animator.preloadQueue")
}()
// A flag to avoid invalidating the displayLink on deinit if it was never created, because displayLink is so lazy.
private var isDisplayLinkInitialized: Bool = false
// A display link that keeps calling the `updateFrame` method on every screen refresh.
private lazy var displayLink: CADisplayLink = {
isDisplayLinkInitialized = true
let displayLink = CADisplayLink(target: TargetProxy(target: self), selector: #selector(TargetProxy.onScreenUpdate))
displayLink.add(to: .main, forMode: runLoopMode)
displayLink.isPaused = true
return displayLink
}()
// MARK: - Override
override open var image: KFCrossPlatformImage? {
didSet {
if image != oldValue {
reset()
}
setNeedsDisplay()
layer.setNeedsDisplay()
}
}
open override var isHighlighted: Bool {
get {
super.isHighlighted
}
set {
// Highlighted image is unsupported for animated images.
// See https://github.com/onevcat/Kingfisher/issues/1679
if displayLink.isPaused {
super.isHighlighted = newValue
}
}
}
deinit {
if isDisplayLinkInitialized {
displayLink.invalidate()
}
}
override open var isAnimating: Bool {
if isDisplayLinkInitialized {
return !displayLink.isPaused
} else {
return super.isAnimating
}
}
/// Starts the animation.
override open func startAnimating() {
guard !isAnimating else { return }
guard let animator = animator else { return }
guard !animator.isReachMaxRepeatCount else { return }
displayLink.isPaused = false
}
/// Stops the animation.
override open func stopAnimating() {
super.stopAnimating()
if isDisplayLinkInitialized {
displayLink.isPaused = true
}
}
override open func display(_ layer: CALayer) {
if let currentFrame = animator?.currentFrameImage {
layer.contents = currentFrame.cgImage
} else {
layer.contents = image?.cgImage
}
}
override open func didMoveToWindow() {
super.didMoveToWindow()
didMove()
}
override open func didMoveToSuperview() {
super.didMoveToSuperview()
didMove()
}
// This is for back compatibility that using regular `UIImageView` to show animated image.
override func shouldPreloadAllAnimation() -> Bool {
return false
}
// Reset the animator.
private func reset() {
animator = nil
if let image = image, let imageSource = image.kf.imageSource {
let targetSize = bounds.scaled(UIScreen.main.scale).size
let animator = Animator(
imageSource: imageSource,
contentMode: contentMode,
size: targetSize,
imageSize: image.kf.size,
imageScale: image.kf.scale,
framePreloadCount: framePreloadCount,
repeatCount: repeatCount,
preloadQueue: preloadQueue)
animator.delegate = self
animator.needsPrescaling = needsPrescaling
animator.backgroundDecode = backgroundDecode
animator.prepareFramesAsynchronously()
self.animator = animator
}
didMove()
}
private func didMove() {
if autoPlayAnimatedImage && animator != nil {
if let _ = superview, let _ = window {
startAnimating()
} else {
stopAnimating()
}
}
}
/// Update the current frame with the displayLink duration.
private func updateFrameIfNeeded() {
guard let animator = animator else {
return
}
guard !animator.isFinished else {
stopAnimating()
delegate?.animatedImageViewDidFinishAnimating(self)
return
}
let duration: CFTimeInterval
// CA based display link is opt-out from ProMotion by default.
// So the duration and its FPS might not match.
// See [#718](https://github.com/onevcat/Kingfisher/issues/718)
// By setting CADisableMinimumFrameDuration to YES in Info.plist may
// cause the preferredFramesPerSecond being 0
let preferredFramesPerSecond = displayLink.preferredFramesPerSecond
if preferredFramesPerSecond == 0 {
duration = displayLink.duration
} else {
// Some devices (like iPad Pro 10.5) will have a different FPS.
duration = 1.0 / TimeInterval(preferredFramesPerSecond)
}
animator.shouldChangeFrame(with: duration) { [weak self] hasNewFrame in
if hasNewFrame {
self?.layer.setNeedsDisplay()
}
}
}
}
protocol AnimatorDelegate: AnyObject {
func animator(_ animator: AnimatedImageView.Animator, didPlayAnimationLoops count: UInt)
}
extension AnimatedImageView: AnimatorDelegate {
func animator(_ animator: Animator, didPlayAnimationLoops count: UInt) {
delegate?.animatedImageView(self, didPlayAnimationLoops: count)
}
}
extension AnimatedImageView {
// Represents a single frame in a GIF.
struct AnimatedFrame {
// The image to display for this frame. Its value is nil when the frame is removed from the buffer.
let image: UIImage?
// The duration that this frame should remain active.
let duration: TimeInterval
// A placeholder frame with no image assigned.
// Used to replace frames that are no longer needed in the animation.
var placeholderFrame: AnimatedFrame {
return AnimatedFrame(image: nil, duration: duration)
}
// Whether this frame instance contains an image or not.
var isPlaceholder: Bool {
return image == nil
}
// Returns a new instance from an optional image.
//
// - parameter image: An optional `UIImage` instance to be assigned to the new frame.
// - returns: An `AnimatedFrame` instance.
func makeAnimatedFrame(image: UIImage?) -> AnimatedFrame {
return AnimatedFrame(image: image, duration: duration)
}
}
}
extension AnimatedImageView {
// MARK: - Animator
/// An animator which used to drive the data behind `AnimatedImageView`.
public class Animator {
private let size: CGSize
private let imageSize: CGSize
private let imageScale: CGFloat
/// The maximum count of image frames that needs preload.
public let maxFrameCount: Int
private let imageSource: CGImageSource
private let maxRepeatCount: RepeatCount
private let maxTimeStep: TimeInterval = 1.0
private let animatedFrames = SafeArray<AnimatedFrame>()
private var frameCount = 0
private var timeSinceLastFrameChange: TimeInterval = 0.0
private var currentRepeatCount: UInt = 0
var isFinished: Bool = false
var needsPrescaling = true
var backgroundDecode = true
weak var delegate: AnimatorDelegate?
// Total duration of one animation loop
var loopDuration: TimeInterval = 0
/// The image of the current frame.
public var currentFrameImage: UIImage? {
return frame(at: currentFrameIndex)
}
/// The duration of the current active frame duration.
public var currentFrameDuration: TimeInterval {
return duration(at: currentFrameIndex)
}
/// The index of the current animation frame.
public internal(set) var currentFrameIndex = 0 {
didSet {
previousFrameIndex = oldValue
}
}
var previousFrameIndex = 0 {
didSet {
preloadQueue.async {
self.updatePreloadedFrames()
}
}
}
var isReachMaxRepeatCount: Bool {
switch maxRepeatCount {
case .once:
return currentRepeatCount >= 1
case .finite(let maxCount):
return currentRepeatCount >= maxCount
case .infinite:
return false
}
}
/// Whether the current frame is the last frame or not in the animation sequence.
public var isLastFrame: Bool {
return currentFrameIndex == frameCount - 1
}
var preloadingIsNeeded: Bool {
return maxFrameCount < frameCount - 1
}
var contentMode = UIView.ContentMode.scaleToFill
private lazy var preloadQueue: DispatchQueue = {
return DispatchQueue(label: "com.onevcat.Kingfisher.Animator.preloadQueue")
}()
/// Creates an animator with image source reference.
///
/// - Parameters:
/// - source: The reference of animated image.
/// - mode: Content mode of the `AnimatedImageView`.
/// - size: Size of the `AnimatedImageView`.
/// - imageSize: Size of the `KingfisherWrapper`.
/// - imageScale: Scale of the `KingfisherWrapper`.
/// - count: Count of frames needed to be preloaded.
/// - repeatCount: The repeat count should this animator uses.
/// - preloadQueue: Dispatch queue used for preloading images.
init(imageSource source: CGImageSource,
contentMode mode: UIView.ContentMode,
size: CGSize,
imageSize: CGSize,
imageScale: CGFloat,
framePreloadCount count: Int,
repeatCount: RepeatCount,
preloadQueue: DispatchQueue) {
self.imageSource = source
self.contentMode = mode
self.size = size
self.imageSize = imageSize
self.imageScale = imageScale
self.maxFrameCount = count
self.maxRepeatCount = repeatCount
self.preloadQueue = preloadQueue
GraphicsContext.begin(size: imageSize, scale: imageScale)
}
deinit {
GraphicsContext.end()
}
/// Gets the image frame of a given index.
/// - Parameter index: The index of desired image.
/// - Returns: The decoded image at the frame. `nil` if the index is out of bound or the image is not yet loaded.
public func frame(at index: Int) -> KFCrossPlatformImage? {
return animatedFrames[index]?.image
}
public func duration(at index: Int) -> TimeInterval {
return animatedFrames[index]?.duration ?? .infinity
}
func prepareFramesAsynchronously() {
frameCount = Int(CGImageSourceGetCount(imageSource))
animatedFrames.reserveCapacity(frameCount)
preloadQueue.async { [weak self] in
self?.setupAnimatedFrames()
}
}
func shouldChangeFrame(with duration: CFTimeInterval, handler: (Bool) -> Void) {
incrementTimeSinceLastFrameChange(with: duration)
if currentFrameDuration > timeSinceLastFrameChange {
handler(false)
} else {
resetTimeSinceLastFrameChange()
incrementCurrentFrameIndex()
handler(true)
}
}
private func setupAnimatedFrames() {
resetAnimatedFrames()
var duration: TimeInterval = 0
(0..<frameCount).forEach { index in
let frameDuration = GIFAnimatedImage.getFrameDuration(from: imageSource, at: index)
duration += min(frameDuration, maxTimeStep)
animatedFrames.append(AnimatedFrame(image: nil, duration: frameDuration))
if index > maxFrameCount { return }
animatedFrames[index] = animatedFrames[index]?.makeAnimatedFrame(image: loadFrame(at: index))
}
self.loopDuration = duration
}
private func resetAnimatedFrames() {
animatedFrames.removeAll()
}
private func loadFrame(at index: Int) -> UIImage? {
let resize = needsPrescaling && size != .zero
let options: [CFString: Any]?
if resize {
options = [
kCGImageSourceCreateThumbnailFromImageIfAbsent: true,
kCGImageSourceCreateThumbnailWithTransform: true,
kCGImageSourceShouldCacheImmediately: true,
kCGImageSourceThumbnailMaxPixelSize: max(size.width, size.height)
]
} else {
options = nil
}
guard let cgImage = CGImageSourceCreateImageAtIndex(imageSource, index, options as CFDictionary?) else {
return nil
}
let image = KFCrossPlatformImage(cgImage: cgImage)
guard let context = GraphicsContext.current(size: imageSize, scale: imageScale, inverting: true, cgImage: cgImage) else {
return image
}
return backgroundDecode ? image.kf.decoded(on: context) : image
}
private func updatePreloadedFrames() {
guard preloadingIsNeeded else {
return
}
animatedFrames[previousFrameIndex] = animatedFrames[previousFrameIndex]?.placeholderFrame
preloadIndexes(start: currentFrameIndex).forEach { index in
guard let currentAnimatedFrame = animatedFrames[index] else { return }
if !currentAnimatedFrame.isPlaceholder { return }
animatedFrames[index] = currentAnimatedFrame.makeAnimatedFrame(image: loadFrame(at: index))
}
}
private func incrementCurrentFrameIndex() {
currentFrameIndex = increment(frameIndex: currentFrameIndex)
if isLastFrame {
currentRepeatCount += 1
if isReachMaxRepeatCount {
isFinished = true
}
delegate?.animator(self, didPlayAnimationLoops: currentRepeatCount)
}
}
private func incrementTimeSinceLastFrameChange(with duration: TimeInterval) {
timeSinceLastFrameChange += min(maxTimeStep, duration)
}
private func resetTimeSinceLastFrameChange() {
timeSinceLastFrameChange -= currentFrameDuration
}
private func increment(frameIndex: Int, by value: Int = 1) -> Int {
return (frameIndex + value) % frameCount
}
private func preloadIndexes(start index: Int) -> [Int] {
let nextIndex = increment(frameIndex: index)
let lastIndex = increment(frameIndex: index, by: maxFrameCount)
if lastIndex >= nextIndex {
return [Int](nextIndex...lastIndex)
} else {
return [Int](nextIndex..<frameCount) + [Int](0...lastIndex)
}
}
}
}
class SafeArray<Element> {
private var array: Array<Element> = []
private let lock = NSLock()
subscript(index: Int) -> Element? {
get {
lock.lock()
defer { lock.unlock() }
return array.indices ~= index ? array[index] : nil
}
set {
lock.lock()
defer { lock.unlock() }
if let newValue = newValue, array.indices ~= index {
array[index] = newValue
}
}
}
var count : Int {
lock.lock()
defer { lock.unlock() }
return array.count
}
func reserveCapacity(_ count: Int) {
lock.lock()
defer { lock.unlock() }
array.reserveCapacity(count)
}
func append(_ element: Element) {
lock.lock()
defer { lock.unlock() }
array += [element]
}
func removeAll() {
lock.lock()
defer { lock.unlock() }
array = []
}
}
#endif
#endif
| lgpl-3.0 | a77051ed7314ad852dba6cb026b621d1 | 34.047184 | 133 | 0.610136 | 5.573953 | false | false | false | false |
WitcherHunter/DouyuZhibo | DouyuZhibo/DouyuZhibo/Classes/Main/View/PageContentView.swift | 1 | 5303 | //
// PageContentView.swift
// DouyuZhibo
//
// Created by 毛豆 on 2017/10/18.
// Copyright © 2017年 毛豆. All rights reserved.
//
import UIKit
protocol PageContentViewDelegate: class {
func pageContentView(contentView: PageContentView, progress: CGFloat, sourceIndex: Int, targetIndex: Int)
}
fileprivate let contentCellId = "contentCellId"
class PageContentView: UIView{
//MARK: 定义属性
fileprivate var childViewControllers: [UIViewController]
fileprivate weak var parentViewController: UIViewController?
fileprivate var startOffsetX: CGFloat = 0
fileprivate var isForbidScrollDelegate = false
weak var delegate : PageContentViewDelegate?
fileprivate lazy var collectionView: UICollectionView = { [weak self] in
//创建layout
let layout = UICollectionViewFlowLayout()
layout.itemSize = (self?.bounds.size)!
layout.minimumLineSpacing = 0
layout.minimumInteritemSpacing = 0
layout.scrollDirection = .horizontal
//创建collectionView
let collectionView = UICollectionView(frame: CGRect.zero, collectionViewLayout: layout)
collectionView.showsHorizontalScrollIndicator = false
collectionView.isPagingEnabled = true
collectionView.bounces = false
collectionView.dataSource = self
collectionView.register(UICollectionViewCell.self, forCellWithReuseIdentifier: contentCellId)
collectionView.delegate = self
return collectionView
}()
init(frame: CGRect, childViewControllers: [UIViewController], parentViewController: UIViewController?) {
self.childViewControllers = childViewControllers
self.parentViewController = parentViewController
super.init(frame: frame)
setupUI()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
extension PageContentView: UICollectionViewDelegate {
func scrollViewWillBeginDragging(_ scrollView: UIScrollView) {
isForbidScrollDelegate = true
startOffsetX = scrollView.contentOffset.x
}
func scrollViewDidScroll(_ scrollView: UIScrollView) {
if !isForbidScrollDelegate {
return
}
var progress : CGFloat = 0
var sourceIndex : Int = 0
var targetIndex : Int = 0
let currentOffsetX = scrollView.contentOffset.x
let scrollViewWidth = scrollView.bounds.width
if currentOffsetX > startOffsetX {
//左滑
progress = currentOffsetX / scrollViewWidth - floor(currentOffsetX / scrollViewWidth)
sourceIndex = Int(currentOffsetX / scrollViewWidth)
targetIndex = sourceIndex + 1
if targetIndex >= childViewControllers.count {
targetIndex = childViewControllers.count - 1
}
if currentOffsetX - startOffsetX == scrollViewWidth {
progress = 1
targetIndex = sourceIndex
}
} else {
//右滑
progress = 1 - (currentOffsetX / scrollViewWidth - floor(currentOffsetX / scrollViewWidth))
targetIndex = Int(currentOffsetX / scrollViewWidth)
sourceIndex = targetIndex + 1
if sourceIndex >= childViewControllers.count {
sourceIndex = childViewControllers.count - 1
}
if startOffsetX - currentOffsetX == scrollViewWidth {
progress = 1
sourceIndex = targetIndex
}
}
delegate?.pageContentView(contentView: self, progress: progress, sourceIndex: sourceIndex, targetIndex: targetIndex)
}
}
extension PageContentView {
fileprivate func setupUI() {
//添加子控制器
for child in childViewControllers {
parentViewController?.addChildViewController(child)
}
//添加UICollectionView用于在Cell中存放控制器的View
addSubview(collectionView)
collectionView.frame = bounds
}
}
extension PageContentView: UICollectionViewDataSource{
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return childViewControllers.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: contentCellId, for: indexPath)
for view in cell.contentView.subviews {
view.removeFromSuperview()
}
let childVc = childViewControllers[indexPath.item]
childVc.view.frame = cell.contentView.bounds
cell.contentView.addSubview(childVc.view)
return cell
}
}
extension PageContentView {
func setupCurrentIndex(currentIndex: Int) {
isForbidScrollDelegate = true
let offsetX = CGFloat(currentIndex) * collectionView.frame.width
collectionView.setContentOffset(CGPoint(x : offsetX, y: 0), animated: false)
}
}
| mit | 4a7ea9327eb523aa3be75e8294277deb | 31.90566 | 124 | 0.64526 | 6.35723 | false | false | false | false |
banxi1988/Staff | Pods/BXForm/Pod/Classes/View/OvalButton.swift | 1 | 1049 | //
// OvalButton.swift
// Pods
//
// Created by Haizhen Lee on 15/12/29.
//
//
import UIKit
public class OvalButton:UIButton{
public lazy var maskLayer : CAShapeLayer = { [unowned self] in
let maskLayer = CAShapeLayer()
maskLayer.frame = self.frame
self.layer.mask = maskLayer
return maskLayer
}()
public override func layoutSubviews() {
super.layoutSubviews()
maskLayer.frame = bounds
updateOutlinePath()
}
private func updateOutlinePath(){
let path:UIBezierPath
switch outlineStyle{
case .Rounded:
path = UIBezierPath(roundedRect: bounds, cornerRadius: cornerRadius)
case .Oval:
path = UIBezierPath(ovalInRect: bounds)
case .Semicircle:
path = UIBezierPath(roundedRect: bounds, cornerRadius: bounds.height * 0.5)
}
maskLayer.path = path.CGPath
}
public var outlineStyle = BXOutlineStyle.Oval{
didSet{
updateOutlinePath()
}
}
public var cornerRadius:CGFloat = 4.0 {
didSet{
updateOutlinePath()
}
}
}
| mit | 486264f0f50d2a89f8982e3a0a40ae36 | 19.173077 | 81 | 0.656816 | 4.29918 | false | false | false | false |
almas-dev/APMAlertController | Pod/Classes/APMAlertController.swift | 1 | 15079 | //
// Created by Alexander Maslennikov on 09.11.15.
//
import UIKit
open class APMAlertController: UIViewController {
public enum Style {
case alert
case actionSheet
}
fileprivate let verticalAlertIndent: CGFloat = 25
open var buttonTitleColor: UIColor?
open var customButtonFont: UIFont? {
didSet {
buttonsContainerView.arrangedSubviews
.flatMap { $0 as? UIButton }
.forEach { $0.titleLabel?.font = customButtonFont }
}
}
open var buttonBackgroundColor: UIColor? {
didSet {
buttonsContainerView.arrangedSubviews
.flatMap { $0 as? UIButton }
.forEach { $0.backgroundColor = buttonBackgroundColor ?? .white }
}
}
open var customDescriptionFont: UIFont?
open var disableImageIconTemplate: Bool = false
open var separatorColor = UIColor(white: 0.75, alpha: 0.6)
open var showTitleMessageSeparator: Bool = false
open var tintColor: UIColor = UIColor.black
open private(set) lazy var messageContentView: UIStackView = {
let stackView = UIStackView()
stackView.isLayoutMarginsRelativeArrangement = true
stackView.layoutMargins = UIEdgeInsets(top: 0, left: 30, bottom: 15, right: 30)
stackView.alignment = .fill
return stackView
}()
let alertView = UIView()
fileprivate let topScrollView = UIScrollView()
fileprivate var topScrollViewHeightConstraint: NSLayoutConstraint?
fileprivate let contentView = UIView()
fileprivate var titleMessageSeparatorConstraint: NSLayoutConstraint?
private(set) lazy var titleMessageSeparator: UIView = {
let view = LineView(axis: .horizontal)
view.backgroundColor = self.separatorColor
view.isHidden = true
return view
}()
fileprivate var messageLabel: UILabel?
fileprivate lazy var buttonsContainerView: UIStackView = {
let stackView = UIStackView()
stackView.distribution = .fillEqually
stackView.alignment = .fill
return stackView
}()
fileprivate var alertTitle: String?
fileprivate var alertTitleImage: UIImage?
fileprivate var alertMessage: String?
fileprivate var alertAttributedMessage: NSAttributedString?
fileprivate var actions = [APMAlertActionProtocol]()
fileprivate var centerYConstraint: NSLayoutConstraint?
var notificationCenter = NotificationCenter.default
// MARK: - Constructors
deinit {
notificationCenter.removeObserver(self, name: Notification.Name.UIKeyboardWillShow, object: nil)
notificationCenter.removeObserver(self, name: Notification.Name.UIKeyboardDidHide, object: nil)
}
public required init(coder _: NSCoder) {
fatalError("NSCoding not supported")
}
public init() {
super.init(nibName: nil, bundle: nil)
modalPresentationStyle = UIModalPresentationStyle.custom
transitioningDelegate = self
}
public convenience init(title: String?, message: String?, preferredStyle _: Style) {
self.init()
alertTitle = title
alertMessage = message
}
public convenience init(title: String?, attributedMessage: NSAttributedString?, preferredStyle _: Style) {
self.init()
alertTitle = title
alertAttributedMessage = attributedMessage
}
public convenience init(titleImage: UIImage?, message: String?, preferredStyle _: Style) {
self.init()
alertTitleImage = titleImage
alertMessage = message
}
public convenience init(title: String?, preferredStyle _: Style) {
self.init()
alertTitle = title
}
// MARK: - View Controller lifecycle
open override func viewDidLoad() {
super.viewDidLoad()
configureView()
configureLayout()
notificationCenter.addObserver(
self,
selector: #selector(keyboardWillShow(with:)),
name: Notification.Name.UIKeyboardWillShow,
object: nil
)
notificationCenter.addObserver(
self,
selector: #selector(keyboardDidHide(with:)),
name: Notification.Name.UIKeyboardDidHide,
object: nil
)
}
open override func viewWillLayoutSubviews() {
super.viewWillLayoutSubviews()
topScrollView.updateConstraintsIfNeeded()
topScrollView.contentSize = contentStackView.frame.size
if view.frame.size.height - verticalAlertIndent * 2 - 45 >= contentStackView.frame.size.height {
topScrollViewHeightConstraint?.constant = contentStackView.frame.size.height
} else {
topScrollViewHeightConstraint?.constant = view.frame.size.height - verticalAlertIndent * 2 - 45
}
titleMessageSeparator.isHidden = !showTitleMessageSeparator
if let messageLabel = self.messageLabel, alertAttributedMessage == nil {
messageLabel.textColor = tintColor
}
}
// MARK: - Public methods
open func addAction(_ action: APMAlertActionProtocol) {
actions.append(action)
let button = UIButton()
if let buttonFont = self.customButtonFont {
button.titleLabel?.font = buttonFont
}
button.translatesAutoresizingMaskIntoConstraints = false
button.setTitle(action.title, for: .normal)
button.setTitleColor(buttonTitleColor ?? tintColor, for: .normal)
button.setTitleColor(buttonTitleColor ?? tintColor.withAlphaComponent(0.33), for: .highlighted)
button.setTitleColor(buttonTitleColor ?? tintColor.withAlphaComponent(0.33), for: .selected)
button.backgroundColor = buttonBackgroundColor ?? .white
button.addTarget(self, action: #selector(btnPressed(_:)), for: .touchUpInside)
buttonsContainerView.addArrangedSubview(button)
button.tag = buttonsContainerView.arrangedSubviews.count
if buttonsContainerView.arrangedSubviews.count > 1 {
let lineView = LineView(axis: .vertical)
lineView.backgroundColor = separatorColor
lineView.placeAboveView(button)
}
}
// MARK: - Content sections
public private(set) lazy var titleStackView: UIStackView = {
let stackView = UIStackView()
stackView.alignment = .fill
stackView.isLayoutMarginsRelativeArrangement = true
stackView.layoutMargins = UIEdgeInsets(top: 15, left: 30, bottom: 0, right: 30)
if self.alertTitleImage != nil {
stackView.addArrangedSubview(self.titleImageView)
} else if self.alertTitle != nil {
stackView.addArrangedSubview(self.titleLabel)
}
return stackView
}()
private lazy var titleLabel: UILabel = {
let titleLabel = UILabel()
titleLabel.textColor = self.tintColor
titleLabel.font = UIFont.boldSystemFont(ofSize: 16)
titleLabel.textAlignment = .center
titleLabel.numberOfLines = 0
titleLabel.text = self.alertTitle
return titleLabel
}()
private lazy var titleImageView: UIImageView = {
let titleImageView = UIImageView()
titleImageView.tintColor = self.tintColor
titleImageView.contentMode = .scaleAspectFit
titleImageView.image = self.disableImageIconTemplate ? self.alertTitleImage : self.alertTitleImage?.withRenderingMode(.alwaysTemplate)
titleImageView.alpha = 0.8
return titleImageView
}()
fileprivate lazy var contentStackView: UIStackView = {
let stackView = UIStackView()
stackView.translatesAutoresizingMaskIntoConstraints = false
stackView.spacing = 15
stackView.axis = .vertical
stackView.alignment = .fill
return stackView
}()
}
// MARK: - Keyboard handlers
extension APMAlertController {
@objc
func keyboardWillShow(with notification: Notification) {
guard let centerYConstraint = self.centerYConstraint,
let userInfo = notification.userInfo,
let keyboardFrame = userInfo[UIKeyboardFrameEndUserInfoKey] as? NSValue,
let animationDuration = userInfo[UIKeyboardAnimationDurationUserInfoKey] as? NSNumber else {
return
}
let frame = keyboardFrame.cgRectValue
centerYConstraint.constant = -frame.size.height / 2
UIView.animate(withDuration: animationDuration.doubleValue) {
self.view.layoutIfNeeded()
}
}
@objc
func keyboardDidHide(with notification: Notification) {
guard let centerYConstraint = self.centerYConstraint,
let userInfo = notification.userInfo,
let animationDuration = userInfo[UIKeyboardAnimationDurationUserInfoKey] as? NSNumber else {
return
}
centerYConstraint.constant = 0
UIView.animate(withDuration: animationDuration.doubleValue) {
self.view.layoutIfNeeded()
}
}
}
// MARK: - Private methods
private extension APMAlertController {
@objc
func btnPressed(_ button: UIButton) {
button.isSelected = true
dismiss(animated: true, completion: {
let action = self.actions[button.tag - 1]
action.handler?(action)
})
}
func configureLayout() {
centerYConstraint = alertView.centerYAnchor.constraint(equalTo: view.centerYAnchor)
centerYConstraint?.isActive = true
alertView.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true
alertView.widthAnchor.constraint(equalToConstant: 270).isActive = true
alertView.heightAnchor.constraint(lessThanOrEqualTo: view.heightAnchor, constant: -(verticalAlertIndent * 2)).isActive = true
}
func configureTopScrollView() {
topScrollView.addSubview(contentStackView)
NSLayoutConstraint.activate([
contentStackView.topAnchor.constraint(equalTo: topScrollView.topAnchor),
contentStackView.bottomAnchor.constraint(equalTo: topScrollView.bottomAnchor),
contentStackView.leftAnchor.constraint(equalTo: topScrollView.leftAnchor),
contentStackView.rightAnchor.constraint(equalTo: topScrollView.rightAnchor),
contentStackView.widthAnchor.constraint(equalTo: topScrollView.widthAnchor)
])
contentStackView.addArrangedSubview(titleStackView)
contentStackView.addArrangedSubview(titleMessageSeparator)
contentStackView.addArrangedSubview(messageContentView)
if alertMessage != nil || alertAttributedMessage != nil {
let messageLabel = UILabel()
messageLabel.translatesAutoresizingMaskIntoConstraints = false
messageLabel.font = customDescriptionFont ?? UIFont.systemFont(ofSize: 16)
messageLabel.textAlignment = .center
if let alertMessage = self.alertMessage {
messageLabel.text = alertMessage
} else if let alertAttributedMessage = self.alertAttributedMessage {
messageLabel.attributedText = alertAttributedMessage
}
messageLabel.numberOfLines = 0
messageContentView.addArrangedSubview(messageLabel)
self.messageLabel = messageLabel
}
}
func configureView() {
alertView.translatesAutoresizingMaskIntoConstraints = false
alertView.backgroundColor = UIColor(white: 1, alpha: 0.95)
alertView.layer.cornerRadius = 12
alertView.clipsToBounds = true
view.addSubview(alertView)
topScrollView.translatesAutoresizingMaskIntoConstraints = false
alertView.addSubview(topScrollView)
let topScrollViewHeightConstraint = topScrollView.heightAnchor.constraint(equalToConstant: 0)
NSLayoutConstraint.activate([
topScrollView.topAnchor.constraint(equalTo: alertView.topAnchor),
topScrollView.leadingAnchor.constraint(equalTo: alertView.leadingAnchor),
topScrollView.trailingAnchor.constraint(equalTo: alertView.trailingAnchor),
topScrollViewHeightConstraint
])
self.topScrollViewHeightConstraint = topScrollViewHeightConstraint
buttonsContainerView.translatesAutoresizingMaskIntoConstraints = false
alertView.addSubview(buttonsContainerView)
NSLayoutConstraint.activate([
buttonsContainerView.topAnchor.constraint(equalTo: topScrollView.bottomAnchor),
buttonsContainerView.leadingAnchor.constraint(equalTo: alertView.leadingAnchor),
buttonsContainerView.trailingAnchor.constraint(equalTo: alertView.trailingAnchor),
buttonsContainerView.bottomAnchor.constraint(equalTo: alertView.bottomAnchor),
buttonsContainerView.heightAnchor.constraint(equalToConstant: 45)
])
let lineView = LineView(axis: .horizontal)
lineView.backgroundColor = separatorColor
lineView.placeAboveView(buttonsContainerView)
configureTopScrollView()
}
}
extension APMAlertController: UIViewControllerTransitioningDelegate {
public func animationController(
forPresented _: UIViewController,
presenting _: UIViewController,
source _: UIViewController
) -> UIViewControllerAnimatedTransitioning? {
return APMAlertAnimation(presenting: true)
}
public func animationController(
forDismissed _: UIViewController
) -> UIViewControllerAnimatedTransitioning? {
return APMAlertAnimation(presenting: false)
}
}
private final class LineView: UIView {
required init(coder _: NSCoder) {
fatalError("NSCoding not supported")
}
enum LineAxis {
case horizontal, vertical
}
private let axis: LineAxis
init(axis: LineAxis) {
self.axis = axis
super.init(frame: CGRect.zero)
translatesAutoresizingMaskIntoConstraints = false
switch axis {
case .horizontal:
let constraint = heightAnchor.constraint(equalToConstant: 1)
constraint.priority = UILayoutPriority(rawValue: 999)
constraint.isActive = true
case .vertical:
let constraint = widthAnchor.constraint(equalToConstant: 1)
constraint.priority = UILayoutPriority(rawValue: 999)
constraint.isActive = true
}
}
func placeAboveView(_ view: UIView) {
view.addSubview(self)
switch axis {
case .horizontal:
NSLayoutConstraint.activate([
view.leftAnchor.constraint(equalTo: leftAnchor),
view.topAnchor.constraint(equalTo: topAnchor),
view.rightAnchor.constraint(equalTo: rightAnchor)
])
case .vertical:
NSLayoutConstraint.activate([
view.topAnchor.constraint(equalTo: topAnchor),
view.bottomAnchor.constraint(equalTo: bottomAnchor),
view.leftAnchor.constraint(equalTo: leftAnchor)
])
}
}
}
| mit | 89b7a1237640ca760646d0d262d8e184 | 35.510896 | 142 | 0.674647 | 5.938952 | false | false | false | false |
brandons/Swifter | Swifter/Dictionary+Swifter.swift | 5 | 2619 | //
// Dictionary+Swifter.swift
// Swifter
//
// Copyright (c) 2014 Matt Donnelly.
//
// 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
extension Dictionary {
func filter(predicate: Element -> Bool) -> Dictionary {
var filteredDictionary = Dictionary()
for (key, value) in self {
if predicate(key, value) {
filteredDictionary[key] = value
}
}
return filteredDictionary
}
func queryStringWithEncoding() -> String {
var parts = [String]()
for (key, value) in self {
let keyString: String = "\(key)"
let valueString: String = "\(value)"
let query: String = "\(keyString)=\(valueString)"
parts.append(query)
}
return parts.joinWithSeparator("&")
}
func urlEncodedQueryStringWithEncoding(encoding: NSStringEncoding) -> String {
var parts = [String]()
for (key, value) in self {
let keyString: String = "\(key)".urlEncodedStringWithEncoding(encoding)
let valueString: String = "\(value)".urlEncodedStringWithEncoding(encoding)
let query: String = "\(keyString)=\(valueString)"
parts.append(query)
}
return parts.joinWithSeparator("&")
}
}
infix operator +| {}
func +| <K,V>(left: Dictionary<K,V>, right: Dictionary<K,V>) -> Dictionary<K,V> {
var map = Dictionary<K,V>()
for (k, v) in left {
map[k] = v
}
for (k, v) in right {
map[k] = v
}
return map
}
| mit | 3d8f1ff3b001fcd1a742a5012a582176 | 31.7375 | 87 | 0.641084 | 4.484589 | false | false | false | false |
acchou/SwiftFirebaseTests | SwiftFirebaseTests/AppDelegate.swift | 1 | 4798 | //
// AppDelegate.swift
// SwiftFirebaseTests
//
// Created by Andy Chou on 2/10/17.
// Copyright © 2017 GiantSquidBaby. All rights reserved.
//
import UIKit
import Firebase
import GoogleSignIn
import RxSwift
import RxCocoa
import GTMSessionFetcher
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
public var authEvents = PublishSubject<AuthEvent>()
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
FIRApp.configure()
let signIn = GIDSignIn.sharedInstance()!
signIn.clientID = FIRApp.defaultApp()?.options.clientID
signIn.delegate = self
// Request access to Gmail API.
let scopes: NSArray = signIn.scopes as NSArray? ?? []
signIn.scopes = scopes.addingObjects(from: global.rxGmail.serviceScopes)
// Log all Google API requests. Location of log file is printed to console.
GTMSessionFetcher.setLoggingEnabled(true)
return true
}
func application(_ app: UIApplication, open url: URL, options: [UIApplicationOpenURLOptionsKey : Any]) -> Bool {
let sourceApplication = options[UIApplicationOpenURLOptionsKey.sourceApplication] as! String?
if GIDSignIn.sharedInstance().handle(url, sourceApplication: sourceApplication, annotation: [:]) {
return true
}
return false
}
func applicationWillResignActive(_ application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
}
func applicationDidEnterBackground(_ application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(_ application: UIApplication) {
// Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(_ application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(_ application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}
}
extension AppDelegate: GIDSignInDelegate {
// TODO:
// Continue following instructions at: https://firebase.google.com/docs/auth/ios/google-signin
func sign(_ signIn: GIDSignIn!, didSignInFor user: GIDGoogleUser!, withError error: Error!) {
let event = AuthEvent.googleSignIn(signIn: signIn, user: user, error: error)
print("signin: \(event)")
authEvents.onNext(event)
if let error = error {
print("Error signing in: \(error.localizedDescription)")
return
}
guard let authentication = user.authentication else { return }
let credential = FIRGoogleAuthProvider.credential(
withIDToken: authentication.idToken,
accessToken: authentication.accessToken
)
auth.signIn(with: credential) { (user, error) in
self.authEvents.onNext(.firebaseSignIn(user: user, error: error))
if let error = error {
print("Error with firebase signin: \(error)")
}
}
global.gmailService.authorizer = user.authentication.fetcherAuthorizer()
assert(global.gmailService.authorizer?.canAuthorize == true)
}
func sign(_ signIn: GIDSignIn!, didDisconnectWith user: GIDGoogleUser!, withError error: Error!) {
let event = AuthEvent.googleSignOut(signIn: signIn, user: user, error: error)
print("signout: \(event)")
authEvents.onNext(event)
if let error = error {
print("Error disconnecting user: \(error.localizedDescription)")
return
}
}
}
| mit | 15ec26536865c10e3fcd81b4c9cb5ffe | 43.831776 | 285 | 0.701897 | 5.277228 | false | false | false | false |
SebastianBoldt/Jelly | Jelly/Classes/public/Models/Presentations/CoverPresentation.swift | 1 | 2206 | import UIKit
public struct CoverPresentation: Presentation,
PresentationDismissDirectionProvider,
PresentationShowDirectionProvider,
PresentationMarginGuardsProvider,
PresentationSizeProvider,
PresentationAlignmentProvider,
PresentationSpringProvider,
InteractionConfigurationProvider {
public var showDirection: Direction
public var dismissDirection: Direction
public var presentationTiming: PresentationTimingProtocol
public var presentationUIConfiguration: PresentationUIConfigurationProtocol
public var presentationSize: PresentationSizeProtocol
public var presentationAlignment: PresentationAlignmentProtocol
public var spring: Spring
public var marginGuards: UIEdgeInsets
public var interactionConfiguration: InteractionConfiguration?
public init(directionShow: Direction,
directionDismiss: Direction,
uiConfiguration: PresentationUIConfigurationProtocol = PresentationUIConfiguration(),
size: PresentationSizeProtocol = PresentationSize(),
alignment: PresentationAlignmentProtocol = PresentationAlignment.centerAlignment,
marginGuards: UIEdgeInsets = .zero,
timing: PresentationTimingProtocol = PresentationTiming(),
spring: Spring = .none,
interactionConfiguration: InteractionConfiguration? = nil) {
dismissDirection = directionDismiss
showDirection = directionShow
presentationTiming = timing
presentationUIConfiguration = uiConfiguration
presentationSize = size
presentationAlignment = alignment
self.spring = spring
self.marginGuards = marginGuards
presentationAlignment = alignment
self.interactionConfiguration = interactionConfiguration
}
}
extension CoverPresentation: PresentationAnimatorProvider {
public var showAnimator: UIViewControllerAnimatedTransitioning {
return CoverAnimator(presentationType: .show, presentation: self)
}
public var dismissAnimator: UIViewControllerAnimatedTransitioning {
return CoverAnimator(presentationType: .dismiss, presentation: self)
}
}
| mit | 97b799147d256b37bdcc3274a42b7272 | 42.254902 | 101 | 0.750227 | 6.72561 | false | true | false | false |
adrianortiz/Instagram-clon | ParseStarterProject/ViewController.swift | 1 | 8108 | //
// ViewController.swift
//
// Copyright 2015 Codizer. All rights reserved.
//
import UIKit
import Parse
// Implementar delegados
class ViewController: UIViewController { //, UINavigationControllerDelegate, UIImagePickerControllerDelegate {
/*
// Imagen seleccionada
@IBOutlet weak var pickedImage: UIImageView!
let loading = UIActivityIndicatorView()
// Action del button Pause
@IBAction func pause(sender: AnyObject) {
// Mostrar un loading
loading.center = self.view.center
loading.hidesWhenStopped = true
loading.activityIndicatorViewStyle = UIActivityIndicatorViewStyle.Gray
loading.startAnimating()
// Añadir a la vista
self.view.addSubview(loading)
// Evitar que se pulsen otros botones
// UIApplication.sharedApplication().beginIgnoringInteractionEvents()
}
// Action button Reanudar
@IBAction func restart(sender: AnyObject) {
self.loading.stopAnimating()
// UIApplication.sharedApplication().endIgnoringInteractionEvents()
}
// Action button Crear Alerta
@IBAction func createAlert(sender: AnyObject) {
let alert = UIAlertController(title: "Un momento", message: "Estás seguro de continuar?", preferredStyle: UIAlertControllerStyle.Alert)
// Agregar button al alert
alert.addAction(UIAlertAction(title: "Aceptar", style: .Default, handler: { (action) in
self.dismissViewControllerAnimated(true, completion: nil)
}))
self.presentViewController(alert, animated: true, completion: nil)
}
// Action del button Elegir foto
@IBAction func pickImage(sender: AnyObject) {
let imagePC = UIImagePickerController()
// delegado que va a informar, es este propio view controller self
imagePC.delegate = self
// De donde obntedrá las fotos fotos del usuario
imagePC.sourceType = UIImagePickerControllerSourceType.PhotoLibrary // .Camera
// Evitar que puede editar las fotos
imagePC.allowsEditing = false
// Mostrar al usuario el view controller de fotos
self.presentViewController(imagePC, animated: true, completion: nil)
}
// Identificar cuando un usuario ha elegido una foto
func imagePickerController(picker: UIImagePickerController, didFinishPickingImage image: UIImage, editingInfo: [String : AnyObject]?) {
print("El usuario ha elegido una foto")
// Mostrar la foto seleccionada
self.pickedImage.image = image
// Desactivar modal
self.dismissViewControllerAnimated(true, completion: nil)
}
*/
let loading = UIActivityIndicatorView()
var signUpActive = true
@IBOutlet weak var username: UITextField!
@IBOutlet weak var password: UITextField!
@IBOutlet weak var signUpToggleButton: UIButton!
@IBOutlet weak var alreadyRegistered: UILabel!
@IBOutlet weak var signUpLabel: UILabel!
@IBOutlet weak var signUpButton: UIButton!
func displayAlert(title:String, message:String) {
let alert = UIAlertController(title: title, message: message, preferredStyle: UIAlertControllerStyle.Alert)
alert.addAction(UIAlertAction(title: "Aceptar", style: .Default, handler: { (action) in
self.dismissViewControllerAnimated(true, completion: nil)
}))
self.presentViewController(alert, animated: true, completion: nil)
}
@IBAction func signUp(sender: AnyObject) {
var error = ""
if self.username.text == "" || self.password.text == "" {
error = "Por favor, introduce un usuario y contraseña"
} else {
// loading
loading.center = self.view.center
loading.hidesWhenStopped = true
loading.activityIndicatorViewStyle = UIActivityIndicatorViewStyle.Gray
loading.startAnimating()
self.view.addSubview(loading)
// Desactivar eventos en la vista
UIApplication.sharedApplication().beginIgnoringInteractionEvents()
if signUpActive {
// Registrar
let user = PFUser()
user.username = self.username.text
user.password = self.password.text
user.signUpInBackgroundWithBlock({ (succeed: Bool, signUpError: NSError?) in
// Activar eventos en la vista
self.loading.stopAnimating()
UIApplication.sharedApplication().endIgnoringInteractionEvents()
if signUpError == nil {
print("Usuario registrado")
} else {
if let errorString = signUpError!.userInfo["error"] as? NSString {
self.displayAlert("Error al registrar", message: String(errorString))
} else {
self.displayAlert("Error al registrar", message: "Por favor reinténtalo")
}
}
})
}
else {
// Iniciar sesión
PFUser.logInWithUsernameInBackground(self.username.text!, password:self.password.text!) {
(user: PFUser?, loginError: NSError?) -> Void in
// Activar eventos en la vista
self.loading.stopAnimating()
UIApplication.sharedApplication().endIgnoringInteractionEvents()
if user != nil {
print("El usuario ha podido acceder!")
} else {
if let errorString = loginError!.userInfo["error"] as? NSString {
self.displayAlert("Error al acceder", message: String(errorString))
} else {
self.displayAlert("Error al acceder", message: "Por favor reinténtalo")
}
}
}
}
}
if error != "" {
self.displayAlert("Error en el formulario", message: error)
}
}
@IBAction func signUpToggle(sender: AnyObject) {
if signUpActive {
// Estoy en modo registro, voy a modo acceso
self.signUpToggleButton.setTitle("Registrarse", forState: .Normal)
self.alreadyRegistered.text = "¿Aún no registrado?"
self.signUpButton.setTitle("Acceder", forState: .Normal)
self.signUpLabel.text = "Usa el formulario inferiror para acceder"
signUpActive = false
} else {
// Estoy en modo acceso, voy a cambiar a modo registro
self.signUpToggleButton.setTitle("Acceder", forState: .Normal)
self.alreadyRegistered.text = "¿Ya registrado?"
self.signUpButton.setTitle("Registrar nuevo usuario", forState: .Normal)
self.signUpLabel.text = "Usa el formulario inferiror para registrarte"
signUpActive = true
}
}
override func viewDidLoad() {
super.viewDidLoad()
// Saber el usuario que esta logueado
// print(PFUser.currentUser())
}
// Se recomianda realizar las animaciónes de las pantallas aqui
override func viewDidAppear(animated: Bool) {
super.viewWillAppear(animated)
if PFUser.currentUser() != nil {
self.performSegueWithIdentifier("jumpToUsersTable", sender: self)
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
| apache-2.0 | 8d2551a9c8429d6bdb63f6d184aad70d | 35.638009 | 143 | 0.579227 | 5.572608 | false | false | false | false |
chanhx/Octogit | iGithub/ViewModels/BaseTableViewModel.swift | 2 | 600 | //
// BaseTableViewModel.swift
// iGithub
//
// Created by Chan Hocheung on 7/21/16.
// Copyright © 2016 Hocheung. All rights reserved.
//
import UIKit
import RxSwift
import ObjectMapper
class BaseTableViewModel<T> {
var dataSource: Variable<[T]> = Variable([])
let error = Variable<Swift.Error?>(nil)
let disposeBag = DisposeBag()
var page: Int = 1
var endCursor: String?
var hasNextPage = true
@objc func fetchData() {}
@objc func refresh() {
page = 1
endCursor = nil
hasNextPage = true
fetchData()
}
}
| gpl-3.0 | b2311275222f9fde69c84420e1f86d37 | 18.322581 | 51 | 0.607679 | 4.131034 | false | false | false | false |
Osnobel/GDGameExtensions | GDGameExtensions/GDOpenSocial/GDOpenSocialViewController.swift | 1 | 2809 | //
// GDOpenSocialViewController.swift
// GDOpenSocial
//
// Created by Bell on 16/5/28.
// Copyright © 2016年 GoshDo <http://goshdo.sinaapp.com>. All rights reserved.
//
import Foundation
import UIKit
@available(iOS 8.0, *)
public class GDOpenSocialViewController: UIActivityViewController {
public var sourceView: UIView? = UIApplication.sharedApplication().keyWindow?.subviews.first {
didSet {
if let view = sourceView {
popoverPresentationController?.sourceView = view
popoverPresentationController?.sourceRect = view.frame
}
}
}
public init(message: GDOSMessage) {
var activityItems: [AnyObject] = [message]
if message.description != nil {
activityItems.append(message.description!)
}
if message.image != nil {
activityItems.append(message.image!)
}
if message.link != nil {
activityItems.append(NSURL(string: message.link!)!)
}
var activities: [UIActivity]? = nil
activities = [GDOpenSocialWeChatSessionActivity(), GDOpenSocialWeChatTimelineActivity(), GDOpenSocialQQFriendsActivity(), GDOpenSocialQQZoneActivity(), GDOpenSocialWeiboActivity()]
super.init(activityItems: activityItems, applicationActivities: activities)
if let view = sourceView {
popoverPresentationController?.sourceView = view
popoverPresentationController?.sourceRect = view.frame
}
popoverPresentationController?.permittedArrowDirections = .Any
excludedActivityTypes = [UIActivityTypePrint, UIActivityTypeCopyToPasteboard, UIActivityTypeAssignToContact, UIActivityTypeSaveToCameraRoll, UIActivityTypeAddToReadingList, UIActivityTypeAirDrop]
if #available(iOS 9.0, *) {
excludedActivityTypes?.append(UIActivityTypeOpenInIBooks)
excludedActivityTypes?.append("com.apple.reminders.RemindersEditorExtension")
excludedActivityTypes?.append("com.apple.mobilenotes.SharingExtension")
}
// have app
if GDOpenSocial.isWeiboApiAvailable {
excludedActivityTypes?.append(UIActivityTypePostToWeibo)
}
}
// private func _shouldExcludeActivityType(activity: UIActivity) -> Bool {
// if (activity.classForCoder as! UIActivity.Type).activityCategory() == .Action {
// return true
// }
// if let excludedActivityTypes = excludedActivityTypes {
// if let activityType = activity.activityType() {
// return excludedActivityTypes.contains(activityType)
// }
// }
// return false
// }
}
public extension GDOpenSocial {
public static var shareViewController: GDOpenSocialViewController?
}
| mit | 72f01cf293b7faed3513217b528b406c | 39.085714 | 203 | 0.671418 | 5.437984 | false | false | false | false |
srn214/Floral | Floral/Pods/CryptoSwift/Sources/CryptoSwift/Foundation/Data+Extension.swift | 2 | 2991 | //
// CryptoSwift
//
// Copyright (C) 2014-2017 Marcin Krzyżanowski <[email protected]>
// This software is provided 'as-is', without any express or implied warranty.
//
// In no event will the authors be held liable for any damages arising from the use of this software.
//
// Permission is granted to anyone to use this software for any purpose,including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions:
//
// - The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation is required.
// - Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software.
// - This notice may not be removed or altered from any source or binary distribution.
//
import Foundation
extension Data {
/// Two octet checksum as defined in RFC-4880. Sum of all octets, mod 65536
public func checksum() -> UInt16 {
var s: UInt32 = 0
var bytesArray = bytes
for i in 0 ..< bytesArray.count {
s = s + UInt32(bytesArray[i])
}
s = s % 65536
return UInt16(s)
}
public func md5() -> Data {
return Data( Digest.md5(bytes))
}
public func sha1() -> Data {
return Data( Digest.sha1(bytes))
}
public func sha224() -> Data {
return Data( Digest.sha224(bytes))
}
public func sha256() -> Data {
return Data( Digest.sha256(bytes))
}
public func sha384() -> Data {
return Data( Digest.sha384(bytes))
}
public func sha512() -> Data {
return Data( Digest.sha512(bytes))
}
public func sha3(_ variant: SHA3.Variant) -> Data {
return Data( Digest.sha3(bytes, variant: variant))
}
public func crc32(seed: UInt32? = nil, reflect: Bool = true) -> Data {
return Data( Checksum.crc32(bytes, seed: seed, reflect: reflect).bytes())
}
public func crc32c(seed: UInt32? = nil, reflect: Bool = true) -> Data {
return Data( Checksum.crc32c(bytes, seed: seed, reflect: reflect).bytes())
}
public func crc16(seed: UInt16? = nil) -> Data {
return Data( Checksum.crc16(bytes, seed: seed).bytes())
}
public func encrypt(cipher: Cipher) throws -> Data {
return Data( try cipher.encrypt(bytes.slice))
}
public func decrypt(cipher: Cipher) throws -> Data {
return Data( try cipher.decrypt(bytes.slice))
}
public func authenticate(with authenticator: Authenticator) throws -> Data {
return Data( try authenticator.authenticate(bytes))
}
}
extension Data {
public init(hex: String) {
self.init(Array<UInt8>(hex: hex))
}
public var bytes: Array<UInt8> {
return Array(self)
}
public func toHexString() -> String {
return bytes.toHexString()
}
}
| mit | 9e311625b76aa5ab1feaa447b6bfeb9c | 30.473684 | 217 | 0.644147 | 4.056988 | false | false | false | false |
YOCKOW/SwiftCGIResponder | Sources/CGIResponder/FormData.swift | 1 | 11733 | /* *************************************************************************************************
FormData.swift
© 2017-2018, 2020 YOCKOW.
Licensed under MIT License.
See "LICENSE.txt" for more information.
************************************************************************************************ */
import Foundation
import TemporaryFile
import yExtensions
import yProtocols
private let CR: UInt8 = 0x0D
private let LF: UInt8 = 0x0A
private let HYPHEN: UInt8 = 0x2D
private let TWO_HYPHENS = Data([HYPHEN, HYPHEN])
private let CRLF = Data([CR, LF])
private let BUFFER_SIZE = 16384
private extension HTTPHeader {
func _canInsertField(named name: HTTPHeaderFieldName) -> Bool {
let fields = self[name]
guard let field = fields.first else { return true }
return field.isAppendable || field.isDuplicable
}
var _name_filename: (name:String, filename:String?)? {
guard
let dispositionField = self[.contentDisposition].first,
case let disposition as ContentDisposition = dispositionField.source,
disposition.value == .formData,
let dispositionParameters = disposition.parameters,
let name = dispositionParameters[.name],
!name.isEmpty else
{
return nil
}
return (name: name, filename: dispositionParameters[.filename])
}
var _contentType: ContentType? {
guard
let contentTypeField = self[.contentType].first,
case let contentType as ContentType = contentTypeField.source else
{
return nil
}
return contentType
}
var _stringEncoding: String.Encoding? {
return (self._contentType?.parameters?["charset"]).flatMap {
String.Encoding(ianaCharacterSetName: $0)
}
}
var _transferEncoding: ContentTransferEncoding? {
guard
let transferEncodingField = self[.contentTransferEncoding].first,
case let transferEncoding as ContentTransferEncoding = transferEncodingField.source else
{
return nil
}
return transferEncoding
}
}
/// A sequence that represents "multipart/form-data".
/// Iterating items consumes(reads) `stdin`.
public final class FormData: Sequence, IteratorProtocol {
public typealias Element = Item
public typealias Iterator = FormData
public enum Error: Swift.Error {
case base64DecodingFailure
case invalidBoundary
case invalidHTTPHeader
case invalidInput
case invalidRequest
case quotedPrintableDecodingFailure
case tooLongBoundary
case unexpectedError
}
// MARK: - FormData.Item
/// Represents each item of contents of "multipart/form-data"
public struct Item {
/// Represents a value of the item.
/// `content` may be expressed by `String`, `URL`, or `TemporaryFile`.
public struct Value {
/// Posted data
public let content: CGIContent
/// The filename tied up with the data.
public let filename: String?
/// The content type of the data.
public let contentType: ContentType?
fileprivate init(content: CGIContent, filename: String? = nil, contentType: ContentType? = nil) {
self.content = content
self.filename = filename
self.contentType = contentType
}
}
/// A name of the item.
public let name: String
/// A value of the item.
public let value: Value
fileprivate init(name: String, value: Value) {
self.name = name
self.value = value
}
}
// MARK: - Properties of `FormData`
/// Usually this value is `stdin`; You can specify other input for the purpose of debug.
private var _input: AnyFileHandle! = nil
private var _encoding: String.Encoding! = nil
private var _boundary: Data! = nil
private lazy var _boundaryLength: Int = self._boundary.count
private var _closeBoundary: Data! = nil
private lazy var _closeBounadryLength: Int = self._closeBoundary.count
private var _temporaryDirectory: TemporaryDirectory! = nil
private var _neverIterate: Bool = false
/// The last error that has occurred when the instance is initialized, or the input is parsed.
/// Why this property exists is because `func next() -> Element?` that is required by
/// `IteratorProtocol` cannot throw any errors.
public fileprivate(set) var error: Swift.Error? = nil
// MARK: End of properties of `FormData` -
/// This initializer must be called from `_FormData`.
/// `input` will be read to first boundary.
fileprivate init<FH>(__input input: FH,
boundary: String,
stringEncoding encoding: String.Encoding,
temporaryDirectory: TemporaryDirectory) throws where FH: FileHandleProtocol {
if boundary.isEmpty {
throw Error.invalidBoundary
}
// This should be O(1) because https://swift.org/blog/utf8-string/
if boundary.utf8.count > 512 {
throw Error.tooLongBoundary
}
if temporaryDirectory.isClosed {
throw CGIResponderError.illegalOperation
}
guard let boundaryData = boundary.data(using: encoding) else {
throw Error.invalidBoundary
}
self._boundary = TWO_HYPHENS + boundaryData
self._closeBoundary = TWO_HYPHENS + boundaryData + TWO_HYPHENS
self._input = AnyFileHandle(input)
self._encoding = encoding
self._temporaryDirectory = temporaryDirectory
// Skip empty lines and handle first boundary
while true {
guard let firstLine = try self._input.read(toByte: LF, upToCount: BUFFER_SIZE) else {
throw Error.invalidInput
}
if firstLine == CRLF { continue }
guard
firstLine.count == self._boundaryLength + 2,
firstLine[self._boundaryLength] == CR,
firstLine.dropLast(2) == self._boundary
else {
throw Error.invalidInput
}
break
}
}
public func makeIterator() -> FormData {
return self
}
public func next() -> Item? {
if self._neverIterate || self._temporaryDirectory.isClosed { return nil }
do {
// Header fields
var header = HTTPHeader([])
while true {
guard let line = try self._input.read(toByte: LF, upToCount: BUFFER_SIZE) else {
return nil
}
if line == CRLF { break } // end of header
guard
let headerFieldString = String(data: line, encoding: self._encoding),
let headerField = HTTPHeaderField(string: headerFieldString),
header._canInsertField(named: headerField.name)
else {
throw Error.invalidHTTPHeader
}
header.insert(headerField, removingExistingFields: false)
}
guard let (name, filename) = header._name_filename else { throw Error.invalidHTTPHeader }
let nilableContentType = header._contentType
let stringEncoding: String.Encoding = header._stringEncoding ?? self._encoding
let transferEncoding = header._transferEncoding ?? ._7bit
let temporaryFile = try TemporaryFile(in: self._temporaryDirectory, prefix: "FormData-")
// Anyway, let's read & write data
while true {
guard let data = try self._input.read(toByte: LF, upToCount: BUFFER_SIZE) else {
return nil
}
if data.isEmpty { throw Error.unexpectedError } // data must not be empty because boundary contains "LF"
func _dataIs(_ boundary: Data, length: Int, acceptEOF: Bool) -> Bool {
if acceptEOF && data.count == length && data == boundary { return true }
guard data.count == length + 2 else { return false }
guard data[length] == CR else { return false }
guard data.dropLast(2) == boundary else { return false }
return true
}
let dataIsBoundary: Bool =
_dataIs(self._boundary, length: self._boundaryLength, acceptEOF: false)
let dataIsCloseBoundary: Bool =
!dataIsBoundary &&
_dataIs(self._closeBoundary, length: self._closeBounadryLength, acceptEOF: true)
if dataIsBoundary || dataIsCloseBoundary {
// If `data` is boundary,
// preceding "\r\n" has been already written to the file
// unless transfer-encoding is base64
if transferEncoding != .base64 {
guard try temporaryFile.offset() >= 2 else { throw Error.unexpectedError }
// delete last "\r\n"
try temporaryFile.truncate(atOffset: temporaryFile.offset() - 2)
}
if dataIsCloseBoundary {
// end of data
self._neverIterate = true
}
break
}
// write the data...
switch transferEncoding {
case ._7bit, ._8bit, .binary:
try temporaryFile.write(contentsOf: data)
case .base64:
guard let decoded = Data(base64Encoded: data, options: [.ignoreUnknownCharacters]) else {
throw Error.base64DecodingFailure
}
try temporaryFile.write(contentsOf: decoded)
case .quotedPrintable:
guard let decoded = Data(quotedPrintableEncoded: data) else {
throw Error.quotedPrintableDecodingFailure
}
try temporaryFile.write(contentsOf: decoded)
}
} // end of while-loop (read & write data)
// if `filename` is nil, regard the data as simple string.
let value: FormData.Item.Value = try ({
try temporaryFile.seek(toOffset: 0)
if filename == nil {
guard let data = try temporaryFile.readToEnd() else {
return FormData.Item.Value(content: .string("", encoding: stringEncoding))
}
guard let string = String(data: data, encoding: stringEncoding) else {
throw CGIResponderError.stringConversionFailure
}
return FormData.Item.Value(content: .string(string, encoding: stringEncoding))
} else {
return FormData.Item.Value(content: .init(temporaryFile: temporaryFile),
filename: filename,
contentType: nilableContentType)
}
})()
return FormData.Item(name: name, value: value)
} catch {
self.error = error
self._neverIterate = true
return nil
}
}
}
private extension FileHandleProtocol {
var _objectIdentifier: ObjectIdentifier {
if case let fh as AnyFileHandle = self {
return fh.objectIdentifier
} else {
return .init(self)
}
}
}
private var _instances: [ObjectIdentifier: FormData] = [:]
private protocol _FormData {}
extension _FormData {
init<FH>(_input input: FH,
boundary: String,
stringEncoding encoding: String.Encoding,
temporaryDirectory: TemporaryDirectory) throws where FH: FileHandleProtocol {
if let instance = _instances[input._objectIdentifier] {
self = instance as! Self
} else {
let newInstance = try FormData(__input: input,
boundary: boundary,
stringEncoding: encoding,
temporaryDirectory: temporaryDirectory)
_instances[ObjectIdentifier(input)] = newInstance
self = newInstance as! Self
}
}
}
extension FormData: _FormData {
internal convenience init<FH>(input: FH,
boundary: String,
stringEncoding encoding: String.Encoding,
temporaryDirectory: TemporaryDirectory) throws where FH: FileHandleProtocol {
try self.init(_input: input,
boundary: boundary,
stringEncoding: encoding,
temporaryDirectory: temporaryDirectory)
}
}
| mit | 117e5bcd5b8d69801c1aa365c545b758 | 33.204082 | 112 | 0.623338 | 4.8802 | false | false | false | false |
ImJCabus/UIBezierPath-Superpowers | Demo/BezierPlayground/FractionDemoView.swift | 1 | 4064 | //
// FractionDemoView.swift
// UIBezierPath+Length
//
// Created by Maximilian Kraus on 15.07.17.
// Copyright © 2017 Maximilian Kraus. All rights reserved.
//
import UIKit
class FractionDemoView: MXView {
var scaleAndCenterPath = true
var path: UIBezierPath?
var pathRect: CGRect {
return CGRect(x: 16, y: 84, width: frame.width - 32, height: frame.height / 2)
}
fileprivate let shapeLayer = CAShapeLayer()
let dotLayer = CALayer()
let slider = UISlider()
fileprivate let sliderValueLabel = UILabel()
fileprivate let lengthLabel = UILabel()
fileprivate let hintLabel = UILabel()
override init() {
super.init()
backgroundColor = .white
shapeLayer.lineWidth = 1
shapeLayer.lineCap = kCALineCapRound
shapeLayer.fillColor = UIColor.clear.cgColor
shapeLayer.strokeColor = UIColor.black.cgColor
layer.addSublayer(shapeLayer)
dotLayer.frame = CGRect(x: 0, y: 0, width: 25, height: 25)
dotLayer.backgroundColor = tintColor.cgColor
dotLayer.cornerRadius = dotLayer.frame.width / 2
layer.addSublayer(dotLayer)
slider.addTarget(self, action: #selector(sliderValueChanged(sender:)), for: .valueChanged)
slider.sizeToFit()
addSubview(slider)
addSubview(sliderValueLabel)
addSubview(lengthLabel)
hintLabel.text = "Tap to add line point."
hintLabel.textColor = UIColor(hue: 0, saturation: 0, brightness: 0.39, alpha: 1)
hintLabel.sizeToFit()
addSubview(hintLabel)
}
func configure(with path: UIBezierPath) {
self.path = path
setNeedsLayout()
}
@objc private func sliderValueChanged(sender: UISlider) {
sliderValueLabel.text = "Slider value: \(CGFloat(slider.value).string(fractionDigits: 2))"
}
override func layoutSubviews() {
super.layoutSubviews()
guard let path = path else { return }
if scaleAndCenterPath {
// Scale to fit and center path inside the top half of this view.
let scale = min(pathRect.width / path.bounds.width, pathRect.height / path.bounds.height)
if scale != 1 {
path.apply(CGAffineTransform(scaleX: scale, y: scale))
}
let offset = UIOffset(horizontal: pathRect.midX - path.bounds.midX, vertical: pathRect.midY - path.bounds.midY)
if offset != .zero {
path.apply(CGAffineTransform(translationX: offset.horizontal, y: offset.vertical))
}
}
shapeLayer.path = nil
shapeLayer.path = path.cgPath
// Re-position the dot (neccessary for valid layout after rotation).
CATransaction.begin()
CATransaction.setDisableActions(true)
dotLayer.position = path.mx_point(atFractionOfLength: CGFloat(slider.value))
CATransaction.commit()
slider.frame.origin.x = 32
slider.frame.origin.y = pathRect.maxY + 44
slider.frame.size.width = bounds.width - 64
sliderValueLabel.text = "Slider value: \(CGFloat(slider.value).string(fractionDigits: 2))"
sliderValueLabel.sizeToFit()
sliderValueLabel.frame.size.width = slider.frame.width
sliderValueLabel.frame.origin.x = 32
sliderValueLabel.frame.origin.y = slider.frame.maxY + 24
lengthLabel.text = "Path length: \(path.mx_length.string(fractionDigits: 2))"
lengthLabel.sizeToFit()
lengthLabel.frame.origin.x = 32
lengthLabel.frame.origin.y = sliderValueLabel.frame.maxY + 32
hintLabel.center = CGPoint(x: pathRect.midX, y: pathRect.midY)
hintLabel.isHidden = !path.isEmpty
}
override func draw(_ rect: CGRect) {
super.draw(rect)
UIColor(hue: 0, saturation: 0, brightness: 0.94, alpha: 1).setFill()
UIRectFill(pathRect.insetBy(dx: -8, dy: -8))
}
}
fileprivate extension CGFloat {
func string(fractionDigits:Int) -> String {
let formatter = NumberFormatter()
formatter.minimumFractionDigits = fractionDigits
formatter.maximumFractionDigits = fractionDigits
formatter.decimalSeparator = "."
return formatter.string(from: NSNumber(value: Float(self))) ?? "\(self)"
}
}
| mit | 4a3a9f05c440703dd93d2c20afcec9c6 | 29.780303 | 117 | 0.684716 | 4.272345 | false | false | false | false |
corchwll/amos-ss15-proj5_ios | MobileTimeAccounting/Database/ProfileDAO.swift | 1 | 4421 | /*
Mobile Time Accounting
Copyright (C) 2015
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. If not, see <http://www.gnu.org/licenses/>.
*/
import Foundation
let profileDAO = ProfileDAO()
class ProfileDAO
{
var userDefaults = NSUserDefaults()
private var firstnameKey = "firstname_key"
private var lastnameKey = "lastname_key"
private var employeeIdKey = "employee_id_key"
private var weeklyWorkingTimeKey = "weekly_working_time_key"
private var totalVacationTimeKey = "total_vacation_time_key"
private var currentVacationTimeKey = "current_vacation_time_key"
private var currentOvertimeKey = "current_overtime_key"
private var registrationDateKey = "registration_date_key"
/*
Adds new profile into user defaults.
@methodtype Command
@pre -
@post Stored user profile
*/
func setProfile(profile: Profile)
{
userDefaults.setObject(profile.firstname, forKey: firstnameKey)
userDefaults.setObject(profile.lastname, forKey: lastnameKey)
userDefaults.setObject(profile.employeeId, forKey: employeeIdKey)
userDefaults.setObject(profile.weeklyWorkingTime, forKey: weeklyWorkingTimeKey)
userDefaults.setObject(profile.totalVacationTime, forKey: totalVacationTimeKey)
userDefaults.setObject(profile.currentVacationTime, forKey: currentVacationTimeKey)
userDefaults.setObject(profile.currentOvertime, forKey: currentOvertimeKey)
userDefaults.setObject(Int(profile.registrationDate.timeIntervalSince1970), forKey: registrationDateKey)
}
/*
Returns profile from user defaults.
@methodtype Query
@pre -
@post Get user profile
*/
func getProfile()->Profile?
{
if let employeeId = userDefaults.stringForKey(employeeIdKey)
{
let firstname = userDefaults.stringForKey(firstnameKey)!
let lastname = userDefaults.stringForKey(lastnameKey)!
let weeklyWorkingTime = userDefaults.integerForKey(weeklyWorkingTimeKey)
let totalVacationTime = userDefaults.integerForKey(totalVacationTimeKey)
let currentVacationTime = userDefaults.integerForKey(currentVacationTimeKey)
let currentOvertime = userDefaults.integerForKey(currentOvertimeKey)
let registrationDate = NSDate(timeIntervalSince1970: NSTimeInterval(userDefaults.integerForKey(registrationDateKey)))
return Profile(firstname: firstname, lastname: lastname, employeeId: employeeId, weeklyWorkingTime: weeklyWorkingTime, totalVacationTime: totalVacationTime, currentVacationTime: currentVacationTime, currentOvertime: currentOvertime, registrationDate: registrationDate)
}
return nil
}
/*
Removes profile from user defaults.
@methodtype Command
@pre -
@post All objects are removed, profile is not registered anymore
*/
func removeProfile()
{
userDefaults.removeObjectForKey(firstnameKey)
userDefaults.removeObjectForKey(lastnameKey)
userDefaults.removeObjectForKey(employeeIdKey)
userDefaults.removeObjectForKey(weeklyWorkingTimeKey)
userDefaults.removeObjectForKey(totalVacationTimeKey)
userDefaults.removeObjectForKey(currentVacationTimeKey)
userDefaults.removeObjectForKey(currentOvertimeKey)
}
/*
Asserts if profile is already available, meaning user is registered or not.
@methodtype Assertion
@pre -
@post Assert if user is registered or not
*/
func isRegistered()->Bool
{
if let employeeId = userDefaults.stringForKey(employeeIdKey)
{
return true
}
return false
}
} | agpl-3.0 | 784fdda834e54cd05d742163fc125231 | 36.794872 | 280 | 0.703235 | 5.451295 | false | false | false | false |
bgilham/Bixlet | Bixlet/StationsMapController.swift | 1 | 2348 | //
// StationsMapController.swift
// Bixlet
//
// Created by Brian Gilham on 2016-01-18.
// Copyright © 2016 Brian Gilham. All rights reserved.
//
import UIKit
import MapKit
class StationAnnotation:NSObject, MKAnnotation {
let title:String?
let latitude:Double
let longitude:Double
var coordinate:CLLocationCoordinate2D {
return CLLocationCoordinate2DMake(latitude, longitude)
}
init(title: String?, latitude: Double, longitude: Double) {
self.title = title
self.latitude = latitude
self.longitude = longitude
}
}
class StationsMapController:NSObject, MKMapViewDelegate {
var mapView:MKMapView?
var stations:[Station] = [] {
didSet {
self.displayStations()
}
}
struct LocationConstants {
static let InitialLatitude = 43.656866
static let InitialLongitude = -79.384230
}
init(mapView:MKMapView?) {
self.mapView = mapView
super.init()
}
func showInitialLocation(animated:Bool) {
if let map = self.mapView {
let span = MKCoordinateSpanMake(0.05, 0.05)
let location = CLLocation(
latitude: LocationConstants.InitialLatitude,
longitude: LocationConstants.InitialLongitude
)
let region = MKCoordinateRegion(
center: location.coordinate,
span: span
)
map.setRegion(region, animated: animated)
}
}
func showUserLocation(animated:Bool) {
if let map = self.mapView {
let span = MKCoordinateSpanMake(0.1, 0.1)
let region = MKCoordinateRegion(
center: map.userLocation.coordinate,
span: span
)
map.setRegion(region, animated: animated)
}
}
func displayStations() {
if let map = self.mapView {
map.removeAnnotations(map.annotations)
for station in self.stations {
let annotation = StationAnnotation(
title: station.stationName,
latitude: station.latitude,
longitude: station.longitude
)
map.addAnnotation(annotation)
}
}
}
}
| mit | fa978dff85ebec968d0b2b23147f0dd3 | 26.290698 | 63 | 0.569663 | 5.047312 | false | false | false | false |
lvogelzang/Blocky | Blocky/SceneController.swift | 1 | 10001 | //
// SceneController.swift
// Blocky
//
// Created by Lodewijck on 11/08/2018.
// Copyright © 2018 Lodewijck. All rights reserved.
//
import UIKit
import SceneKit
let blockyCategory:Int = 1 << 1
let enemyCategory:Int = 1 << 2
let foodCategory:Int = 1 << 3
class SceneController: NSObject, SCNPhysicsContactDelegate {
let mainViewController: MainViewController
var level: Level
let scene: SCNScene
var cameraStartPosition: SCNVector3
var lastControl: Control?
var lastDied: Date = Date(timeIntervalSince1970: 0)
var won: Bool = false
// Initializes scene controller, does not yet load scene.
required init(mainViewController: MainViewController, level: Level) {
self.mainViewController = mainViewController
self.level = level
scene = SCNScene(named: level.getSceneName())!
cameraStartPosition = scene.rootNode.childNode(withName: "Camera", recursively: false)!.position
super.init()
scene.isPaused = true
scene.physicsWorld.contactDelegate = self
scene.physicsWorld.gravity = SCNVector3Zero
level.blocky.node = getNodeNamed("Blocky")
level.blocky.node!.physicsBody = createBoxPhysicsBody(categoryBitMask: blockyCategory, collisionBitMask: enemyCategory | foodCategory, edge: 0.8)
for enemy: Enemy in level.enemies {
enemy.node = getNodeNamed("Enemy\(enemy.enemyNumber)")
enemy.node!.physicsBody = createBoxPhysicsBody(categoryBitMask: enemyCategory, collisionBitMask: blockyCategory, edge: 0.8)
enemy.addAnimation()
}
for food: Food in level.foods {
food.node = getNodeNamed("Food\(food.foodNumber)")
food.node!.physicsBody = createBoxPhysicsBody(categoryBitMask: foodCategory, collisionBitMask: blockyCategory, edge: 0.2)
}
}
// Reset scene, called when retrying level after one died.
internal func reset() {
lastControl = nil
level.blocky.reset()
for food: Food in level.foods {
food.reset()
}
for enemy: Enemy in level.enemies {
enemy.reset()
}
// Animate camera back.
if (level.cameraFollowsBlock) {
moveCamera(to: cameraStartPosition)
}
// Put breakable tiles back.
for y in 0 ..< level.tiles.count {
for x in 0 ..< level.tiles[0].count {
if (level.tiles[y][x] == 3) {
getNodeNamed("Tile\(x)_\(y)").isHidden = false
level.tiles[y][x] = 2
}
}
}
}
internal func setPaused(_ paused: Bool) {
scene.isPaused = paused
}
// Handles pan as default game control gesture.
internal func handlePan(_ gestureRecognizer: UIGestureRecognizer) {
// Don't handle pans just after player died.
let threshold = Date(timeInterval: -0.2, since: Date())
if lastDied.compare(threshold) == ComparisonResult.orderedDescending {
return
}
let panGesture = gestureRecognizer as! UIPanGestureRecognizer
let velocity = panGesture.velocity(in: gestureRecognizer.view)
let xVelocity = velocity.x
let yVelocity = velocity.y
var direction:Direction = .north
// If horizontal movement is bigger.
if (abs(xVelocity) > abs(yVelocity)) {
if (xVelocity > 0) {
direction = .east
} else {
direction = .west
}
}
// If vertical movement is bigger.
else {
if (yVelocity < 0) {
direction = .north
} else {
direction = .south
}
}
lastControl = Control(direction: direction, timestamp: Date())
checkForMove()
}
// Perform move if not animating yet, move was played and move is possible.
fileprivate func checkForMove() {
if (level.blocky.isAnimating == false) {
if let control = lastControl {
let threshold = Date(timeInterval: -0.2, since: Date())
if control.timestamp.compare(threshold) == ComparisonResult.orderedDescending {
if canMoveInDirection(control.direction) {
breakTileIfNeeded()
level.blocky.location = newLocation(level.blocky.location, direction: control.direction)
move(control.direction)
}
}
}
}
}
// Checks if block can move in given direction, based on map.
fileprivate func canMoveInDirection(_ direction: Direction) -> Bool {
let (newX, newY) = newLocation(level.blocky.location, direction: direction)
let maxX = level.tiles.first!.count - 1
let maxY = level.tiles.count - 1
// If not outside borders.
if (newX >= 0 && newX <= maxX && newY >= 0 && newY <= maxY) {
// If new position is a normal tile or a breakable tile.
if (level.tiles[newY][newX] == 1 || level.tiles[newY][newX] == 2) {
return true
}
}
return false
}
// Returns location after one move in given direction from given location.
fileprivate func newLocation(_ currentLocation: (Int, Int), direction: Direction) -> (Int, Int) {
let (oldX, oldY) = currentLocation
switch(direction) {
case Direction.north: return (oldX, oldY+1)
case Direction.east: return (oldX+1, oldY)
case Direction.south: return (oldX, oldY-1)
case Direction.west: return (oldX-1, oldY)
}
}
fileprivate func move(_ direction: Direction) {
if (level.blocky.started == false) {
level.blocky.started = true
Database.incrementTriesForLevel(level.levelNumber)
}
// Animate block.
let blockAnimation = AnimationFactory.getDefaultBlockAnimation(direction: direction, duration: 0.5)
level.blocky.isAnimating = true
level.blocky.node!.runAction(blockAnimation, completionHandler: {
self.level.blocky.isAnimating = false
// If Block is on end location.
if (self.level.blocky.location.0 == self.level.blocky.endLocation.0 &&
self.level.blocky.location.1 == self.level.blocky.endLocation.1) {
// Check if Block has eaten all foods.
var ateAllFoods = true
for food: Food in self.level.foods {
if (food.eaten == false) {
ateAllFoods = false
}
}
if (ateAllFoods) {
self.win()
return
}
}
self.checkForMove()
})
// Animate camera if needed.
if (level.cameraFollowsBlock) {
let camera = getNodeNamed("Camera")
let cameraAnimation = AnimationFactory.getDefaultMove(direction: direction, duration: 0.5)
camera.runAction(cameraAnimation)
}
for enemy in level.enemies {
enemy.stepAnimation()
}
}
// Makes tile invisble if old tile was breakable.
fileprivate func breakTileIfNeeded() {
if (level.tiles[level.blocky.location.1][level.blocky.location.0] == 2) {
getNodeNamed("Tile\(level.blocky.location.0)_\(level.blocky.location.1)").isHidden = true
level.tiles[level.blocky.location.1][level.blocky.location.0] = 3
}
}
// Returns node with given name from currently loaded scene.
fileprivate func getNodeNamed(_ name: String) -> SCNNode {
return scene.rootNode.childNode(withName: name, recursively: false)!
}
// Returns default cube as physics body
fileprivate func createBoxPhysicsBody(categoryBitMask: Int, collisionBitMask: Int, edge: CGFloat) -> SCNPhysicsBody {
let blockBox = SCNBox(width: edge, height: edge, length: edge, chamferRadius: 0)
let blockPhysicsShape = SCNPhysicsShape(geometry: blockBox, options: nil)
let body = SCNPhysicsBody(type: SCNPhysicsBodyType.kinematic, shape: blockPhysicsShape)
body.categoryBitMask = categoryBitMask
// Since iOS 9.0 uses contacts instead of collisions. More info in iOS documentation.
if #available(iOS 9.0, *) {
body.contactTestBitMask = collisionBitMask
} else {
body.collisionBitMask = collisionBitMask
}
return body
}
// Collision detected between Block and an Enemy.
func physicsWorld(_ world: SCNPhysicsWorld, didBegin contact: SCNPhysicsContact) {
// No collisions on start location: prevent bugs on resetting scene.
if (level.blocky.location.0 != level.blocky.startLocation.0 ||
level.blocky.location.1 != level.blocky.startLocation.1) {
// If contact with Enemy.
if (contact.nodeB.physicsBody?.categoryBitMask == enemyCategory) {
die()
}
// If contact with Food.
else if (contact.nodeB.physicsBody?.categoryBitMask == foodCategory) {
contact.nodeB.isHidden = true
}
}
}
internal func moveCamera(to: SCNVector3) {
let camera = getNodeNamed("Camera")
let cameraAnimation = SCNAction.move(to: to, duration: 0.5)
camera.runAction(cameraAnimation)
}
func win() {
Database.wonLevel(level.levelNumber)
won = true
mainViewController.setMenuVisible(true)
}
func die() {
lastDied = Date()
reset()
}
}
| mit | 81c3a2cb02bd8335d5e52700e5db6100 | 35.231884 | 153 | 0.5803 | 4.889976 | false | false | false | false |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.