hexsha
stringlengths 40
40
| size
int64 3
1.03M
| content
stringlengths 3
1.03M
| avg_line_length
float64 1.33
100
| max_line_length
int64 2
1k
| alphanum_fraction
float64 0.25
0.99
|
---|---|---|---|---|---|
46e02f2f39532525ea7d4a18c5947b500b2400d1 | 4,681 | //
// SAIToolboxInputViewLayout.swift
// SAC
//
// Created by SAGESSE on 9/15/16.
// Copyright © 2016-2017 SAGESSE. All rights reserved.
//
import UIKit
@objc
internal protocol SAIToolboxInputViewLayoutDelegate: UICollectionViewDelegate {
@objc optional func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: SAIToolboxInputViewLayout, insetForSectionAt index: Int) -> UIEdgeInsets
@objc optional func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: SAIToolboxInputViewLayout, numberOfRowsForSectionAt index: Int) -> Int
@objc optional func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: SAIToolboxInputViewLayout, numberOfColumnsForSectionAt index: Int) -> Int
}
internal class SAIToolboxInputViewLayout: UICollectionViewLayout {
func numberOfRows(in section: Int) -> Int {
guard let collectionView = collectionView else {
return 2
}
guard let delegate = collectionView.delegate as? SAIToolboxInputViewLayoutDelegate else {
return 2
}
return delegate.collectionView?(collectionView, layout: self, numberOfRowsForSectionAt: section) ?? 2
}
func numberOfColumns(in section: Int) -> Int {
guard let collectionView = collectionView else {
return 4
}
guard let delegate = collectionView.delegate as? SAIToolboxInputViewLayoutDelegate else {
return 4
}
return delegate.collectionView?(collectionView, layout: self, numberOfColumnsForSectionAt: section) ?? 4
}
func contentInset(in section: Int) -> UIEdgeInsets {
guard let collectionView = collectionView else {
return .zero
}
guard let delegate = collectionView.delegate as? SAIToolboxInputViewLayoutDelegate else {
return .zero
}
return delegate.collectionView?(collectionView, layout: self, insetForSectionAt: section) ?? .zero
}
weak var delegate: SAIToolboxInputViewLayoutDelegate? {
return collectionView?.delegate as? SAIToolboxInputViewLayoutDelegate
}
override var collectionViewContentSize: CGSize {
let count = collectionView?.numberOfItems(inSection: 0) ?? 0
let maxCount = numberOfRows(in: 0) * numberOfColumns(in: 0)
let page = (count + (maxCount - 1)) / maxCount
let frame = collectionView?.frame ?? CGRect.zero
return CGSize(width: frame.width * CGFloat(page) - 1, height: 0)
}
override func shouldInvalidateLayout(forBoundsChange newBounds: CGRect) -> Bool {
if collectionView?.frame.width != newBounds.width {
return true
}
return false
}
override func prepare() {
super.prepare()
_attributesCache = nil
}
override func layoutAttributesForElements(in rect: CGRect) -> [UICollectionViewLayoutAttributes]? {
if let attributes = _attributesCache {
return attributes
}
var ats = [UICollectionViewLayoutAttributes]()
// 生成
let edg = contentInset(in: 0)
let frame = collectionView?.bounds ?? .zero
let count = collectionView?.numberOfItems(inSection: 0) ?? 0
let width = frame.width - edg.left - edg.right
let height = frame.height - edg.top - edg.bottom
let irows = numberOfRows(in: 0)
let icolumns = numberOfColumns(in: 0)
let rows = CGFloat(irows)
let columns = CGFloat(icolumns)
let w: CGFloat = min(trunc((width - 8 * columns) / columns), 80)
let h: CGFloat = min(trunc((height - 4 * rows) / rows), 80)
let yg: CGFloat = (height / rows) - h
let xg: CGFloat = (width / columns) - w
// fill
for i in 0 ..< count {
// 计算。
let r = CGFloat((i / icolumns) % irows)
let c = CGFloat((i % icolumns))
let idx = IndexPath(item: i, section: 0)
let page = CGFloat(i / (irows * icolumns))
let a = self.layoutAttributesForItem(at: idx) ?? UICollectionViewLayoutAttributes(forCellWith: idx)
let x = edg.left + xg / 2 + c * (w + xg) + page * frame.width
let y = edg.top + yg / 2 + r * (h + yg)
a.frame = CGRect(x: x, y: y, width: w, height: h)
ats.append(a)
}
_attributesCache = ats
return ats
}
private var _defaultRows: Int = 2
private var _defaultColumns: Int = 4
private var _attributesCache: [UICollectionViewLayoutAttributes]?
}
| 39.008333 | 177 | 0.634053 |
ef30cf43b29df440557eb339a33e1202b273fd1e | 1,778 | /*
* JLToastCenter.swift
*
* DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE
* Version 2, December 2004
*
* Copyright (C) 2013-2015 Su Yeol Jeon
*
* Everyone is permitted to copy and distribute verbatim or modified
* copies of this license document, and changing it is allowed as long
* as the name is changed.
*
* DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE
* TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
*
* 0. You just DO WHAT THE FUCK YOU WANT TO.
*
*/
import UIKit
@objc public class JLToastCenter: NSObject {
private var _queue: NSOperationQueue!
public var currentToast: JLToast? {
return self._queue.operations.first as? JLToast
}
private struct Singletone {
static let defaultCenter = JLToastCenter()
}
public class func defaultCenter() -> JLToastCenter {
return Singletone.defaultCenter
}
override init() {
super.init()
self._queue = NSOperationQueue()
self._queue.maxConcurrentOperationCount = 1
NSNotificationCenter.defaultCenter().addObserver(
self,
selector: #selector(self.deviceOrientationDidChange),
name: UIDeviceOrientationDidChangeNotification,
object: nil
)
}
public func addToast(toast: JLToast) {
self._queue.addOperation(toast)
}
func deviceOrientationDidChange(sender: AnyObject?) {
if self._queue.operations.count > 0 {
let lastToast: JLToast = _queue.operations[0] as! JLToast
lastToast.view.updateView()
}
}
public func cancelAllToasts() {
for toast in self._queue.operations {
toast.cancel()
}
}
}
| 26.147059 | 70 | 0.630484 |
dd1a40335be42d9de9f432fec788350490555429 | 2,077 | //
// AppDelegate.swift
// ReadersWriters
//
// Created by Alex on 5/9/21.
// Copyright © 2021 AlexCo. All rights reserved.
//
import Cocoa
@NSApplicationMain
class AppDelegate: NSObject, NSApplicationDelegate {
@IBOutlet weak var window: NSWindow!
private var operations = [OperationPerformer]()
private let storage: Storage = StorageImpl()
func applicationDidFinishLaunching(_ aNotification: Notification) {
// Insert code here to initialize your application
let reader1Perfromer = OperationPerformer(id: 0, storage: storage)
operations.append(reader1Perfromer)
reader1Perfromer.perform { (storage, id) in
if let str = storage.readLast() {
Swift.print("Reader: \(id): \(str)")
} else {
Swift.print("Storage empty")
}
}
let reader2Perfromer = OperationPerformer(id: 1, storage: storage)
operations.append(reader2Perfromer)
reader2Perfromer.perform({ (storage, id) in
if let str = storage.readLast() {
Swift.print("Reader: \(id): \(str)")
} else {
Swift.print("Storage empty")
}
})
let addPerformer = OperationPerformer(id: 2, storage: storage)
operations.append(addPerformer)
addPerformer.perform({ (storage, id) in
storage.add("\(Date())")
Swift.print("Add Performer: \(id):")
})
let removeLastPerfromer = OperationPerformer(id: 3, storage: storage)
operations.append(removeLastPerfromer)
removeLastPerfromer.perform({ (storage, id) in
storage.removeLast()
Swift.print("Remove Last Performer: \(id)")
})
}
func applicationWillTerminate(_ aNotification: Notification) {
// Insert code here to tear down your application
}
func applicationShouldTerminateAfterLastWindowClosed(_ sender: NSApplication) -> Bool {
return true
}
}
| 28.847222 | 91 | 0.597496 |
28eab95050505cf0b2a2d8e81d1113f5b31651b9 | 44,410 | // RUN: %target-typecheck-verify-swift -swift-version 3
// Tests for tuple argument behavior in Swift 3, which was broken.
// The Swift 4 test is in test/Compatibility/tuple_arguments_4.swift.
// The test for the most recent version is in test/Constraints/tuple_arguments.swift.
// Key:
// - "Crashes in actual Swift 3" -- snippets which crashed in Swift 3.0.1.
// These don't have well-defined semantics in Swift 3 mode and don't
// matter for source compatibility purposes.
//
// - "Does not diagnose in Swift 3 mode" -- snippets which failed to typecheck
// in Swift 3.0.1, but now typecheck. This is fine.
//
// - "Diagnoses in Swift 3 mode" -- snippets which typechecked in Swift 3.0.1,
// but now fail to typecheck. These are bugs in Swift 3 mode that should be
// fixed.
//
// - "Crashes in Swift 3 mode" -- snippets which did not crash Swift 3.0.1,
// but now crash. These are bugs in Swift 3 mode that should be fixed.
func concrete(_ x: Int) {}
func concreteLabeled(x: Int) {}
func concreteTwo(_ x: Int, _ y: Int) {} // expected-note 3 {{'concreteTwo' declared here}}
func concreteTuple(_ x: (Int, Int)) {}
do {
concrete(3)
concrete((3))
concreteLabeled(x: 3)
concreteLabeled(x: (3))
concreteLabeled((x: 3)) // expected-error {{missing argument label 'x:' in call}}
concreteTwo(3, 4)
concreteTwo((3, 4)) // expected-error {{missing argument for parameter #2 in call}}
concreteTuple(3, 4) // expected-error {{global function 'concreteTuple' expects a single parameter of type '(Int, Int)'}} {{17-17=(}} {{21-21=)}}
concreteTuple((3, 4))
}
do {
let a = 3
let b = 4
let c = (3)
let d = (a, b)
concrete(a)
concrete((a))
concrete(c)
concreteTwo(a, b)
concreteTwo((a, b))
concreteTwo(d) // expected-error {{passing 2 arguments to a callee as a single tuple value has been removed in Swift 3}}
concreteTuple(a, b)
concreteTuple((a, b))
concreteTuple(d)
}
do {
var a = 3
var b = 4
var c = (3)
var d = (a, b)
concrete(a)
concrete((a))
concrete(c)
concreteTwo(a, b)
concreteTwo((a, b)) // expected-error {{missing argument for parameter #2 in call}}
concreteTwo(d) // expected-error {{missing argument for parameter #2 in call}}
concreteTuple(a, b) // expected-error {{global function 'concreteTuple' expects a single parameter of type '(Int, Int)'}} {{17-17=(}} {{21-21=)}}
concreteTuple((a, b))
concreteTuple(d)
}
func generic<T>(_ x: T) {}
func genericLabeled<T>(x: T) {}
func genericTwo<T, U>(_ x: T, _ y: U) {} // expected-note 5 {{'genericTwo' declared here}}
func genericTuple<T, U>(_ x: (T, U)) {}
do {
generic(3)
generic(3, 4)
generic((3))
generic((3, 4))
genericLabeled(x: 3)
genericLabeled(x: 3, 4) // expected-error {{extra argument in call}}
genericLabeled(x: (3))
genericLabeled(x: (3, 4))
genericTwo(3, 4)
genericTwo((3, 4)) // expected-error {{missing argument for parameter #2 in call}}
genericTuple(3, 4) // expected-error {{global function 'genericTuple' expects a single parameter of type '(T, U)'}} {{16-16=(}} {{20-20=)}}
genericTuple((3, 4))
}
do {
let a = 3
let b = 4
let c = (3)
let d = (a, b)
generic(a)
generic(a, b)
generic((a))
generic(c)
generic((a, b))
generic(d)
genericTwo(a, b)
genericTwo((a, b)) // expected-error {{missing argument for parameter #2 in call}}
genericTwo(d) // expected-error {{missing argument for parameter #2 in call}}
genericTuple(a, b) // expected-error {{global function 'genericTuple' expects a single parameter of type '(T, U)'}} {{16-16=(}} {{20-20=)}}
genericTuple((a, b))
genericTuple(d)
}
do {
var a = 3
var b = 4
var c = (3)
var d = (a, b)
generic(a)
// generic(a, b) // Crashes in actual Swift 3
generic((a))
generic(c)
generic((a, b))
generic(d)
genericTwo(a, b)
genericTwo((a, b)) // expected-error {{missing argument for parameter #2 in call}}
genericTwo(d) // expected-error {{missing argument for parameter #2 in call}}
genericTuple(a, b) // expected-error {{global function 'genericTuple' expects a single parameter of type '(T, U)'}} {{16-16=(}} {{20-20=)}}
genericTuple((a, b))
genericTuple(d)
}
var function: (Int) -> ()
var functionTwo: (Int, Int) -> () // expected-note 3 {{'functionTwo' declared here}}
var functionTuple: ((Int, Int)) -> ()
do {
function(3)
function((3))
functionTwo(3, 4)
functionTwo((3, 4)) // expected-error {{missing argument for parameter #2 in call}}
functionTuple(3, 4) // expected-error {{var 'functionTuple' expects a single parameter of type '(Int, Int)'}} {{17-17=(}} {{21-21=)}}
functionTuple((3, 4))
}
do {
let a = 3
let b = 4
let c = (3)
let d = (a, b)
function(a)
function((a))
function(c)
functionTwo(a, b)
functionTwo((a, b))
functionTwo(d) // expected-error {{passing 2 arguments to a callee as a single tuple value has been removed in Swift 3}}
functionTuple(a, b)
functionTuple((a, b))
functionTuple(d)
}
do {
var a = 3
var b = 4
var c = (3)
var d = (a, b)
function(a)
function((a))
function(c)
functionTwo(a, b)
functionTwo((a, b)) // expected-error {{missing argument for parameter #2 in call}}
functionTwo(d) // expected-error {{missing argument for parameter #2 in call}}
functionTuple(a, b) // expected-error {{var 'functionTuple' expects a single parameter of type '(Int, Int)'}} {{17-17=(}} {{21-21=)}}
functionTuple((a, b))
functionTuple(d)
}
struct Concrete {}
extension Concrete {
func concrete(_ x: Int) {}
func concreteTwo(_ x: Int, _ y: Int) {} // expected-note 3 {{'concreteTwo' declared here}}
func concreteTuple(_ x: (Int, Int)) {}
}
do {
let s = Concrete()
s.concrete(3)
s.concrete((3))
s.concreteTwo(3, 4)
s.concreteTwo((3, 4)) // expected-error {{missing argument for parameter #2 in call}}
s.concreteTuple(3, 4) // expected-error {{instance method 'concreteTuple' expects a single parameter of type '(Int, Int)'}} {{19-19=(}} {{23-23=)}}
s.concreteTuple((3, 4))
}
do {
let s = Concrete()
let a = 3
let b = 4
let c = (3)
let d = (a, b)
s.concrete(a)
s.concrete((a))
s.concrete(c)
s.concreteTwo(a, b)
s.concreteTwo((a, b))
s.concreteTwo(d) // expected-error {{passing 2 arguments to a callee as a single tuple value has been removed in Swift 3}}
s.concreteTuple(a, b)
s.concreteTuple((a, b))
s.concreteTuple(d)
}
do {
var s = Concrete()
var a = 3
var b = 4
var c = (3)
var d = (a, b)
s.concrete(a)
s.concrete((a))
s.concrete(c)
s.concreteTwo(a, b)
s.concreteTwo((a, b)) // expected-error {{missing argument for parameter #2 in call}}
s.concreteTwo(d) // expected-error {{missing argument for parameter #2 in call}}
s.concreteTuple(a, b) // expected-error {{instance method 'concreteTuple' expects a single parameter of type '(Int, Int)'}} {{19-19=(}} {{23-23=)}}
s.concreteTuple((a, b))
s.concreteTuple(d)
}
extension Concrete {
func generic<T>(_ x: T) {}
func genericLabeled<T>(x: T) {}
func genericTwo<T, U>(_ x: T, _ y: U) {} // expected-note 5 {{'genericTwo' declared here}}
func genericTuple<T, U>(_ x: (T, U)) {}
}
do {
let s = Concrete()
s.generic(3)
s.generic(3, 4)
s.generic((3))
s.generic((3, 4))
s.genericLabeled(x: 3)
s.genericLabeled(x: 3, 4) // expected-error {{extra argument in call}}
s.genericLabeled(x: (3))
s.genericLabeled(x: (3, 4))
s.genericTwo(3, 4)
s.genericTwo((3, 4)) // expected-error {{missing argument for parameter #2 in call}}
s.genericTuple(3, 4) // expected-error {{instance method 'genericTuple' expects a single parameter of type '(T, U)'}} {{18-18=(}} {{22-22=)}}
s.genericTuple((3, 4))
}
do {
let s = Concrete()
let a = 3
let b = 4
let c = (3)
let d = (a, b)
s.generic(a)
s.generic(a, b)
s.generic((a))
s.generic((a, b))
s.generic(d)
s.genericTwo(a, b)
s.genericTwo((a, b)) // expected-error {{missing argument for parameter #2 in call}}
s.genericTwo(d) // expected-error {{missing argument for parameter #2 in call}}
s.genericTuple(a, b) // expected-error {{instance method 'genericTuple' expects a single parameter of type '(T, U)'}} {{18-18=(}} {{22-22=)}}
s.genericTuple((a, b))
s.genericTuple(d)
}
do {
var s = Concrete()
var a = 3
var b = 4
var c = (3)
var d = (a, b)
s.generic(a)
// s.generic(a, b) // Crashes in actual Swift 3
s.generic((a))
s.generic((a, b))
s.generic(d)
s.genericTwo(a, b)
s.genericTwo((a, b)) // expected-error {{missing argument for parameter #2 in call}}
s.genericTwo(d) // expected-error {{missing argument for parameter #2 in call}}
s.genericTuple(a, b) // expected-error {{instance method 'genericTuple' expects a single parameter of type '(T, U)'}} {{18-18=(}} {{22-22=)}}
s.genericTuple((a, b))
s.genericTuple(d)
}
extension Concrete {
mutating func mutatingConcrete(_ x: Int) {}
mutating func mutatingConcreteTwo(_ x: Int, _ y: Int) {} // expected-note 3 {{'mutatingConcreteTwo' declared here}}
mutating func mutatingConcreteTuple(_ x: (Int, Int)) {}
}
do {
var s = Concrete()
s.mutatingConcrete(3)
s.mutatingConcrete((3))
s.mutatingConcreteTwo(3, 4)
s.mutatingConcreteTwo((3, 4)) // expected-error {{missing argument for parameter #2 in call}}
s.mutatingConcreteTuple(3, 4) // expected-error {{instance method 'mutatingConcreteTuple' expects a single parameter of type '(Int, Int)'}} {{27-27=(}} {{31-31=)}}
s.mutatingConcreteTuple((3, 4))
}
do {
var s = Concrete()
let a = 3
let b = 4
let c = (3)
let d = (a, b)
s.mutatingConcrete(a)
s.mutatingConcrete((a))
s.mutatingConcrete(c)
s.mutatingConcreteTwo(a, b)
s.mutatingConcreteTwo((a, b))
s.mutatingConcreteTwo(d) // expected-error {{passing 2 arguments to a callee as a single tuple value has been removed in Swift 3}}
s.mutatingConcreteTuple(a, b)
s.mutatingConcreteTuple((a, b))
s.mutatingConcreteTuple(d)
}
do {
var s = Concrete()
var a = 3
var b = 4
var c = (3)
var d = (a, b)
s.mutatingConcrete(a)
s.mutatingConcrete((a))
s.mutatingConcrete(c)
s.mutatingConcreteTwo(a, b)
s.mutatingConcreteTwo((a, b)) // expected-error {{missing argument for parameter #2 in call}}
s.mutatingConcreteTwo(d) // expected-error {{missing argument for parameter #2 in call}}
s.mutatingConcreteTuple(a, b) // expected-error {{instance method 'mutatingConcreteTuple' expects a single parameter of type '(Int, Int)'}} {{27-27=(}} {{31-31=)}}
s.mutatingConcreteTuple((a, b))
s.mutatingConcreteTuple(d)
}
extension Concrete {
mutating func mutatingGeneric<T>(_ x: T) {}
mutating func mutatingGenericLabeled<T>(x: T) {}
mutating func mutatingGenericTwo<T, U>(_ x: T, _ y: U) {} // expected-note 5 {{'mutatingGenericTwo' declared here}}
mutating func mutatingGenericTuple<T, U>(_ x: (T, U)) {}
}
do {
var s = Concrete()
s.mutatingGeneric(3)
s.mutatingGeneric(3, 4)
s.mutatingGeneric((3))
s.mutatingGeneric((3, 4))
s.mutatingGenericLabeled(x: 3)
s.mutatingGenericLabeled(x: 3, 4) // expected-error {{extra argument in call}}
s.mutatingGenericLabeled(x: (3))
s.mutatingGenericLabeled(x: (3, 4))
s.mutatingGenericTwo(3, 4)
s.mutatingGenericTwo((3, 4)) // expected-error {{missing argument for parameter #2 in call}}
s.mutatingGenericTuple(3, 4) // expected-error {{instance method 'mutatingGenericTuple' expects a single parameter of type '(T, U)'}} {{26-26=(}} {{30-30=)}}
s.mutatingGenericTuple((3, 4))
}
do {
var s = Concrete()
let a = 3
let b = 4
let c = (3)
let d = (a, b)
s.mutatingGeneric(a)
s.mutatingGeneric(a, b)
s.mutatingGeneric((a))
s.mutatingGeneric((a, b))
s.mutatingGeneric(d)
s.mutatingGenericTwo(a, b)
s.mutatingGenericTwo((a, b)) // expected-error {{missing argument for parameter #2 in call}}
s.mutatingGenericTwo(d) // expected-error {{missing argument for parameter #2 in call}}
s.mutatingGenericTuple(a, b) // expected-error {{instance method 'mutatingGenericTuple' expects a single parameter of type '(T, U)'}} {{26-26=(}} {{30-30=)}}
s.mutatingGenericTuple((a, b))
s.mutatingGenericTuple(d)
}
do {
var s = Concrete()
var a = 3
var b = 4
var c = (3)
var d = (a, b)
s.mutatingGeneric(a)
// s.mutatingGeneric(a, b) // Crashes in actual Swift 3
s.mutatingGeneric((a))
s.mutatingGeneric((a, b))
s.mutatingGeneric(d)
s.mutatingGenericTwo(a, b)
s.mutatingGenericTwo((a, b)) // expected-error {{missing argument for parameter #2 in call}}
s.mutatingGenericTwo(d) // expected-error {{missing argument for parameter #2 in call}}
s.mutatingGenericTuple(a, b) // expected-error {{instance method 'mutatingGenericTuple' expects a single parameter of type '(T, U)'}} {{26-26=(}} {{30-30=)}}
s.mutatingGenericTuple((a, b))
s.mutatingGenericTuple(d)
}
extension Concrete {
var function: (Int) -> () { return concrete }
var functionTwo: (Int, Int) -> () { return concreteTwo }
var functionTuple: ((Int, Int)) -> () { return concreteTuple }
}
do {
let s = Concrete()
s.function(3)
s.function((3))
s.functionTwo(3, 4)
s.functionTwo((3, 4)) // expected-error {{missing argument for parameter #2 in call}}
s.functionTuple(3, 4) // expected-error {{single parameter of type '(Int, Int)' is expected in call}} {{19-19=(}} {{23-23=)}}
s.functionTuple((3, 4))
}
do {
let s = Concrete()
let a = 3
let b = 4
let c = (3)
let d = (a, b)
s.function(a)
s.function((a))
s.function(c)
s.functionTwo(a, b)
s.functionTwo((a, b))
s.functionTwo(d) // expected-error {{passing 2 arguments to a callee as a single tuple value has been removed in Swift 3}}
s.functionTuple(a, b)
s.functionTuple((a, b))
s.functionTuple(d)
}
do {
var s = Concrete()
var a = 3
var b = 4
var c = (3)
var d = (a, b)
s.function(a)
s.function((a))
s.function(c)
s.functionTwo(a, b)
s.functionTwo((a, b)) // expected-error {{missing argument for parameter #2 in call}}
s.functionTwo(d) // expected-error {{missing argument for parameter #2 in call}}
s.functionTuple(a, b) // expected-error {{single parameter of type '(Int, Int)' is expected in call}} {{19-19=(}} {{23-23=)}}
s.functionTuple((a, b))
s.functionTuple(d)
}
struct InitTwo {
init(_ x: Int, _ y: Int) {} // expected-note 3 {{'init' declared here}}
}
struct InitTuple {
init(_ x: (Int, Int)) {}
}
struct InitLabeledTuple {
init(x: (Int, Int)) {}
}
do {
_ = InitTwo(3, 4)
_ = InitTwo((3, 4)) // expected-error {{missing argument for parameter #2 in call}}
_ = InitTuple(3, 4) // expected-error {{initializer expects a single parameter of type '(Int, Int)'}} {{17-17=(}} {{21-21=)}}
_ = InitTuple((3, 4))
_ = InitLabeledTuple(x: 3, 4) // expected-error {{initializer expects a single parameter of type '(Int, Int)'}}
_ = InitLabeledTuple(x: (3, 4))
}
do {
let a = 3
let b = 4
let c = (a, b)
_ = InitTwo(a, b)
_ = InitTwo((a, b))
_ = InitTwo(c) // expected-error {{passing 2 arguments to a callee as a single tuple value has been removed in Swift 3}}
_ = InitTuple(a, b)
_ = InitTuple((a, b))
_ = InitTuple(c)
}
do {
var a = 3
var b = 4
var c = (a, b)
_ = InitTwo(a, b)
_ = InitTwo((a, b)) // expected-error {{missing argument for parameter #2 in call}}
_ = InitTwo(c) // expected-error {{missing argument for parameter #2 in call}}
_ = InitTuple(a, b) // expected-error {{initializer expects a single parameter of type '(Int, Int)'}} {{17-17=(}} {{21-21=)}}
_ = InitTuple((a, b))
_ = InitTuple(c)
}
struct SubscriptTwo {
subscript(_ x: Int, _ y: Int) -> Int { get { return 0 } set { } } // expected-note 3 {{'subscript' declared here}}
}
struct SubscriptTuple {
subscript(_ x: (Int, Int)) -> Int { get { return 0 } set { } }
}
struct SubscriptLabeledTuple {
subscript(x x: (Int, Int)) -> Int { get { return 0 } set { } }
}
do {
let s1 = SubscriptTwo()
_ = s1[3, 4]
_ = s1[(3, 4)] // expected-error {{missing argument for parameter #2 in call}}
let s2 = SubscriptTuple()
_ = s2[3, 4] // expected-error {{subscript expects a single parameter of type '(Int, Int)'}} {{10-10=(}} {{14-14=)}}
_ = s2[(3, 4)]
let s3 = SubscriptLabeledTuple()
_ = s3[x: 3, 4] // expected-error {{subscript expects a single parameter of type '(Int, Int)'}}
_ = s3[x: (3, 4)]
}
do {
let a = 3
let b = 4
let d = (a, b)
let s1 = SubscriptTwo()
_ = s1[a, b]
_ = s1[(a, b)]
_ = s1[d]
let s2 = SubscriptTuple()
_ = s2[a, b]
_ = s2[(a, b)]
_ = s2[d]
}
do {
// TODO: Restore regressed diagnostics rdar://problem/31724211
var a = 3
var b = 4
var d = (a, b)
var s1 = SubscriptTwo()
_ = s1[a, b]
_ = s1[(a, b)] // expected-error {{missing argument for parameter #2 in call}}
_ = s1[d] // expected-error {{missing argument for parameter #2 in call}}
var s2 = SubscriptTuple()
_ = s2[a, b] // expected-error {{subscript expects a single parameter of type '(Int, Int)'}} {{10-10=(}} {{14-14=)}}
_ = s2[(a, b)]
_ = s2[d]
}
enum Enum {
case two(Int, Int) // expected-note 3 {{'two' declared here}}
case tuple((Int, Int))
case labeledTuple(x: (Int, Int))
}
do {
_ = Enum.two(3, 4)
_ = Enum.two((3, 4)) // expected-error {{missing argument for parameter #2 in call}}
_ = Enum.tuple(3, 4) // expected-error {{enum element 'tuple' expects a single parameter of type '(Int, Int)'}} {{18-18=(}} {{22-22=)}}
_ = Enum.tuple((3, 4))
_ = Enum.labeledTuple(x: 3, 4) // expected-error {{enum element 'labeledTuple' expects a single parameter of type '(Int, Int)'}}
_ = Enum.labeledTuple(x: (3, 4))
}
do {
let a = 3
let b = 4
let c = (a, b)
_ = Enum.two(a, b)
_ = Enum.two((a, b))
_ = Enum.two(c) // expected-error {{passing 2 arguments to a callee as a single tuple value has been removed in Swift 3}}
_ = Enum.tuple(a, b)
_ = Enum.tuple((a, b))
_ = Enum.tuple(c)
}
do {
var a = 3
var b = 4
var c = (a, b)
_ = Enum.two(a, b)
_ = Enum.two((a, b)) // expected-error {{missing argument for parameter #2 in call}}
_ = Enum.two(c) // expected-error {{missing argument for parameter #2 in call}}
_ = Enum.tuple(a, b) // expected-error {{enum element 'tuple' expects a single parameter of type '(Int, Int)'}} {{18-18=(}} {{22-22=)}}
_ = Enum.tuple((a, b))
_ = Enum.tuple(c)
}
struct Generic<T> {}
extension Generic {
func generic(_ x: T) {}
func genericLabeled(x: T) {}
func genericTwo(_ x: T, _ y: T) {} // expected-note 2 {{'genericTwo' declared here}}
func genericTuple(_ x: (T, T)) {}
}
do {
let s = Generic<Double>()
s.generic(3.0)
s.generic((3.0))
s.genericLabeled(x: 3.0)
s.genericLabeled(x: (3.0))
s.genericTwo(3.0, 4.0)
s.genericTwo((3.0, 4.0)) // expected-error {{missing argument for parameter #2 in call}}
s.genericTuple(3.0, 4.0) // expected-error {{instance method 'genericTuple' expects a single parameter of type '(Double, Double)'}} {{18-18=(}} {{26-26=)}}
s.genericTuple((3.0, 4.0))
let sTwo = Generic<(Double, Double)>()
sTwo.generic(3.0, 4.0) // expected-error {{instance method 'generic' expects a single parameter of type '(Double, Double)'}} {{16-16=(}} {{24-24=)}}
sTwo.generic((3.0, 4.0))
sTwo.genericLabeled(x: 3.0, 4.0) // expected-error {{instance method 'genericLabeled' expects a single parameter of type '(Double, Double)'}}
sTwo.genericLabeled(x: (3.0, 4.0))
}
do {
let s = Generic<Double>()
let a = 3.0
let b = 4.0
let c = (3.0)
let d = (a, b)
s.generic(a)
s.generic((a))
s.generic(c)
s.genericTwo(a, b)
s.genericTwo((a, b))
s.genericTuple(a, b)
s.genericTuple((a, b))
let sTwo = Generic<(Double, Double)>()
sTwo.generic(a, b)
sTwo.generic((a, b))
sTwo.generic(d)
}
do {
var s = Generic<Double>()
var a = 3.0
var b = 4.0
var c = (3.0)
var d = (a, b)
s.generic(a)
s.generic((a))
s.generic(c)
s.genericTwo(a, b)
s.genericTwo((a, b)) // expected-error {{missing argument for parameter #2 in call}}
s.genericTuple(a, b) // expected-error {{instance method 'genericTuple' expects a single parameter of type '(Double, Double)'}} {{18-18=(}} {{22-22=)}}
s.genericTuple((a, b))
var sTwo = Generic<(Double, Double)>()
sTwo.generic(a, b) // expected-error {{instance method 'generic' expects a single parameter of type '(Double, Double)'}} {{16-16=(}} {{20-20=)}}
sTwo.generic((a, b))
sTwo.generic(d)
}
extension Generic {
mutating func mutatingGeneric(_ x: T) {}
mutating func mutatingGenericLabeled(x: T) {}
mutating func mutatingGenericTwo(_ x: T, _ y: T) {} // expected-note 2 {{'mutatingGenericTwo' declared here}}
mutating func mutatingGenericTuple(_ x: (T, T)) {}
}
do {
var s = Generic<Double>()
s.mutatingGeneric(3.0)
s.mutatingGeneric((3.0))
s.mutatingGenericLabeled(x: 3.0)
s.mutatingGenericLabeled(x: (3.0))
s.mutatingGenericTwo(3.0, 4.0)
s.mutatingGenericTwo((3.0, 4.0)) // expected-error {{missing argument for parameter #2 in call}}
s.mutatingGenericTuple(3.0, 4.0) // expected-error {{instance method 'mutatingGenericTuple' expects a single parameter of type '(Double, Double)'}} {{26-26=(}} {{34-34=)}}
s.mutatingGenericTuple((3.0, 4.0))
var sTwo = Generic<(Double, Double)>()
sTwo.mutatingGeneric(3.0, 4.0) // expected-error {{instance method 'mutatingGeneric' expects a single parameter of type '(Double, Double)'}} {{24-24=(}} {{32-32=)}}
sTwo.mutatingGeneric((3.0, 4.0))
sTwo.mutatingGenericLabeled(x: 3.0, 4.0) // expected-error {{instance method 'mutatingGenericLabeled' expects a single parameter of type '(Double, Double)'}}
sTwo.mutatingGenericLabeled(x: (3.0, 4.0))
}
do {
var s = Generic<Double>()
let a = 3.0
let b = 4.0
let c = (3.0)
let d = (a, b)
s.mutatingGeneric(a)
s.mutatingGeneric((a))
s.mutatingGeneric(c)
s.mutatingGenericTwo(a, b)
s.mutatingGenericTwo((a, b))
s.mutatingGenericTuple(a, b)
s.mutatingGenericTuple((a, b))
var sTwo = Generic<(Double, Double)>()
sTwo.mutatingGeneric(a, b)
sTwo.mutatingGeneric((a, b))
sTwo.mutatingGeneric(d)
}
do {
var s = Generic<Double>()
var a = 3.0
var b = 4.0
var c = (3.0)
var d = (a, b)
s.mutatingGeneric(a)
s.mutatingGeneric((a))
s.mutatingGeneric(c)
s.mutatingGenericTwo(a, b)
s.mutatingGenericTwo((a, b)) // expected-error {{missing argument for parameter #2 in call}}
s.mutatingGenericTuple(a, b) // expected-error {{instance method 'mutatingGenericTuple' expects a single parameter of type '(Double, Double)'}} {{26-26=(}} {{30-30=)}}
s.mutatingGenericTuple((a, b))
var sTwo = Generic<(Double, Double)>()
sTwo.mutatingGeneric(a, b) // expected-error {{instance method 'mutatingGeneric' expects a single parameter of type '(Double, Double)'}} {{24-24=(}} {{28-28=)}}
sTwo.mutatingGeneric((a, b))
sTwo.mutatingGeneric(d)
}
extension Generic {
var genericFunction: (T) -> () { return generic }
var genericFunctionTwo: (T, T) -> () { return genericTwo }
var genericFunctionTuple: ((T, T)) -> () { return genericTuple }
}
do {
let s = Generic<Double>()
s.genericFunction(3.0)
s.genericFunction((3.0))
s.genericFunctionTwo(3.0, 4.0)
s.genericFunctionTwo((3.0, 4.0)) // expected-error {{missing argument for parameter #2 in call}}
s.genericFunctionTuple(3.0, 4.0) // expected-error {{single parameter of type '(Double, Double)' is expected in call}} {{26-26=(}} {{34-34=)}}
s.genericFunctionTuple((3.0, 4.0))
let sTwo = Generic<(Double, Double)>()
sTwo.genericFunction(3.0, 4.0)
sTwo.genericFunction((3.0, 4.0)) // Does not diagnose in Swift 3 mode
}
do {
let s = Generic<Double>()
let a = 3.0
let b = 4.0
let c = (3.0)
let d = (a, b)
s.genericFunction(a)
s.genericFunction((a))
s.genericFunction(c)
s.genericFunctionTwo(a, b)
s.genericFunctionTwo((a, b))
s.genericFunctionTuple(a, b)
s.genericFunctionTuple((a, b))
let sTwo = Generic<(Double, Double)>()
sTwo.genericFunction(a, b)
sTwo.genericFunction((a, b))
sTwo.genericFunction(d) // Does not diagnose in Swift 3 mode
}
do {
var s = Generic<Double>()
var a = 3.0
var b = 4.0
var c = (3.0)
var d = (a, b)
s.genericFunction(a)
s.genericFunction((a))
s.genericFunction(c)
s.genericFunctionTwo(a, b)
s.genericFunctionTwo((a, b)) // expected-error {{missing argument for parameter #2 in call}}
s.genericFunctionTuple(a, b) // expected-error {{single parameter of type '(Double, Double)' is expected in call}} {{26-26=(}} {{30-30=)}}
s.genericFunctionTuple((a, b))
var sTwo = Generic<(Double, Double)>()
sTwo.genericFunction(a, b)
sTwo.genericFunction((a, b)) // Does not diagnose in Swift 3 mode
sTwo.genericFunction(d) // Does not diagnose in Swift 3 mode
}
struct GenericInit<T> { // expected-note 2 {{'T' declared as parameter to type 'GenericInit'}}
init(_ x: T) {}
}
struct GenericInitLabeled<T> {
init(x: T) {}
}
struct GenericInitTwo<T> {
init(_ x: T, _ y: T) {} // expected-note 8 {{'init' declared here}}
}
struct GenericInitTuple<T> {
init(_ x: (T, T)) {}
}
struct GenericInitLabeledTuple<T> {
init(x: (T, T)) {}
}
do {
_ = GenericInit(3, 4)
_ = GenericInit((3, 4))
_ = GenericInitLabeled(x: 3, 4) // expected-error {{extra argument in call}}
_ = GenericInitLabeled(x: (3, 4))
_ = GenericInitTwo(3, 4)
_ = GenericInitTwo((3, 4)) // expected-error {{missing argument for parameter #2 in call}}
_ = GenericInitTuple(3, 4) // expected-error {{initializer expects a single parameter of type '(T, T)'}} {{24-24=(}} {{28-28=)}}
_ = GenericInitTuple((3, 4))
_ = GenericInitLabeledTuple(x: 3, 4) // expected-error {{initializer expects a single parameter of type '(T, T)'}}
_ = GenericInitLabeledTuple(x: (3, 4))
}
do {
_ = GenericInit<(Int, Int)>(3, 4)
_ = GenericInit<(Int, Int)>((3, 4)) // expected-error {{expression type 'GenericInit<(Int, Int)>' is ambiguous without more context}}
_ = GenericInitLabeled<(Int, Int)>(x: 3, 4) // expected-error {{extra argument in call}}
_ = GenericInitLabeled<(Int, Int)>(x: (3, 4))
_ = GenericInitTwo<Int>(3, 4)
_ = GenericInitTwo<Int>((3, 4)) // expected-error {{missing argument for parameter #2 in call}}
_ = GenericInitTuple<Int>(3, 4) // expected-error {{initializer expects a single parameter of type '(T, T)'}} {{29-29=(}} {{33-33=)}}
_ = GenericInitTuple<Int>((3, 4))
_ = GenericInitLabeledTuple<Int>(x: 3, 4) // expected-error {{initializer expects a single parameter of type '(T, T)'}}
_ = GenericInitLabeledTuple<Int>(x: (3, 4))
}
do {
let a = 3
let b = 4
let c = (a, b)
_ = GenericInit(a, b)
_ = GenericInit((a, b))
_ = GenericInit(c)
_ = GenericInitTwo(a, b)
_ = GenericInitTwo((a, b)) // expected-error {{missing argument for parameter #2 in call}}
_ = GenericInitTwo(c) // expected-error {{missing argument for parameter #2 in call}}
_ = GenericInitTuple(a, b) // expected-error {{initializer expects a single parameter of type '(T, T)'}} {{24-24=(}} {{28-28=)}}
_ = GenericInitTuple((a, b))
_ = GenericInitTuple(c)
}
do {
let a = 3
let b = 4
let c = (a, b)
_ = GenericInit<(Int, Int)>(a, b)
_ = GenericInit<(Int, Int)>((a, b))
_ = GenericInit<(Int, Int)>(c)
_ = GenericInitTwo<Int>(a, b)
_ = GenericInitTwo<Int>((a, b)) // Does not diagnose in Swift 3 mode
_ = GenericInitTwo<Int>(c) // expected-error {{passing 2 arguments to a callee as a single tuple value has been removed in Swift 3}}
_ = GenericInitTuple<Int>(a, b) // Does not diagnose in Swift 3 mode
_ = GenericInitTuple<Int>((a, b))
_ = GenericInitTuple<Int>(c)
}
do {
var a = 3
var b = 4
var c = (a, b)
_ = GenericInit(a, b) // expected-error {{extra argument in call}}
_ = GenericInit((a, b)) // expected-error {{generic parameter 'T' could not be inferred}} // expected-note {{explicitly specify the generic arguments to fix this issue}}
_ = GenericInit(c) // expected-error {{generic parameter 'T' could not be inferred}} // expected-note {{explicitly specify the generic arguments to fix this issue}}
_ = GenericInitTwo(a, b)
_ = GenericInitTwo((a, b)) // expected-error {{missing argument for parameter #2 in call}}
_ = GenericInitTwo(c) // expected-error {{missing argument for parameter #2 in call}}
_ = GenericInitTuple(a, b) // expected-error {{initializer expects a single parameter of type '(T, T)'}} {{24-24=(}} {{28-28=)}}
_ = GenericInitTuple((a, b))
_ = GenericInitTuple(c)
}
do {
var a = 3
var b = 4
var c = (a, b)
// _ = GenericInit<(Int, Int)>(a, b) // Crashes in Swift 3
_ = GenericInit<(Int, Int)>((a, b)) // expected-error {{expression type 'GenericInit<(Int, Int)>' is ambiguous without more context}}
_ = GenericInit<(Int, Int)>(c) // expected-error {{expression type 'GenericInit<(Int, Int)>' is ambiguous without more context}}
_ = GenericInitTwo<Int>(a, b)
_ = GenericInitTwo<Int>((a, b)) // expected-error {{missing argument for parameter #2 in call}}
_ = GenericInitTwo<Int>(c) // expected-error {{missing argument for parameter #2 in call}}
_ = GenericInitTuple<Int>(a, b) // expected-error {{initializer expects a single parameter of type '(T, T)'}} {{29-29=(}} {{33-33=)}}
_ = GenericInitTuple<Int>((a, b))
_ = GenericInitTuple<Int>(c)
}
struct GenericSubscript<T> {
// TODO: Restore regressed diagnostics rdar://problem/31724211
subscript(_ x: T) -> Int { get { return 0 } set { } } // expected-note* {{}}
}
struct GenericSubscriptLabeled<T> {
subscript(x x: T) -> Int { get { return 0 } set { } }
}
struct GenericSubscriptTwo<T> {
subscript(_ x: T, _ y: T) -> Int { get { return 0 } set { } } // expected-note 3 {{'subscript' declared here}}
}
struct GenericSubscriptTuple<T> {
subscript(_ x: (T, T)) -> Int { get { return 0 } set { } }
}
struct GenericSubscriptLabeledTuple<T> {
subscript(x x: (T, T)) -> Int { get { return 0 } set { } }
}
do {
let s1 = GenericSubscript<(Double, Double)>()
_ = s1[3.0, 4.0]
// TODO: Restore regressed diagnostics rdar://problem/31724211
_ = s1[(3.0, 4.0)] // expected-error {{}}
let s1a = GenericSubscriptLabeled<(Double, Double)>()
_ = s1a [x: 3.0, 4.0] // expected-error {{extra argument in call}}
_ = s1a [x: (3.0, 4.0)]
let s2 = GenericSubscriptTwo<Double>()
_ = s2[3.0, 4.0]
_ = s2[(3.0, 4.0)] // expected-error {{missing argument for parameter #2 in call}}
let s3 = GenericSubscriptTuple<Double>()
_ = s3[3.0, 4.0] // expected-error {{subscript expects a single parameter of type '(T, T)'}} {{10-10=(}} {{18-18=)}}
_ = s3[(3.0, 4.0)]
let s3a = GenericSubscriptLabeledTuple<Double>()
_ = s3a[x: 3.0, 4.0] // expected-error {{subscript expects a single parameter of type '(T, T)'}}
_ = s3a[x: (3.0, 4.0)]
}
do {
let a = 3.0
let b = 4.0
let d = (a, b)
let s1 = GenericSubscript<(Double, Double)>()
_ = s1[a, b]
_ = s1[(a, b)]
_ = s1[d]
let s2 = GenericSubscriptTwo<Double>()
_ = s2[a, b]
_ = s2[(a, b)] // Does not diagnose in Swift 3 mode
_ = s2[d] // Does not diagnose in Swift 3 mode
let s3 = GenericSubscriptTuple<Double>()
_ = s3[a, b] // Does not diagnose in Swift 3 mode
_ = s3[(a, b)]
_ = s3[d]
}
do {
// TODO: Restore regressed diagnostics rdar://problem/31724211
var a = 3.0
var b = 4.0
var d = (a, b)
var s1 = GenericSubscript<(Double, Double)>()
_ = s1[a, b]
// TODO: Restore regressed diagnostics rdar://problem/31724211
// These two lines give different regressed behavior in S3 and S4 mode
// _ = s1[(a, b)] // e/xpected-error {{expression type '@lvalue Int' is ambiguous without more context}}
// _ = s1[d] // e/xpected-error {{expression type '@lvalue Int' is ambiguous without more context}}
var s2 = GenericSubscriptTwo<Double>()
_ = s2[a, b]
_ = s2[(a, b)] // expected-error {{missing argument for parameter #2 in call}}
_ = s2[d] // expected-error {{missing argument for parameter #2 in call}}
var s3 = GenericSubscriptTuple<Double>()
_ = s3[a, b] // expected-error {{subscript expects a single parameter of type '(T, T)'}} {{10-10=(}} {{14-14=)}}
_ = s3[(a, b)]
_ = s3[d]
}
enum GenericEnum<T> {
case one(T)
case labeled(x: T)
case two(T, T) // expected-note 8 {{'two' declared here}}
case tuple((T, T))
}
do {
_ = GenericEnum.one(3, 4)
_ = GenericEnum.one((3, 4))
_ = GenericEnum.labeled(x: 3, 4) // expected-error {{extra argument in call}}
_ = GenericEnum.labeled(x: (3, 4))
_ = GenericEnum.labeled(3, 4) // expected-error {{extra argument in call}}
_ = GenericEnum.labeled((3, 4)) // expected-error {{missing argument label 'x:' in call}}
_ = GenericEnum.two(3, 4)
_ = GenericEnum.two((3, 4)) // expected-error {{missing argument for parameter #2 in call}}
_ = GenericEnum.tuple(3, 4) // expected-error {{enum element 'tuple' expects a single parameter of type '(T, T)'}} {{25-25=(}} {{29-29=)}}
_ = GenericEnum.tuple((3, 4))
}
do {
_ = GenericEnum<(Int, Int)>.one(3, 4)
_ = GenericEnum<(Int, Int)>.one((3, 4)) // Does not diagnose in Swift 3 mode
_ = GenericEnum<(Int, Int)>.labeled(x: 3, 4) // expected-error {{enum element 'labeled' expects a single parameter of type '(Int, Int)'}}
_ = GenericEnum<(Int, Int)>.labeled(x: (3, 4))
_ = GenericEnum<(Int, Int)>.labeled(3, 4) // expected-error {{enum element 'labeled' expects a single parameter of type '(Int, Int)'}}
_ = GenericEnum<(Int, Int)>.labeled((3, 4)) // expected-error {{missing argument label 'x:' in call}}
_ = GenericEnum<Int>.two(3, 4)
_ = GenericEnum<Int>.two((3, 4)) // expected-error {{missing argument for parameter #2 in call}}
_ = GenericEnum<Int>.tuple(3, 4) // expected-error {{enum element 'tuple' expects a single parameter of type '(Int, Int)'}} {{30-30=(}} {{34-34=)}}
_ = GenericEnum<Int>.tuple((3, 4))
}
do {
let a = 3
let b = 4
let c = (a, b)
_ = GenericEnum.one(a, b)
_ = GenericEnum.one((a, b))
_ = GenericEnum.one(c)
_ = GenericEnum.two(a, b)
_ = GenericEnum.two((a, b)) // expected-error {{missing argument for parameter #2 in call}}
_ = GenericEnum.two(c) // expected-error {{missing argument for parameter #2 in call}}
_ = GenericEnum.tuple(a, b) // expected-error {{enum element 'tuple' expects a single parameter of type '(T, T)'}} {{25-25=(}} {{29-29=)}}
_ = GenericEnum.tuple((a, b))
_ = GenericEnum.tuple(c)
}
do {
let a = 3
let b = 4
let c = (a, b)
_ = GenericEnum<(Int, Int)>.one(a, b)
_ = GenericEnum<(Int, Int)>.one((a, b))
_ = GenericEnum<(Int, Int)>.one(c)
_ = GenericEnum<Int>.two(a, b)
_ = GenericEnum<Int>.two((a, b))
_ = GenericEnum<Int>.two(c) // expected-error {{passing 2 arguments to a callee as a single tuple value has been removed in Swift 3}}
_ = GenericEnum<Int>.tuple(a, b)
_ = GenericEnum<Int>.tuple((a, b))
_ = GenericEnum<Int>.tuple(c)
}
do {
var a = 3
var b = 4
var c = (a, b)
// _ = GenericEnum.one(a, b) // Crashes in actual Swift 3
_ = GenericEnum.one((a, b)) // Does not diagnose in Swift 3 mode
_ = GenericEnum.one(c) // Does not diagnose in Swift 3 mode
_ = GenericEnum.two(a, b)
_ = GenericEnum.two((a, b)) // expected-error {{missing argument for parameter #2 in call}}
_ = GenericEnum.two(c) // expected-error {{missing argument for parameter #2 in call}}
_ = GenericEnum.tuple(a, b) // expected-error {{enum element 'tuple' expects a single parameter of type '(T, T)'}} {{25-25=(}} {{29-29=)}}
_ = GenericEnum.tuple((a, b))
_ = GenericEnum.tuple(c)
}
do {
var a = 3
var b = 4
var c = (a, b)
// _ = GenericEnum<(Int, Int)>.one(a, b) // Crashes in actual Swift 3
_ = GenericEnum<(Int, Int)>.one((a, b)) // Does not diagnose in Swift 3 mode
_ = GenericEnum<(Int, Int)>.one(c) // Does not diagnose in Swift 3 mode
_ = GenericEnum<Int>.two(a, b)
_ = GenericEnum<Int>.two((a, b)) // expected-error {{missing argument for parameter #2 in call}}
_ = GenericEnum<Int>.two(c) // expected-error {{missing argument for parameter #2 in call}}
_ = GenericEnum<Int>.tuple(a, b) // expected-error {{enum element 'tuple' expects a single parameter of type '(Int, Int)'}} {{30-30=(}} {{34-34=)}}
_ = GenericEnum<Int>.tuple((a, b))
_ = GenericEnum<Int>.tuple(c)
}
protocol Protocol {
associatedtype Element
}
extension Protocol {
func requirement(_ x: Element) {}
func requirementLabeled(x: Element) {}
func requirementTwo(_ x: Element, _ y: Element) {} // expected-note 2 {{'requirementTwo' declared here}}
func requirementTuple(_ x: (Element, Element)) {}
}
struct GenericConforms<T> : Protocol {
typealias Element = T
}
do {
let s = GenericConforms<Double>()
s.requirement(3.0)
s.requirement((3.0))
s.requirementLabeled(x: 3.0)
s.requirementLabeled(x: (3.0))
s.requirementTwo(3.0, 4.0)
s.requirementTwo((3.0, 4.0)) // expected-error {{missing argument for parameter #2 in call}}
s.requirementTuple(3.0, 4.0) // expected-error {{instance method 'requirementTuple' expects a single parameter of type '(Double, Double)'}} {{22-22=(}} {{30-30=)}}
s.requirementTuple((3.0, 4.0))
let sTwo = GenericConforms<(Double, Double)>()
sTwo.requirement(3.0, 4.0) // expected-error {{instance method 'requirement' expects a single parameter of type '(Double, Double)'}} {{20-20=(}} {{28-28=)}}
sTwo.requirement((3.0, 4.0))
sTwo.requirementLabeled(x: 3.0, 4.0) // expected-error {{instance method 'requirementLabeled' expects a single parameter of type '(Double, Double)'}}
sTwo.requirementLabeled(x: (3.0, 4.0))
}
do {
let s = GenericConforms<Double>()
let a = 3.0
let b = 4.0
let c = (3.0)
let d = (a, b)
s.requirement(a)
s.requirement((a))
s.requirement(c)
s.requirementTwo(a, b)
s.requirementTwo((a, b)) // Does not diagnose in Swift 3 mode
s.requirementTuple(a, b) // Does not diagnose in Swift 3 mode
s.requirementTuple((a, b))
let sTwo = GenericConforms<(Double, Double)>()
sTwo.requirement(a, b)
sTwo.requirement((a, b))
sTwo.requirement(d)
}
do {
var s = GenericConforms<Double>()
var a = 3.0
var b = 4.0
var c = (3.0)
var d = (a, b)
s.requirement(a)
s.requirement((a))
s.requirement(c)
s.requirementTwo(a, b)
s.requirementTwo((a, b)) // expected-error {{missing argument for parameter #2 in call}}
s.requirementTuple(a, b) // expected-error {{instance method 'requirementTuple' expects a single parameter of type '(Double, Double)'}} {{22-22=(}} {{26-26=)}}
s.requirementTuple((a, b))
var sTwo = GenericConforms<(Double, Double)>()
sTwo.requirement(a, b) // expected-error {{instance method 'requirement' expects a single parameter of type '(Double, Double)'}} {{20-20=(}} {{24-24=)}}
sTwo.requirement((a, b))
sTwo.requirement(d)
}
extension Protocol {
func takesClosure(_ fn: (Element) -> ()) {}
func takesClosureTwo(_ fn: (Element, Element) -> ()) {}
func takesClosureTuple(_ fn: ((Element, Element)) -> ()) {}
}
do {
let s = GenericConforms<Double>()
s.takesClosure({ _ = $0 })
s.takesClosure({ x in })
s.takesClosure({ (x: Double) in })
s.takesClosureTwo({ _ = $0 })
s.takesClosureTwo({ x in })
s.takesClosureTwo({ (x: (Double, Double)) in })
s.takesClosureTwo({ _ = $0; _ = $1 })
s.takesClosureTwo({ (x, y) in })
s.takesClosureTwo({ (x: Double, y:Double) in })
s.takesClosureTuple({ _ = $0 })
s.takesClosureTuple({ x in })
s.takesClosureTuple({ (x: (Double, Double)) in })
s.takesClosureTuple({ _ = $0; _ = $1 })
s.takesClosureTuple({ (x, y) in })
s.takesClosureTuple({ (x: Double, y:Double) in })
let sTwo = GenericConforms<(Double, Double)>()
sTwo.takesClosure({ _ = $0 })
sTwo.takesClosure({ x in })
sTwo.takesClosure({ (x: (Double, Double)) in })
sTwo.takesClosure({ _ = $0; _ = $1 })
sTwo.takesClosure({ (x, y) in })
sTwo.takesClosure({ (x: Double, y: Double) in })
}
do {
let _: ((Int, Int)) -> () = { _ = $0 }
let _: ((Int, Int)) -> () = { _ = ($0.0, $0.1) }
let _: ((Int, Int)) -> () = { t in _ = (t.0, t.1) }
let _: ((Int, Int)) -> () = { _ = ($0, $1) }
let _: ((Int, Int)) -> () = { t, u in _ = (t, u) }
let _: (Int, Int) -> () = { _ = $0 }
let _: (Int, Int) -> () = { _ = ($0.0, $0.1) }
let _: (Int, Int) -> () = { t in _ = (t.0, t.1) }
let _: (Int, Int) -> () = { _ = ($0, $1) }
let _: (Int, Int) -> () = { t, u in _ = (t, u) }
}
// rdar://problem/28952837 - argument labels ignored when calling function
// with single 'Any' parameter
func takesAny(_: Any) {}
enum HasAnyCase {
case any(_: Any)
}
do {
let fn: (Any) -> () = { _ in }
fn(123)
fn(data: 123)
takesAny(123)
takesAny(data: 123)
_ = HasAnyCase.any(123)
_ = HasAnyCase.any(data: 123)
}
// rdar://problem/29739905 - protocol extension methods on Array had
// ParenType sugar stripped off the element type
typealias BoolPair = (Bool, Bool)
func processArrayOfFunctions(f1: [((Bool, Bool)) -> ()],
f2: [(Bool, Bool) -> ()],
c: Bool) {
let p = (c, c)
f1.forEach { block in
block(p)
block((c, c))
block(c, c)
}
f2.forEach { block in
block(p) // expected-error {{passing 2 arguments to a callee as a single tuple value has been removed in Swift 3}}
block((c, c))
block(c, c)
}
f2.forEach { (block: ((Bool, Bool)) -> ()) in
block(p)
block((c, c))
block(c, c)
}
f2.forEach { (block: (Bool, Bool) -> ()) in
block(p) // expected-error {{passing 2 arguments to a callee as a single tuple value has been removed in Swift 3}}
block((c, c))
block(c, c)
}
}
// expected-error@+1 {{cannot create a single-element tuple with an element label}}
func singleElementTupleArgument(completion: ((didAdjust: Bool)) -> Void) {
// TODO: Error could be improved.
// expected-error@+1 {{cannot convert value of type '(didAdjust: Bool)' to expected argument type 'Bool'}}
completion((didAdjust: true))
}
// SR-4378 -- FIXME -- this should type check, it used to work in Swift 3.0
final public class MutableProperty<Value> {
public init(_ initialValue: Value) {}
}
enum DataSourcePage<T> {
case notLoaded
}
let pages1: MutableProperty<(data: DataSourcePage<Int>, totalCount: Int)> = MutableProperty((
// expected-error@-1 {{expression type 'MutableProperty<(data: DataSourcePage<Int>, totalCount: Int)>' is ambiguous without more context}}
data: .notLoaded,
totalCount: 0
))
let pages2: MutableProperty<(data: DataSourcePage<Int>, totalCount: Int)> = MutableProperty((
// expected-error@-1 {{cannot convert value of type 'MutableProperty<(data: DataSourcePage<_>, totalCount: Int)>' to specified type 'MutableProperty<(data: DataSourcePage<Int>, totalCount: Int)>'}}
data: DataSourcePage.notLoaded,
totalCount: 0
))
let pages3: MutableProperty<(data: DataSourcePage<Int>, totalCount: Int)> = MutableProperty((
// expected-error@-1 {{expression type 'MutableProperty<(data: DataSourcePage<Int>, totalCount: Int)>' is ambiguous without more context}}
data: DataSourcePage<Int>.notLoaded,
totalCount: 0
))
// rdar://problem/32301091 - Make sure that in Swift 3 mode following expressions still compile just fine
func rdar32301091_1(_ :((Int, Int) -> ())!) {}
rdar32301091_1 { _ in } // Ok in Swift 3
func rdar32301091_2(_ :(Int, Int) -> ()) {}
rdar32301091_2 { _ in } // Ok in Swift 3
// rdar://problem/35198459 - source-compat-suite failure: Moya (toType->hasUnresolvedType() && "Should have handled this above")
do {
func foo(_: (() -> Void)?) {}
func bar() -> ((()) -> Void)? { return nil }
foo(bar()) // OK in Swift 3 mode
}
// https://bugs.swift.org/browse/SR-6509
public extension Optional {
public func apply<Result>(_ transform: ((Wrapped) -> Result)?) -> Result? {
return self.flatMap { value in
transform.map { $0(value) }
}
}
public func apply<Value, Result>(_ value: Value?) -> Result?
where Wrapped == (Value) -> Result {
return value.apply(self)
}
}
// https://bugs.swift.org/browse/SR-6837
do {
func takeFn(fn: (_ i: Int, _ j: Int?) -> ()) {}
func takePair(_ pair: (Int, Int?)) {}
takeFn(fn: takePair)
takeFn(fn: { (pair: (Int, Int?)) in } )
takeFn { (pair: (Int, Int?)) in }
}
// https://bugs.swift.org/browse/SR-6796
do {
func f(a: (() -> Void)? = nil) {}
func log<T>() -> ((T) -> Void)? { return nil }
f(a: log() as ((()) -> Void)?) // Allow ((()) -> Void)? to be passed in place of (() -> Void)?
func logNoOptional<T>() -> (T) -> Void { }
f(a: logNoOptional() as ((()) -> Void)) // Also allow the optional-injected form.
func g() {}
g(())
func h(_: ()) {}
h()
}
| 28.893949 | 201 | 0.630646 |
29b60d1f1f704a407e4aecfdc20043e817bbc15f | 2,151 | //
// ServerManager.swift
// SocketServer
//
// Created by aStudyer on 2019/10/2.
// Copyright © 2019 aStudyer. All rights reserved.
//
import Cocoa
import SwiftSocket
class ServerManager: NSObject {
fileprivate lazy var server: TCPServer = TCPServer(address: "0.0.0.0", port: 9999)
fileprivate var isServerRunning: Bool = false
fileprivate lazy var clientManagers: [ClientManager] = [ClientManager]()
}
extension ServerManager {
func startRunning() {
isServerRunning = true
// 1.开启监听
switch server.listen() {
case .success:
// 2.开始接受客户端
DispatchQueue.global().async {
while self.isServerRunning {
if let client = self.server.accept() {
print("newclient from:\(client.address)[\(client.port)]")
DispatchQueue.global().async {
self.handleClient(client)
}
} else {
print("accept error")
}
}
}
case .failure(let error):
print("listen error:\(error)")
}
}
func stopRunning() {
isServerRunning = false
server.close()
}
}
extension ServerManager {
fileprivate func handleClient(_ client: TCPClient) {
// 1.用一个ClientManager管理TCPClient
let manager = ClientManager(client)
manager.delegate = self
// 2.保存客户端
clientManagers.append(manager)
// 3.client开始接收消息
manager.startReadMessage()
}
}
extension ServerManager: ClientManagerDelegate {
func sendMessageToClient(_ data: Data) {
for manager in clientManagers {
switch manager.tcpClient.send(data: data) {
case .failure(let error):
print("send failure:\(error)")
default:
break
}
}
}
func removeClient(_ client: ClientManager) {
guard let index = clientManagers.firstIndex(of: client) else {
return
}
clientManagers.remove(at: index)
}
}
| 29.067568 | 86 | 0.551836 |
de19647a3a3bb78b9be97ae5ff2674408866dcf2 | 1,149 | //
// BackTableVC.swift
// bac_final
//
// Created by Mae Patton on 12/10/16.
// Copyright © 2016 Mae Patton. All rights reserved.
//
import Foundation
import UIKit
class BackTableVC: UITableViewController{
var TableArray = [String]()
override func viewDidLoad() {
TableArray = ["User Info","BAC","History","About"]
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return TableArray.count
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
var cell = tableView.dequeueReusableCellWithIdentifier(TableArray[indexPath.row], forIndexPath: indexPath) as UITableViewCell
cell.textLabel?.text = TableArray[indexPath.row] //this will make it so the cells in the table view take the titles from my array
cell.textLabel?.textColor = UIColor.whiteColor()
let fontSize = cell.textLabel?.font.pointSize
cell.textLabel?.font = UIFont(name: "Avenir", size: fontSize!)
return cell
}
} | 30.236842 | 137 | 0.664056 |
465ba658cf8baffa32c53db349659f717ac5d121 | 385 |
// Problem code
func coinChange(_ coins: [Int], _ amount: Int) -> Int {
var minCoins = Array(repeating: amount + 1, count: amount + 1)
minCoins[0] = 0
for sum in 1..<minCoins.count {
for coin in coins {
if sum >= coin {
minCoins[sum] = min(minCoins[sum], minCoins[sum - coin] + 1)
}
}
}
if minCoins[amount] == amount + 1 {
return -1
}
return minCoins[amount]
}
| 21.388889 | 64 | 0.615584 |
9bb2a75eef6f27069eebec78f2ac4c32fffcfb99 | 1,829 | /*
* Copyright (C) 2014-2019 halo https://github.com/halo/macosvpn
*
* 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 Controller {
public enum Run {
public static func call() throws {
// To keep this application extensible we introduce different
// commands right from the beginning. We start off with "create"
switch Arguments.options.command {
case .create:
Log.info("You wish to create one or more VPN service(s)")
try Create.call()
break
case .delete:
Log.info("You wish to delete one or more VPN service(s)")
try Delete.call()
break
default:
throw ExitError(message: "Unknown command. Try --help for instructions.",
code: .unknownCommand)
}
}
}
}
| 43.547619 | 133 | 0.710224 |
c1e4f6008d70fd46c5fa01c472d95aa9360e3bb3 | 2,541 | //
// constants.swift
// LeChessEngine
//
// Created by Leigh Appel on 13/12/2015.
// Copyright © 2015 JasperVine. All rights reserved.
//
import Foundation
let INFINITY = Int.max
let CHECKMATE = 100000
let RANK_1:BitBoard = 0x00000000000000ff
let RANK_2:BitBoard = 0x000000000000ff00
let RANK_3:BitBoard = 0x0000000000ff0000
let RANK_4:BitBoard = 0x00000000ff000000
let RANK_5:BitBoard = 0x000000ff00000000
let RANK_6:BitBoard = 0x0000ff0000000000
let RANK_7:BitBoard = 0x00ff000000000000
let RANK_8:BitBoard = 0xff00000000000000
let FILE_A:BitBoard = 0x0101010101010101
let FILE_B:BitBoard = 0x0202020202020202
let FILE_C:BitBoard = 0x0404040404040404
let FILE_D:BitBoard = 0x0808080808080808
let FILE_E:BitBoard = 0x1010101010101010
let FILE_F:BitBoard = 0x2020202020202020
let FILE_G:BitBoard = 0x4040404040404040
let FILE_H:BitBoard = 0x8080808080808080
let ALL_MASK = FILE_A | FILE_B | FILE_C | FILE_D | FILE_E | FILE_F | FILE_G | FILE_H
let FILES = [FILE_A, FILE_B, FILE_C, FILE_D, FILE_E, FILE_F, FILE_G, FILE_H]
let RANKS = [RANK_1, RANK_2, RANK_3, RANK_4, RANK_5, RANK_6, RANK_7, RANK_8]
let WHITE_QUEEN_CASTLE_MASK:BitBoard = 0b1100
let WHITE_KING_CASTLE_MASK:BitBoard = 0b1100000
let WHITE_QUEEN_BLOCKING_CASTLE_MASK:BitBoard = 0b1110
let WHITE_KING_BLOCKING_CASTLE_MASK:BitBoard = 0b1100000
let BLACK_QUEEN_CASTLE_MASK:BitBoard = 0xC00000000000000
let BLACK_KING_CASTLE_MASK :BitBoard = 0x6000000000000000
let BLACK_QUEEN_BLOCKING_CASTLE_MASK:BitBoard = 0xE00000000000000
let BLACK_KING_BLOCKING_CASTLE_MASK :BitBoard = 0x6000000000000000
//Knight Span on E5
let KNIGHT_SPAN:BitBoard = 0b0000000000101000010001000000000001000100001010000000000000000000
//King Span on E5
let KING_SPAN:BitBoard = 0b0000000000000000001110000010100000111000000000000000000000000000
// From top left to bottom right
let DiagonalMasks:[BitBoard] = [
0x1, 0x102, 0x10204, 0x1020408, 0x102040810, 0x10204081020, 0x1020408102040,
0x102040810204080, 0x204081020408000, 0x408102040800000, 0x810204080000000,
0x1020408000000000, 0x2040800000000000, 0x4080000000000000, 0x8000000000000000
]
// From top right to bottom left
let AntiDiagonalMasks:[BitBoard] = [
0x80, 0x8040, 0x804020, 0x80402010, 0x8040201008, 0x804020100804, 0x80402010080402,
0x8040201008040201, 0x4020100804020100, 0x2010080402010000, 0x1008040201000000,
0x804020100000000, 0x402010000000000, 0x201000000000000, 0x100000000000000
]
//PERFT Representation of a new game
let NewGame = "rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1"
| 36.3 | 93 | 0.817395 |
bb387f33efa83d12dc71bd6ad99f449101e9f3b0 | 8,281 | //
// MSGMessengerViewController.swift
// MessengerKit
//
// Created by Stephen Radford on 08/06/2018.
// Copyright © 2018 Cocoon Development Ltd. All rights reserved.
//
import UIKit
/// `MSGMessengerViewController` is a drop in messenger interface.
/// It incorporates both `MSGCollectionView` and `MSGInputView` into one UI.
///
/// If you wish to use your own `MSGCollectionView` or `MSGInputView` subclass please use the appropriate initializer or subclass.
open class MSGMessengerViewController: UIViewController {
// MARK: - Subviews
/// The input view that's used within the messenger
private(set) public lazy var messageInputView: MSGInputView = {
var inputView: MSGInputView!
if let nib = style.inputView.nib,
let view = nib.instantiate(withOwner: self, options: nil).first as? MSGInputView {
inputView = view
} else {
inputView = style.inputView.init()
}
inputView.style = style
inputView.tintColor = tintColor
return inputView
}()
/// The collection view that's used within the messenger
private(set) public lazy var collectionView: MSGCollectionView = {
let collectionView = style.collectionView.init()
collectionView.keyboardDismissMode = keyboardDismissMode
return collectionView
}()
// MARK: - Private Properties
/// The layout guide for the keyboard
private let keyboardLayoutGuide = KeyboardLayoutGuide()
/// Sizes of the bubbles will be cached here for styles that use them
internal var cachedSizes = [Int:CGSize]()
/// This is set when the collection view `contentSize` changed so we know it's loaded
private var collectionViewLoaded = false {
didSet {
if collectionViewLoaded && shouldScrollToBottom && !oldValue {
collectionView.scrollToBottom(animated: false)
}
}
}
// MARK: - Public Properties
/// The data source for the messenger
public weak var dataSource: MSGDataSource?
/// The delegate for the messenger
public weak var delegate: MSGDelegate?
/// The style of the messenger
open var style: MSGMessengerStyle {
return MessengerKit.Styles.iMessage
}
/// How the keyboard should be dismissed by the Messenger View Controller
open var keyboardDismissMode: UIScrollView.KeyboardDismissMode = .interactive {
didSet {
collectionView.keyboardDismissMode = keyboardDismissMode
}
}
@IBInspectable
open var tintColor: UIColor? {
didSet {
messageInputView.tintColor = tintColor
}
}
/// Whether the view controller should automatically scroll to bottom on appear.
/// Defaults to `true`.
public var shouldScrollToBottom: Bool = true
// MARK: - Lifecycle
open override func viewDidLoad() {
super.viewDidLoad()
if tintColor == nil {
tintColor = view.tintColor
}
view.backgroundColor = style.backgroundColor
setupCollectionView()
setupInput()
}
open override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
// Setup an observer so we can detect the keyboard appearing and keep the collectionview at the bottom
NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillShow(_:)), name: UIResponder.keyboardWillShowNotification, object: nil)
if shouldScrollToBottom {
collectionView.scrollToBottom(animated: true)
}
}
open override func viewDidDisappear(_ animated: Bool) {
super.viewDidDisappear(animated)
NotificationCenter.default.removeObserver(self)
}
open override func loadView() {
loadFromDefaultNib()
}
open override func traitCollectionDidChange(_ previousTraitCollection: UITraitCollection?) {
super.traitCollectionDidChange(previousTraitCollection)
// We clear the cached sizes when the collection view changes
cachedSizes = [:]
}
private func loadFromDefaultNib() {
let view = UINib(nibName: "MSGMessengerView", bundle: MessengerKit.bundle)
.instantiate(withOwner: self, options: nil).first as? MSGMessengerView
view?.frame = CGRect.zero
view?.backgroundView.backgroundColor = style.inputViewBackgroundColor
view?.add(collectionView)
view?.add(messageInputView)
self.view = view
}
// MARK: - Setup
private func setupInput() {
guard let view = view as? MSGMessengerView else {
fatalError("Root view is not MSGMessengerView!!")
}
view.addLayoutGuide(keyboardLayoutGuide)
view.inputViewContainer.bottomAnchor.constraint(equalTo: keyboardLayoutGuide.topAnchor).isActive = true
messageInputView.addTarget(self, action: #selector(inputViewDidChange(inputView:)), for: .valueChanged)
messageInputView.addTarget(self, action: #selector(inputViewPrimaryActionTriggered(inputView:)), for: .primaryActionTriggered)
}
open func setupCollectionView() {
collectionView.style = style
collectionView.delegate = self
collectionView.dataSource = self
if #available(iOS 10.0, *) {
collectionView.prefetchDataSource = self
collectionView.isPrefetchingEnabled = true
}
if #available(iOS 10.0, *) {
collectionView.contentInset = UIEdgeInsets(top: 16, left: 0, bottom: 16, right: 0)
} else {
collectionView.topAnchor.constraint(equalTo: self.topLayoutGuide.bottomAnchor).isActive = true
}
collectionView.addObserver(self, forKeyPath: "contentSize", options: .old, context: nil)
}
override open func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
if let observedObject = object as? MSGCollectionView, observedObject == collectionView {
collectionViewLoaded = true
collectionView.removeObserver(self, forKeyPath: "contentSize")
}
}
// MARK: - Actions
@objc open dynamic func inputViewDidChange(inputView: MSGInputView) { }
@objc open dynamic func inputViewPrimaryActionTriggered(inputView: MSGInputView) { }
// MARK: - Keyboard
@objc open dynamic func keyboardWillShow(_ notification: Notification) {
collectionView.scrollToBottom(animated: false)
}
// MARK: - Users Typing
/// Sets the users that are currently typing.
/// Can be overridden for additional control.
///
/// - Parameter users: The users that are typing.
open func setUsersTyping(_ users: [MSGUser]) {
// TODO: add appearance proxy!!
guard users.count > 0 else {
collectionView.typingLabel.text = nil
collectionView.layoutTypingLabelIfNeeded()
return
}
var attributedText: NSMutableAttributedString!
if users.count == 1 {
attributedText = NSMutableAttributedString(string: users[0].displayName, attributes: [
.font: UIFont.systemFont(ofSize: 14, weight: .bold),
.foregroundColor: UIColor.darkText
])
} else {
attributedText = NSMutableAttributedString(string: "\(users.count) people", attributes: [
.font: UIFont.systemFont(ofSize: 14, weight: .bold),
.foregroundColor: UIColor.darkText
])
}
attributedText.append(NSAttributedString(string: users.count == 1 ? " is typing…" : " typing…", attributes: [
.font: UIFont.systemFont(ofSize: 14, weight: .medium),
.foregroundColor: UIColor.black
]))
collectionView.typingLabel.attributedText = attributedText
collectionView.layoutTypingLabelIfNeeded()
}
}
| 33.257028 | 156 | 0.637242 |
fea4bf4837ca99b7cd03d7391183b977ad0c7562 | 587 | //
// ProductCellTests.swift
// CleanArchitecture
//
// Created by Tuan Truong on 6/7/18.
// Copyright © 2018 Sun Asterisk. All rights reserved.
//
import XCTest
@testable import CleanArchitecture
final class SectionedProductCellTests: XCTestCase {
var cell: SectionedProductCell!
override func setUp() {
super.setUp()
cell = SectionedProductCell.loadFromNib()
}
func test_ibOutlets() {
XCTAssertNotNil(cell)
XCTAssertNotNil(cell.nameLabel)
XCTAssertNotNil(cell.priceLabel)
XCTAssertNotNil(cell.editButton)
}
}
| 21.740741 | 55 | 0.688245 |
3818d73fbaa2e8537410635dec1b3d4769f2beda | 1,589 | // RUN: %empty-directory(%t)
// RUN: %target-build-swift -lswiftSwiftReflectionTest %s -o %t/reflect_Int16
// RUN: %target-run %target-swift-reflection-test %t/reflect_Int16 2>&1 | %FileCheck %s --check-prefix=CHECK-%target-ptrsize
// REQUIRES: objc_interop
// REQUIRES: executable_test
import SwiftReflectionTest
class TestClass {
var t: Int16
init(t: Int16) {
self.t = t
}
}
var obj = TestClass(t: 123)
reflect(object: obj)
// CHECK-64: Reflecting an object.
// CHECK-64: Instance pointer in child address space: 0x{{[0-9a-fA-F]+}}
// CHECK-64: Type reference:
// CHECK-64: (class reflect_Int16.TestClass)
// CHECK-64: Type info:
// CHECK-64: (class_instance size=18 alignment=2 stride=18 num_extra_inhabitants=0
// CHECK-64: (field name=t offset=16
// CHECK-64: (struct size=2 alignment=2 stride=2 num_extra_inhabitants=0
// CHECK-64: (field name=_value offset=0
// CHECK-64: (builtin size=2 alignment=2 stride=2 num_extra_inhabitants=0)))))
// CHECK-32: Reflecting an object.
// CHECK-32: Instance pointer in child address space: 0x{{[0-9a-fA-F]+}}
// CHECK-32: Type reference:
// CHECK-32: (class reflect_Int16.TestClass)
// CHECK-32: Type info:
// CHECK-32: (class_instance size=10 alignment=2 stride=10 num_extra_inhabitants=0
// CHECK-32: (field name=t offset=8
// CHECK-32: (struct size=2 alignment=2 stride=2 num_extra_inhabitants=0
// CHECK-32: (field name=_value offset=0
// CHECK-32: (builtin size=2 alignment=2 stride=2 num_extra_inhabitants=0)))))
doneReflecting()
// CHECK-64: Done.
// CHECK-32: Done.
| 32.428571 | 124 | 0.695406 |
4b29f775eb4e47e0ef1376ff73fcbeba9e433f6b | 907 | //
// XCSourceExtensions.swift
// Genee
//
// Created by Tomas Kohout on 23/10/2016.
// Copyright © 2016 Genie. All rights reserved.
//
import Foundation
import XcodeKit
import GenieFramework
//Converts XCSource position to sourcekit offset
extension XCSourceTextPosition: SourcePositionToOffsetConvertable {}
extension XCSourceTextRange {
func fullLineOffsetRange(inBuffer buffer: XCSourceTextBuffer) -> OffsetRange {
return XCSourceTextPosition(line: self.start.line, column: 0).offset(allLines: buffer.lines.map { $0 as! String }) ..< XCSourceTextPosition(line: self.end.line+1, column: 0).offset(allLines: buffer.lines.map { $0 as! String })
}
func offsetRange(inBuffer buffer: XCSourceTextBuffer) -> OffsetRange {
return self.start.offset(allLines: buffer.lines.map { $0 as! String }) ..< self.end.offset(allLines: buffer.lines.map { $0 as! String })
}
}
| 32.392857 | 234 | 0.726571 |
2fdf13e7ff673ae51a3380399a97ad05b9848ff4 | 2,346 | //
// FeaturedImageDownloader.swift
// NetNewsWire
//
// Created by Brent Simmons on 11/26/17.
// Copyright © 2017 Ranchero Software. All rights reserved.
//
import Foundation
import Articles
import RSCore
import RSParser
final class FeaturedImageDownloader {
private let imageDownloader: ImageDownloader
private var articleURLToFeaturedImageURLCache = [String: String]()
private var articleURLsWithNoFeaturedImage = Set<String>()
private var urlsInProgress = Set<String>()
init(imageDownloader: ImageDownloader) {
self.imageDownloader = imageDownloader
}
func image(for article: Article) -> RSImage? {
if let imageLink = article.imageLink {
return image(forFeaturedImageURL: imageLink)
}
if let link = article.link {
return image(forArticleURL: link)
}
return nil
}
func image(forArticleURL articleURL: String) -> RSImage? {
if articleURLsWithNoFeaturedImage.contains(articleURL) {
return nil
}
if let featuredImageURL = cachedURL(for: articleURL) {
return image(forFeaturedImageURL: featuredImageURL)
}
findFeaturedImageURL(for: articleURL)
return nil
}
func image(forFeaturedImageURL featuredImageURL: String) -> RSImage? {
if let data = imageDownloader.image(for: featuredImageURL) {
return RSImage(data: data)
}
return nil
}
}
private extension FeaturedImageDownloader {
func cachedURL(for articleURL: String) -> String? {
return articleURLToFeaturedImageURLCache[articleURL]
}
func cacheURL(for articleURL: String, _ featuredImageURL: String) {
articleURLsWithNoFeaturedImage.remove(articleURL)
articleURLToFeaturedImageURLCache[articleURL] = featuredImageURL
}
func findFeaturedImageURL(for articleURL: String) {
guard !urlsInProgress.contains(articleURL) else {
return
}
urlsInProgress.insert(articleURL)
HTMLMetadataDownloader.downloadMetadata(for: articleURL) { (metadata) in
self.urlsInProgress.remove(articleURL)
guard let metadata = metadata else {
return
}
self.pullFeaturedImageURL(from: metadata, articleURL: articleURL)
}
}
func pullFeaturedImageURL(from metadata: RSHTMLMetadata, articleURL: String) {
if let url = metadata.bestFeaturedImageURL() {
cacheURL(for: articleURL, url)
let _ = image(forFeaturedImageURL: url)
return
}
articleURLsWithNoFeaturedImage.insert(articleURL)
}
}
| 23.227723 | 79 | 0.757033 |
d7a79e6c257d73cb49d7589d5d322d9cd41fe509 | 7,253 | import ReSwift
struct GetAttestationsBuilder {
let requestId: JsonRpcId
let oidcRealmUrlString: String
let applicationName: String
let subject: String?
let dispatch: DispatchFunction
let getState: () -> AppState?
let channel: TelepathChannel
func build() -> GetAttestations {
guard let url = URL(string: oidcRealmUrlString) else {
return GetAttestationsInvalid(requestId: requestId,
error: .invalidRealmUrl,
dispatch: dispatch,
channel: channel)
}
guard
let state = getState(),
let identityReference = state.telepath.channels[channel],
let facet = state.diamond.facets[identityReference]
else {
return GetAttestationsInvalid(
requestId: requestId,
error: .invalidConfiguration,
dispatch: dispatch,
channel: channel
)
}
return GetAttestationsValid(
requestId: requestId,
applicationName: applicationName,
oidcRealmUrl: url,
subject: subject,
dispatch: dispatch,
state: state,
facet: facet,
channel: channel
)
}
}
protocol GetAttestations {
var dispatch: DispatchFunction { get }
func execute()
}
extension GetAttestations {
func send(id: JsonRpcId, error: TelepathError, on channel: TelepathChannel) {
dispatch(TelepathActions.Send(
id: id,
error: error,
on: channel
))
}
}
struct GetAttestationsInvalid: GetAttestations {
let requestId: JsonRpcId
let error: AttestationError
let dispatch: DispatchFunction
let channel: TelepathChannel
func execute() {
send(id: requestId, error: error, on: channel)
}
}
struct GetAttestationsValid: GetAttestations {
let requestId: JsonRpcId
let applicationName: String
let oidcRealmUrl: URL
let subject: String?
let dispatch: DispatchFunction
let state: AppState
let facet: Identity
let channel: TelepathChannel
init(requestId: JsonRpcId,
applicationName: String,
oidcRealmUrl: URL,
subject: String?,
dispatch: @escaping DispatchFunction,
state: AppState,
facet: Identity,
channel: TelepathChannel) {
self.requestId = requestId
self.applicationName = applicationName
self.oidcRealmUrl = oidcRealmUrl
self.subject = subject
self.dispatch = dispatch
self.state = state
self.facet = facet
self.channel = channel
}
func execute() {
if let idToken = facet.findOpenIDToken(claim: "iss", value: oidcRealmUrl.absoluteString) {
if GetAttestationsValid.alreadyProvided(idToken: idToken, state: state, on: channel) {
send(requestId: requestId, idToken: idToken, on: channel)
} else {
showRequestAccessDialog(idToken: idToken)
}
} else {
showLoginRequiredDialog()
}
}
static func send(requestId: JsonRpcId,
idToken: String,
dispatch: DispatchFunction,
state: AppState,
on channel: TelepathChannel) {
dispatch(TelepathActions.Send(id: requestId, result: idToken, on: channel))
guard let channelId = channel.id else {
return
}
dispatch(OpenIDAttestationActions.Provided(idToken: idToken, channel: channelId))
}
func send(requestId: JsonRpcId, idToken: String, on channel: TelepathChannel) {
GetAttestationsValid.send(
requestId: requestId,
idToken: idToken,
dispatch: dispatch,
state: state,
on: channel
)
}
func showRequestAccessDialog(idToken: String) {
let requestId = self.requestId
let alert = RequestedAlert(
title: "Request for access",
message: "Application \(applicationName) wants to access the credentials " +
"from \(self.oidcRealmUrl.absoluteString) for your identity:",
actions: [
AlertAction(title: "Deny", style: .cancel) { _ in
self.send(id: requestId,
error: AttestationError.userDeniedAccess,
on: self.channel)
},
AlertAction(title: "Approve", style: .default) { _ in
self.send(requestId: requestId, idToken: idToken, on: self.channel)
}
],
textFieldConfigurator: textFieldConfigurator(facet: facet))
self.dispatch(DialogPresenterActions.RequestAlert(requestedAlert: alert))
}
func showLoginRequiredDialog() {
let requestId = self.requestId
let alert = RequestedAlert(
title: "Login required",
message: "Application \(applicationName) requires you to login to " +
"\(self.oidcRealmUrl.absoluteString) using your identity:",
actions: [
AlertAction(title: "Cancel", style: .cancel) { _ in
self.send(id: requestId,
error: AttestationError.userCancelledLogin,
on: self.channel)
},
AlertAction(title: "Login", style: .default) { _ in
self.startAttestation()
}
],
textFieldConfigurator: textFieldConfigurator(facet: facet))
self.dispatch(DialogPresenterActions.RequestAlert(requestedAlert: alert))
}
func textFieldConfigurator(facet: Identity) -> ((UITextField) -> Void) {
return { (textField: UITextField) in
textField.isUserInteractionEnabled = false
textField.font = UIFont(name: "Snell Roundhand", size: 30)
textField.text = facet.description
textField.textAlignment = .center
}
}
func startAttestation() {
self.dispatch(OpenIDAttestationActions.StartAttestation(
for: self.facet,
requestId: requestId,
oidcRealmUrl: self.oidcRealmUrl,
subject: self.subject,
requestedOnChannel: channel.id
))
}
private static func alreadyProvided(idToken: String,
state: AppState,
on channel: TelepathChannel) -> Bool {
guard let channelId = channel.id,
let providedTokens = state.attestations.providedAttestations[channelId] else {
return false
}
return providedTokens.contains { $0 == idToken }
}
}
struct AttestationsResult: Codable {
let idToken: String?
let errorCode: Int?
let errorMessage: String?
init(idToken: String? = nil, errorCode: Int? = nil, errorMessage: String? = nil) {
self.idToken = idToken
self.errorCode = errorCode
self.errorMessage = errorMessage
}
}
| 34.051643 | 98 | 0.575072 |
dde93a463dc85fe9ec5a876e1b291cbca0d3d352 | 1,345 | //
// AppDelegate.swift
// GetDataFromAPI
//
// Created by Tian on 2/24/21.
//
import UIKit
@main
class AppDelegate: UIResponder, UIApplicationDelegate {
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
return true
}
// MARK: UISceneSession Lifecycle
func application(_ application: UIApplication, configurationForConnecting connectingSceneSession: UISceneSession, options: UIScene.ConnectionOptions) -> UISceneConfiguration {
// Called when a new scene session is being created.
// Use this method to select a configuration to create the new scene with.
return UISceneConfiguration(name: "Default Configuration", sessionRole: connectingSceneSession.role)
}
func application(_ application: UIApplication, didDiscardSceneSessions sceneSessions: Set<UISceneSession>) {
// Called when the user discards a scene session.
// If any sessions were discarded while the application was not running, this will be called shortly after application:didFinishLaunchingWithOptions.
// Use this method to release any resources that were specific to the discarded scenes, as they will not return.
}
}
| 36.351351 | 179 | 0.745725 |
21db9e8aa3058e382de49d316df7bbd2adfa72a1 | 6,069 | // SimpleMath
// Copyright (c) Filip Lazov 2020
// MIT license - see LICENSE file for more info
import SwiftUI
struct Container: View {
var body: some View {
ZStack {
MiniDeviceView(width: 100, animate: true)
}
}
}
struct MiniDeviceView: View {
private let timer = Timer.publish(every: 1.6, on: .main, in: .common).autoconnect()
@State private var isDrifted = false
private let height: CGFloat
private var inputMockupColor = Color.miniDeviceInputMockupGray
private var correctAnswersMockupColor = Color.miniDeviceInputMockupGreen
private var equationRowColor = Color.primaryText
var width: CGFloat
var animate: Bool
init(width: CGFloat, animate: Bool) {
self.width = width
self.animate = animate
height = width * 2
}
var body: some View {
ZStack {
IPhoneView(width: width, height: height, screenColor: Color.background)
equationsMockup()
.animation(.easeInOut(duration: 1.5))
.onReceive(timer) { _ in
guard self.animate else { return }
self.isDrifted.toggle()
}
inputMockup()
}
.drawingGroup()
.frame(width: width, height: height)
}
private func square(size: CGSize, color: Color) -> some View {
Rectangle()
.fill(color)
.frame(width: size.width, height: size.height)
}
private func squareRow(squareSize: CGSize, count: Int, color: Color) -> some View {
HStack(spacing: width / 15 ) {
ForEach(0..<count) { _ in
self.square(size: squareSize, color: color)
}
}
}
private func inputMockup() -> some View {
let squareSize = CGSize(width: width * 0.08, height: width * 0.08)
return Group {
ForEach(0..<3) { index in
self.squareRow(squareSize: squareSize, count: 3, color: self.inputMockupColor)
.offset(x: 0, y: self.height * (0.12 + CGFloat(index) * 0.07))
}
squareRow(squareSize: squareSize, count: 1, color: inputMockupColor)
.offset(x: 0, y: height * 0.33)
square(size: squareSize, color: inputMockupColor)
.offset(x: -width * 0.33, y: height * 0.19)
square(size: squareSize, color: inputMockupColor)
.offset(x: width * 0.33, y: height * 0.19)
square(size: squareSize, color: correctAnswersMockupColor)
.offset(x: width * 0.33, y: -height * 0.31)
square(size: squareSize, color: inputMockupColor)
.offset(x: -width * 0.33, y: -height * 0.31)
}
}
// disabling linter because this will be refactored
// swiftlint:disable:next function_body_length
private func equationsMockup() -> some View {
Group {
Rectangle()
.fill(equationRowColor)
.frame(width: width * 0.4, height: width * 0.1)
.offset(x: isDrifted ? -width * 0.15 : -width * 0.1, y: height * 0.04)
Rectangle()
.fill(Color.unanswered)
.frame(width: width * 0.15, height: width * 0.1)
.offset(x: isDrifted ? width * 0.17 : width * 0.22, y: height * 0.04)
Rectangle()
.fill(equationRowColor)
.frame(width: width * 0.4, height: width * 0.1)
.offset(x: isDrifted ? -width * 0.05 : -width * 0.1, y: -height * 0.03)
Rectangle()
.fill(Color.unanswered)
.frame(width: width * 0.15, height: width * 0.1)
.offset(x: isDrifted ? width * 0.27 : width * 0.22, y: -height * 0.03)
Rectangle()
.fill(equationRowColor)
.frame(width: width * 0.4, height: width * 0.1)
.offset(x: isDrifted ? -width * 0.15 : -width * 0.1, y: -height * 0.10)
Rectangle()
.fill(Color.currentAnswer)
.frame(width: width * 0.15, height: width * 0.1)
.offset(x: isDrifted ? width * 0.17 : width * 0.22, y: -height * 0.10)
Rectangle()
.fill(equationRowColor)
.frame(width: width * 0.4, height: width * 0.1)
.offset(x: isDrifted ? -width * 0.05 : -width * 0.1, y: -height * 0.17)
Rectangle()
.fill(Color.correctAnswer)
.frame(width: width * 0.15, height: width * 0.1)
.offset(x: isDrifted ? width * 0.27 : width * 0.22, y: -height * 0.17)
Rectangle()
.fill(equationRowColor)
.frame(width: width * 0.4, height: width * 0.1)
.offset(x: isDrifted ? -width * 0.15 : -width * 0.1, y: -height * 0.24)
Rectangle()
.fill(Color.correctAnswer)
.frame(width: width * 0.15, height: width * 0.1)
.offset(x: isDrifted ? width * 0.17 : width * 0.22, y: -height * 0.24)
}
}
}
private struct IPhoneView: View {
private var hardwareStrokeColor = Color.miniDeviceHardwareStroke
let width: CGFloat
let height: CGFloat
var screenColor: Color
init(width: CGFloat, height: CGFloat, screenColor: Color) {
self.width = width
self.height = height
self.screenColor = screenColor
}
var body: some View {
ZStack {
// bazel
RoundedRectangle(cornerRadius: width / 6.6, style: .continuous)
.fill(Color.miniDeviceFrame)
// screen
Rectangle()
.fill(screenColor)
.frame(width: width * 0.83, height: height * 0.74)
// home button
Circle()
.stroke(lineWidth: width / 100)
.foregroundColor(hardwareStrokeColor)
.frame(width: width * 0.15, height: width * 0.15)
.offset(x: 0, y: height * 0.43)
// camera
Circle()
.stroke(lineWidth: width / 200)
.foregroundColor(hardwareStrokeColor)
.frame(width: width * 0.045, height: width * 0.045)
.offset(x: 0, y: -height * 0.45)
// speaker
RoundedRectangle(cornerRadius: width * 0.015, style: .continuous)
.stroke(lineWidth: width / 200)
.foregroundColor(hardwareStrokeColor)
.frame(width: width * 0.16, height: height * 0.014)
.offset(x: 0, y: -height * 0.405)
}
.frame(width: width, height: height)
}
}
struct SwiftUIView_Previews: PreviewProvider {
static var previews: some View {
Container()
.previewDevice(PreviewDevice(rawValue: "iPhone 8"))
.previewDisplayName("iPhone 8")
}
}
| 32.111111 | 86 | 0.607019 |
288f21031deb18c769d42cad37e79a5fbd3fed41 | 4,830 | //
// SectionCell.swift
// LaLoop
//
// Created by Daniel Bogomazov on 2019-05-02.
// Copyright © 2018 Daniel Bogomazov. All rights reserved.
//
import UIKit
class SectionCell: UITableViewCell {
private lazy var titleLabel = UILabel()
private lazy var detailLabel = UILabel()
private lazy var selectionSwitch = UISwitch()
var switchAction: ((Any) -> Void)?
var sectionViewModel: SectionViewModel! {
didSet {
titleLabel.text = sectionViewModel.title
detailLabel.text = sectionViewModel.detail
selectionSwitch.isOn = sectionViewModel.isOn
createAndUpdateConstraints()
}
}
init() {
super.init(style: .subtitle, reuseIdentifier: "sectionCell")
backgroundColor = UIColor.white.withAlphaComponent(0.03)
selectionStyle = .none
createAndUpdateConstraints()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func createAndUpdateConstraints() {
let wrapperView = UIView()
wrapperView.translatesAutoresizingMaskIntoConstraints = false
contentView.addSubview(wrapperView)
contentView.addConstraints([NSLayoutConstraint(item: wrapperView, attribute: .left, relatedBy: .equal, toItem: contentView, attribute: .left, multiplier: 1.0, constant: 12),
NSLayoutConstraint(item: wrapperView, attribute: .right, relatedBy: .equal, toItem: contentView, attribute: .right, multiplier: 1.0, constant: -20),
NSLayoutConstraint(item: wrapperView, attribute: .centerY, relatedBy: .equal, toItem: contentView, attribute: .centerY, multiplier: 1.0, constant: 0)])
titleLabel.translatesAutoresizingMaskIntoConstraints = false
wrapperView.addSubview(titleLabel)
wrapperView.addConstraints([NSLayoutConstraint(item: titleLabel, attribute: .top, relatedBy: .equal, toItem: wrapperView, attribute: .top, multiplier: 1.0, constant: 0),
NSLayoutConstraint(item: titleLabel, attribute: .left, relatedBy: .equal, toItem: wrapperView, attribute: .left, multiplier: 1.0, constant: 0),
NSLayoutConstraint(item: titleLabel, attribute: .right, relatedBy: .equal, toItem: wrapperView, attribute: .right, multiplier: 1.0, constant: 0)])
titleLabel.setupLabel(fontWeight: .medium, fontSize: 18, textColor: .white)
titleLabel.numberOfLines = 1
if detailLabel.text != "" && detailLabel.text != nil {
detailLabel.translatesAutoresizingMaskIntoConstraints = false
wrapperView.addSubview(detailLabel)
wrapperView.addConstraints([NSLayoutConstraint(item: detailLabel, attribute: .top, relatedBy: .equal, toItem: titleLabel, attribute: .bottom, multiplier: 1.0, constant: 0),
NSLayoutConstraint(item: detailLabel, attribute: .left, relatedBy: .equal, toItem: wrapperView, attribute: .left, multiplier: 1.0, constant: 0),
NSLayoutConstraint(item: detailLabel, attribute: .right, relatedBy: .equal, toItem: wrapperView, attribute: .right, multiplier: 1.0, constant: 0),
NSLayoutConstraint(item: detailLabel, attribute: .bottom, relatedBy: .equal, toItem: wrapperView, attribute: .bottom, multiplier: 1.0, constant: 0)])
detailLabel.setupLabel(fontWeight: .thin, fontSize: 12, textColor: UIColor.white.withAlphaComponent(0.5))
} else {
contentView.addConstraint(NSLayoutConstraint(item: titleLabel, attribute: .bottom, relatedBy: .equal, toItem: wrapperView, attribute: .bottom, multiplier: 1.0, constant: 0))
}
selectionSwitch.translatesAutoresizingMaskIntoConstraints = false
accessoryView = UIView(frame: CGRect(x: 0, y: 0, width: selectionSwitch.frame.width, height: selectionSwitch.frame.height))
accessoryView?.addSubview(selectionSwitch)
accessoryView?.addConstraints([NSLayoutConstraint(item: selectionSwitch, attribute: .right, relatedBy: .equal, toItem: accessoryView, attribute: .right, multiplier: 1.0, constant: -12),
NSLayoutConstraint(item: selectionSwitch, attribute: .centerY, relatedBy: .equal, toItem: accessoryView, attribute: .centerY, multiplier: 1.0, constant: 0)])
selectionSwitch.onTintColor = Util.Color.main
selectionSwitch.tintColor = Util.Color.main
selectionSwitch.addTarget(self, action: #selector(selectionSwitchDidChangeValue(_:)), for: .valueChanged)
}
@objc func selectionSwitchDidChangeValue(_ sender: UISwitch) {
switchAction?(sender)
}
}
| 57.5 | 196 | 0.666046 |
b9b001cc4b1c68c28a66b38b0f4ee30806e3d7dd | 778 | //
// ViewController.swift
// RateMyApp
//
// Created by Jimmy Jose on 08/09/14.
// Copyright (c) 2014 Varshyl Mobile Pvt. Ltd. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
let rate = RateMyApp.sharedInstance
rate.debug = true
rate.appID = "857846130"
DispatchQueue.main.async(execute: { () -> Void in
rate.trackAppUsage()
})
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
| 21.611111 | 80 | 0.59126 |
1e1e40094a4ba089d127c86e774dbc1dbe751d1c | 1,284 | //
// SDAuthenticator.swift
// SwiftyDuke
//
// Created by Lucy Zhang on 12/21/17.
// Copyright © 2017 Lucy Zhang. All rights reserved.
//
import UIKit
import os.log
public class SDAuthenticator: NSObject {
let requester = SDRequester(baseURL: SDConstants.URL.oauth)
public static let shared = SDAuthenticator()
public func authenticate(clientID:String, redirectURI:String, scope:String, completion:@escaping ([String:Any]) -> Void){
let endpoint = "authorize.php?response_type=code&client_id=\(clientID)&scope=\(scope)&redirect_uri=\(redirectURI)"
requester.makeHTTPRequest(method: "GET", endpoint: endpoint, headers: nil, body: nil, error: { (message) in
if #available(iOS 10.0, *) {
os_log("%@: Error: %@", self.description, message)
} else {
print("%@: Error: %@", self.description, message)
}
}, completion: { (response) in
if #available(iOS 10.0, *) {
os_log("%@: Response: %@", self.description, response as! [String:Any])
} else {
print("%@: Response: %@", self.description, response as! [String:Any])
}
completion(response as! [String:Any])
})
}
}
| 33.789474 | 125 | 0.58567 |
e9d8465a2b17f9ce4252b5b7e36a34aa85b41d93 | 297 | //
// TableDataLeafContext.swift
// DataContext
//
// Created by Vladimir Pirogov on 17/10/16.
// Copyright © 2016 Vladimir Pirogov. All rights reserved.
//
import Foundation
open class TableDataLeafContext: DataLeafContext {
open func getDefaultHeight() -> CGFloat {
return 30.0
}
}
| 17.470588 | 59 | 0.717172 |
39e790cefa76a286cd824d8b8fde6c6fe49294c1 | 3,410 | //
// QuestCategoryDA.swift
// AwesomeCore
//
// Created by Antonio on 1/9/18.
//
//import Foundation
//
//class QuestCategoryDA {
//
// // MARK: - Parser
//
// func parseToCoreData(_ questCategory: QuestCategory, result: @escaping (CDCategory) -> Void) {
// AwesomeCoreDataAccess.shared.backgroundContext.perform {
// let cdCategory = self.parseToCoreData(questCategory)
// result(cdCategory)
// }
// }
//
// func parseToCoreData(_ questCategory: QuestCategory) -> CDCategory {
//
// guard let categoryId = questCategory.id else {
// fatalError("CDCategory object can't be created without id.")
// }
// let p = predicate(categoryId, questCategory.questId ?? "")
// let cdCategory = CDCategory.getObjectAC(predicate: p, createIfNil: true) as! CDCategory
//
// cdCategory.id = questCategory.id
// cdCategory.name = questCategory.name
// return cdCategory
// }
//
// func parseFromCoreData(_ cdCategory: CDCategory) -> QuestCategory {
//
// /**
// * As we have a relationship QuestCategory to Many Quests we have to go through
// * both relationships looking for a combination.
// */
// var questId: String? {
// guard let quests = cdCategory.quests else { return nil }
// for cdQuest in quests.allObjects {
// if (cdQuest as! CDQuest).categories == nil { continue }
// for categories in (cdQuest as! CDQuest).categories!.allObjects where (categories as! CDCategory) == cdCategory {
// return (cdQuest as! CDQuest).id
// }
// }
// return nil
// }
//
// return QuestCategory(id: cdCategory.id, name: cdCategory.name, questId: questId)
// }
//
// // MARK: - Fetch
//
// func loadBy(categoryId: String, questId: String, result: @escaping (CDCategory?) -> Void) {
// func perform() {
// let p = predicate(categoryId, questId)
// guard let cdCategory = CDCategory.listAC(predicate: p).first as? CDCategory else {
// result(nil)
// return
// }
// result(cdCategory)
// }
// AwesomeCoreDataAccess.shared.performBackgroundBatchOperation({ (workerContext) in
// perform()
// })
// }
//
// // MARK: - Helpers
//
// func extractCDCategories(_ questCategories: [QuestCategory]?) -> NSSet {
// var categories = NSSet()
// guard let questCategories = questCategories else { return categories }
// for qc in questCategories {
// categories = categories.adding(parseToCoreData(qc)) as NSSet
// }
// return categories
// }
//
// func extractQuestCategories(_ questCategories: NSSet?) -> [QuestCategory] {
// var categories = [QuestCategory]()
// guard let questCategories = questCategories else { return categories }
// for qc in questCategories {
// categories.append(parseFromCoreData(qc as! CDCategory))
// }
// return categories
// }
//
// private func predicate(_ categoryId: String, _ questId: String) -> NSPredicate {
// return NSPredicate(format: "id == %@ AND quests.id CONTAINS[cd] %@", categoryId, questId)
// }
//
//}
| 35.894737 | 130 | 0.575367 |
89f08c1787f52f31c45a2defb2a2756da9d2361b | 867 | //
// ServerView.swift
// wallabag
//
// Created by Marinel Maxime on 18/07/2019.
//
import SwiftUI
struct ServerView: View {
@ObservedObject var serverViewModel = ServerViewModel()
var body: some View {
Form {
Section(header: Text("Server")) {
TextField("https://your-instance.domain", text: $serverViewModel.url)
.disableAutocorrection(true)
.autocapitalization(.none)
}
NavigationLink(destination: ClientIdClientSecretView()) {
Text("Next")
}.disabled(!serverViewModel.isValid)
}.navigationBarTitle("Server")
}
}
#if DEBUG
struct ServerView_Previews: PreviewProvider {
static var previews: some View {
NavigationView {
ServerView()
}
}
}
#endif
| 24.083333 | 85 | 0.565167 |
ef57539e30febf421c17fb0bb34dbedc1f8b9bcd | 1,747 | //
// Path+Points.swift
// SwiftLogoPlay
//
// Created by Howard Katz on 2020-06-09.
// Copyright © 2020 Howard Katz. All rights reserved.
//
import SwiftUI
/*
example usage: print("\(123.456).format: ".2"))")
*/
extension CGFloat {
func format(f: String) -> String {
return String(format: "%\(f)f", self)
}
}
extension Path {
func scaled(toFit rect: CGRect) -> Path {
let scaleW = rect.width/boundingRect.width
let scaleH = rect.height/boundingRect.height
let scaleFactor = min(scaleW, scaleH)
return applying(CGAffineTransform(scaleX: scaleFactor, y: scaleFactor))
}
mutating func addMarker(radius r: CGFloat) {
let rect = CGRect(origin: self.currentPoint!,
size: CGSize(width: 2*r, height: 2*r))
self.addEllipse(in: rect.offsetBy(dx: -r, dy: -r))
}
func verticesOnly() -> [CGPoint] {
var points = [CGPoint]()
self.forEach { element in
switch element {
case .closeSubpath:
break
case .curve(let to, _, _) :
points.append(to)
case .line(let to) :
points.append(to)
case .move(let to) :
points.append(to)
case .quadCurve(let to, _) :
points.append(to)
}
}
// print("\nextension Path.verticesOnly():"
// + " {\(points.count)} points")
// print("boundingRect: {\(self.boundingRect)}")
//
// for (ix, pt) in points.enumerated() {
// print("[\(ix)]: {" +
// "x: \(pt.x.format(f: ".4")) " +
// "y: \(pt.y.format(f: ".4"))}")
// }
return points
}
}
| 26.876923 | 79 | 0.511734 |
61aef05ef847495bb0ee5842bd75a716f63fca17 | 859 | import Foundation
import SwiftyJSON
public class FlightOffersPrice {
private var client: Client
public init(client: Client) {
self.client = client
}
/// Gets a confirmed price and availability of a flight
///
/// - Returns:
/// `JSON` object
///
public func post(body: JSON, params: [String: String] = [:], onCompletion: @escaping AmadeusResponse) {
var flightOffers: JSON = body
if body.arrayValue.count == 0 {
flightOffers = [body]
}
let pricing: JSON = [ "data": [ "type": "flight-offers-pricing", "flightOffers": flightOffers] ]
client.post(path: "/v1/shopping/flight-offers/pricing", body: pricing, params: params, onCompletion: {
response, error in
onCompletion(response, error)
})
}
}
| 26.84375 | 109 | 0.580908 |
03c4cc1bf4e201d3c63879b7531b98e46cfa232a | 15,712 | //
// SettingsLauncher.swift
// Community Calendar
//
// Created by Michael on 5/14/20.
// Copyright © 2020 Mazjap Co. All rights reserved.
//
import UIKit
class SettingsLauncher: NSObject, UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout {
let blackView = UIView()
let editProfileView = UIView()
let profileImageView = UIImageView()
let imageBackgroundView = UIView()
let firstNameTextField = UITextField()
let lastNameTextField = UITextField()
let firstUnderlineView = UIView()
let lastUnderlineView = UIView()
let saveButton = UIButton()
let cancelButton = UIButton()
let settingsCollectionView: UICollectionView = {
let layout = UICollectionViewFlowLayout()
layout.scrollDirection = .vertical
let cv = UICollectionView(frame: .zero, collectionViewLayout: layout)
cv.backgroundColor = #colorLiteral(red: 0.1721869707, green: 0.1871494651, blue: 0.2290506661, alpha: 1)
cv.layer.cornerRadius = 12
cv.contentInset.top = 100
// cv.contentInset.top = 25
return cv
}()
var height: CGFloat = 0
var y: CGFloat = 0
let testLabel = UILabel()
let logoutButton = UIButton()
let cellID = "SettingCell"
var profileImage: UIImage? {
didSet {
print("Profile Image Set")
}
}
var firstName: String? {
didSet {
print("First Name Set")
}
}
var lastName: String? {
didSet {
print("Last Name Set")
}
}
override init() {
super.init()
settingsCollectionView.delegate = self
settingsCollectionView.dataSource = self
settingsCollectionView.register(SettingCollectionViewCell.self, forCellWithReuseIdentifier: cellID)
saveButton.addGestureRecognizer(UIGestureRecognizer(target: self, action: #selector(self.saveButtonTapped)))
}
func showSettings() {
let window = UIApplication.shared.windows.filter {$0.isKeyWindow}.first
if let window = window {
blackView.backgroundColor = UIColor(white: 0, alpha: 0.5)
blackView.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(handleDismiss)))
window.addSubview(blackView)
let height: CGFloat = window.frame.height / 3
let y = window.frame.height - height
self.height = height
self.y = y
let width: CGFloat = window.frame.width / 2.5
let x = 0 - width
settingsCollectionView.frame = CGRect(x: x, y: 0, width: width, height: window.frame.height)
// settingsCollectionView.frame = CGRect(x: 0, y: window.frame.height, width: window.frame.width, height: height)
window.addSubview(settingsCollectionView)
// window.addSubview(editProfileView)
// editViewConstraints()
// setupSubviews()
blackView.frame = CGRect(x: 0, y: 0, width: window.frame.width, height: window.frame.height)
blackView.alpha = 0
UIView.animate(withDuration: 0.5, delay: 0, usingSpringWithDamping: 1, initialSpringVelocity: 1, options: .curveEaseOut, animations: {
self.blackView.alpha = 1
self.settingsCollectionView.frame = CGRect(x: -7, y: 0, width: width, height: window.frame.height)
self.settingsCollectionView.settingsShadow()
// self.settingsCollectionView.frame = CGRect(x: 0, y: y, width: self.settingsCollectionView.frame.width, height: self.settingsCollectionView.frame.height)
}, completion: nil)
}
}
@objc func handleDismiss() {
UIView.animate(withDuration: 0.5, animations: {
self.blackView.alpha = 0
let window = UIApplication.shared.windows.filter {$0.isKeyWindow}.first
if let window = window {
let width = window.frame.width / 2.5
self.settingsCollectionView.frame = CGRect(x: -width, y: 0, width: width, height: window.frame.height)
// self.settingsCollectionView.frame = CGRect(x: 0, y: window.frame.height, width: self.settingsCollectionView.frame.width, height: self.settingsCollectionView.frame.height)
// self.editProfileView.frame = CGRect(x: window.frame.width, y: window.frame.height - self.height, width: window.frame.width, height: self.height)
}
}) { _ in
self.settingsCollectionView.removeFromSuperview()
self.editProfileView.removeFromSuperview()
self.saveButton.removeFromSuperview()
}
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return SettingsOptions.allCases.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
guard let cell = collectionView.dequeueReusableCell(withReuseIdentifier: cellID, for: indexPath) as? SettingCollectionViewCell else { return UICollectionViewCell() }
let option = SettingsOptions(rawValue: indexPath.item)?.description
cell.settingLabel.text = option
switch indexPath.item {
case 0:
cell.settingsOptions = .editProfile
case 1:
cell.settingsOptions = .logout
default:
break
}
return cell
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
return CGSize(width: UIScreen.main.bounds.width, height: 50)
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat {
0
}
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
if indexPath.item == 0 {
NotificationCenter.default.post(.init(name: .editProfile))
self.handleDismiss()
} else if indexPath.item == 1 {
NotificationCenter.default.post(.init(name: .handleLogout))
self.handleDismiss()
}
}
func createAttrText(with title: String, color: UIColor, fontName: String) -> NSAttributedString {
guard let font = UIFont(name: fontName, size: 17) else { return NSAttributedString() }
let attrString = NSAttributedString(string: title,
attributes: [NSAttributedString.Key.foregroundColor: color, NSAttributedString.Key.font: font])
return attrString
}
@objc func saveButtonTapped() {
UIView.animate(withDuration: 0.5, animations: {
self.blackView.alpha = 0
let window = UIApplication.shared.windows.filter {$0.isKeyWindow}.first
print("Save Button Tapped!")
if let window = window {
self.editProfileView.frame = CGRect(x: window.frame.width, y: window.frame.height - self.height, width: self.editProfileView.frame.width, height: self.editProfileView.frame.height)
}
}) { _ in
self.editProfileView.removeFromSuperview()
self.saveButton.removeFromSuperview()
}
}
func presentEditView(completion: @escaping () -> Void) {
settingsCollectionView.removeFromSuperview()
self.profileImageView.image = self.profileImage
self.firstNameTextField.text = self.firstName
self.lastNameTextField.text = self.lastName
UIView.animate(withDuration: 0.5, delay: 0, usingSpringWithDamping: 1, initialSpringVelocity: 1, options: .curveEaseOut, animations: {
self.editProfileView.frame = CGRect(x: 0, y: self.y, width: self.editProfileView.frame.width, height: self.editProfileView.frame.height)
}) { (true) in
self.settingsCollectionView.removeFromSuperview()
}
}
func editViewConstraints() {
let window = UIApplication.shared.windows.filter {$0.isKeyWindow}.first
if let window = window {
let height = window.frame.height / 3
editProfileView.frame = CGRect(x: window.frame.width, y: window.frame.height - height, width: window.frame.width, height: height)
window.addSubview(editProfileView)
editProfileView.addSubview(imageBackgroundView)
editProfileView.addSubview(firstNameTextField)
editProfileView.addSubview(lastNameTextField)
editProfileView.addSubview(firstUnderlineView)
editProfileView.addSubview(lastUnderlineView)
editProfileView.addSubview(saveButton)
editProfileView.addSubview(cancelButton)
let imageheight = editProfileView.frame.height / 2
imageBackgroundView.anchor(top: editProfileView.topAnchor, leading: nil, trailing: nil, bottom: nil, centerX: editProfileView.centerXAnchor, centerY: nil, padding: .init(top: 20, left: 0, bottom: 0, right: 0), size: .init(width: imageheight, height: imageheight))
imageBackgroundView.addSubview(profileImageView)
profileImageView.anchor(top: imageBackgroundView.topAnchor, leading: imageBackgroundView.leadingAnchor, trailing: imageBackgroundView.trailingAnchor, bottom: imageBackgroundView.bottomAnchor, centerX: nil, centerY: nil, padding: .init(top: 2, left: 2, bottom: -2, right: -2), size: .zero)
firstNameTextField.anchor(top: imageBackgroundView.bottomAnchor, leading: editProfileView.leadingAnchor, trailing: editProfileView.centerXAnchor, bottom: nil, centerX: nil, centerY: nil, padding: .init(top: 8, left: 20, bottom: 0, right: -16), size: .zero)
lastNameTextField.anchor(top: imageBackgroundView.bottomAnchor, leading: editProfileView.centerXAnchor, trailing: editProfileView.trailingAnchor, bottom: nil, centerX: nil, centerY: nil, padding: .init(top: 8, left: 16, bottom: 0, right: -20), size: .zero)
firstUnderlineView.anchor(top: firstNameTextField.bottomAnchor, leading: firstNameTextField.leadingAnchor, trailing: firstNameTextField.trailingAnchor, bottom: firstNameTextField.bottomAnchor, centerX: nil, centerY: nil, padding: .init(top: -1, left: -2, bottom: 1, right: 2), size: .zero)
lastUnderlineView.anchor(top: lastNameTextField.bottomAnchor, leading: lastNameTextField.leadingAnchor, trailing: lastNameTextField.trailingAnchor, bottom: lastNameTextField.bottomAnchor, centerX: nil, centerY: nil, padding: .init(top: -1, left: -2, bottom: 1, right: 2), size: .zero)
saveButton.frame = CGRect(x: editProfileView.center.x - 50, y: editProfileView.frame.height - 80, width: 40, height: 100)
saveButton.anchor(top: firstNameTextField.bottomAnchor, leading: nil, trailing: nil, bottom: nil, centerX: editProfileView.centerXAnchor, centerY: nil, padding: .init(top: 20, left: 0, bottom: 0, right: 0), size: .init(width: 100, height: 40))
cancelButton.anchor(top: editProfileView.topAnchor, leading: editProfileView.leadingAnchor, trailing: nil, bottom: nil, centerX: nil, centerY: nil, padding: .init(top: 20, left: 20, bottom: 0, right: 0), size: .init(width: 15, height: 15))
saveButton.addGestureRecognizer(UIGestureRecognizer(target: self, action: #selector(self.saveButtonTapped)))
profileImageView.layer.cornerRadius = imageheight / 2
imageBackgroundView.layer.cornerRadius = imageheight / 2
}
}
func setupSubviews() {
editProfileView.backgroundColor = #colorLiteral(red: 0.1721869707, green: 0.1871494651, blue: 0.2290506661, alpha: 1)
editProfileView.layer.cornerRadius = 12
imageBackgroundView.backgroundColor = #colorLiteral(red: 0.7410163879, green: 0.4183317125, blue: 0.4147843719, alpha: 1)
firstUnderlineView.backgroundColor = #colorLiteral(red: 0.7410163879, green: 0.4183317125, blue: 0.4147843719, alpha: 1)
lastUnderlineView.backgroundColor = #colorLiteral(red: 0.7410163879, green: 0.4183317125, blue: 0.4147843719, alpha: 1)
lastNameTextField.borderStyle = .none
firstNameTextField.borderStyle = .none
lastNameTextField.backgroundColor = #colorLiteral(red: 0.1721869707, green: 0.1871494651, blue: 0.2290506661, alpha: 1)
firstNameTextField.backgroundColor = #colorLiteral(red: 0.1721869707, green: 0.1871494651, blue: 0.2290506661, alpha: 1)
firstUnderlineView.layer.cornerRadius = 0.5
lastUnderlineView.layer.cornerRadius = 0.5
self.saveButton.addGestureRecognizer(UIGestureRecognizer(target: self, action: #selector(self.saveButtonTapped)))
self.saveButton.setTitle("Save", for: .normal)
self.saveButton.titleLabel?.font = UIFont(name: PoppinsFont.semiBold.rawValue, size: 17)
self.saveButton.backgroundColor = #colorLiteral(red: 0.7410163879, green: 0.4183317125, blue: 0.4147843719, alpha: 1)
self.saveButton.setTitleColor(UIColor.white, for: .normal)
self.saveButton.layer.borderWidth = 2.0
self.saveButton.layer.borderColor = #colorLiteral(red: 0.7410163879, green: 0.4183317125, blue: 0.4147843719, alpha: 1)
self.saveButton.layer.cornerRadius = 12
self.saveButton.isEnabled = true
firstNameTextField.textAlignment = .center
lastNameTextField.textAlignment = .center
lastNameTextField.textColor = .white
firstNameTextField.textColor = .white
firstNameTextField.layer.cornerRadius = 12
lastNameTextField.layer.cornerRadius = 12
profileImageView.contentMode = .scaleAspectFill
profileImageView.layer.masksToBounds = true
}
func configSaveButton(completion: @escaping () -> Void) {
let window = UIApplication.shared.windows.filter {$0.isKeyWindow}.first
if let window = window {
let x = window.frame.width / 2
let saveButtonY = window.frame.height - 80
self.saveButton.frame = CGRect(x: x - 50, y: saveButtonY, width: 100, height: 40)
window.addSubview(saveButton)
self.saveButton.addGestureRecognizer(UIGestureRecognizer(target: self, action: #selector(self.saveButtonTapped)))
self.saveButton.setTitle("Save", for: .normal)
self.saveButton.titleLabel?.font = UIFont(name: PoppinsFont.semiBold.rawValue, size: 15)
self.saveButton.backgroundColor = #colorLiteral(red: 0.7410163879, green: 0.4183317125, blue: 0.4147843719, alpha: 1)
self.saveButton.setTitleColor(UIColor.white, for: .normal)
self.saveButton.layer.borderWidth = 2.0
self.saveButton.layer.borderColor = #colorLiteral(red: 0.7410163879, green: 0.4183317125, blue: 0.4147843719, alpha: 1)
self.saveButton.layer.cornerRadius = 12
print("Save Button's Frame: \(self.saveButton.frame)")
completion()
}
}
}
| 50.198083 | 301 | 0.649695 |
615494084ce45ea0e266ce408e9e8eb0681a1209 | 6,939 | /*
* Copyright 2019, 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.
*/
#if os(iOS)
import CoreTelephony
import Dispatch
import SystemConfiguration
/// This class may be used to monitor changes on the device that can cause gRPC to silently disconnect (making
/// it seem like active calls/connections are hanging), then manually shut down / restart gRPC channels as
/// needed. The root cause of these problems is that the backing gRPC-Core doesn't get the optimizations
/// made by iOS' networking stack when changes occur on the device such as switching from wifi to cellular,
/// switching between 3G and LTE, enabling/disabling airplane mode, etc.
/// Read more: https://github.com/grpc/grpc-swift/tree/master/README.md#known-issues
/// Original issue: https://github.com/grpc/grpc-swift/issues/337
open class ClientNetworkMonitor {
private let queue: DispatchQueue
private let callback: (State) -> Void
private let reachability: SCNetworkReachability
/// Instance of network info being used for obtaining cellular technology names.
public let cellularInfo = CTTelephonyNetworkInfo()
/// Whether the network is currently reachable. Backed by `SCNetworkReachability`.
public private(set) var isReachable: Bool?
/// Whether the device is currently using wifi (versus cellular).
public private(set) var isUsingWifi: Bool?
/// Name of the cellular technology being used (e.g., `CTRadioAccessTechnologyLTE`).
public private(set) var cellularName: String?
/// Represents a state of connectivity.
public struct State: Equatable {
/// The most recent change that was made to the state.
public let lastChange: Change
/// Whether this state is currently reachable/online.
public let isReachable: Bool
}
/// A change in network condition.
public enum Change: Equatable {
/// Reachability changed (online <> offline).
case reachability(isReachable: Bool)
/// The device switched from cellular to wifi.
case cellularToWifi
/// The device switched from wifi to cellular.
case wifiToCellular
/// The cellular technology changed (e.g., 3G <> LTE).
case cellularTechnology(technology: String)
}
/// Designated initializer for the network monitor. Initializer fails if reachability is unavailable.
///
/// - Parameter host: Host to use for monitoring reachability.
/// - Parameter queue: Queue on which to process and update network changes. Will create one if `nil`.
/// Should always be used when accessing properties of this class.
/// - Parameter callback: Closure to call whenever state changes.
public init?(host: String = "google.com", queue: DispatchQueue? = nil, callback: @escaping (State) -> Void) {
guard let reachability = SCNetworkReachabilityCreateWithName(nil, host) else {
return nil
}
self.queue = queue ?? DispatchQueue(label: "SwiftGRPC.ClientNetworkMonitor.queue")
self.callback = callback
self.reachability = reachability
self.startMonitoringReachability(reachability)
self.startMonitoringCellular()
}
deinit {
SCNetworkReachabilitySetCallback(self.reachability, nil, nil)
SCNetworkReachabilityUnscheduleFromRunLoop(self.reachability, CFRunLoopGetMain(),
CFRunLoopMode.commonModes.rawValue)
NotificationCenter.default.removeObserver(self)
}
// MARK: - Cellular
private func startMonitoringCellular() {
let notificationName: Notification.Name
if #available(iOS 12.0, *) {
notificationName = .CTServiceRadioAccessTechnologyDidChange
} else {
notificationName = .CTRadioAccessTechnologyDidChange
}
NotificationCenter.default.addObserver(self, selector: #selector(self.cellularDidChange(_:)),
name: notificationName, object: nil)
}
@objc
private func cellularDidChange(_ notification: NSNotification) {
self.queue.async {
let newCellularName: String?
if #available(iOS 12.0, *) {
let cellularKey = notification.object as? String
newCellularName = cellularKey.flatMap { self.cellularInfo.serviceCurrentRadioAccessTechnology?[$0] }
} else {
newCellularName = notification.object as? String ?? self.cellularInfo.currentRadioAccessTechnology
}
if let newCellularName = newCellularName, self.cellularName != newCellularName {
self.cellularName = newCellularName
self.callback(State(lastChange: .cellularTechnology(technology: newCellularName),
isReachable: self.isReachable ?? false))
}
}
}
// MARK: - Reachability
private func startMonitoringReachability(_ reachability: SCNetworkReachability) {
let info = Unmanaged.passUnretained(self).toOpaque()
var context = SCNetworkReachabilityContext(version: 0, info: info, retain: nil,
release: nil, copyDescription: nil)
let callback: SCNetworkReachabilityCallBack = { _, flags, info in
let observer = info.map { Unmanaged<ClientNetworkMonitor>.fromOpaque($0).takeUnretainedValue() }
observer?.reachabilityDidChange(with: flags)
}
SCNetworkReachabilitySetCallback(reachability, callback, &context)
SCNetworkReachabilityScheduleWithRunLoop(reachability, CFRunLoopGetMain(),
CFRunLoopMode.commonModes.rawValue)
self.queue.async { [weak self] in
var flags = SCNetworkReachabilityFlags()
SCNetworkReachabilityGetFlags(reachability, &flags)
self?.reachabilityDidChange(with: flags)
}
}
private func reachabilityDidChange(with flags: SCNetworkReachabilityFlags) {
self.queue.async {
let isUsingWifi = !flags.contains(.isWWAN)
let isReachable = flags.contains(.reachable)
let notifyForWifi = self.isUsingWifi != nil && self.isUsingWifi != isUsingWifi
let notifyForReachable = self.isReachable != nil && self.isReachable != isReachable
self.isUsingWifi = isUsingWifi
self.isReachable = isReachable
if notifyForWifi {
self.callback(State(lastChange: isUsingWifi ? .cellularToWifi : .wifiToCellular, isReachable: isReachable))
}
if notifyForReachable {
self.callback(State(lastChange: .reachability(isReachable: isReachable), isReachable: isReachable))
}
}
}
}
#endif
| 42.570552 | 115 | 0.711774 |
08cebc776ea520990e45bba0f4691613e08f61f5 | 1,504 |
import UIKit
import SwiftUI
struct ImagePicker: UIViewControllerRepresentable {
var sourceType: UIImagePickerController.SourceType = .photoLibrary
@Binding var selectedImage: UIImage?
@Environment(\.presentationMode) private var presentationMode
func makeUIViewController(context: UIViewControllerRepresentableContext<ImagePicker>) -> UIImagePickerController {
let imagePicker = UIImagePickerController()
imagePicker.allowsEditing = false
imagePicker.sourceType = sourceType
imagePicker.delegate = context.coordinator
return imagePicker
}
func updateUIViewController(_ uiViewController: UIImagePickerController, context: UIViewControllerRepresentableContext<ImagePicker>) {
}
func makeCoordinator() -> Coordinator {
return Coordinator(self)
}
final class Coordinator: NSObject, UIImagePickerControllerDelegate, UINavigationControllerDelegate {
var parent: ImagePicker
init(_ parent: ImagePicker) {
self.parent = parent
}
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {
if let image = info[.originalImage] as? UIImage {
parent.selectedImage = image
}
parent.presentationMode.wrappedValue.dismiss()
}
}
}
| 31.333333 | 148 | 0.667553 |
0a8f6e292279df5dcc7516d73d3d0f56f2d6fecd | 947 | // swift-tools-version:5.1
// The swift-tools-version declares the minimum version of Swift required to build this package.
import PackageDescription
let package = Package(
name: "BaseComponents",
platforms: [.iOS(.v11)],
products: [
// Products define the executables and libraries produced by a package, and make them visible to other packages.
.library(
name: "BaseComponents",
targets: ["BaseComponents"]),
],
dependencies: [
],
targets: [
// Targets are the basic building blocks of a package. A target can define a module or a test suite.
// Targets can depend on other targets in this package, and on products in packages which this package depends on.
.target(
name: "BaseComponents",
dependencies: []),
.testTarget(
name: "BaseComponentsTests",
dependencies: ["BaseComponents"]),
]
)
| 33.821429 | 122 | 0.631468 |
8915fb123ac2c4381fa38495760677b3a95b878f | 4,489 | //
// BRCryptoKey.swift
// BRCrypto
//
// Created by Ed Gamble on 7/22/19.
// Copyright © 2019 Breadwinner AG. All rights reserved.
//
import Foundation // Data
import BRCryptoC
public final class Key {
static var wordList: [String]?
static func createFrom (phrase: String, words: [String]? = wordList) -> Key? {
guard var words = words?.map ({ UnsafePointer<Int8> (strdup($0)) }) else { return nil }
defer { words.forEach { free(UnsafeMutablePointer (mutating: $0)) } }
guard 1 == BRBIP39PhraseIsValid (&words, phrase) else { return nil }
var seed = UInt512.self.init()
var key = BRKey.self.init()
BRBIP39DeriveKey (&seed, phrase, nil)
defer { seed = UInt512() }
var smallSeed = UInt256 (u64: (seed.u64.0, seed.u64.1, seed.u64.2, seed.u64.3))
defer { smallSeed = UInt256() }
BRKeySetSecret (&key, &smallSeed, 0)
defer { BRKeyClean (&key) }
// UInt512 seed;
// BRBIP39DeriveKey (seed.u8, phrase, NULL);
// return seed;
// int BRKeySetSecret(BRKey *key, const UInt256 *secret, int compressed);
return Key (core: key)
}
static func createForPigeonFrom (key: Key, nonce: Data) -> Key {
return nonce.withUnsafeBytes { (nonceBytes: UnsafeRawBufferPointer) -> Key in
let nonceAddr = nonceBytes.baseAddress?.assumingMemoryBound(to: UInt8.self)
var pairingKey = BRKey()
defer { BRKeyClean (&pairingKey) }
var privateKey = key.core
BRKeyPigeonPairingKey (&privateKey, &pairingKey, nonceAddr, nonce.count)
// let nonce = Array(remoteIdentifier)
// var privKey = authKey
// var pairingKey = BRKey()
// BRKeyPigeonPairingKey(&privKey, &pairingKey, nonce, nonce.count)
return Key (core: pairingKey)
}
}
static func createForBIP32ApiAuth (phrase: String, words: [String]? = wordList) -> Key? {
guard var words = words?.map ({ UnsafePointer<Int8> (strdup($0)) }) else { return nil }
defer { words.forEach { free(UnsafeMutablePointer (mutating: $0)) } }
guard 1 == BRBIP39PhraseIsValid (&words, phrase) else { return nil }
var seed = UInt512.self.init()
var key = BRKey.self.init()
BRBIP39DeriveKey (&seed, phrase, nil)
defer { seed = UInt512() }
BRBIP32APIAuthKey (&key, &seed, MemoryLayout<UInt512>.size)
defer { BRKeyClean (&key) }
// BRBIP39DeriveKey(&seed, phrase, nil)
// BRBIP32APIAuthKey(&key, &seed, MemoryLayout<UInt512>.size)
// seed = UInt512() // clear seed
// let pkLen = BRKeyPrivKey(&key, nil, 0)
// var pkData = CFDataCreateMutable(secureAllocator, pkLen) as Data
// pkData.count = pkLen
// guard pkData.withUnsafeMutableBytes({ BRKeyPrivKey(&key, $0.baseAddress?.assumingMemoryBound(to: Int8.self), pkLen) }) == pkLen else { return nil }
// key.clean()
return Key (core: key)
}
static func createForBIP32BitID (phrase: String, index: Int, uri:String, words: [String]? = wordList) -> Key? {
guard var words = words?.map ({ UnsafePointer<Int8> (strdup($0)) }) else { return nil }
defer { words.forEach { free(UnsafeMutablePointer (mutating: $0)) } }
guard 1 == BRBIP39PhraseIsValid (&words, phrase) else { return nil }
var seed = UInt512.self.init()
var key = BRKey.self.init()
BRBIP39DeriveKey (&seed, phrase, nil)
defer { seed = UInt512() }
BRBIP32BitIDKey (&key, &seed, MemoryLayout<UInt512>.size, UInt32(index), uri)
defer { BRKeyClean (&key) }
return Key (core: key)
}
// The Core representation
var core: BRKey
deinit { BRKeyClean (&core) }
var isCompressed: Bool {
get { return 1 == core.compressed}
set { core.compressed = (newValue ? 1 : 0) }
}
var hasSecret: Bool {
// seed not all zero
return false
}
var serializedPublicKey: Data {
return Data (count:0)
}
var serializedPrivateKey: Data? {
guard hasSecret else { return nil }
return nil
}
internal init (core: BRKey) {
self.core = core
// Ensure that the public key is provided
BRKeyPubKey (&self.core, nil, 0)
}
}
| 33.007353 | 165 | 0.58454 |
8fce58021477a80d06e0683af03fabebdba11f96 | 2,773 |
import UIKit
protocol ArticleAsLivingDocHorizontallyScrollingCellDelegate: AnyObject {
func tappedLink(_ url: URL)
}
class ArticleAsLivingDocHorizontallyScrollingCell: CollectionViewCell {
let descriptionTextView = UITextView()
private var theme: Theme?
weak var delegate: ArticleAsLivingDocHorizontallyScrollingCellDelegate?
override func reset() {
super.reset()
descriptionTextView.attributedText = nil
}
override func sizeThatFits(_ size: CGSize, apply: Bool) -> CGSize {
fatalError("Must override sizeThatFits in subclass")
}
func configure(change: ArticleAsLivingDocViewModel.Event.Large.ChangeDetail, theme: Theme, delegate: ArticleAsLivingDocHorizontallyScrollingCellDelegate) {
setupDescription(for: change)
updateFonts(with: traitCollection)
setNeedsLayout()
apply(theme: theme)
self.delegate = delegate
}
func setupDescription(for change: ArticleAsLivingDocViewModel.Event.Large.ChangeDetail) {
switch change {
case .snippet(let snippet):
descriptionTextView.attributedText = snippet.description
case .reference(let reference):
descriptionTextView.attributedText = reference.description
}
}
override func setup() {
backgroundView?.layer.cornerRadius = 3
backgroundView?.layer.masksToBounds = true
selectedBackgroundView?.layer.cornerRadius = 3
selectedBackgroundView?.layer.masksToBounds = true
layer.shadowOffset = CGSize(width: 0, height: 2)
layer.shadowOpacity = 0.3
layer.shadowRadius = 3
descriptionTextView.isEditable = false
descriptionTextView.isScrollEnabled = false
descriptionTextView.delegate = self
descriptionTextView.textContainer.lineBreakMode = .byTruncatingTail
descriptionTextView.textContainerInset = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 0)
contentView.addSubview(descriptionTextView)
super.setup()
}
}
extension ArticleAsLivingDocHorizontallyScrollingCell: UITextViewDelegate {
func textView(_ textView: UITextView, shouldInteractWith URL: URL, in characterRange: NSRange, interaction: UITextItemInteraction) -> Bool {
delegate?.tappedLink(URL)
return false
}
}
extension ArticleAsLivingDocHorizontallyScrollingCell: Themeable {
func apply(theme: Theme) {
self.theme = theme
backgroundColor = .clear
descriptionTextView.backgroundColor = .clear
setBackgroundColors(theme.colors.subCellBackground, selected: theme.colors.midBackground)
layer.shadowColor = theme.colors.cardShadow.cgColor
}
}
| 35.101266 | 159 | 0.700685 |
501c26afcbcf11b14f13bfcc24d1bc78190bbcaa | 12,241 | //
// HYPushShareView.swift
// e企_2015
//
// Created by 叶佳骏 on 2017/9/25.
// Copyright © 2017年 yejiajun. All rights reserved.
//
import UIKit
@objc(HYSharedViewDelegate)
protocol HYSharedViewDelegate {
func didSharedCommonButtonClicked(type: SharedCommonType)
func didSharedNormalButtonClicked(type: SharedNormalType)
}
class HYSharedView: UIView {
// MARK: - properties
weak internal var delegate: HYSharedViewDelegate?
fileprivate lazy var backgroundView: UIView = {
let backgroundView = UIView()
backgroundView.backgroundColor = UIColor.black
backgroundView.alpha = 0
let tapGesture = UITapGestureRecognizer(target: self, action: #selector(hide))
backgroundView.addGestureRecognizer(tapGesture)
return backgroundView
}()
fileprivate lazy var sharedView: UIView = {
let sharedView = UIView()
sharedView.backgroundColor = UIColor.white
return sharedView
}()
private lazy var topView: UIView = {
let topView = UIView()
topView.backgroundColor = UIColor.clear
return topView
}()
private lazy var titleView: UILabel = {
let titleView = UILabel()
titleView.text = "分享到"
titleView.font = UIFont.systemFont(ofSize: CGFloat(adValue: 13))
titleView.textColor = UIColor(valueRGB: 0x999999, alpha: 1)
return titleView
}()
private lazy var titleLeftLine: UIView = {
let titleLeftLine = UIView()
titleLeftLine.backgroundColor = UIColor(valueRGB: 0xdddddd, alpha: 1)
return titleLeftLine
}()
private lazy var titleRightLine: UIView = {
let titleRightLine = UIView()
titleRightLine.backgroundColor = UIColor(valueRGB: 0xdddddd, alpha: 1)
return titleRightLine
}()
private lazy var commonScrollView: UIScrollView = {
let commonScrollView = UIScrollView()
commonScrollView.backgroundColor = UIColor.clear
commonScrollView.showsVerticalScrollIndicator = false
commonScrollView.showsHorizontalScrollIndicator = false
return commonScrollView
}()
private lazy var contentDividingLine: UIView = {
let contentDividingLine = UIView()
contentDividingLine.backgroundColor = UIColor(valueRGB: 0xdddddd, alpha: 1)
return contentDividingLine
}()
private lazy var normalScrollView: UIScrollView = {
let normalScrollView = UIScrollView()
normalScrollView.backgroundColor = UIColor.clear
normalScrollView.showsHorizontalScrollIndicator = false
normalScrollView.showsVerticalScrollIndicator = false
return normalScrollView
}()
private lazy var bottomDividingLine: UIView = {
let bottomDividingLine = UIView()
bottomDividingLine.backgroundColor = UIColor(valueRGB: 0xdddddd, alpha: 1)
return bottomDividingLine
}()
fileprivate lazy var cancelButton: UIButton = {
let cancelButton = UIButton()
cancelButton.setTitle("取消", for: .normal)
cancelButton.setTitleColor(UIColor(valueRGB: 0x1da1f2, alpha: 1), for: .normal)
cancelButton.titleLabel?.font = UIFont.systemFont(ofSize: CGFloat(16))
cancelButton.addTarget(self, action: #selector(hide), for: .touchUpInside)
return cancelButton
}()
fileprivate let animationTime = 0.25
fileprivate let backgroundViewAlpha: CGFloat = 0.35
fileprivate var sharedViewHeight: CGFloat = 0
private let padding: CGFloat = 20
private let topViewHeight: CGFloat = 20
private let srollViewHeight: CGFloat = JJAdapter(65)
private let bottomDividingLineHeight: CGFloat = 5
private let bottomViewHeight: CGFloat = 45
private var sharedButtonWith: CGFloat = 0
private var isNormalScrollViewHidden = false
// 兼容OC的初始化方法
convenience init(frame: CGRect, commonTypes: [NSInteger], normalTypes: [NSInteger]?) {
self.init(frame: frame, commonTypes: commonTypes, normalTypes: normalTypes, title: nil)
}
// 兼容OC的初始化方法
convenience init(frame: CGRect, commonTypes: [NSInteger], normalTypes: [NSInteger]?, title: String?) {
var sharedCommonTypes = [SharedCommonType]()
var sharedNormalTypes = [SharedNormalType]()
commonTypes.forEach { type in
if let commonType = SharedCommonType(rawValue: type) {
sharedCommonTypes += [commonType]
}
}
if let normalTypes = normalTypes {
normalTypes.forEach { type in
if let normalType = SharedNormalType(rawValue: type) {
sharedNormalTypes += [normalType]
}
}
}
self.init(frame: frame, sharedCommonTypes: sharedCommonTypes, sharedNormalTypes: sharedNormalTypes, title: title)
}
// Swift初始化方法
init(frame: CGRect, sharedCommonTypes: [SharedCommonType], sharedNormalTypes: [SharedNormalType], title: String? = "分享到" ) {
super.init(frame: frame)
self.backgroundColor = UIColor.clear
sharedButtonWith = ScreenWidth / CGFloat(sharedCommonTypes.count >= 3 ? 3 : sharedCommonTypes.count)
if sharedNormalTypes.count > 0 {
sharedViewHeight = padding + topViewHeight + padding + srollViewHeight * 2 + padding * 3 + bottomDividingLineHeight + bottomViewHeight
} else {
isNormalScrollViewHidden = true
sharedViewHeight = padding + topViewHeight + padding + srollViewHeight + padding + bottomDividingLineHeight + bottomViewHeight
}
self.addSubview(backgroundView)
self.addSubview(sharedView)
sharedView.addSubview(topView)
sharedView.addSubview(bottomDividingLine)
sharedView.addSubview(cancelButton)
topView.addSubview(titleView)
topView.addSubview(titleLeftLine)
topView.addSubview(titleRightLine)
sharedView.addSubview(commonScrollView)
if !isNormalScrollViewHidden {
sharedView.addSubview(contentDividingLine)
sharedView.addSubview(normalScrollView)
}
layoutSnpSubviews()
titleView.text = title
commonScrollView.contentSize = CGSize(width: CGFloat(sharedCommonTypes.count) * sharedButtonWith, height: 0)
for (index, type) in sharedCommonTypes.enumerated() {
let frame = CGRect(x: CGFloat(index) * sharedButtonWith, y: 0, width: sharedButtonWith, height: srollViewHeight)
let sharedButton = HYSharedButton(frame: frame, title: type.title, imageName: type.imageName)
sharedButton.tag = type.rawValue
sharedButton.addTarget(self, action: #selector(sharedCommonButtonClicked(sender:)), for: .touchUpInside)
commonScrollView.addSubview(sharedButton)
}
normalScrollView.contentSize = CGSize(width: CGFloat(sharedNormalTypes.count) * sharedButtonWith, height: 0)
for (index, type) in sharedNormalTypes.enumerated() {
let frame = CGRect(x: CGFloat(index) * sharedButtonWith, y: 0, width: sharedButtonWith, height: srollViewHeight)
let sharedButton = HYSharedButton(frame: frame, title: type.title, imageName: type.imageName)
sharedButton.tag = type.rawValue
sharedButton.addTarget(self, action: #selector(sharedNormalButtonClicked(sender:)), for: .touchUpInside)
normalScrollView.addSubview(sharedButton)
}
}
private func layoutSnpSubviews() {
backgroundView.snp.makeConstraints { make in
make.top.equalTo(self)
make.left.equalTo(self)
make.size.equalTo(self)
}
sharedView.snp.makeConstraints { make in
make.top.equalTo(self.bottom)
make.left.equalTo(self)
make.width.equalTo(self)
make.height.equalTo(sharedViewHeight)
}
topView.snp.makeConstraints { make in
make.top.equalTo(sharedView).offset(padding)
make.left.equalTo(self)
make.width.equalTo(self)
make.height.equalTo(topViewHeight)
}
titleView.snp.makeConstraints { make in
make.center.equalTo(topView)
make.width.greaterThanOrEqualTo(1)
make.height.equalTo(topView)
}
titleLeftLine.snp.makeConstraints { make in
make.left.equalTo(topView).offset(JJAdapter(20))
make.right.equalTo(titleView.snp.left).offset(JJAdapter(-15))
make.centerY.equalTo(topView)
make.height.equalTo(0.5)
}
titleRightLine.snp.makeConstraints { make in
make.right.equalTo(topView).offset(JJAdapter(-20))
make.left.equalTo(titleView.snp.right).offset(JJAdapter(15))
make.centerY.equalTo(titleLeftLine)
make.height.equalTo(titleLeftLine)
}
commonScrollView.snp.makeConstraints { make in
make.left.equalTo(sharedView)
make.top.equalTo(topView.snp.bottom).offset(padding)
make.width.equalTo(sharedView)
make.height.equalTo(srollViewHeight)
}
if !isNormalScrollViewHidden {
contentDividingLine.snp.makeConstraints { make in
make.left.equalTo(sharedView)
make.right.equalTo(sharedView)
make.bottom.equalTo(commonScrollView).offset(padding)
make.height.equalTo(titleLeftLine)
}
normalScrollView.snp.makeConstraints { make in
make.left.equalTo(commonScrollView)
make.top.equalTo(contentDividingLine.snp.bottom).offset(padding)
make.width.equalTo(commonScrollView)
make.height.equalTo(commonScrollView)
}
}
bottomDividingLine.snp.makeConstraints { make in
if !isNormalScrollViewHidden {
make.top.equalTo(normalScrollView.snp.bottom).offset(padding)
} else {
make.top.equalTo(commonScrollView.snp.bottom).offset(padding)
}
make.left.equalTo(sharedView)
make.width.equalTo(sharedView)
make.height.equalTo(bottomDividingLineHeight)
}
cancelButton.snp.makeConstraints { make in
make.bottom.equalTo(sharedView)
make.left.equalTo(sharedView)
make.width.equalTo(sharedView)
make.height.equalTo(bottomViewHeight)
}
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
// MARK: - Action
extension HYSharedView {
internal func show() {
self.isHidden = false
UIView.animate(withDuration: animationTime) {
self.backgroundView.alpha = self.backgroundViewAlpha
self.sharedView.frame = CGRect(x: 0, y: ScreenHeight - self.sharedViewHeight, width: ScreenWidth, height: self.sharedViewHeight)
}
}
@objc internal func hide() {
UIView.animate(withDuration: animationTime, animations: {
self.backgroundView.alpha = 0
self.sharedView.frame = CGRect(x: 0, y: ScreenHeight, width: ScreenWidth, height: self.sharedViewHeight)
}) { isCompleted in
self.isHidden = true
}
}
internal func hideWithoutAnimataion() {
self.backgroundView.alpha = 0
self.sharedView.frame = CGRect(x: 0, y: ScreenHeight, width: ScreenWidth, height: self.sharedViewHeight)
self.isHidden = true
}
@objc fileprivate func sharedCommonButtonClicked(sender: UIButton) {
let type = SharedCommonType(rawValue: sender.tag)
if let type = type {
self.delegate?.didSharedCommonButtonClicked(type: type)
}
}
@objc fileprivate func sharedNormalButtonClicked(sender: UIButton) {
let type = SharedNormalType(rawValue: sender.tag)
if let type = type {
self.delegate?.didSharedNormalButtonClicked(type: type)
}
}
}
| 38.737342 | 146 | 0.644964 |
71e87944e02ef62da1f88b713ba7ea08415e2bf0 | 27,017 | //
// MyApprovalsViewController.swift
// OIMApp
//
// Created by Linh NGUYEN on 5/12/15.
// Copyright (c) 2015 Persistent Systems. All rights reserved.
//
import UIKit
class ApprovalsViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
@IBOutlet var tableView : UITableView!
@IBOutlet var menuItem : UIBarButtonItem!
@IBOutlet var toolbar : UIToolbar!
@IBOutlet var labelTitle: UILabel!
@IBOutlet var lblTotalCounter: UILabel!
@IBOutlet var btnEdit: UIBarButtonItem!
@IBOutlet var btnEditDecline: UIBarButtonItem!
@IBOutlet var btnEditLabel: UIBarButtonItem!
@IBOutlet weak var bottonMargin: NSLayoutConstraint!
//var viewLoadMore : UIView!
var showViewLoadMore = true
var isVeryFirstTime = true
var imageAsync : UIImage!
var isFirstTime = true
var refreshControl:UIRefreshControl!
var itemHeading: NSMutableArray! = NSMutableArray()
var nagivationStyleToPresent : String?
let transitionOperator = TransitionOperator()
var tasks : [Tasks]!
var selectedtasks : [Tasks] = []
var api : API!
var utl : UTIL!
//---> For Pagination
var cursor = 1;
let limit = 7;
@IBAction func btnEditCeclineAction(sender: AnyObject) {
let alertController = UIAlertController(title: "Decline Confirmation", message: "Bulk Decline", preferredStyle: .Alert)
let cancelAction = UIAlertAction(title: "Cancel", style: .Cancel) { action in
}
alertController.addAction(cancelAction)
self.presentViewController(alertController, animated: true){
}
}
@IBAction func btnEditAction(sender: AnyObject) {
if self.selectedtasks.count > 0 {
let doalert = DOAlertController(title: "Approval Confirmation", message: "Please confirm approval for the selected request(s)", preferredStyle: .Alert)
doalert.addTextFieldWithConfigurationHandler { textField in
textField.placeholder = " Enter Comments "
}
let approveAction = DOAlertAction(title: "OK", style: .Default) { action in
let textField = doalert.textFields![0] as! UITextField
let url = myAPIEndpoint + "/approvals"
let taskaction = "APPROVE" as String!
var paramstring = "{\"requester\": {\"User Login\": \"" + myLoginId + "\"},\"task\": ["
for var i = 0; i < self.selectedtasks.count; ++i {
let task = self.selectedtasks[i]
paramstring += "{\"requestId\": \""
paramstring += task.requestId + "\",\"taskId\": \""
paramstring += task.taskId + "\", \"taskNumber\": \""
paramstring += task.taskNumber + "\",\"taskPriority\": \""
paramstring += task.taskPriority + "\",\"taskState\": \""
paramstring += task.taskState + "\",\"taskTitle\": \""
paramstring += task.taskTitle + "\" ,\"taskActionComments\": \""
paramstring += textField.text! + "\",\"taskAction\": \""
paramstring += taskaction + "\"},"
}
paramstring += "]}"
let idx = paramstring.endIndex.advancedBy(-3)
var substring1 = paramstring.substringToIndex(idx)
substring1 += "]}"
self.api.RequestApprovalAction(myLoginId, params : substring1, url : url) { (succeeded: Bool, msg: String) -> () in
let alert = UIAlertController(title: "Success!", message: msg, preferredStyle: .Alert)
//-->self.presentViewController(alert, animated: true, completion: nil) uncomment code if we want to display alert on success.
if(succeeded) {
alert.title = "Success!"
alert.message = msg
}
else {
alert.title = "Failed : ("
alert.message = msg
}
dispatch_async(dispatch_get_main_queue(), { () -> Void in
for var i = 0; i < self.selectedtasks.count; ++i {
if let indexPath = self.tableView.indexPathForSelectedRow {
self.tasks.removeAtIndex(indexPath.row)
self.tableView.beginUpdates()
self.tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: UITableViewRowAnimation.Left)
self.tableView.endUpdates()
}
}
let delayTime = dispatch_time(DISPATCH_TIME_NOW, Int64(0.2 * Double(NSEC_PER_SEC)))
dispatch_after(delayTime, dispatch_get_main_queue()) {
self.tableView.reloadData()
}
})
}
}
let cancelAction = DOAlertAction(title: "Cancel", style: .Cancel) { action in
}
doalert.addAction(cancelAction)
doalert.addAction(approveAction)
presentViewController(doalert, animated: true, completion: nil)
} else {
let alertController = UIAlertController(title: "Error : (", message: "You must select at least one", preferredStyle: .Alert)
let cancelAction = UIAlertAction(title: "Cancel", style: .Cancel) { action in
}
alertController.addAction(cancelAction)
self.presentViewController(alertController, animated: true, completion: nil)
}
}
@IBAction func btnEdit(sender: AnyObject) {
if tableView.editing {
///--->>> Un-Hiding Bottom Toolbar By Defaults
self.bottonMargin.constant = self.bottonMargin.constant - 44;
self.tableView.setEditing(false, animated: true)
btnEditLabel.title = "Edit"
btnEdit.title = ""
btnEditDecline.title = ""
btnEdit.image = UIImage()
btnEdit.enabled = false
btnEditDecline.enabled = false
} else {
///--->>> Hiding Bottom Toolbar By Defaults
self.bottonMargin.constant = self.bottonMargin.constant + 44;
self.tableView.setEditing(true, animated: true)
btnEditLabel.title = "Cancel"
btnEdit.image = UIImage(named:"toolbar-approve")
btnEditDecline.title = ""
btnEdit.enabled = true
btnEditDecline.enabled = false
}
self.tableView.reloadData()
}
override func viewDidLoad() {
super.viewDidLoad()
if (totalCounter > 0) {
self.lblTotalCounter.hidden = false
self.lblTotalCounter.layer.cornerRadius = 9;
lblTotalCounter.layer.masksToBounds = true;
self.lblTotalCounter.text = "\(totalCounter)"
} else {
self.lblTotalCounter.hidden = true
}
tableView.delegate = self
tableView.dataSource = self
tableView.separatorStyle = UITableViewCellSeparatorStyle.SingleLine
tableView.separatorColor = UIColor.blackColor().colorWithAlphaComponent(0.1)
tableView.allowsMultipleSelectionDuringEditing = true
tableView.allowsSelectionDuringEditing = true
labelTitle.text = "Pending Approvals"
toolbar.clipsToBounds = true
toolbar.tintColor = UIColor.blackColor()
menuItem.image = UIImage(named: "menu")
itemHeading.addObject("Approvals")
btnEdit.enabled = false
btnEditDecline.enabled = false
self.bottonMargin.constant = self.bottonMargin.constant - 44;
self.tasks = [Tasks]()
self.api = API()
let url = myAPIEndpoint + "/users/" + myLoginId + "/approvals/?cursor=\(self.cursor)&limit=\(self.limit)"
api.loadPendingApprovals(myLoginId, apiUrl: url, completion : didLoadData)
refreshControl = UIRefreshControl()
refreshControl.tintColor = UIColor.redColor()
refreshControl.addTarget(self, action: "refresh", forControlEvents: UIControlEvents.ValueChanged)
tableView.addSubview(refreshControl)
let recognizer = UIPanGestureRecognizer(target: self, action: "panGestureRecognized:")
self.view.addGestureRecognizer(recognizer)
/*
let localNotification:UILocalNotification = UILocalNotification()
localNotification.alertAction = "Approve"
localNotification.alertBody = "Kevin Clark is requesting West Data Center Access."
localNotification.soundName = UILocalNotificationDefaultSoundName
localNotification.applicationIconBadgeNumber = 1
localNotification.fireDate = NSDate(timeIntervalSinceNow: 15)
UIApplication.sharedApplication().scheduleLocalNotification(localNotification)
*/
}
func loadMore() {
self.showViewLoadMore = true
let url = myAPIEndpoint + "/users/" + myLoginId + "/approvals/?cursor=\(self.cursor)&limit=\(self.limit)"
api.loadPendingApprovals(myLoginId, apiUrl: url, completion : didLoadData)
}
// MARK: swipe gestures
func panGestureRecognized(sender: UIPanGestureRecognizer) {
self.view.endEditing(true)
self.frostedViewController.view.endEditing(true)
self.frostedViewController.panGestureRecognized(sender)
}
func refresh(){
self.tasks = [Tasks]()
self.cursor = 1
let url = myAPIEndpoint + "/users/" + myLoginId + "/approvals/?cursor=\(self.cursor)&limit=\(self.limit)"
api.loadPendingApprovals(myLoginId, apiUrl: url, completion : didLoadData)
SoundPlayer.play("upvote.wav")
}
func didLoadData(loadedData: [Tasks]){
for data in loadedData {
self.tasks.append(data)
}
if isFirstTime {
self.view.showLoading()
}
//---> Increment Cursor
self.cursor = self.cursor + 7;
if self.cursor > myApprovals {
self.showViewLoadMore = false
}
self.tableView.reloadData()
self.view.hideLoading()
self.refreshControl?.endRefreshing()
}
override func viewDidAppear(animated: Bool) {
super.viewDidAppear(true)
if isFirstTime {
view.showLoading()
isFirstTime = false
}
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if self.tasks == nil {
return 0
}
if self.showViewLoadMore {
return self.tasks!.count + 1
} else {
return self.tasks!.count
}
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
self.utl = UTIL()
if (indexPath.row < self.tasks.count) {
let task = tasks[indexPath.row]
let cell = tableView.dequeueReusableCellWithIdentifier("TasksCell") as! TasksCell
cell.approveBtn.tag = indexPath.row
cell.approveBtn.setBackgroundImage(UIImage(named:"btn-approve"), forState: .Normal)
cell.approveBtn.addTarget(self, action: "buttonAction:", forControlEvents: .TouchUpInside)
cell.declineBtn.tag = indexPath.row
cell.declineBtn.setBackgroundImage(UIImage(named:"btn-decline"), forState: .Normal)
cell.declineBtn.addTarget(self, action: "buttonAction:", forControlEvents: .TouchUpInside)
cell.moreBtn.tag = indexPath.row
cell.moreBtn.setBackgroundImage(UIImage(named:"btn-more"), forState: .Normal)
cell.moreBtn.addTarget(self, action: "buttonAction:", forControlEvents: .TouchUpInside)
var titleText = ""
for ent in task.requestEntityName {
if titleText.isEmpty {
titleText = ent.entityname
} else {
titleText += " , \(ent.entityname)"
}
}
cell.nameLabel.text = titleText
cell.postLabel?.text = task.requestType
cell.beneficiaryLabel.text = "Beneficiaries:"
var beneficiaryText = ""
for ben in task.beneficiaryUser {
if beneficiaryText.isEmpty {
beneficiaryText = ben.beneficiary
} else {
beneficiaryText += " , \(ben.beneficiary)"
}
}
cell.typeImageView.image = utl.GetLocalAvatarByName(beneficiaryText)
cell.beneiciaryUserLabel.text = beneficiaryText
cell.justificationLabel.text = task.requestJustification
cell.dateLabel.text = task.requestedDate + " | Request " + task.requestId
cell.selectionStyle = UITableViewCellSelectionStyle.Default
if self.tableView.editing {
cell.approveBtn.enabled = false
cell.declineBtn.enabled = false
cell.moreBtn.enabled = false
cell.moreBtn.hidden = true
} else {
cell.approveBtn.enabled = true
cell.declineBtn.enabled = true
cell.moreBtn.enabled = true
cell.moreBtn.hidden = false
}
if (myApprovals < 7) {
//--->>> No Load More Here
self.showViewLoadMore = false
} else {
///---->>> Load More Should Call
if (indexPath.row == self.tasks.count - 7 /*- 2*/){
if (self.cursor <= myApprovals) {
//print("in CellforRowAtIndexPath -- Calling Load More")
self.loadMore();
} else {
////--->>> Do Nothing
}
}
}
self.tableView.separatorStyle = UITableViewCellSeparatorStyle.SingleLine
return cell
} else if (self.showViewLoadMore == true) {
if self.isVeryFirstTime == true {
self.isVeryFirstTime = false
let cell = UITableViewCell()
self.tableView.separatorStyle = UITableViewCellSeparatorStyle.None
return cell
} else {
let cell = tableView.dequeueReusableCellWithIdentifier("LoadMoreCC") as! LoadMoreCC
cell.viewSpinner.frame = CGRectMake(cell.viewSpinner.frame.origin.x, cell.viewSpinner.frame.origin.y, cell.viewSpinner.frame.size.width, 30)
cell.spinner.color = UIColor(red: 73.0/255.0, green: 143.0/255.0, blue: 225.0/255.0, alpha: 1.0)
cell.spinner.startAnimating()
self.tableView.separatorStyle = UITableViewCellSeparatorStyle.None
return cell
}
} else {
let cell = UITableViewCell()
self.tableView.separatorStyle = UITableViewCellSeparatorStyle.None
return cell
}
}
func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
if (indexPath.row == self.tasks.count) {
return 30.0
} else {
return 180.0
}
}
///---->>> Also Working for Load More
func tableView(tableView: UITableView, willDisplayCell cell: UITableViewCell, forRowAtIndexPath indexPath: NSIndexPath) {
let lastSectionIndex = tableView.numberOfSections - 1
let lastRowIndex = tableView.numberOfRowsInSection(lastSectionIndex) - 1
if ((indexPath.section == lastSectionIndex) && (indexPath.row == lastRowIndex)) {
//--->>> This is the last Cell
//print("This is the last Cell...")
// self.loadMore()
}
}
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
/*
if let indexPath = self.tableView.indexPathsForSelectedRows as? [NSIndexPath]! {
self.selectedtasks.removeAll(keepCapacity: true)
for idx in indexPath {
let info = tasks[idx.item]
self.selectedtasks.append(info)
}
/* not using - save for later
let selectedcell = tableView.cellForRowAtIndexPath(indexPath)
if (selectedcell!.accessoryType == UITableViewCellAccessoryType.None) {
selectedcell!.accessoryType = UITableViewCellAccessoryType.Checkmark
//self.selectedtasks.append(info)
//self.selectedtasks.sort({ $0.requestId < $1.requestId })
}else{
selectedcell!.accessoryType = UITableViewCellAccessoryType.None
//self.selectedtasks.removeAtIndex(indexPath.row)
//self.selectedtasks.filter() { $0.requestId != info.requestId }
//self.selectedtasks.sort({ $0.requestId < $1.requestId })
}*/
}*/
if self.tableView.editing {
if let indexPath = self.tableView.indexPathsForSelectedRows as [NSIndexPath]! {
self.selectedtasks.removeAll(keepCapacity: true)
for idx in indexPath {
let info = tasks[idx.item]
self.selectedtasks.append(info)
}
}
} else {
if let indexPath = self.tableView.indexPathForSelectedRow {
let info = tasks[indexPath.row]
let storyboard = UIStoryboard(name: "Main", bundle: nil)
let controller = storyboard.instantiateViewControllerWithIdentifier("ApprovalsDetailViewController") as! ApprovalsDetailViewController
controller.approvalId = info.requestId
var titleText = ""
for ent in info.requestEntityName {
if titleText.isEmpty {
titleText = ent.entityname
} else {
titleText += " , \(ent.entityname)"
}
}
controller.approvalTitle = titleText
controller.navigationController
showViewController(controller, sender: self)
}
tableView.deselectRowAtIndexPath(indexPath, animated: false)
}
}
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return itemHeading.count
}
func tableView(tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
let view: UIView! = UIView(frame: CGRectMake(0, 0, self.view.frame.size.width, 40))
view.backgroundColor = UIColor(red: 236.0/255.0, green: 243.0/255.0, blue: 244.0/255.0, alpha: 1)
let lblHeading : UILabel! = UILabel(frame: CGRectMake(20, 0, 200, 20))
lblHeading.font = UIFont.systemFontOfSize(12)
lblHeading.textColor = UIColor.darkGrayColor()
lblHeading.text = itemHeading.objectAtIndex(section) as! NSString as String
view.addSubview(lblHeading)
return view
}
@IBAction func presentNavigation(sender: AnyObject?){
self.view.endEditing(true)
self.frostedViewController.view.endEditing(true)
self.frostedViewController.presentMenuViewController()
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
let toViewController = segue.destinationViewController
toViewController.transitioningDelegate = self.transitionOperator
}
func dismiss(){
dismissViewControllerAnimated(true, completion: nil)
}
func buttonAction(sender:UIButton!)
{
let btnsendtag:UIButton = sender
let action = sender.currentTitle
let task = self.tasks[btnsendtag.tag]
let requestid = task.requestId as String!
let taskid = task.taskId as String!
let tasknumber = task.taskNumber as String!
let taskpriority = task.taskPriority as String!
let taskstate = task.taskState as String!
let tasktitle = task.taskTitle as String!
var taskaction : String!
var alerttitle : String!
var alertmsg : String!
var titleText = ""
for ent in task.requestEntityName {
if titleText.isEmpty {
titleText = ent.entityname
} else {
titleText += " , \(ent.entityname)"
}
}
if action == "Approve" {
taskaction = "APPROVE"
alerttitle = "Approval Confirmation"
alertmsg = "Please confirm approval for " + titleText + " Requested by " + task.requestRaisedByUser
} else if action == "Decline" {
taskaction = "REJECT"
alerttitle = "Decline Confirmation"
alertmsg = "Please confirm rejection of " + titleText + " Requested by " + task.requestRaisedByUser
} else if action == "More" {
taskaction = ""
alerttitle = "More Options"
alertmsg = ""
}
var doalert : DOAlertController
if action != "More" {
doalert = DOAlertController(title: alerttitle, message: alertmsg, preferredStyle: .Alert)
// Add the text field for text entry.
doalert.addTextFieldWithConfigurationHandler { textField in
// If you need to customize the text field, you can do so here.
textField.placeholder = " Enter Comments "
}
let approveAction = DOAlertAction(title: "OK", style: .Default) { action in
let textField = doalert.textFields![0] as! UITextField
let url = myAPIEndpoint + "/approvals"
var paramstring = "{\"requester\": {\"User Login\": \""
paramstring += myLoginId + "\"},\"task\": [{\"requestId\": \""
paramstring += requestid + "\",\"taskId\": \""
paramstring += taskid + "\", \"taskNumber\": \""
paramstring += tasknumber + "\",\"taskPriority\": \""
paramstring += taskpriority + "\",\"taskState\": \""
paramstring += taskstate + "\",\"taskTitle\": \""
paramstring += tasktitle + "\" ,\"taskActionComments\": \""
paramstring += textField.text! + "\",\"taskAction\": \""
paramstring += taskaction + "\"}]}"
self.api.RequestApprovalAction(myLoginId, params : paramstring, url : url) { (succeeded: Bool, msg: String) -> () in
let alert = UIAlertController(title: "Success!", message: msg, preferredStyle: .Alert)
//-->self.presentViewController(alert, animated: true, completion: nil) uncomment code if we want to display alert on success.
if(succeeded) {
alert.title = "Success!"
alert.message = msg
}
else {
alert.title = "Failed : ("
alert.message = msg
}
dispatch_async(dispatch_get_main_queue(), { () -> Void in
//--->>> Getting IndexPath for Row to Delete
let indexPath = NSIndexPath(forRow:btnsendtag.tag, inSection:0) as NSIndexPath
//--->> Removing Data from Data SOurce
self.tasks.removeAtIndex(btnsendtag.tag)
//--->>> Removing Row with Animation
self.tableView.beginUpdates()
self.tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: UITableViewRowAnimation.Left)
self.tableView.endUpdates()
let delayTime = dispatch_time(DISPATCH_TIME_NOW, Int64(0.2 * Double(NSEC_PER_SEC)))
dispatch_after(delayTime, dispatch_get_main_queue()) {
//--->>> Reload Data to Refresh IndexPaths
self.tableView.reloadData()
}
})
}
}
let cancelAction = DOAlertAction(title: "Cancel", style: .Cancel) { action in
}
doalert.addAction(cancelAction)
doalert.addAction(approveAction)
presentViewController(doalert, animated: true, completion: nil)
} else {
doalert = DOAlertController(title: nil, message: nil, preferredStyle: .ActionSheet)
//let approveAction = DOAlertAction(title: "Approve", style: .Destructive) { action in
//}
let reassignAction = DOAlertAction(title: "Reassign", style: .Destructive) { action in
}
let claimAction = DOAlertAction(title: "Claim", style: .Destructive) { action in
}
//let declineAction = DOAlertAction(title: "Decline", style: .Destructive) { action in
//}
let delegateAction = DOAlertAction(title: "Delegate", style: .Destructive) { action in
}
let resetAction = DOAlertAction(title: "Reset", style: .Destructive) { action in
}
let cancelAction = DOAlertAction(title: "Cancel", style: .Cancel) { action in
}
// Add the action.
doalert.addAction(reassignAction)
doalert.addAction(claimAction)
doalert.addAction(delegateAction)
doalert.addAction(resetAction)
doalert.addAction(cancelAction)
presentViewController(doalert, animated: true, completion: nil)
}
}
}
| 41.500768 | 163 | 0.550912 |
0a8b11a5a3f15fced6e7f2216381e7a8e3e11a53 | 905 | // swift-tools-version:5.3
// The swift-tools-version declares the minimum version of Swift required to build this package.
import PackageDescription
let package = Package(
name: "Swifty",
platforms: [.iOS(.v9), .macOS(.v10_11)],
products: [
// Products define the executables and libraries a package produces, and make them visible to other packages.
.library(
name: "Swifty",
targets: ["Swifty"])
],
dependencies: [
// Dependencies declare other packages that this package depends on.
// .package(url: /* package url */, from: "1.0.0"),
],
targets: [
// Targets are the basic building blocks of a package. A target can define a module or a test suite.
// Targets can depend on other targets in this package, and on products in packages this package depends on.
.target(name: "Swifty")
]
)
| 36.2 | 117 | 0.641989 |
8af2362c7b2c03a51aab1a616a0198d0593f3539 | 1,017 | //
// Operator.swift
// Reactive
//
// Created by Jens Jakob Jensen on 25/08/14.
// Copyright (c) 2014 Jayway. All rights reserved.
//
infix operator .. { precedence 91 associativity right } // Precedence one higher than assignment
// Merge an intermediate with a sink
public func .. <I,O>(f: TypesIO<I,O>.OutputSink -> TypesIO<I,O>.InputSink, sink: TypesIO<I,O>.OutputSink) -> TypesIO<I,O>.InputSink {
return f(sink)
}
// Merge an emitter and a sink
public func .. <T>(emitter: Types<T>.Emitter, sink: Types<T>.Sink) -> TerminatorType {
return emitter(sink)
}
// Merge an emitter and an intermediate
public func .. <T>(emitter: Types<T>.Emitter, f: Types<T>.Sink -> Types<T>.Sink) (sink: Types<T>.Sink) -> TerminatorType {
return emitter .. f .. sink
}
// Merge two intermediates
public func .. <I,T,O>(f: TypesIO<I,T>.OutputSink -> TypesIO<I,T>.InputSink, g: TypesIO<T,O>.OutputSink -> TypesIO<T,O>.InputSink) (sink: TypesIO<T,O>.OutputSink) -> TypesIO<I,T>.InputSink {
return f(g(sink))
}
| 33.9 | 190 | 0.674533 |
9122928e388eae252b5275f5557a8236ba20adb8 | 4,718 | //
// ISSMapViewController.swift
// InternationalSpaceStation
//
// Created by Allen Wong on 3/16/16.
// Copyright © 2016 Allen Wong. All rights reserved.
//
import UIKit
import MapKit
class ISSMapViewController: UIViewController, MKMapViewDelegate
{
let issNetwork = ISSNetwork()
let favoriteLocation = ISSFavoriteLocation.sharedInstance
var selectedAnnotation: MKAnnotation?
//MARK: - IBOutlet
@IBOutlet weak var mapView: MKMapView!
@IBOutlet weak var addFavoriteLocationButton: UIButton!
//MARK: - IBAction
@IBAction func addFavoriteButtonAction(sender: UIButton)
{
addFavoriteLocationButton.hidden = true
self.performSegueWithIdentifier("SegueToAddFavorite", sender: nil)
}
@IBAction func addFavoriteBarButton(sender: UIBarButtonItem)
{
addFavoriteLocationButton.hidden = false
}
@IBAction func reloadISSBarButtonAction(sender: UIBarButtonItem)
{
let currentAnnotationPin = self.mapView.annotations.filter({$0.title! == "SpaceStation"})
self.mapView.removeAnnotations(currentAnnotationPin)
self.displayCurrentISSPosition()
}
override func viewDidAppear(animated: Bool)
{
super.viewDidAppear(animated)
if favoriteLocation.favoriteLocation.isEmpty
{
return
}
mapView.addAnnotations(favoriteLocation.favoriteLocation)
}
//MARK: - MapDelegate
func mapViewDidFinishLoadingMap(mapView: MKMapView)
{
if mapView.annotations.filter({$0.title! == "SpaceStation"}).isEmpty
{
self.displayCurrentISSPosition()
}
}
func mapView(mapView: MKMapView, viewForAnnotation annotation: MKAnnotation) -> MKAnnotationView?
{
if let positiionAnnotation = annotation as? ISSPositionAnnotation
{
return spaceStationPosition(positiionAnnotation)
}
return favoriteAnnotation(annotation)
}
func mapView(mapView: MKMapView, didSelectAnnotationView view: MKAnnotationView)
{
selectedAnnotation = view.annotation
addFavoriteLocationButton.hidden = true
}
func mapView(mapView: MKMapView, didDeselectAnnotationView view: MKAnnotationView)
{
selectedAnnotation = nil
}
func spaceStationPosition(annotation: MKAnnotation) -> MKAnnotationView
{
let issAnnotationView = MKAnnotationView(annotation: annotation, reuseIdentifier: "ISSPositationView")
issAnnotationView.image = UIImage(named: "spaceStationIcon")
issAnnotationView.canShowCallout = true
return issAnnotationView
}
func favoriteAnnotation(annotation: MKAnnotation) -> MKAnnotationView
{
let favoriteAnnotation = MKAnnotationView(annotation: annotation, reuseIdentifier: "FavoriteLocation")
favoriteAnnotation.image = UIImage(named: "favoriteLocation")
favoriteAnnotation.canShowCallout = true
let button = UIButton(type: UIButtonType.DetailDisclosure)
button.addTarget(self, action: "buttonClicked", forControlEvents: UIControlEvents.TouchUpInside)
favoriteAnnotation.rightCalloutAccessoryView = button
return favoriteAnnotation
}
func buttonClicked()
{
guard let _ = self.selectedAnnotation else
{
return
}
self.performSegueWithIdentifier("SegueToAddFavorite", sender: nil)
}
func displayCurrentISSPosition()
{
self.issNetwork.getCurrentISSLocation { [weak self] (position) in
guard let strongSelf = self else
{
return
}
if let currentPosition = position,
coordinate = currentPosition.coordinate
{
let issPositionPin = ISSPositionAnnotation(issPosition: currentPosition, title: "SpaceStation")
strongSelf.mapView.addAnnotation(issPositionPin)
strongSelf.mapView.centerCoordinate = coordinate
}
}
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?)
{
if let addFavoriteViewController = segue.destinationViewController as? ISSAddFavoriteViewController
{
if let savedCoordinate = selectedAnnotation?.coordinate
{
addFavoriteViewController.favoriteCoordinate = savedCoordinate
addFavoriteViewController.savedLocation = true
}
else
{
addFavoriteViewController.favoriteCoordinate = mapView.centerCoordinate
addFavoriteViewController.savedLocation = false
}
}
}
}
| 28.944785 | 111 | 0.670411 |
23c34a1478d0d83090a6e436cca3771ee050d3c3 | 743 | import XCTest
import xAlert
class Tests: XCTestCase {
override func setUp() {
super.setUp()
// Put setup code here. This method is called before the invocation of each test method in the class.
}
override func tearDown() {
// Put teardown code here. This method is called after the invocation of each test method in the class.
super.tearDown()
}
func testExample() {
// This is an example of a functional test case.
XCTAssert(true, "Pass")
}
func testPerformanceExample() {
// This is an example of a performance test case.
self.measure() {
// Put the code you want to measure the time of here.
}
}
}
| 25.62069 | 111 | 0.598923 |
fecac5631d83665bdb9030e9218403820c21caeb | 2,099 | import Foundation
/*
Pair of Numbers
Assuming you have been given an array of numbers and
you need to find a pair of numbers which are equal to the given target value.
Numbers can be either positive, negative or both.
Can you design an algorithm that works in O(n) — linear time or greater?
let sequence = [8, 10, 2, 9, 7, 5]
let results = pairValues(11) = //returns (9, 2)
What’s interesting about this solution is that it can be solved using different techniques.
The main objective is calculating which numbers can be paired to achieve the expected result.
How could this work, assuming your algorithm is only permitted to scan the sequence once?
*/
func fastPairValues(_ s:[Int], _ g: Int) -> [Int]{ //O(n)
let isNegative = g < 0
let absValue = abs(g)
guard s.count > 1 else { return [Int]()}
let m = s.count
var hash = [Int:Int]()
var res = [Int]()
for n in 0..<m {
let x = s[n]
if hash[abs(x - absValue)] != nil && x + hash[abs(x - absValue)]! == absValue {
res.append(isNegative ? -x : x)
res.append(isNegative ? -((-x) - (-absValue))
: abs(x - absValue))
}
hash[x] = x
}
return res
}
func pairValueExpensive( _ s: [Int], _ g: Int) -> [Int] { //O(n^2)
let isNegative = g < 0
let absValue = abs(g)
guard s.count > 1 else {return [Int]()}
let m = s.count
var n = 0
var res = [Int]()
while n < m {
let x = s[n]
for i in n + 1..<m {
if abs(x + s[i]) == absValue {
res.append(isNegative ? -x : x )
res.append(isNegative ? -(s[i]) : s[i])
}
}
n += 1
}
return res
}
let result = fastPairValues([2,4,3,1,6,8,7,5,9,10,11,12,15,14,16,18,17,13,19], 30)
print(result)
let resultExpensive = pairValueExpensive([2,4,3,1,6,8,7,5,9,10,11,12,15,14,16,18,17,13,19], 30)
print(resultExpensive)
| 36.189655 | 95 | 0.53454 |
1dac9e508b2b6084ca259ae1b7dd6c8ab0c4056e | 3,875 | //
// ViewController.swift
// Checklists
//
// Created by 穆康 on 2018/9/4.
// Copyright © 2018年 穆康. All rights reserved.
//
import UIKit
class ChecklistViewController: UITableViewController, AddItemViewControllerDelegate {
var items: [CheckListItem]
required init?(coder aDecoder: NSCoder) {
items = [CheckListItem]()
let row0Item = CheckListItem()
row0Item.text = "Walk the dog"
row0Item.checked = false
items.append(row0Item)
let row1Item = CheckListItem()
row1Item.text = "Brush my teeth"
row1Item.checked = false
items.append(row1Item)
let row2Item = CheckListItem()
row2Item.text = "Learn iOS devlopment"
row2Item.checked = false
items.append(row2Item)
let row3Item = CheckListItem()
row3Item.text = "Soccer practice"
row3Item.checked = false
items.append(row3Item)
let row4Item = CheckListItem()
row4Item.text = "Eat ice cream"
row4Item.checked = false
items.append(row4Item)
super.init(coder: aDecoder)
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
if #available(iOS 11.0, *) {
navigationController?.navigationBar.prefersLargeTitles = true
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return items.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "ChecklistItem", for: indexPath)
let item = items[indexPath.row]
configureText(for: cell, with: item)
configureCheckmark(for: cell, with: item)
return cell
}
override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {
items.remove(at: indexPath.row)
tableView.deleteRows(at: [indexPath], with: .automatic)
}
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
if let cell = tableView.cellForRow(at: indexPath) {
let item = items[indexPath.row]
item.toggleChecked()
configureCheckmark(for: cell, with: item)
}
tableView.deselectRow(at: indexPath, animated: true)
}
func configureCheckmark(for cell: UITableViewCell, with item: CheckListItem) {
cell.accessoryType = item.checked ? .checkmark : .none
}
func configureText(for cell: UITableViewCell, with item: CheckListItem) {
let label = cell.viewWithTag(10000) as! UILabel
label.text = item.text
}
func addItemViewControllerDidCancel(_ controller: AddItemViewController) {
navigationController?.popViewController(animated: true)
}
func addItemViewController(_ controller: AddItemViewController, didFinishAdding item: CheckListItem) {
let newRowIndex = items.count
items.append(item)
let indexPath = IndexPath(row: newRowIndex, section: 0)
tableView.insertRows(at: [indexPath], with: .automatic)
navigationController?.popViewController(animated: true)
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "AddItem" {
let controller = segue.destination as! AddItemViewController
controller.delegate = self
}
}
}
| 32.563025 | 136 | 0.64 |
7a419fbc01f16ef4f068f202dcfac030e1fb4358 | 936 | //
// EasyAutoLayoutTests.swift
// EasyAutoLayoutTests
//
// Created by Fumiya Tanaka on 2019/08/02.
// Copyright © 2019 Fumiya Tanaka. All rights reserved.
//
import XCTest
@testable import EasyAutoLayout
class EasyAutoLayoutTests: XCTestCase {
override func setUp() {
// Put setup code here. This method is called before the invocation of each test method in the class.
}
override func tearDown() {
// Put teardown code here. This method is called after the invocation of each test method in the class.
}
func testExample() {
// This is an example of a functional test case.
// Use XCTAssert and related functions to verify your tests produce the correct results.
}
func testPerformanceExample() {
// This is an example of a performance test case.
self.measure {
// Put the code you want to measure the time of here.
}
}
}
| 26.742857 | 111 | 0.665598 |
677615c2d3a2d157293c0eb4f4207a7b710bd712 | 282 | // Distributed under the terms of the MIT license
// Test case submitted to project by https://github.com/practicalswift (practicalswift)
// Test case found by fuzzing
enum S {
class d {
class B
{
let a {
let a {
class A {
var d {
-> {
{
}
let NSObject {
class d {
class
case c,
{
| 13.428571 | 87 | 0.684397 |
d969dc1beb3f5d6a38f0490d8a50af6eb00dfadb | 3,064 | //
// Designer.swift
// AR Store
//
// Created by Admin on 23.05.2018.
// Copyright © 2018 Vertical. All rights reserved.
//
import Foundation
import UIKit
extension UIColor {
convenience init(hexString: String) {
let hex = hexString.trimmingCharacters(in: CharacterSet.alphanumerics.inverted)
var int = UInt32()
Scanner(string: hex).scanHexInt32(&int)
let a, r, g, b: UInt32
switch hex.characters.count {
case 3: // RGB (12-bit)
(a, r, g, b) = (255, (int >> 8) * 17, (int >> 4 & 0xF) * 17, (int & 0xF) * 17)
case 6: // RGB (24-bit)
(a, r, g, b) = (255, int >> 16, int >> 8 & 0xFF, int & 0xFF)
case 8: // ARGB (32-bit)
(a, r, g, b) = (int >> 24, int >> 16 & 0xFF, int >> 8 & 0xFF, int & 0xFF)
default:
(a, r, g, b) = (255, 0, 0, 0)
}
self.init(red: CGFloat(r) / 255, green: CGFloat(g) / 255, blue: CGFloat(b) / 255, alpha: CGFloat(a) / 255)
}
}
class RoundButton: UIButton {
override func didMoveToWindow() {
self.backgroundColor = UIColor(hexString: "#4f9cdf")
self.layer.cornerRadius = self.frame.height / 2
self.setTitleColor(UIColor.white, for: .normal)
self.layer.shadowColor = UIColor.blue.cgColor
self.layer.shadowRadius = 4
self.layer.shadowOpacity = 0.5
self.layer.shadowOffset = CGSize(width: 0, height: 0)
}
}
class DarkLabel: UILabel {
override func didMoveToWindow() {
self.backgroundColor = UIColor.darkGray.withAlphaComponent(0.35)
self.textColor = UIColor.white
self.layer.shadowColor = UIColor.darkGray.cgColor
self.layer.shadowOpacity = 0.5
self.layer.shadowOffset = CGSize(width: 0, height: 0)
}
}
class DarkTextField: UITextField {
override func didMoveToWindow() {
self.backgroundColor = UIColor.lightGray.withAlphaComponent(0.2)
self.textColor = UIColor.white
let paddingView = UIView(frame: CGRect(x: 0, y: 0, width: 15, height: self.frame.size.height))
self.leftView = paddingView
self.leftViewMode = .always
// self.clipsToBounds = true
// self.layer.cornerRadius = 10
// self.layer.shadowColor = UIColor.darkGray.cgColor
// self.layer.shadowRadius = 4
// self.layer.shadowOpacity = 0.5
// self.layer.shadowOffset = CGSize(width: 0, height: 0)
}
}
class DarkTextView: UITextView {
override func didMoveToWindow() {
self.backgroundColor = UIColor.gray.withAlphaComponent(0.2)
self.textColor = UIColor.white
self.contentInset = UIEdgeInsetsMake(8, 7, 0, 0)
// self.clipsToBounds = true
// self.layer.cornerRadius = 10
// self.layer.shadowColor = UIColor.darkGray.cgColor
// self.layer.shadowRadius = 4
// self.layer.shadowOpacity = 0.5
// self.layer.shadowOffset = CGSize(width: 0, height: 0)
}
}
class PosterAttributesEditorView: UIView {
override func didMoveToWindow() {
let backgroundImage = UIImageView(frame: UIScreen.main.bounds)
backgroundImage.image = UIImage(named: "background.png")
backgroundImage.contentMode = UIViewContentMode.scaleAspectFill
self.insertSubview(backgroundImage, at: 0)
}
}
| 32.946237 | 110 | 0.670692 |
0902ee463c62c7a68f30f83f1ab27b034394dbc4 | 3,416 | //
// RainLevelsTest.swift
// NowCastMapView
//
// Created by Hiroshi Noto on 2/7/16.
// Copyright © 2016 Hiroshi Noto. All rights reserved.
//
import MapKit
import XCTest
@testable import NowCastMapView
class RainLevelsTest: BaseTestCase {
func testRainLevel() {
XCTAssertEqual(RainLevel.min, 0)
XCTAssertEqual(RainLevel.max, 8)
}
func testInit() {
let testPoints: [(point: CGPoint, expectedLevel: Int)] = [
(CGPoint(x: 0, y: 2), 0),
(CGPoint(x: 0, y: 0), 1),
(CGPoint(x: 8, y: 15), 2),
(CGPoint(x: 89, y: 104), 3),
(CGPoint(x: 86, y: 106), 4),
(CGPoint(x: 86, y: 111), 5),
(CGPoint(x: 89, y: 114), 6),
(CGPoint(x: 90, y: 114), 7),
(CGPoint(x: 87, y: 116), 8)]
guard let baseTime = baseTime(file: "OldBaseTime") else { XCTFail(); return }
guard let image = image(file: "tile") else { XCTFail(); return }
guard let modifiers = Tile.Modifiers(zoomLevel: .level6, latitude: 0, longitude: 0) else { XCTFail(); return }
guard let url = URL(baseTime: baseTime, index: 0, modifiers: modifiers) else { XCTFail(); return }
let tile = Tile(image: image, baseTime: baseTime, index: 0, modifiers: modifiers, url: url)
for point in testPoints {
guard let coordinate = tile.coordinate(at: point.point) else { XCTFail(); return }
let tiles = [0: tile]
do {
let rainLevels = try RainLevels(baseTime: baseTime, coordinate: coordinate, tiles: tiles)
XCTAssertEqual(rainLevels.levels[0]?.rawValue, point.expectedLevel)
} catch {
XCTFail()
}
}
}
func testInit0000() {
let testPoints: [(point: CGPoint, expectedLevel: Int)] = [
(CGPoint(x: 0, y: 0), 0)]
guard let baseTime = baseTime(file: "OldBaseTime") else { XCTFail(); return }
guard let image = image(file: "tile2") else { XCTFail(); return }
guard let modifiers = Tile.Modifiers(zoomLevel: .level6, latitude: 0, longitude: 0) else { XCTFail(); return }
guard let url = URL(baseTime: baseTime, index: 0, modifiers: modifiers) else { XCTFail(); return }
let tile = Tile(image: image, baseTime: baseTime, index: 0, modifiers: modifiers, url: url)
for point in testPoints {
guard let coordinate = tile.coordinate(at: point.point) else { XCTFail(); return }
let tiles = [0: tile]
do {
let rainLevels = try RainLevels(baseTime: baseTime, coordinate: coordinate, tiles: tiles)
XCTAssertEqual(rainLevels.levels[0]?.rawValue, point.expectedLevel)
} catch {
XCTFail()
}
}
}
func testInitWithCoordinate() {
guard let baseTime = baseTime(file: "OldBaseTime") else { XCTFail(); return }
guard let image = image(file: "tile") else { XCTFail(); return }
guard let modifiers = Tile.Modifiers(zoomLevel: .level6, latitude: 0, longitude: 0) else { XCTFail(); return }
guard let url = URL(baseTime: baseTime, index: 0, modifiers: modifiers) else { XCTFail(); return }
let tile = Tile(image: image, baseTime: baseTime, index: 0, modifiers: modifiers, url: url)
let tiles = [0: tile]
do {
_ = try RainLevels(baseTime: baseTime, coordinate: CLLocationCoordinate2DMake(62, 99), tiles: tiles)
} catch NCError.outOfService {
} catch {
XCTFail()
}
}
}
| 35.216495 | 115 | 0.611534 |
1a30024c651c2eea8675f98e4fa5ab06d3efa009 | 1,026 | //
// HitsTableViewDelegate.swift
// InstantSearch
//
// Created by Vladislav Fitc on 02/08/2019.
//
#if !InstantSearchCocoaPods
import InstantSearchCore
#endif
#if canImport(UIKit) && (os(iOS) || os(tvOS) || os(macOS))
import UIKit
@available(*, unavailable, message: "Use your own UITableViewController conforming to HitsController protocol")
open class HitsTableViewDelegate<DataSource: HitsSource>: NSObject, UITableViewDelegate {
public var clickHandler: TableViewClickHandler<DataSource.Record>
public weak var hitsSource: DataSource?
public init(clickHandler: @escaping TableViewClickHandler<DataSource.Record>) {
self.clickHandler = clickHandler
}
open func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
guard let hitsSource = hitsSource else {
InstantSearchLogger.missingHitsSourceWarning()
return
}
guard let hit = hitsSource.hit(atIndex: indexPath.row) else {
return
}
clickHandler(tableView, hit, indexPath)
}
}
#endif
| 25.65 | 111 | 0.745614 |
d7ac956e70795418671257ccd89e19487d45d28f | 2,918 | /* Copyright 2018-2021 Prebid.org, Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
import XCTest
class PrebidMRAIDResizeWithErrorsUITest: RepeatedUITestCase {
private let title = "MRAID 2.0: Resize with Errors (In-App)"
private let waitingTimeout = 10.0
override func setUp() {
useMockServerOnSetup = true
super.setUp()
}
func testBasic() {
repeatTesting(times: 7) {
openAndWaitAd()
let mraidView = app.buttons["PBMAdView"]
waitForExists(element: mraidView, waitSeconds: waitingTimeout)
let propertiesTextLabel = mraidView.staticTexts["Test properties:"]
waitForExists(element: propertiesTextLabel, waitSeconds: waitingTimeout)
let offScreenTextLabel = mraidView.staticTexts["Test offScreen:"]
waitForExists(element: offScreenTextLabel, waitSeconds: waitingTimeout)
}
}
func testResize() {
repeatTesting(times: 7) {
openAndWaitAd()
let mraidView = app.buttons["PBMAdView"]
waitForExists(element: mraidView, waitSeconds: waitingTimeout)
var offScreenButton = mraidView.staticTexts["TRUE"]
waitForExists(element: offScreenButton, waitSeconds: waitingTimeout)
offScreenButton.tap()
Thread.sleep(forTimeInterval: 1)
offScreenButton = mraidView.staticTexts["FALSE"]
waitForExists(element: offScreenButton, waitSeconds: waitingTimeout)
let arrowButton = mraidView.staticTexts["→"]
waitForExists(element: arrowButton, waitSeconds: waitingTimeout)
arrowButton.tap()
Thread.sleep(forTimeInterval: 1)
let closeBtn = app.buttons["PBMCloseButton"]
waitForHittable(element: closeBtn, waitSeconds: waitingTimeout)
closeBtn.tap()
}
}
// MARK: - Private methods
private func openAndWaitAd() {
navigateToExamplesSection()
navigateToExample(title)
let adReceivedButton = app.buttons["adViewDidReceiveAd called"]
let adFailedToLoadButton = app.buttons["adViewDidFailToLoadAd called"]
waitForEnabled(element: adReceivedButton, failElement: adFailedToLoadButton, waitSeconds: waitingTimeout)
}
}
| 35.156627 | 113 | 0.653187 |
7a08b4346a3f297c6e843cc1d96dd65b962878c3 | 972 | //
// BuildingProtocol.swift
// PennMobile
//
// Created by Dominic Holmes on 8/6/18.
// Copyright © 2018 PennLabs. All rights reserved.
//
import Foundation
import MapKit
enum BuildingCellType {
case title
case image
case weekHours
case foodMenu
case map
}
enum BuildingType {
case diningHall
case diningRetail
case fitnessCenter
case fitnessCourt
}
protocol BuildingDetailDisplayable {
func cellsToDisplay() -> [BuildingCellType]
func numberOfCellsToDisplay() -> Int
func getBuildingType() -> BuildingType
}
protocol BuildingHeaderDisplayable {
func getTitle() -> String
func getSubtitle() -> String
func getStatus() -> BuildingHeaderState
}
protocol BuildingImageDisplayable { func getImage() -> String }
protocol BuildingHoursDisplayable { func getTimeStrings() -> [String] }
protocol BuildingMapDisplayable {
func getRegion() -> MKCoordinateRegion
func getAnnotation() -> MKAnnotation
}
| 20.680851 | 71 | 0.721193 |
21b5c2f48c8d07e56ab7c167ddb680f952e09b89 | 789 | //
// Tests_macOSLaunchTests.swift
// Tests macOS
//
// Created by Jose Harold on 21/12/2021.
//
import XCTest
class Tests_macOSLaunchTests: XCTestCase {
override class var runsForEachTargetApplicationUIConfiguration: Bool {
true
}
override func setUpWithError() throws {
continueAfterFailure = false
}
func testLaunch() throws {
let app = XCUIApplication()
app.launch()
// Insert steps here to perform after app launch but before taking a screenshot,
// such as logging into a test account or navigating somewhere in the app
let attachment = XCTAttachment(screenshot: app.screenshot())
attachment.name = "Launch Screen"
attachment.lifetime = .keepAlways
add(attachment)
}
}
| 23.909091 | 88 | 0.667934 |
64a40ba9efcbcdbb427bc363e8ed7bf147657262 | 462 | //
// ErrorTracking.swift
// GEFoundation
//
// Created by Grigorii Entin on 06/12/2017.
// Copyright © 2017 Grigory Entin. All rights reserved.
//
import GETracing
import Foundation
private func defaultErrorTracker(error: Error) {
_ = x$(error)
}
public var errorTrackers: [(Error) -> ()] = [defaultErrorTracker]
public func trackError(_ error: Error) {
for errorTracker in errorTrackers {
errorTracker(error)
}
}
| 17.769231 | 65 | 0.662338 |
d5ae5cb0e356777c088aba41c6eef13aedf5eda0 | 1,117 | //
// ViewController.swift
// DecodeFailable
//
// Created by George Marmaridis on 01/17/2019.
// Copyright (c) 2019 George Marmaridis. All rights reserved.
//
import UIKit
import DecodeFailable
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// DecodeFailable Options
DecodeFailableOptions.logsErrors = true
DecodeFailableOptions.errorClosure = { error in
print("You may track the error here")
print(error)
}
// Mapping
do {
let getPeopleResponse = try decoder.decode(GetPeopleResponse.self,
from: peopleResponseData)
print(getPeopleResponse)
} catch(let error) {
print(error)
}
}
// MARK: Helpers
lazy var peopleResponseData: Data = {
let path = Bundle.main.path(forResource: "PeopleResponse", ofType: "json")!
return try! Data(contentsOf: URL(fileURLWithPath: path), options: [])
}()
let decoder = JSONDecoder()
}
| 27.243902 | 83 | 0.587287 |
33cc4976ed7a4adb8e468b340496e9c8aa20c46b | 2,679 | //
// Window.swift
// Kineo
//
// Created by Gregory Todd Williams on 3/8/19.
//
import Foundation
import SPARQLSyntax
public struct WindowRowsRange {
var from: Int?
var to: Int?
public func indices<C>(relativeTo results: C) -> Range<Int> where C : Collection, C.Indices == Range<Int> {
if let begin = from {
if let end = to {
let window = begin...end
let range = window.relative(to: results)
return range.clamped(to: results.indices)
} else {
let window = begin...
let range = window.relative(to: results)
return range.clamped(to: results.indices)
}
} else {
if let end = to {
let window = ...end
let range = window.relative(to: results)
return range.clamped(to: results.indices)
} else {
return results.indices
}
}
}
public mutating func slide(by offset: Int) {
switch (from, to) {
case (nil, nil):
break
case let (nil, .some(max)):
to = max + offset
case let (.some(min), nil):
from = min + offset
case let (.some(min), .some(max)):
from = min + offset
to = max + offset
}
}
}
public extension WindowFrame {
private func offsetValue(for bound: FrameBound, evaluator ee: ExpressionEvaluator) throws -> Int? {
switch bound {
case .unbound:
return nil
case .current:
return 0
case .preceding(let expr):
let term = try ee.evaluate(expression: expr, result: SPARQLResultSolution<Term>(bindings: [:]))
guard let n = term.numeric else {
throw QueryError.typeError("Window PRECEDING range bound value is not a numeric value")
}
let offset = Int(n.value)
return -offset
case .following(let expr):
let term = try ee.evaluate(expression: expr, result: SPARQLResultSolution<Term>(bindings: [:]))
guard let n = term.numeric else {
throw QueryError.typeError("Window FOLLOWING range bound value is not a numeric value")
}
let offset = Int(n.value)
return offset
}
}
func startRowsRange() throws -> WindowRowsRange {
let ee = ExpressionEvaluator(base: nil)
let begin = try offsetValue(for: from, evaluator: ee)
let end = try offsetValue(for: to, evaluator: ee)
return WindowRowsRange(from: begin, to: end)
}
}
| 32.277108 | 111 | 0.539007 |
4a790858d56b50fed939abbd2695b30acec4cbce | 1,988 | //
// KREMeetingNotesElementViewCell.swift
// KoreBotSDK
//
// Created by Srinivas Vasadi on 08/01/2020.
// Copyright © 2019 Srinivas Vasadi. All rights reserved.
//
import UIKit
class KREMeetingNotesElementViewCell: UITableViewCell {
// MARK: - properties
let bundle = Bundle(for: KAKnowledgeTableViewCell.self)
lazy var templateView: KREMeetingNotesTemplateView = {
let templateView = KREMeetingNotesTemplateView(frame: .zero)
templateView.translatesAutoresizingMaskIntoConstraints = false
return templateView
}()
lazy var stackView: UIStackView = {
let stackView = UIStackView(frame: .zero)
stackView.translatesAutoresizingMaskIntoConstraints = false
stackView.axis = .vertical
stackView.backgroundColor = .clear
stackView.distribution = .fill
stackView.alignment = .fill
stackView.spacing = 0.0
return stackView
}()
// MARK: - init
override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
setup()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
setup()
}
override public func prepareForReuse() {
super.prepareForReuse()
}
public override func layoutSubviews() {
super.layoutSubviews()
templateView.layoutSubviews()
}
// MARK: - setup
func setup() {
selectionStyle = .none
contentView.addSubview(stackView)
let views = ["stackView": stackView]
contentView.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "H:|[stackView]|", options: [], metrics: nil, views: views))
contentView.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "V:|[stackView]|", options: [], metrics: nil, views: views))
stackView.addArrangedSubview(templateView)
}
}
| 31.555556 | 144 | 0.662978 |
718dc086ea006b74367ff042e19a7c35d99307be | 1,633 | //
// InputOutOfBoundActions.swift
// nRFMeshProvision
//
// Created by Mostafa Berg on 20/12/2017.
//
import Foundation
public enum InputOutOfBoundActions: UInt16 {
case noInput = 0x00
case push = 0x01
case twist = 0x02
case inputNumber = 0x04
case inputAlphaNumeric = 0x08
public func toByteValue() -> UInt8? {
switch self {
case .noInput:
return nil
case .push:
return 0
case .twist:
return 1
case .inputNumber:
return 2
case .inputAlphaNumeric:
return 3
}
}
public static func allValues() -> [InputOutOfBoundActions] {
return [
.push,
.twist,
.inputNumber,
.inputAlphaNumeric
]
}
public static func calculateInputActionsFromBitmask(aBitMask: UInt16) -> [InputOutOfBoundActions] {
var supportedActions = [InputOutOfBoundActions]()
for anAction in InputOutOfBoundActions.allValues() {
if aBitMask & anAction.rawValue == anAction.rawValue {
supportedActions.append(anAction)
}
}
return supportedActions
}
public func description() -> String {
switch self {
case .noInput:
return "No input"
case .push:
return "Push"
case .twist:
return "Twist"
case .inputNumber:
return "Input number"
case .inputAlphaNumeric:
return "Input alphanumeric"
}
}
}
| 24.742424 | 103 | 0.536436 |
deace786890b1cccdbd68f2c83058873292e4f26 | 810 | //
// BetaLicenseAgreementAppLinkageResponse.swift
// AppStoreConnect-Swift-SDK
//
// Created by Pascal Edmond on 12/11/2018.
//
import Foundation
/// A response containing the ID of the related resource.
public struct BetaLicenseAgreementAppLinkageResponse: Decodable {
/// (Required) A response containing the ID of the related resource.
public let data: BetaLicenseAgreementAppLinkageResponse.Data
/// (Required) Navigational links including the self-link and links to the related data.
public let links: DocumentLinks
public struct Data: Decodable {
/// (Required) The opaque resource ID that uniquely identifies the resource.
public let `id`: String
/// (Required) The resource type.Value: apps
public let type: String
}
}
| 28.928571 | 92 | 0.706173 |
e58bd85d4d0fc5a4019538917101dec84e467437 | 3,500 | //
// BBIReceipt.swift
// UInnIAP
//
// Created by Theo Chen on 11/28/18.
//
import Foundation
/// App 内购买项目收据字段
///
/// 官方文档:https://developer.apple.com/cn/app-store/Receipt-Validation-Programming-Guide-CN.pdf
/// 注意:App Store返回的JSON中有很多看起来很有用的字段,但如果这些字段没有在“官方文档”中列出,在BBIReceipt类进行修改,
/// 请忽略这些未在“官方文档”中列出的属性保留供系统使用,因为它们的内容随时可能被App Store更改。
/// * 在进行消耗型产品购买时,该 App 内购买项目收据被添加到收据中。
/// * 在您的 App 完成该笔交易之前, 该 App 内购买项目收据会一直保留在收据内。
/// * 在交易完成后,该 App 内购买项目收据会在下次收据更新时(例如,顾客进行下一次购买,或者您的 App 明确刷新收据时)从收据中移除。
/// * 非消耗型产品、自动续期订阅、非续期订阅或免费订阅的 App 内购买项目收据无限期保留在收据中。
@objc public class UInnIAPReceipt:NSObject, Codable {
@objc public let bundle_id:String
@objc public let application_version:String
/// App 内购买项目收据,一组 App 内购买项目收据属性
/// 注意: 空数组为有效收据。
/// * 在进行消耗型产品购买时,该 App 内购买项目收据被添加到收据中。
/// * 在您的 App 完成该笔交易之前, 该 App 内购买项目收据会一直保留在收据内。
/// * 在交易完成后,该 App 内购买项目收据会在下次收据更新时(例如,顾客进行下一次购买,或者您的 App 明确刷新收据时)从收据中移除。
/// * 非消耗型产品、自动续期订阅、非续期订阅或免费订阅的 App 内购买项目收据无限期保留在收据中。
@objc public let in_app:[UInnIAPReceiptInApp]
/// 原始应用程序版本
/// 最初购买的 App 的版本。
/// 此值与最初进行购买时Info.plist 文件中的 CFBundleVersion(iOS 中)或 CFBundleShortVersionString(macOS 中)的值相对应。在沙箱技术环境中,这个字段值始终为 “1.0” 。
@objc public let original_application_version:String
/// App 收据的创建日期。
/// 验证收据时,使用这个日期验证收据的签名。
/// 应当确保您的 App 始终使用“收据创建日期”字段中的日期对收据签名进行验证。
@objc public let receipt_creation_date:String
}
extension UInnIAPReceipt {
/// 验证收据官方文档:https://developer.apple.com/cn/app-store/Receipt-Validation-Programming-Guide-CN.pdf
/// 要验证收据,请按顺序执行以下测试:
/// 1. 找到收据。
/// 如果没有收据,则验证失败。
/// 2. 验证收据是否由 Apple 正确签署
/// 如果收据不是由 Apple 签署,则验证失败。
/// 3. 验证收据中的 Bundle Identifier(数据包标识符)与在 Info.plist 文件中含有您要的CFBundleIdentifier 值的硬编码常量相匹配。
/// 如果两者不匹配,则验证失败。
/// 4. 验证收据中的版本标识符字符串与在 Info.plist 文件中含有您要的 CFBundleShortVersionString值(macOS)或CFBundleVersion 值(iOS)的硬编码常量相匹配。
/// 如果两者不匹配,则验证失败。
/// 5. 按照 “计算 GUID 的哈希(Hash) (第 8 页)” 所述计算 GUID 的哈希(Hash)。
/// 如果结果与收据中的哈希(Hash)不匹配,则验证失败。
/// 如果通过所有测试,则验证成功。
internal var isValidated: Bool {
if !isBundleValidated {
return false
}
if !isAppVersionValidated {
return false
}
return true
}
/// 3. 验证收据中的 Bundle Identifier(数据包标识符)与在 Info.plist 文件中含有您要的CFBundleIdentifier 值的硬编码常量相匹配。
/// 如果两者不匹配,则验证失败。
private var isBundleValidated:Bool {
if let bundleIdentifier = Bundle.main.bundleIdentifier {
//uu_print("check bundleId: \(bundle_id) == \(bundleIdentifier)")
return bundle_id == bundleIdentifier
}
return false
}
/// 4. 验证收据中的版本标识符字符串与在 Info.plist 文件中含有您要的 CFBundleShortVersionString值(macOS)或 CFBundleVersion 值(iOS)的硬编码常量相匹配。
/// 如果两者不匹配,则验证失败。
private var isAppVersionValidated:Bool {
//uu_print("check appVersion vs CFBundleShortVersionString: \(application_version) == \(Bundle.main.bbu_bundleShortVersion)")
let appVersionValidated = application_version == Bundle.main.uu_bundleShortVersion
//uu_print("check appVersion vs CFBundleVersion: \(application_version) == \(Bundle.main.bbu_bundleVersion)")
let bundleVersionValidated = application_version == Bundle.main.uu_bundleVersion
return appVersionValidated || bundleVersionValidated
}
/// 5. 按照 “计算 GUID 的哈希(Hash) (第 8 页)” 所述计算 GUID 的哈希(Hash)。
/// 如果结果与收据中的哈希(Hash)不匹配,则验证失败。
}
| 37.234043 | 133 | 0.683714 |
0e9497f52d54e41b47054e51c75b60a315bccc7f | 879 | //
// LeftImageRightTextButton.swift
// Created by jsonshenglong on 2019/1/15.
// Copyright © 2019年 jsonshenglong. All rights reserved.
import UIKit
class LeftImageRightTextButton: UIButton {
override init(frame: CGRect) {
super.init(frame: frame)
titleLabel?.font = UIFont.systemFont(ofSize: 15)
imageView?.contentMode = UIView.ContentMode.center
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func layoutSubviews() {
super.layoutSubviews()
imageView?.frame = CGRect(x: 0, y: (height - (imageView?.size.height)!) * 0.5, width: (imageView?.size.width)!, height: (imageView?.size.height)!)
titleLabel?.frame = CGRect(x: (imageView?.size.width)! + 10, y: 0, width: width - (imageView?.size.width)! - 10, height: height)
}
}
| 32.555556 | 154 | 0.65529 |
72c99788b5448ca2c79415e0303c318acda6919e | 8,430 | //
// AppKit.View.swift
// hyperdrive
//
// Created by Matyáš Kříž on 26/06/2019.
//
#if canImport(SwiftCodeGen)
import SwiftCodeGen
#endif
#if HyperdriveRuntime && canImport(AppKit)
import AppKit
#endif
extension Module.AppKit {
public class View: UIElement, SwiftExtensionWorkaround {
public class var availableProperties: [PropertyDescription] {
return Properties.view.allProperties
}
public class var availableToolingProperties: [PropertyDescription] {
return ToolingProperties.view.allProperties
}
// runtime type is used in generator for style parameters
public class func runtimeType() throws -> String {
return "NS\(self)"
}
public func runtimeType(for platform: RuntimePlatform) throws -> RuntimeType {
if let runtimeTypeOverride = runtimeTypeOverride {
return runtimeTypeOverride
}
switch platform {
case .iOS, .tvOS:
return RuntimeType(name: "UI\(type(of: self))", module: "UIKit")
case .macOS:
return RuntimeType(name: "NS\(type(of: self))", module: "AppKit")
}
}
public class var parentModuleImport: String {
return "AppKit"
}
public var requiredImports: Set<String> {
return ["AppKit"]
}
public let factory: UIElementFactory
public var id: UIElementID
public var isExported: Bool
public var injectionOptions: UIElementInjectionOptions
public var styles: [StyleName]
public var layout: Layout
public var properties: [Property]
public var toolingProperties: [String: Property]
public var handledActions: [HyperViewAction]
public var runtimeTypeOverride: RuntimeType?
public func supportedActions(context: ComponentContext) throws -> [UIElementAction] {
return [
ViewTapAction()
]
}
#if HyperdriveRuntime && canImport(AppKit)
public func initialize(context: ReactantLiveUIWorker.Context) throws -> NSView {
return NSView()
}
#endif
#if canImport(SwiftCodeGen)
public var extraDeclarations: [Structure] {
return []
}
public func initialization(for platform: RuntimePlatform, context: ComponentContext) throws -> Expression {
return .constant("\(try runtimeType(for: platform).name)()")
}
#endif
public required init(context: UIElementDeserializationContext, factory: UIElementFactory) throws {
self.factory = factory
let node = context.element
id = try node.value(ofAttribute: "id", defaultValue: context.elementIdProvider.next(for: node.name))
isExported = try node.value(ofAttribute: "export", defaultValue: false)
injectionOptions = try node.value(ofAttribute: "injected", defaultValue: .none)
layout = try node.value()
styles = try node.value(ofAttribute: "style", defaultValue: []) as [StyleName]
if node.name == "View" && node.count != 0 {
throw TokenizationError(message: "View must not have any children, use Container instead.")
}
properties = try PropertyHelper.deserializeSupportedProperties(properties: type(of: self).availableProperties, in: node)
toolingProperties = try PropertyHelper.deserializeToolingProperties(properties: type(of: self).availableToolingProperties, in: node)
handledActions = try node.allAttributes.compactMap { _, value in
try HyperViewAction(attribute: value)
}
if let classOverride = node.value(ofAttribute: "override:class") as String? {
if let moduleOverride = node.value(ofAttribute: "override:module") as String? {
runtimeTypeOverride = RuntimeType(name: classOverride, module: moduleOverride)
} else {
runtimeTypeOverride = RuntimeType(name: classOverride)
}
}
}
public init() {
preconditionFailure("Not implemented!")
// id = nil
isExported = false
injectionOptions = .none
styles = []
layout = Layout(contentCompressionPriorityHorizontal: View.defaultContentCompression.horizontal,
contentCompressionPriorityVertical: View.defaultContentCompression.vertical,
contentHuggingPriorityHorizontal: View.defaultContentHugging.horizontal,
contentHuggingPriorityVertical: View.defaultContentHugging.vertical)
properties = []
toolingProperties = [:]
handledActions = []
}
public func serialize(context: DataContext) -> XMLSerializableElement {
var builder = XMLAttributeBuilder()
if case .provided(let id) = id {
builder.attribute(name: "id", value: id)
}
if isExported {
builder.attribute(name: "export", value: "true")
}
let styleNames = styles.map { $0.serialize() }.joined(separator: " ")
if !styleNames.isEmpty {
builder.attribute(name: "style", value: styleNames)
}
#if SanAndreas
(properties + toolingProperties.values)
.map {
$0.dematerialize(context: PropertyContext(parentContext: context, property: $0))
}
.forEach {
builder.add(attribute: $0)
}
#endif
layout.serialize().forEach { builder.add(attribute: $0) }
let typeOfSelf = type(of: self)
#warning("TODO Implement")
fatalError("Not implemented")
let name = "" // ElementMapping.mapping.first(where: { $0.value == typeOfSelf })?.key ?? "\(typeOfSelf)"
return XMLSerializableElement(name: name, attributes: builder.attributes, children: [])
}
}
public class ViewProperties: PropertyContainer {
// TODO: Add option to translate "backgroundColor" to "layer.backgroundColor"?
public let isHidden: StaticAssignablePropertyDescription<Bool>
public let alphaValue: StaticAssignablePropertyDescription<Double>
public let isOpaque: StaticAssignablePropertyDescription<Bool>
public let autoresizesSubviews: StaticAssignablePropertyDescription<Bool>
public let translatesAutoresizingMaskIntoConstraints: StaticAssignablePropertyDescription<Bool>
public let tag: StaticAssignablePropertyDescription<Int>
// public let visibility: StaticAssignablePropertyDescription<ViewVisibility>
// public let collapseAxis: StaticAssignablePropertyDescription<ViewCollapseAxis>
public let frame: StaticAssignablePropertyDescription<Rect>
public let bounds: StaticAssignablePropertyDescription<Rect>
//
public let layer: LayerProperties
public required init(configuration: PropertyContainer.Configuration) {
isHidden = configuration.property(name: "isHidden", key: "hidden")
alphaValue = configuration.property(name: "alphaValue", defaultValue: 1)
isOpaque = configuration.property(name: "isOpaque", key: "opaque", defaultValue: true)
autoresizesSubviews = configuration.property(name: "autoresizesSubviews", defaultValue: true)
translatesAutoresizingMaskIntoConstraints = configuration.property(name: "translatesAutoresizingMaskIntoConstraints", defaultValue: true)
tag = configuration.property(name: "tag")
// canBecomeFocused = configuration.property(name: "canBecomeFocused")
// visibility = configuration.property(name: "visibility", defaultValue: .visible)
// collapseAxis = configuration.property(name: "collapseAxis", defaultValue: .vertical)
frame = configuration.property(name: "frame", defaultValue: .zero)
bounds = configuration.property(name: "bounds", defaultValue: .zero)
layer = configuration.namespaced(in: "layer", LayerProperties.self)
super.init(configuration: configuration)
}
}
}
| 43.010204 | 149 | 0.630368 |
f4386a8d2566e67be42c92b3682ea1f6cd493bd5 | 1,030 | //
// StrokePathAction.swift
// PVViewDemo
//
// Created by Toan Nguyen on 5/21/19.
// Copyright © 2019 TNT. All rights reserved.
//
import Foundation
import PVView
protocol ShapeLayerContainerType {
var shapeLayer: CAShapeLayer { get }
}
struct StrokePathAction: PVActionBasicType {
let parameters: PVParameters
let fromValue: Double
let toValue: Double
init(fromValue: Double, toValue: Double, parameters: PVParameters = .default) {
self.fromValue = fromValue
self.toValue = toValue
self.parameters = parameters
}
func step(_ progress: Double, target: UIView) {
guard let layer = (target as? ShapeLayerContainerType)?.shapeLayer else { return }
let current = fromValue + (toValue - fromValue) * progress
layer.strokeEnd = CGFloat(current)
}
func reverse(with newParameters: PVParameters) -> StrokePathAction {
return StrokePathAction(fromValue: toValue, toValue: fromValue, parameters: newParameters)
}
}
| 27.105263 | 98 | 0.682524 |
ab3f94d4fe7ad6251838c4808f46c563d665186d | 1,469 | //
// EmojiMemoryGameView.swift
// Assignment-2
//
// Created by Vinícius Couto on 16/07/21.
//
import SwiftUI
struct EmojiMemoryGameView: View {
@ObservedObject var viewModel: EmojiMemoryGame
var body: some View {
VStack {
HStack {
Text(viewModel.theme.name)
.font(.title)
.fontWeight(.heavy)
Spacer()
Text("Score: \(viewModel.score)")
.font(.body)
.fontWeight(.semibold)
}
.padding(.horizontal)
ScrollView {
LazyVGrid(columns: [GridItem(.adaptive(minimum: 65))]) {
ForEach(viewModel.cards) { card in
CardView(card: card)
.aspectRatio(2/3, contentMode: .fit)
.onTapGesture {
viewModel.choose(card)
}
}
}
}
.foregroundColor(viewModel.getCardColor())
.padding(.horizontal)
Button {
viewModel.newGame()
} label: {
Text("New Game")
}
.padding()
}
}
}
struct ContentView_Previews: PreviewProvider {
static let game = EmojiMemoryGame()
static var previews: some View {
EmojiMemoryGameView(viewModel: game)
}
}
| 24.898305 | 72 | 0.455412 |
6218ab20b1664256ca1a61e2cb3f02d8510bf89e | 4,715 | import Foundation
// MARK: Screens
extension TrackingPaths {
internal struct Screens {
// Terms and condition Path
static func getTermsAndCondiontionPath() -> String {
return TrackingPaths.pxTrack + payments + "/terms_and_conditions"
}
// Discount details path
static func getDiscountDetailPath() -> String {
return TrackingPaths.pxTrack + payments + "/applied_discount"
}
// Error path
static func getErrorPath() -> String {
return TrackingPaths.pxTrack + "/generic_error"
}
// Security Code Paths
static func getSecurityCodePath(paymentTypeId: String) -> String {
return pxTrack + "/security_code"
}
}
}
// MARK: Payment Result Screen Paths
extension TrackingPaths.Screens {
internal struct PaymentResult {
private static let success = "/success"
private static let furtherAction = "/further_action_needed"
private static let error = "/error"
private static let abort = "/abort"
private static let _continue = "/continue"
private static let primaryAction = "/primary_action"
private static let secondaryAction = "/secondary_action"
private static let changePaymentMethod = "/change_payment_method"
private static let remedy = "/remedy"
private static let result = "/result"
static func getSuccessPath(basePath: String = TrackingPaths.pxTrack) -> String {
return basePath + result + success
}
static func getSuccessAbortPath() -> String {
return getSuccessPath() + abort
}
static func getSuccessContinuePath() -> String {
return getSuccessPath() + _continue
}
static func getSuccessPrimaryActionPath() -> String {
return getSuccessPath() + primaryAction
}
static func getSuccessSecondaryActionPath() -> String {
return getSuccessPath() + secondaryAction
}
static func getFurtherActionPath(basePath: String = TrackingPaths.pxTrack) -> String {
return basePath + result + furtherAction
}
static func getFurtherActionAbortPath() -> String {
return getFurtherActionPath() + abort
}
static func getFurtherActionContinuePath() -> String {
return getFurtherActionPath() + _continue
}
static func getFurtherActionPrimaryActionPath() -> String {
return getFurtherActionPath() + primaryAction
}
static func getFurtherActionSecondaryActionPath() -> String {
return getFurtherActionPath() + secondaryAction
}
static func getErrorPath(basePath: String = TrackingPaths.pxTrack) -> String {
return basePath + result + error
}
static func getErrorAbortPath() -> String {
return getErrorPath() + abort
}
static func getErrorChangePaymentMethodPath() -> String {
return getErrorPath() + changePaymentMethod
}
static func getErrorRemedyPath() -> String {
return getErrorPath() + remedy
}
static func getErrorPrimaryActionPath() -> String {
return getErrorPath() + primaryAction
}
static func getErrorSecondaryActionPath() -> String {
return getErrorPath() + secondaryAction
}
}
}
// MARK: Payment Result Screen Paths
extension TrackingPaths.Screens {
internal struct PaymentVault {
private static let ticket = "/ticket"
private static let cardType = "/cards"
static func getPaymentVaultPath() -> String {
return TrackingPaths.pxTrack + TrackingPaths.payments + TrackingPaths.selectMethod
}
static func getTicketPath() -> String {
return getPaymentVaultPath() + ticket
}
static func getCardTypePath() -> String {
return getPaymentVaultPath() + cardType
}
}
}
// MARK: OneTap Screen Paths
extension TrackingPaths.Screens {
internal struct OneTap {
static func getOneTapPath() -> String {
return TrackingPaths.pxTrack + "/review/one_tap"
}
static func getOneTapInstallmentsPath() -> String {
return TrackingPaths.pxTrack + "/review/one_tap/installments"
}
static func getOneTapDisabledModalPath() -> String {
return TrackingPaths.pxTrack + "/review/one_tap/disabled_payment_method_detail"
}
static func getOfflineMethodsPath() -> String {
return getOneTapPath() + "/offline_methods"
}
}
}
| 31.433333 | 94 | 0.623754 |
5b9f00b419cb908a6c584ce4ec6ec257400f9365 | 4,057 | //
// NVActivityIndicatorAnimationCubeTransition.swift
// NVActivityIndicatorViewDemo
//
// The MIT License (MIT)
// Copyright (c) 2016 Vinh Nguyen
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
//
import UIKit
class NVActivityIndicatorAnimationCubeTransition: NVActivityIndicatorAnimationDelegate {
func setUpAnimation(in layer: CALayer, size: CGSize, color: UIColor) {
let squareSize = size.width / 5
let x = (layer.bounds.size.width - size.width) / 2
let y = (layer.bounds.size.height - size.height) / 2
let deltaX = size.width - squareSize
let deltaY = size.height - squareSize
let duration: CFTimeInterval = 1.6
let beginTime = CACurrentMediaTime()
let beginTimes: [CFTimeInterval] = [0, -0.8]
let timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseInEaseOut)
// Scale animation
let scaleAnimation = CAKeyframeAnimation(keyPath: "transform.scale")
scaleAnimation.keyTimes = [0, 0.25, 0.5, 0.75, 1]
scaleAnimation.timingFunctions = [timingFunction, timingFunction, timingFunction, timingFunction]
scaleAnimation.values = [1, 0.5, 1, 0.5, 1]
scaleAnimation.duration = duration
// Translate animation
let translateAnimation = CAKeyframeAnimation(keyPath: "transform.translation")
translateAnimation.keyTimes = scaleAnimation.keyTimes
translateAnimation.timingFunctions = scaleAnimation.timingFunctions
translateAnimation.values = [
NSValue(cgSize: CGSize(width: 0, height: 0)),
NSValue(cgSize: CGSize(width: deltaX, height: 0)),
NSValue(cgSize: CGSize(width: deltaX, height: deltaY)),
NSValue(cgSize: CGSize(width: 0, height: deltaY)),
NSValue(cgSize: CGSize(width: 0, height: 0)),
]
translateAnimation.duration = duration
// Rotate animation
let rotateAnimation = CAKeyframeAnimation(keyPath: "transform.rotation.z")
rotateAnimation.keyTimes = scaleAnimation.keyTimes
rotateAnimation.timingFunctions = scaleAnimation.timingFunctions
rotateAnimation.values = [0, -Double.pi / 2, -Double.pi, -1.5 * Double.pi, -2 * Double.pi]
rotateAnimation.duration = duration
// Animation
let animation = CAAnimationGroup()
animation.animations = [scaleAnimation, translateAnimation, rotateAnimation]
animation.duration = duration
animation.repeatCount = HUGE
animation.isRemovedOnCompletion = false
// Draw squares
for i in 0 ..< 2 {
let square = NVActivityIndicatorShape.rectangle.layerWith(size: CGSize(width: squareSize, height: squareSize), color: color)
let frame = CGRect(x: x, y: y, width: squareSize, height: squareSize)
animation.beginTime = beginTime + beginTimes[i]
square.frame = frame
square.add(animation, forKey: "animation")
layer.addSublayer(square)
}
}
}
| 43.623656 | 136 | 0.694109 |
c137e776b22151d359a8ad4ca043fe36f413c3b3 | 3,403 |
import java_swift
/// generated by: genswift.java 'java/lang|java/util|java/sql' 'Sources' '../java' ///
/// interface com.johnholdsworth.swiftbindings.SwiftMainBinding$Listener ///
public protocol SwiftMainBinding_Listener: JavaProtocol {
/// public abstract void com.johnholdsworth.swiftbindings.SwiftMainBinding$Listener.callSwiftMethod()
func callSwiftMethod()
}
open class SwiftMainBinding_ListenerForward: JNIObjectForward, SwiftMainBinding_Listener {
private static var SwiftMainBinding_ListenerJNIClass: jclass?
/// public abstract void com.johnholdsworth.swiftbindings.SwiftMainBinding$Listener.callSwiftMethod()
private static var callSwiftMethod_MethodID_2: jmethodID?
open func callSwiftMethod() {
var __locals = [jobject]()
var __args = [jvalue]( repeating: jvalue(), count: 1 )
JNIMethod.CallVoidMethod( object: javaObject, methodName: "callSwiftMethod", methodSig: "()V", methodCache: &SwiftMainBinding_ListenerForward.callSwiftMethod_MethodID_2, args: &__args, locals: &__locals )
}
}
private typealias SwiftMainBinding_Listener_callSwiftMethod_0_type = @convention(c) ( _: UnsafeMutablePointer<JNIEnv?>, _: jobject?, _: jlong ) -> ()
private func SwiftMainBinding_Listener_callSwiftMethod_0( _ __env: UnsafeMutablePointer<JNIEnv?>, _ __this: jobject?, _ __swiftObject: jlong ) -> () {
SwiftMainBinding_ListenerLocal_.swiftObject( jniEnv: __env, javaObject: __this, swiftObject: __swiftObject ).callSwiftMethod( )
}
fileprivate class SwiftMainBinding_ListenerLocal_: JNILocalProxy<SwiftMainBinding_Listener, Any> {
fileprivate static let _proxyClass: jclass = {
var natives = [JNINativeMethod]()
let SwiftMainBinding_Listener_callSwiftMethod_0_thunk: SwiftMainBinding_Listener_callSwiftMethod_0_type = SwiftMainBinding_Listener_callSwiftMethod_0
natives.append( JNINativeMethod( name: strdup("__callSwiftMethod"), signature: strdup("(J)V"), fnPtr: unsafeBitCast( SwiftMainBinding_Listener_callSwiftMethod_0_thunk, to: UnsafeMutableRawPointer.self ) ) )
natives.append( JNINativeMethod( name: strdup("__finalize"), signature: strdup("(J)V"), fnPtr: unsafeBitCast( JNIReleasableProxy__finalize_thunk, to: UnsafeMutableRawPointer.self ) ) )
let clazz = JNI.FindClass( proxyClassName() )
withUnsafePointer(to: &natives[0]) {
nativesPtr in
if JNI.api.RegisterNatives( JNI.env, clazz, nativesPtr, jint(natives.count) ) != jint(JNI_OK) {
JNI.report( "Unable to register java natives" )
}
}
defer { JNI.DeleteLocalRef( clazz ) }
return JNI.api.NewGlobalRef( JNI.env, clazz )!
}()
override open class func proxyClassName() -> String { return "org/swiftjava/com_johnholdsworth/SwiftMainBinding_ListenerProxy" }
override open class func proxyClass() -> jclass? { return _proxyClass }
}
extension SwiftMainBinding_Listener {
public func localJavaObject( _ locals: UnsafeMutablePointer<[jobject]> ) -> jobject? {
return SwiftMainBinding_ListenerLocal_( owned: self, proto: self ).localJavaObject( locals )
}
}
open class SwiftMainBinding_ListenerBase: SwiftMainBinding_Listener {
public init() {}
/// public abstract void com.johnholdsworth.swiftbindings.SwiftMainBinding$Listener.callSwiftMethod()
open func callSwiftMethod() /**/ {
}
}
| 39.569767 | 214 | 0.741405 |
e0d365f9434780397293ce28dded23858cc72202 | 1,924 | // Copyright 2021 Saleem Abdulrasool <[email protected]>. All Rights Reserved.
// SPDX-License-Identifier: BSD-3-Clause
import WinSDK
public class IDXGIDevice: IDXGIObject {
override public class var IID: IID { IID_IDXGIDevice }
public func CreateSurface(_ pDesc: UnsafePointer<DXGI_SURFACE_DESC>?, _ NumSurfaces: UINT, _ Usage: DXGI_USAGE, _ pSharedResource: UnsafePointer<DXGI_SHARED_RESOURCE>?) throws -> IDXGISurface {
return try perform(as: WinSDK.IDXGIDevice.self) { pThis in
var pSurface: UnsafeMutablePointer<WinSDK.IDXGISurface>?
try CHECKED(pThis.pointee.lpVtbl.pointee.CreateSurface(pThis, pDesc, NumSurfaces, Usage, pSharedResource, &pSurface))
return IDXGISurface(pUnk: pSurface)
}
}
public func GetAdapter() throws -> IDXGIAdapter {
return try perform(as: WinSDK.IDXGIDevice.self) { pThis in
var pAdapter: UnsafeMutablePointer<WinSDK.IDXGIAdapter>?
try CHECKED(pThis.pointee.lpVtbl.pointee.GetAdapter(pThis, &pAdapter))
return IDXGIAdapter(pUnk: pAdapter)
}
}
public func GetGPUThreadPriority() throws -> INT {
return try perform(as: WinSDK.IDXGIDevice.self) { pThis in
var Priority: INT = 0
try CHECKED(pThis.pointee.lpVtbl.pointee.GetGPUThreadPriority(pThis, &Priority))
return Priority
}
}
public func QueryResourceResidency(_ pResources: UnsafePointer<UnsafeMutablePointer<WinSDK.IUnknown>?>?, _ pResidencyStatus: UnsafeMutablePointer<DXGI_RESIDENCY>?, _ NumResources: UINT) throws {
return try perform(as: WinSDK.IDXGIDevice.self) { pThis in
try CHECKED(pThis.pointee.lpVtbl.pointee.QueryResourceResidency(pThis, pResources, pResidencyStatus, NumResources))
}
}
public func SetGPUThreadPriority(_ Priority: INT) throws {
return try perform(as: WinSDK.IDXGIDevice.self) { pThis in
try CHECKED(pThis.pointee.lpVtbl.pointee.SetGPUThreadPriority(pThis, Priority))
}
}
}
| 42.755556 | 196 | 0.748441 |
8716e00cf2a48f5d4d106d42a06237adce26ab3a | 74,406 | import Foundation
import UIKit
import Postbox
import TelegramCore
import SyncCore
import AsyncDisplayKit
import Display
import UIKit
import SwiftSignalKit
import MobileCoreServices
import TelegramVoip
import OverlayStatusController
import AccountContext
import ContextUI
import LegacyUI
import AppBundle
import SaveToCameraRoll
import PresentationDataUtils
import TelegramPresentationData
import TelegramStringFormatting
import UndoUI
private struct MessageContextMenuData {
let starStatus: Bool?
let canReply: Bool
let canPin: Bool
let canEdit: Bool
let canSelect: Bool
let resourceStatus: MediaResourceStatus?
let messageActions: ChatAvailableMessageActions
}
func canEditMessage(context: AccountContext, limitsConfiguration: LimitsConfiguration, message: Message) -> Bool {
return canEditMessage(accountPeerId: context.account.peerId, limitsConfiguration: limitsConfiguration, message: message)
}
private func canEditMessage(accountPeerId: PeerId, limitsConfiguration: LimitsConfiguration, message: Message, reschedule: Bool = false) -> Bool {
var hasEditRights = false
var unlimitedInterval = reschedule
if message.id.namespace == Namespaces.Message.ScheduledCloud {
if let peer = message.peers[message.id.peerId], let channel = peer as? TelegramChannel {
switch channel.info {
case .broadcast:
if channel.hasPermission(.editAllMessages) || !message.flags.contains(.Incoming) {
hasEditRights = true
}
default:
hasEditRights = true
}
} else {
hasEditRights = true
}
} else if message.id.peerId.namespace == Namespaces.Peer.SecretChat || message.id.namespace != Namespaces.Message.Cloud {
hasEditRights = false
} else if let author = message.author, author.id == accountPeerId, let peer = message.peers[message.id.peerId] {
hasEditRights = true
if let peer = peer as? TelegramChannel {
if peer.flags.contains(.isGigagroup) {
if peer.flags.contains(.isCreator) || peer.adminRights != nil {
hasEditRights = true
} else {
hasEditRights = false
}
}
switch peer.info {
case .broadcast:
if peer.hasPermission(.editAllMessages) || !message.flags.contains(.Incoming) {
unlimitedInterval = true
}
case .group:
if peer.hasPermission(.pinMessages) {
unlimitedInterval = true
}
}
}
} else if message.author?.id == message.id.peerId, let peer = message.peers[message.id.peerId] {
if let peer = peer as? TelegramChannel {
switch peer.info {
case .broadcast:
if peer.hasPermission(.editAllMessages) || !message.flags.contains(.Incoming) {
unlimitedInterval = true
hasEditRights = true
}
case .group:
if peer.hasPermission(.pinMessages) {
unlimitedInterval = true
hasEditRights = true
}
}
}
}
var hasUneditableAttributes = false
if hasEditRights {
for attribute in message.attributes {
if let _ = attribute as? InlineBotMessageAttribute {
hasUneditableAttributes = true
break
}
}
if message.forwardInfo != nil {
hasUneditableAttributes = true
}
for media in message.media {
if let file = media as? TelegramMediaFile {
if file.isSticker || file.isAnimatedSticker || file.isInstantVideo {
hasUneditableAttributes = true
break
}
} else if let _ = media as? TelegramMediaContact {
hasUneditableAttributes = true
break
} else if let _ = media as? TelegramMediaExpiredContent {
hasUneditableAttributes = true
break
} else if let _ = media as? TelegramMediaMap {
hasUneditableAttributes = true
break
} else if let _ = media as? TelegramMediaPoll {
hasUneditableAttributes = true
break
} else if let _ = media as? TelegramMediaDice {
hasUneditableAttributes = true
break
}
}
if !hasUneditableAttributes || reschedule {
if canPerformEditingActions(limits: limitsConfiguration, accountPeerId: accountPeerId, message: message, unlimitedInterval: unlimitedInterval) {
return true
}
}
}
return false
}
private let starIconEmpty = UIImage(bundleImageName: "Chat/Context Menu/StarIconEmpty")?.precomposed()
private let starIconFilled = UIImage(bundleImageName: "Chat/Context Menu/StarIconFilled")?.precomposed()
func canReplyInChat(_ chatPresentationInterfaceState: ChatPresentationInterfaceState) -> Bool {
guard let peer = chatPresentationInterfaceState.renderedPeer?.peer else {
return false
}
if case .scheduledMessages = chatPresentationInterfaceState.subject {
return false
}
if case .pinnedMessages = chatPresentationInterfaceState.subject {
return false
}
guard !peer.id.isReplies else {
return false
}
switch chatPresentationInterfaceState.mode {
case .inline:
return false
default:
break
}
var canReply = false
switch chatPresentationInterfaceState.chatLocation {
case .peer:
if let channel = peer as? TelegramChannel {
if case .member = channel.participationStatus {
canReply = channel.hasPermission(.sendMessages)
}
} else if let group = peer as? TelegramGroup {
if case .Member = group.membership {
canReply = true
}
} else {
canReply = true
}
case .replyThread:
canReply = true
}
return canReply
}
enum ChatMessageContextMenuActionColor {
case accent
case destructive
}
struct ChatMessageContextMenuSheetAction {
let color: ChatMessageContextMenuActionColor
let title: String
let action: () -> Void
}
enum ChatMessageContextMenuAction {
case context(ContextMenuAction)
case sheet(ChatMessageContextMenuSheetAction)
}
struct MessageMediaEditingOptions: OptionSet {
var rawValue: Int32
init(rawValue: Int32) {
self.rawValue = rawValue
}
static let imageOrVideo = MessageMediaEditingOptions(rawValue: 1 << 0)
static let file = MessageMediaEditingOptions(rawValue: 1 << 1)
}
func messageMediaEditingOptions(message: Message) -> MessageMediaEditingOptions {
if message.id.peerId.namespace == Namespaces.Peer.SecretChat {
return []
}
for attribute in message.attributes {
if attribute is AutoremoveTimeoutMessageAttribute {
return []
} else if attribute is AutoclearTimeoutMessageAttribute {
return []
}
}
var options: MessageMediaEditingOptions = []
for media in message.media {
if let _ = media as? TelegramMediaImage {
options.formUnion([.imageOrVideo, .file])
} else if let file = media as? TelegramMediaFile {
for attribute in file.attributes {
switch attribute {
case .Sticker:
return []
case .Animated:
return []
case let .Video(video):
if video.flags.contains(.instantRoundVideo) {
return []
} else {
options.formUnion([.imageOrVideo, .file])
}
case let .Audio(audio):
if audio.isVoice {
return []
} else {
if let _ = message.groupingKey {
return []
} else {
options.formUnion([.imageOrVideo, .file])
}
}
default:
break
}
}
options.formUnion([.imageOrVideo, .file])
}
}
if message.groupingKey != nil {
options.remove(.file)
}
return options
}
func updatedChatEditInterfaceMessageState(state: ChatPresentationInterfaceState, message: Message) -> ChatPresentationInterfaceState {
var updated = state
for media in message.media {
if let webpage = media as? TelegramMediaWebpage, case let .Loaded(content) = webpage.content {
updated = updated.updatedEditingUrlPreview((content.url, webpage))
}
}
var isPlaintext = true
for media in message.media {
if !(media is TelegramMediaWebpage) {
isPlaintext = false
break
}
}
let content: ChatEditInterfaceMessageStateContent
if isPlaintext {
content = .plaintext
} else {
content = .media(mediaOptions: messageMediaEditingOptions(message: message))
}
updated = updated.updatedEditMessageState(ChatEditInterfaceMessageState(content: content, mediaReference: nil))
return updated
}
func contextMenuForChatPresentationInterfaceState(chatPresentationInterfaceState: ChatPresentationInterfaceState, context: AccountContext, messages: [Message], controllerInteraction: ChatControllerInteraction?, selectAll: Bool, interfaceInteraction: ChatPanelInterfaceInteraction?) -> Signal<[ContextMenuItem], NoError> {
guard let interfaceInteraction = interfaceInteraction, let controllerInteraction = controllerInteraction else {
return .single([])
}
var loadStickerSaveStatus: MediaId?
var loadCopyMediaResource: MediaResource?
var isAction = false
var diceEmoji: String?
if messages.count == 1 {
for media in messages[0].media {
if let file = media as? TelegramMediaFile {
for attribute in file.attributes {
if case let .Sticker(_, packInfo, _) = attribute, packInfo != nil {
loadStickerSaveStatus = file.fileId
}
}
} else if media is TelegramMediaAction || media is TelegramMediaExpiredContent {
isAction = true
} else if let image = media as? TelegramMediaImage {
if !messages[0].containsSecretMedia {
loadCopyMediaResource = largestImageRepresentation(image.representations)?.resource
}
} else if let dice = media as? TelegramMediaDice {
diceEmoji = dice.emoji
}
}
}
var canReply = canReplyInChat(chatPresentationInterfaceState)
var canPin = false
let canSelect = !isAction
let message = messages[0]
if Namespaces.Message.allScheduled.contains(message.id.namespace) || message.id.peerId.isReplies {
canReply = false
canPin = false
} else if messages[0].flags.intersection([.Failed, .Unsent]).isEmpty {
switch chatPresentationInterfaceState.chatLocation {
case .peer, .replyThread:
if let channel = messages[0].peers[messages[0].id.peerId] as? TelegramChannel {
if !isAction {
canPin = channel.hasPermission(.pinMessages)
}
} else if let group = messages[0].peers[messages[0].id.peerId] as? TelegramGroup {
if !isAction {
switch group.role {
case .creator, .admin:
canPin = true
default:
if let defaultBannedRights = group.defaultBannedRights {
canPin = !defaultBannedRights.flags.contains(.banPinMessages)
} else {
canPin = true
}
}
}
} else if let _ = messages[0].peers[messages[0].id.peerId] as? TelegramUser, chatPresentationInterfaceState.explicitelyCanPinMessages {
if !isAction {
canPin = true
}
}
/*case .group:
break*/
}
} else {
canReply = false
canPin = false
}
if let peer = messages[0].peers[messages[0].id.peerId] {
if peer.isDeleted {
canPin = false
}
if !(peer is TelegramSecretChat) && messages[0].id.namespace != Namespaces.Message.Cloud {
canPin = false
canReply = false
}
}
var loadStickerSaveStatusSignal: Signal<Bool?, NoError> = .single(nil)
if loadStickerSaveStatus != nil {
loadStickerSaveStatusSignal = context.account.postbox.transaction { transaction -> Bool? in
var starStatus: Bool?
if let loadStickerSaveStatus = loadStickerSaveStatus {
if getIsStickerSaved(transaction: transaction, fileId: loadStickerSaveStatus) {
starStatus = true
} else {
starStatus = false
}
}
return starStatus
}
}
var loadResourceStatusSignal: Signal<MediaResourceStatus?, NoError> = .single(nil)
if let loadCopyMediaResource = loadCopyMediaResource {
loadResourceStatusSignal = context.account.postbox.mediaBox.resourceStatus(loadCopyMediaResource)
|> take(1)
|> map(Optional.init)
}
let loadLimits = context.account.postbox.transaction { transaction -> LimitsConfiguration in
return transaction.getPreferencesEntry(key: PreferencesKeys.limitsConfiguration) as? LimitsConfiguration ?? LimitsConfiguration.defaultValue
}
let cachedData = context.account.postbox.transaction { transaction -> CachedPeerData? in
return transaction.getPeerCachedData(peerId: messages[0].id.peerId)
}
let dataSignal: Signal<(MessageContextMenuData, [MessageId: ChatUpdatingMessageMedia], CachedPeerData?), NoError> = combineLatest(
loadLimits,
loadStickerSaveStatusSignal,
loadResourceStatusSignal,
context.sharedContext.chatAvailableMessageActions(postbox: context.account.postbox, accountPeerId: context.account.peerId, messageIds: Set(messages.map { $0.id })),
context.account.pendingUpdateMessageManager.updatingMessageMedia
|> take(1),
cachedData
)
|> map { limitsConfiguration, stickerSaveStatus, resourceStatus, messageActions, updatingMessageMedia, cachedData -> (MessageContextMenuData, [MessageId: ChatUpdatingMessageMedia], CachedPeerData?) in
var canEdit = false
if !isAction {
let message = messages[0]
canEdit = canEditMessage(context: context, limitsConfiguration: limitsConfiguration, message: message)
}
return (MessageContextMenuData(starStatus: stickerSaveStatus, canReply: canReply, canPin: canPin, canEdit: canEdit, canSelect: canSelect, resourceStatus: resourceStatus, messageActions: messageActions), updatingMessageMedia, cachedData)
}
return dataSignal
|> deliverOnMainQueue
|> map { data, updatingMessageMedia, cachedData -> [ContextMenuItem] in
var actions: [ContextMenuItem] = []
var isPinnedMessages = false
if case .pinnedMessages = chatPresentationInterfaceState.subject {
isPinnedMessages = true
}
if let starStatus = data.starStatus {
actions.append(.action(ContextMenuActionItem(text: starStatus ? chatPresentationInterfaceState.strings.Stickers_RemoveFromFavorites : chatPresentationInterfaceState.strings.Stickers_AddToFavorites, icon: { theme in
return generateTintedImage(image: starStatus ? UIImage(bundleImageName: "Chat/Context Menu/Unstar") : UIImage(bundleImageName: "Chat/Context Menu/Rate"), color: theme.actionSheet.primaryTextColor)
}, action: { _, f in
interfaceInteraction.toggleMessageStickerStarred(messages[0].id)
f(.default)
})))
}
if data.messageActions.options.contains(.rateCall) {
var callId: CallId?
var isVideo: Bool = false
for media in message.media {
if let action = media as? TelegramMediaAction, case let .phoneCall(id, discardReason, _, isVideoValue) = action.action {
isVideo = isVideoValue
if discardReason != .busy && discardReason != .missed {
if let logName = callLogNameForId(id: id, account: context.account) {
let logsPath = callLogsPath(account: context.account)
let logPath = logsPath + "/" + logName
let start = logName.index(logName.startIndex, offsetBy: "\(id)".count + 1)
let end: String.Index
if logName.hasSuffix(".log.json") {
end = logName.index(logName.endIndex, offsetBy: -4 - 5)
} else {
end = logName.index(logName.endIndex, offsetBy: -4)
}
let accessHash = logName[start..<end]
if let accessHash = Int64(accessHash) {
callId = CallId(id: id, accessHash: accessHash)
}
actions.append(.action(ContextMenuActionItem(text: chatPresentationInterfaceState.strings.Call_ShareStats, icon: { theme in
return generateTintedImage(image: UIImage(bundleImageName: "Chat/Context Menu/Forward"), color: theme.actionSheet.primaryTextColor)
}, action: { _, f in
f(.dismissWithoutContent)
let controller = context.sharedContext.makePeerSelectionController(PeerSelectionControllerParams(context: context, filter: [.onlyWriteable, .excludeDisabled]))
controller.peerSelected = { [weak controller] peer in
let peerId = peer.id
if let strongController = controller {
strongController.dismiss()
let id = arc4random64()
let file = TelegramMediaFile(fileId: MediaId(namespace: Namespaces.Media.LocalFile, id: id), partialReference: nil, resource: LocalFileReferenceMediaResource(localFilePath: logPath, randomId: id), previewRepresentations: [], videoThumbnails: [], immediateThumbnailData: nil, mimeType: "application/text", size: nil, attributes: [.FileName(fileName: "CallStats.log")])
let message: EnqueueMessage = .message(text: "", attributes: [], mediaReference: .standalone(media: file), replyToMessageId: nil, localGroupingKey: nil)
let _ = enqueueMessages(account: context.account, peerId: peerId, messages: [message]).start()
}
}
controllerInteraction.navigationController()?.pushViewController(controller)
})))
}
}
break
}
}
if let callId = callId {
actions.append(.action(ContextMenuActionItem(text: chatPresentationInterfaceState.strings.Call_RateCall, icon: { theme in
return generateTintedImage(image: UIImage(bundleImageName: "Chat/Context Menu/Rate"), color: theme.actionSheet.primaryTextColor)
}, action: { _, f in
let _ = controllerInteraction.rateCall(message, callId, isVideo)
f(.dismissWithoutContent)
})))
}
}
var isReplyThreadHead = false
if case let .replyThread(replyThreadMessage) = chatPresentationInterfaceState.chatLocation {
isReplyThreadHead = messages[0].id == replyThreadMessage.effectiveTopId
}
if !isPinnedMessages, !isReplyThreadHead, data.canReply {
actions.append(.action(ContextMenuActionItem(text: chatPresentationInterfaceState.strings.Conversation_ContextMenuReply, icon: { theme in
return generateTintedImage(image: UIImage(bundleImageName: "Chat/Context Menu/Reply"), color: theme.actionSheet.primaryTextColor)
}, action: { _, f in
interfaceInteraction.setupReplyMessage(messages[0].id, { transition in
f(.custom(transition))
})
})))
}
if data.messageActions.options.contains(.sendScheduledNow) {
actions.append(.action(ContextMenuActionItem(text: chatPresentationInterfaceState.strings.ScheduledMessages_SendNow, icon: { theme in
return generateTintedImage(image: UIImage(bundleImageName: "Chat/Context Menu/Resend"), color: theme.actionSheet.primaryTextColor)
}, action: { _, f in
controllerInteraction.sendScheduledMessagesNow(selectAll ? messages.map { $0.id } : [message.id])
f(.dismissWithoutContent)
})))
}
if data.messageActions.options.contains(.editScheduledTime) {
actions.append(.action(ContextMenuActionItem(text: chatPresentationInterfaceState.strings.ScheduledMessages_EditTime, icon: { theme in
return generateTintedImage(image: UIImage(bundleImageName: "Chat/Context Menu/Schedule"), color: theme.actionSheet.primaryTextColor)
}, action: { _, f in
controllerInteraction.editScheduledMessagesTime(selectAll ? messages.map { $0.id } : [message.id])
f(.dismissWithoutContent)
})))
}
let resourceAvailable: Bool
if let resourceStatus = data.resourceStatus, case .Local = resourceStatus {
resourceAvailable = true
} else {
resourceAvailable = false
}
if !messages[0].text.isEmpty || resourceAvailable || diceEmoji != nil {
let message = messages[0]
var isExpired = false
for media in message.media {
if let _ = media as? TelegramMediaExpiredContent {
isExpired = true
}
}
if !isExpired {
actions.append(.action(ContextMenuActionItem(text: chatPresentationInterfaceState.strings.Conversation_ContextMenuCopy, icon: { theme in
return generateTintedImage(image: UIImage(bundleImageName: "Chat/Context Menu/Copy"), color: theme.actionSheet.primaryTextColor)
}, action: { _, f in
if let diceEmoji = diceEmoji {
UIPasteboard.general.string = diceEmoji
} else {
let copyTextWithEntities = {
var messageEntities: [MessageTextEntity]?
for attribute in message.attributes {
if let attribute = attribute as? TextEntitiesMessageAttribute {
messageEntities = attribute.entities
break
}
}
storeMessageTextInPasteboard(message.text, entities: messageEntities)
Queue.mainQueue().after(0.2, {
let content: UndoOverlayContent = .copy(text: chatPresentationInterfaceState.strings.Conversation_MessageCopied)
controllerInteraction.displayUndo(content)
})
}
if resourceAvailable {
for media in message.media {
if let image = media as? TelegramMediaImage, let largest = largestImageRepresentation(image.representations) {
let _ = (context.account.postbox.mediaBox.resourceData(largest.resource, option: .incremental(waitUntilFetchStatus: false))
|> take(1)
|> deliverOnMainQueue).start(next: { data in
if data.complete, let imageData = try? Data(contentsOf: URL(fileURLWithPath: data.path)) {
if let image = UIImage(data: imageData) {
if !message.text.isEmpty {
copyTextWithEntities()
} else {
UIPasteboard.general.image = image
Queue.mainQueue().after(0.2, {
let content: UndoOverlayContent = .copy(text: chatPresentationInterfaceState.strings.Conversation_ImageCopied)
controllerInteraction.displayUndo(content)
})
}
} else {
copyTextWithEntities()
}
} else {
copyTextWithEntities()
}
})
}
}
} else {
copyTextWithEntities()
}
}
f(.default)
})))
if isSpeakSelectionEnabled() && !message.text.isEmpty {
actions.append(.action(ContextMenuActionItem(text: chatPresentationInterfaceState.strings.Conversation_ContextMenuSpeak, icon: { theme in
return generateTintedImage(image: UIImage(bundleImageName: "Chat/Context Menu/Message"), color: theme.actionSheet.primaryTextColor)
}, action: { _, f in
controllerInteraction.performTextSelectionAction(0, NSAttributedString(string: message.text), .speak)
f(.default)
})))
}
}
if resourceAvailable, !message.containsSecretMedia {
var mediaReference: AnyMediaReference?
for media in message.media {
if let image = media as? TelegramMediaImage, let _ = largestImageRepresentation(image.representations) {
mediaReference = ImageMediaReference.standalone(media: image).abstract
break
} else if let file = media as? TelegramMediaFile, file.isVideo {
mediaReference = FileMediaReference.standalone(media: file).abstract
break
}
}
if let mediaReference = mediaReference {
actions.append(.action(ContextMenuActionItem(text: chatPresentationInterfaceState.strings.Preview_SaveToCameraRoll, icon: { theme in
return generateTintedImage(image: UIImage(bundleImageName: "Chat/Context Menu/Save"), color: theme.actionSheet.primaryTextColor)
}, action: { _, f in
let _ = (saveToCameraRoll(context: context, postbox: context.account.postbox, mediaReference: mediaReference)
|> deliverOnMainQueue).start(completed: {
let presentationData = context.sharedContext.currentPresentationData.with { $0 }
controllerInteraction.presentGlobalOverlayController(OverlayStatusController(theme: presentationData.theme, type: .success), nil)
})
f(.default)
})))
}
}
}
var threadId: Int64?
var threadMessageCount: Int = 0
if case .peer = chatPresentationInterfaceState.chatLocation, let channel = chatPresentationInterfaceState.renderedPeer?.peer as? TelegramChannel, case .group = channel.info {
if let cachedData = cachedData as? CachedChannelData, case let .known(maybeValue) = cachedData.linkedDiscussionPeerId, let _ = maybeValue {
if let value = messages[0].threadId {
threadId = value
} else {
for attribute in messages[0].attributes {
if let attribute = attribute as? ReplyThreadMessageAttribute, attribute.count > 0 {
threadId = makeMessageThreadId(messages[0].id)
threadMessageCount = Int(attribute.count)
}
}
}
} else {
for attribute in messages[0].attributes {
if let attribute = attribute as? ReplyThreadMessageAttribute, attribute.count > 0 {
threadId = makeMessageThreadId(messages[0].id)
threadMessageCount = Int(attribute.count)
}
}
}
}
if let _ = threadId, !isPinnedMessages {
let text: String
if threadMessageCount != 0 {
text = chatPresentationInterfaceState.strings.Conversation_ContextViewReplies(Int32(threadMessageCount))
} else {
text = chatPresentationInterfaceState.strings.Conversation_ContextViewThread
}
actions.append(.action(ContextMenuActionItem(text: text, icon: { theme in
return generateTintedImage(image: UIImage(bundleImageName: "Chat/Context Menu/Replies"), color: theme.actionSheet.primaryTextColor)
}, action: { c, _ in
c.dismiss(completion: {
controllerInteraction.openMessageReplies(messages[0].id, true, true)
})
})))
}
let isMigrated: Bool
if chatPresentationInterfaceState.renderedPeer?.peer is TelegramChannel && message.id.peerId.namespace == Namespaces.Peer.CloudGroup {
isMigrated = true
} else {
isMigrated = false
}
if data.canEdit && !isPinnedMessages && !isMigrated {
actions.append(.action(ContextMenuActionItem(text: chatPresentationInterfaceState.strings.Conversation_MessageDialogEdit, icon: { theme in
return generateTintedImage(image: UIImage(bundleImageName: "Chat/Context Menu/Edit"), color: theme.actionSheet.primaryTextColor)
}, action: { c, f in
interfaceInteraction.setupEditMessage(messages[0].id, { transition in
f(.custom(transition))
})
})))
}
var activePoll: TelegramMediaPoll?
for media in message.media {
if let poll = media as? TelegramMediaPoll, !poll.isClosed, message.id.namespace == Namespaces.Message.Cloud, poll.pollId.namespace == Namespaces.Media.CloudPoll {
if !isPollEffectivelyClosed(message: message, poll: poll) {
activePoll = poll
}
}
}
if let activePoll = activePoll, let voters = activePoll.results.voters {
var hasSelected = false
for result in voters {
if result.selected {
hasSelected = true
}
}
if hasSelected, case .poll = activePoll.kind {
actions.append(.action(ContextMenuActionItem(text: chatPresentationInterfaceState.strings.Conversation_UnvotePoll, icon: { theme in
return generateTintedImage(image: UIImage(bundleImageName: "Chat/Context Menu/Unvote"), color: theme.actionSheet.primaryTextColor)
}, action: { _, f in
interfaceInteraction.requestUnvoteInMessage(messages[0].id)
f(.dismissWithoutContent)
})))
}
}
if data.canPin && !isMigrated, case .peer = chatPresentationInterfaceState.chatLocation {
var pinnedSelectedMessageId: MessageId?
for message in messages {
if message.tags.contains(.pinned) {
pinnedSelectedMessageId = message.id
break
}
}
if let pinnedSelectedMessageId = pinnedSelectedMessageId {
actions.append(.action(ContextMenuActionItem(text: chatPresentationInterfaceState.strings.Conversation_Unpin, icon: { theme in
return generateTintedImage(image: UIImage(bundleImageName: "Chat/Context Menu/Unpin"), color: theme.actionSheet.primaryTextColor)
}, action: { c, _ in
interfaceInteraction.unpinMessage(pinnedSelectedMessageId, false, c)
})))
} else {
actions.append(.action(ContextMenuActionItem(text: chatPresentationInterfaceState.strings.Conversation_Pin, icon: { theme in
return generateTintedImage(image: UIImage(bundleImageName: "Chat/Context Menu/Pin"), color: theme.actionSheet.primaryTextColor)
}, action: { c, _ in
interfaceInteraction.pinMessage(messages[0].id, c)
})))
}
}
if let activePoll = activePoll, messages[0].forwardInfo == nil {
var canStopPoll = false
if !messages[0].flags.contains(.Incoming) {
canStopPoll = true
} else {
var hasEditRights = false
if messages[0].id.namespace == Namespaces.Message.Cloud {
if message.id.peerId.namespace == Namespaces.Peer.SecretChat {
hasEditRights = false
} else if let author = message.author, author.id == context.account.peerId {
hasEditRights = true
} else if message.author?.id == message.id.peerId, let peer = message.peers[message.id.peerId] {
if let peer = peer as? TelegramChannel, case .broadcast = peer.info {
if peer.hasPermission(.editAllMessages) {
hasEditRights = true
}
}
}
}
if hasEditRights {
canStopPoll = true
}
}
if canStopPoll {
let stopPollAction: String
switch activePoll.kind {
case .poll:
stopPollAction = chatPresentationInterfaceState.strings.Conversation_StopPoll
case .quiz:
stopPollAction = chatPresentationInterfaceState.strings.Conversation_StopQuiz
}
actions.append(.action(ContextMenuActionItem(text: stopPollAction, icon: { theme in
return generateTintedImage(image: UIImage(bundleImageName: "Chat/Context Menu/StopPoll"), color: theme.actionSheet.primaryTextColor)
}, action: { _, f in
interfaceInteraction.requestStopPollInMessage(messages[0].id)
f(.dismissWithoutContent)
})))
}
}
if let message = messages.first, message.id.namespace == Namespaces.Message.Cloud, let channel = message.peers[message.id.peerId] as? TelegramChannel, !(message.media.first is TelegramMediaAction), !isReplyThreadHead, !isMigrated {
actions.append(.action(ContextMenuActionItem(text: chatPresentationInterfaceState.strings.Conversation_ContextMenuCopyLink, icon: { theme in
return generateTintedImage(image: UIImage(bundleImageName: "Chat/Context Menu/Link"), color: theme.actionSheet.primaryTextColor)
}, action: { _, f in
var threadMessageId: MessageId?
if case let .replyThread(replyThreadMessage) = chatPresentationInterfaceState.chatLocation {
threadMessageId = replyThreadMessage.messageId
}
let _ = (exportMessageLink(account: context.account, peerId: message.id.peerId, messageId: message.id, isThread: threadMessageId != nil)
|> map { result -> String? in
return result
}
|> deliverOnMainQueue).start(next: { link in
if let link = link {
UIPasteboard.general.string = link
let presentationData = context.sharedContext.currentPresentationData.with { $0 }
var warnAboutPrivate = false
if case .peer = chatPresentationInterfaceState.chatLocation {
if channel.addressName == nil {
warnAboutPrivate = true
}
}
Queue.mainQueue().after(0.2, {
if warnAboutPrivate {
controllerInteraction.displayUndo(.linkCopied(text: presentationData.strings.Conversation_PrivateMessageLinkCopiedLong))
} else {
controllerInteraction.displayUndo(.linkCopied(text: presentationData.strings.Conversation_LinkCopied))
}
})
}
})
f(.default)
})))
}
var isUnremovableAction = false
if messages.count == 1 {
let message = messages[0]
var hasAutoremove = false
for attribute in message.attributes {
if let _ = attribute as? AutoremoveTimeoutMessageAttribute {
hasAutoremove = true
break
} else if let _ = attribute as? AutoclearTimeoutMessageAttribute {
hasAutoremove = true
break
}
}
if !hasAutoremove {
for media in message.media {
if media is TelegramMediaAction {
if let channel = message.peers[message.id.peerId] as? TelegramChannel {
if channel.flags.contains(.isCreator) || (channel.adminRights?.rights.contains(.canDeleteMessages) == true) {
} else {
isUnremovableAction = true
}
}
}
if let file = media as? TelegramMediaFile {
if file.isVideo {
if file.isAnimated {
actions.append(.action(ContextMenuActionItem(text: chatPresentationInterfaceState.strings.Conversation_LinkDialogSave, icon: { theme in
return generateTintedImage(image: UIImage(bundleImageName: "Chat/Context Menu/Save"), color: theme.actionSheet.primaryTextColor)
}, action: { _, f in
let _ = addSavedGif(postbox: context.account.postbox, fileReference: .message(message: MessageReference(message), media: file)).start()
f(.default)
})))
}
break
}
}
}
}
}
/*if !isReplyThreadHead, !data.messageActions.options.intersection([.deleteLocally, .deleteGlobally]).isEmpty && isAction {
actions.append(.action(ContextMenuActionItem(text: chatPresentationInterfaceState.strings.Conversation_ContextMenuDelete, textColor: .destructive, icon: { theme in
return generateTintedImage(image: UIImage(bundleImageName: "Chat/Context Menu/Delete"), color: theme.actionSheet.destructiveActionTextColor)
}, action: { controller, f in
interfaceInteraction.deleteMessages(messages, controller, f)
})))
}*/
if data.messageActions.options.contains(.viewStickerPack) {
actions.append(.action(ContextMenuActionItem(text: chatPresentationInterfaceState.strings.StickerPack_ViewPack, icon: { theme in
return generateTintedImage(image: UIImage(bundleImageName: "Chat/Context Menu/Sticker"), color: theme.actionSheet.primaryTextColor)
}, action: { _, f in
let _ = controllerInteraction.openMessage(message, .default)
f(.dismissWithoutContent)
})))
}
if data.messageActions.options.contains(.forward) {
actions.append(.action(ContextMenuActionItem(text: chatPresentationInterfaceState.strings.Conversation_ContextMenuForward, icon: { theme in
return generateTintedImage(image: UIImage(bundleImageName: "Chat/Context Menu/Forward"), color: theme.actionSheet.primaryTextColor)
}, action: { _, f in
interfaceInteraction.forwardMessages(selectAll ? messages : [message])
f(.dismissWithoutContent)
})))
}
if data.messageActions.options.contains(.report) {
actions.append(.action(ContextMenuActionItem(text: chatPresentationInterfaceState.strings.Conversation_ContextMenuReport, icon: { theme in
return generateTintedImage(image: UIImage(bundleImageName: "Chat/Context Menu/Report"), color: theme.actionSheet.primaryTextColor)
}, action: { controller, f in
interfaceInteraction.reportMessages(messages, controller)
})))
} else if message.id.peerId.isReplies {
actions.append(.action(ContextMenuActionItem(text: chatPresentationInterfaceState.strings.Conversation_ContextMenuBlock, textColor: .destructive, icon: { theme in
return generateTintedImage(image: UIImage(bundleImageName: "Chat/Context Menu/Restrict"), color: theme.actionSheet.destructiveActionTextColor)
}, action: { controller, f in
interfaceInteraction.blockMessageAuthor(message, controller)
})))
}
var clearCacheAsDelete = false
if let channel = message.peers[message.id.peerId] as? TelegramChannel, case .broadcast = channel.info, !isMigrated {
var views: Int = 0
for attribute in message.attributes {
if let attribute = attribute as? ViewCountMessageAttribute {
views = attribute.count
}
}
if let cachedData = cachedData as? CachedChannelData, cachedData.flags.contains(.canViewStats), views >= 100 {
actions.append(.action(ContextMenuActionItem(text: chatPresentationInterfaceState.strings.Conversation_ContextViewStats, icon: { theme in
return generateTintedImage(image: UIImage(bundleImageName: "Chat/Context Menu/Statistics"), color: theme.actionSheet.primaryTextColor)
}, action: { c, _ in
c.dismiss(completion: {
controllerInteraction.openMessageStats(messages[0].id)
})
})))
}
clearCacheAsDelete = true
}
if !isReplyThreadHead, (!data.messageActions.options.intersection([.deleteLocally, .deleteGlobally]).isEmpty || clearCacheAsDelete) {
var autoremoveDeadline: Int32?
for attribute in message.attributes {
if let attribute = attribute as? AutoremoveTimeoutMessageAttribute {
if let countdownBeginTime = attribute.countdownBeginTime {
autoremoveDeadline = countdownBeginTime + attribute.timeout
}
break
}
}
let title: String
var isSending = false
var isEditing = false
if updatingMessageMedia[message.id] != nil {
isSending = true
isEditing = true
title = chatPresentationInterfaceState.strings.Conversation_ContextMenuCancelEditing
} else if message.flags.isSending {
isSending = true
title = chatPresentationInterfaceState.strings.Conversation_ContextMenuCancelSending
} else {
title = chatPresentationInterfaceState.strings.Conversation_ContextMenuDelete
}
if let autoremoveDeadline = autoremoveDeadline, !isEditing, !isSending {
actions.append(.custom(ChatDeleteMessageContextItem(timestamp: Double(autoremoveDeadline), action: { controller, f in
if isEditing {
context.account.pendingUpdateMessageManager.cancel(messageId: message.id)
f(.default)
} else {
interfaceInteraction.deleteMessages(selectAll ? messages : [message], controller, f)
}
}), false))
} else if !isUnremovableAction {
actions.append(.action(ContextMenuActionItem(text: title, textColor: .destructive, icon: { theme in
return generateTintedImage(image: UIImage(bundleImageName: isSending ? "Chat/Context Menu/Clear" : "Chat/Context Menu/Delete"), color: theme.actionSheet.destructiveActionTextColor)
}, action: { controller, f in
if isEditing {
context.account.pendingUpdateMessageManager.cancel(messageId: message.id)
f(.default)
} else {
interfaceInteraction.deleteMessages(selectAll ? messages : [message], controller, f)
}
})))
}
}
if !isPinnedMessages, !isReplyThreadHead, data.canSelect {
if !actions.isEmpty {
actions.append(.separator)
}
if !selectAll || messages.count == 1 {
actions.append(.action(ContextMenuActionItem(text: chatPresentationInterfaceState.strings.Conversation_ContextMenuSelect, icon: { theme in
return generateTintedImage(image: UIImage(bundleImageName: "Chat/Context Menu/Select"), color: theme.actionSheet.primaryTextColor)
}, action: { _, f in
interfaceInteraction.beginMessageSelection(selectAll ? messages.map { $0.id } : [message.id], { transition in
f(.custom(transition))
})
})))
}
if messages.count > 1 {
actions.append(.action(ContextMenuActionItem(text: chatPresentationInterfaceState.strings.Conversation_ContextMenuSelectAll(Int32(messages.count)), icon: { theme in
return generateTintedImage(image: UIImage(bundleImageName: "Chat/Context Menu/SelectAll"), color: theme.actionSheet.primaryTextColor)
}, action: { _, f in
interfaceInteraction.beginMessageSelection(messages.map { $0.id }, { transition in
f(.custom(transition))
})
})))
}
}
return actions
}
}
func canPerformEditingActions(limits: LimitsConfiguration, accountPeerId: PeerId, message: Message, unlimitedInterval: Bool) -> Bool {
if message.id.peerId == accountPeerId {
return true
}
if unlimitedInterval {
return true
}
let timestamp = Int32(CFAbsoluteTimeGetCurrent() + NSTimeIntervalSince1970)
if Int64(message.timestamp) + Int64(limits.maxMessageEditingInterval) > Int64(timestamp) {
return true
}
return false
}
private func canPerformDeleteActions(limits: LimitsConfiguration, accountPeerId: PeerId, message: Message) -> Bool {
if message.id.peerId == accountPeerId {
return true
}
if message.id.peerId.namespace == Namespaces.Peer.SecretChat {
return true
}
if !message.flags.contains(.Incoming) {
let timestamp = Int32(CFAbsoluteTimeGetCurrent() + NSTimeIntervalSince1970)
if message.id.peerId.namespace == Namespaces.Peer.CloudUser {
if Int64(message.timestamp) + Int64(limits.maxMessageRevokeIntervalInPrivateChats) > Int64(timestamp) {
return true
}
} else {
if message.timestamp + limits.maxMessageRevokeInterval > timestamp {
return true
}
}
}
return false
}
func chatAvailableMessageActionsImpl(postbox: Postbox, accountPeerId: PeerId, messageIds: Set<MessageId>, messages: [MessageId: Message] = [:], peers: [PeerId: Peer] = [:]) -> Signal<ChatAvailableMessageActions, NoError> {
return postbox.transaction { transaction -> ChatAvailableMessageActions in
let limitsConfiguration: LimitsConfiguration = transaction.getPreferencesEntry(key: PreferencesKeys.limitsConfiguration) as? LimitsConfiguration ?? LimitsConfiguration.defaultValue
var optionsMap: [MessageId: ChatAvailableMessageActionOptions] = [:]
var banPeer: Peer?
var hadPersonalIncoming = false
var hadBanPeerId = false
func getPeer(_ peerId: PeerId) -> Peer? {
if let peer = transaction.getPeer(peerId) {
return peer
} else if let peer = peers[peerId] {
return peer
} else {
return nil
}
}
func getMessage(_ messageId: MessageId) -> Message? {
if let message = transaction.getMessage(messageId) {
return message
} else if let message = messages[messageId] {
return message
} else {
return nil
}
}
for id in messageIds {
let isScheduled = id.namespace == Namespaces.Message.ScheduledCloud
if optionsMap[id] == nil {
optionsMap[id] = []
}
if let message = getMessage(id) {
for media in message.media {
if let file = media as? TelegramMediaFile, file.isSticker {
for case let .Sticker(sticker) in file.attributes {
if let _ = sticker.packReference {
optionsMap[id]!.insert(.viewStickerPack)
}
break
}
} else if let action = media as? TelegramMediaAction, case .phoneCall = action.action {
optionsMap[id]!.insert(.rateCall)
}
}
if id.namespace == Namespaces.Message.ScheduledCloud {
optionsMap[id]!.insert(.sendScheduledNow)
if canEditMessage(accountPeerId: accountPeerId, limitsConfiguration: limitsConfiguration, message: message, reschedule: true) {
optionsMap[id]!.insert(.editScheduledTime)
}
if let peer = getPeer(id.peerId), let channel = peer as? TelegramChannel {
if !message.flags.contains(.Incoming) {
optionsMap[id]!.insert(.deleteLocally)
} else {
if channel.hasPermission(.deleteAllMessages) {
optionsMap[id]!.insert(.deleteLocally)
}
}
} else {
optionsMap[id]!.insert(.deleteLocally)
}
} else if id.peerId == accountPeerId {
if !(message.flags.isSending || message.flags.contains(.Failed)) {
optionsMap[id]!.insert(.forward)
}
optionsMap[id]!.insert(.deleteLocally)
} else if let peer = getPeer(id.peerId) {
var isAction = false
var isDice = false
for media in message.media {
if media is TelegramMediaAction || media is TelegramMediaExpiredContent {
isAction = true
}
if media is TelegramMediaDice {
isDice = true
}
}
if let channel = peer as? TelegramChannel {
if message.flags.contains(.Incoming) {
optionsMap[id]!.insert(.report)
}
if channel.hasPermission(.banMembers), case .group = channel.info {
if message.flags.contains(.Incoming) {
if message.author is TelegramUser {
if !hadBanPeerId {
hadBanPeerId = true
banPeer = message.author
} else if banPeer?.id != message.author?.id {
banPeer = nil
}
} else {
hadBanPeerId = true
banPeer = nil
}
} else {
hadBanPeerId = true
banPeer = nil
}
}
if !message.containsSecretMedia && !isAction {
if message.id.peerId.namespace != Namespaces.Peer.SecretChat {
if !(message.flags.isSending || message.flags.contains(.Failed)) {
optionsMap[id]!.insert(.forward)
}
}
}
if !message.flags.contains(.Incoming) {
optionsMap[id]!.insert(.deleteGlobally)
} else {
if channel.hasPermission(.deleteAllMessages) {
optionsMap[id]!.insert(.deleteGlobally)
}
}
} else if let group = peer as? TelegramGroup {
if message.id.peerId.namespace != Namespaces.Peer.SecretChat && !message.containsSecretMedia {
if !isAction {
if !(message.flags.isSending || message.flags.contains(.Failed)) {
optionsMap[id]!.insert(.forward)
}
}
}
optionsMap[id]!.insert(.deleteLocally)
if !message.flags.contains(.Incoming) {
optionsMap[id]!.insert(.deleteGlobally)
} else {
switch group.role {
case .creator, .admin:
optionsMap[id]!.insert(.deleteGlobally)
case .member:
var hasMediaToReport = false
for media in message.media {
if let _ = media as? TelegramMediaImage {
hasMediaToReport = true
} else if let _ = media as? TelegramMediaFile {
hasMediaToReport = true
} else if let webpage = media as? TelegramMediaWebpage, case let .Loaded(content) = webpage.content {
if let _ = content.image {
hasMediaToReport = true
} else if let _ = content.file {
hasMediaToReport = true
}
}
}
if hasMediaToReport {
optionsMap[id]!.insert(.report)
}
}
}
} else if let user = peer as? TelegramUser {
if !isScheduled && message.id.peerId.namespace != Namespaces.Peer.SecretChat && !message.containsSecretMedia && !isAction && !message.id.peerId.isReplies {
if !(message.flags.isSending || message.flags.contains(.Failed)) {
optionsMap[id]!.insert(.forward)
}
}
optionsMap[id]!.insert(.deleteLocally)
var canDeleteGlobally = false
if canPerformDeleteActions(limits: limitsConfiguration, accountPeerId: accountPeerId, message: message) {
canDeleteGlobally = true
} else if limitsConfiguration.canRemoveIncomingMessagesInPrivateChats {
canDeleteGlobally = true
}
if user.botInfo != nil {
canDeleteGlobally = false
}
let timestamp = Int32(CFAbsoluteTimeGetCurrent() + NSTimeIntervalSince1970)
if isDice && Int64(message.timestamp) + 60 * 60 * 24 > Int64(timestamp) {
canDeleteGlobally = false
}
if message.flags.contains(.Incoming) {
hadPersonalIncoming = true
}
if canDeleteGlobally {
optionsMap[id]!.insert(.deleteGlobally)
}
if user.botInfo != nil && !user.id.isReplies && !isAction {
optionsMap[id]!.insert(.report)
}
} else if let _ = peer as? TelegramSecretChat {
var isNonRemovableServiceAction = false
for media in message.media {
if let action = media as? TelegramMediaAction {
switch action.action {
case .historyScreenshot:
isNonRemovableServiceAction = true
default:
break
}
}
}
if !isNonRemovableServiceAction {
optionsMap[id]!.insert(.deleteGlobally)
}
} else {
assertionFailure()
}
} else {
optionsMap[id]!.insert(.deleteLocally)
}
}
}
if !optionsMap.isEmpty {
var reducedOptions = optionsMap.values.first!
for value in optionsMap.values {
reducedOptions.formIntersection(value)
}
if hadPersonalIncoming && optionsMap.values.contains(where: { $0.contains(.deleteGlobally) }) && !reducedOptions.contains(.deleteGlobally) {
reducedOptions.insert(.unsendPersonal)
}
return ChatAvailableMessageActions(options: reducedOptions, banAuthor: banPeer)
} else {
return ChatAvailableMessageActions(options: [], banAuthor: nil)
}
}
}
final class ChatDeleteMessageContextItem: ContextMenuCustomItem {
fileprivate let timestamp: Double
fileprivate let action: (ContextController, @escaping (ContextMenuActionResult) -> Void) -> Void
init(timestamp: Double, action: @escaping (ContextController, @escaping (ContextMenuActionResult) -> Void) -> Void) {
self.timestamp = timestamp
self.action = action
}
func node(presentationData: PresentationData, getController: @escaping () -> ContextController?, actionSelected: @escaping (ContextMenuActionResult) -> Void) -> ContextMenuCustomNode {
return ChatDeleteMessageContextItemNode(presentationData: presentationData, item: self, getController: getController, actionSelected: actionSelected)
}
}
private let textFont = Font.regular(17.0)
private final class ChatDeleteMessageContextItemNode: ASDisplayNode, ContextMenuCustomNode, ContextActionNodeProtocol {
private let item: ChatDeleteMessageContextItem
private let presentationData: PresentationData
private let getController: () -> ContextController?
private let actionSelected: (ContextMenuActionResult) -> Void
private let backgroundNode: ASDisplayNode
private let highlightedBackgroundNode: ASDisplayNode
private let textNode: ImmediateTextNode
private let statusNode: ImmediateTextNode
private let iconNode: ASImageNode
private let textIconNode: ASImageNode
private let buttonNode: HighlightTrackingButtonNode
private var timer: SwiftSignalKit.Timer?
private var pointerInteraction: PointerInteraction?
init(presentationData: PresentationData, item: ChatDeleteMessageContextItem, getController: @escaping () -> ContextController?, actionSelected: @escaping (ContextMenuActionResult) -> Void) {
self.item = item
self.presentationData = presentationData
self.getController = getController
self.actionSelected = actionSelected
let textFont = Font.regular(presentationData.listsFontSize.baseDisplaySize)
let subtextFont = Font.regular(presentationData.listsFontSize.baseDisplaySize * 13.0 / 17.0)
self.backgroundNode = ASDisplayNode()
self.backgroundNode.isAccessibilityElement = false
self.backgroundNode.backgroundColor = presentationData.theme.contextMenu.itemBackgroundColor
self.highlightedBackgroundNode = ASDisplayNode()
self.highlightedBackgroundNode.isAccessibilityElement = false
self.highlightedBackgroundNode.backgroundColor = presentationData.theme.contextMenu.itemHighlightedBackgroundColor
self.highlightedBackgroundNode.alpha = 0.0
self.textNode = ImmediateTextNode()
self.textNode.isAccessibilityElement = false
self.textNode.isUserInteractionEnabled = false
self.textNode.displaysAsynchronously = false
self.textNode.attributedText = NSAttributedString(string: presentationData.strings.Conversation_ContextMenuDelete, font: textFont, textColor: presentationData.theme.contextMenu.destructiveColor)
self.textNode.maximumNumberOfLines = 1
let statusNode = ImmediateTextNode()
statusNode.isAccessibilityElement = false
statusNode.isUserInteractionEnabled = false
statusNode.displaysAsynchronously = false
statusNode.attributedText = NSAttributedString(string: stringForRemainingTime(Int32(max(0.0, self.item.timestamp - Date().timeIntervalSince1970)), strings: presentationData.strings), font: subtextFont, textColor: presentationData.theme.contextMenu.destructiveColor)
statusNode.maximumNumberOfLines = 1
self.statusNode = statusNode
self.buttonNode = HighlightTrackingButtonNode()
self.buttonNode.isAccessibilityElement = true
self.buttonNode.accessibilityLabel = presentationData.strings.VoiceChat_StopRecording
self.iconNode = ASImageNode()
self.iconNode.image = generateTintedImage(image: UIImage(bundleImageName: "Chat/Context Menu/Delete"), color: presentationData.theme.actionSheet.destructiveActionTextColor)
self.textIconNode = ASImageNode()
self.textIconNode.image = generateTintedImage(image: UIImage(bundleImageName: "Chat/Message/SelfExpiring"), color: presentationData.theme.actionSheet.destructiveActionTextColor)
super.init()
self.addSubnode(self.backgroundNode)
self.addSubnode(self.highlightedBackgroundNode)
self.addSubnode(self.textNode)
self.addSubnode(self.statusNode)
self.addSubnode(self.iconNode)
self.addSubnode(self.textIconNode)
self.addSubnode(self.buttonNode)
self.buttonNode.highligthedChanged = { [weak self] highligted in
guard let strongSelf = self else {
return
}
if highligted {
strongSelf.highlightedBackgroundNode.alpha = 1.0
} else {
strongSelf.highlightedBackgroundNode.alpha = 0.0
strongSelf.highlightedBackgroundNode.layer.animateAlpha(from: 1.0, to: 0.0, duration: 0.3)
}
}
self.buttonNode.addTarget(self, action: #selector(self.buttonPressed), forControlEvents: .touchUpInside)
}
deinit {
self.timer?.invalidate()
}
override func didLoad() {
super.didLoad()
self.pointerInteraction = PointerInteraction(node: self.buttonNode, style: .hover, willEnter: { [weak self] in
if let strongSelf = self {
strongSelf.highlightedBackgroundNode.alpha = 0.75
}
}, willExit: { [weak self] in
if let strongSelf = self {
strongSelf.highlightedBackgroundNode.alpha = 0.0
}
})
let timer = SwiftSignalKit.Timer(timeout: 0.5, repeat: true, completion: { [weak self] in
self?.updateTime(transition: .immediate)
}, queue: Queue.mainQueue())
self.timer = timer
timer.start()
}
private var validLayout: CGSize?
func updateTime(transition: ContainedViewLayoutTransition) {
guard let size = self.validLayout else {
return
}
let subtextFont = Font.regular(self.presentationData.listsFontSize.baseDisplaySize * 13.0 / 17.0)
self.statusNode.attributedText = NSAttributedString(string: stringForRemainingTime(Int32(max(0.0, self.item.timestamp - Date().timeIntervalSince1970)), strings: presentationData.strings), font: subtextFont, textColor: presentationData.theme.contextMenu.destructiveColor)
let sideInset: CGFloat = 16.0
let statusSize = self.statusNode.updateLayout(CGSize(width: size.width - sideInset - 32.0, height: .greatestFiniteMagnitude))
transition.updateFrameAdditive(node: self.statusNode, frame: CGRect(origin: CGPoint(x: self.statusNode.frame.minX, y: self.statusNode.frame.minY), size: statusSize))
}
func updateLayout(constrainedWidth: CGFloat) -> (CGSize, (CGSize, ContainedViewLayoutTransition) -> Void) {
let sideInset: CGFloat = 16.0
let iconSideInset: CGFloat = 12.0
let verticalInset: CGFloat = 12.0
let iconSize: CGSize = self.iconNode.image?.size ?? CGSize(width: 10.0, height: 10.0)
let textIconSize: CGSize = self.textIconNode.image?.size ?? CGSize(width: 2.0, height: 2.0)
let standardIconWidth: CGFloat = 32.0
var rightTextInset: CGFloat = sideInset
if !iconSize.width.isZero {
rightTextInset = max(iconSize.width, standardIconWidth) + iconSideInset + sideInset
}
let textSize = self.textNode.updateLayout(CGSize(width: constrainedWidth - sideInset - rightTextInset, height: .greatestFiniteMagnitude))
let statusSize = self.statusNode.updateLayout(CGSize(width: constrainedWidth - sideInset - rightTextInset - textIconSize.width - 2.0, height: .greatestFiniteMagnitude))
let verticalSpacing: CGFloat = 2.0
let combinedTextHeight = textSize.height + verticalSpacing + statusSize.height
return (CGSize(width: max(textSize.width, statusSize.width) + sideInset + rightTextInset, height: verticalInset * 2.0 + combinedTextHeight), { size, transition in
self.validLayout = size
let verticalOrigin = floor((size.height - combinedTextHeight) / 2.0)
let textFrame = CGRect(origin: CGPoint(x: sideInset, y: verticalOrigin), size: textSize)
transition.updateFrameAdditive(node: self.textNode, frame: textFrame)
transition.updateFrame(node: self.textIconNode, frame: CGRect(origin: CGPoint(x: sideInset, y: verticalOrigin + verticalSpacing + textSize.height + floorToScreenPixels((statusSize.height - textIconSize.height) / 2.0) + 1.0), size: textIconSize))
transition.updateFrameAdditive(node: self.statusNode, frame: CGRect(origin: CGPoint(x: sideInset + textIconSize.width + 2.0, y: verticalOrigin + verticalSpacing + textSize.height), size: statusSize))
if !iconSize.width.isZero {
transition.updateFrameAdditive(node: self.iconNode, frame: CGRect(origin: CGPoint(x: size.width - standardIconWidth - iconSideInset + floor((standardIconWidth - iconSize.width) / 2.0), y: floor((size.height - iconSize.height) / 2.0)), size: iconSize))
}
transition.updateFrame(node: self.backgroundNode, frame: CGRect(origin: CGPoint(x: 0.0, y: 0.0), size: CGSize(width: size.width, height: size.height)))
transition.updateFrame(node: self.highlightedBackgroundNode, frame: CGRect(origin: CGPoint(x: 0.0, y: 0.0), size: CGSize(width: size.width, height: size.height)))
transition.updateFrame(node: self.buttonNode, frame: CGRect(origin: CGPoint(x: 0.0, y: 0.0), size: CGSize(width: size.width, height: size.height)))
})
}
func updateTheme(presentationData: PresentationData) {
self.backgroundNode.backgroundColor = presentationData.theme.contextMenu.itemBackgroundColor
self.highlightedBackgroundNode.backgroundColor = presentationData.theme.contextMenu.itemHighlightedBackgroundColor
let textFont = Font.regular(presentationData.listsFontSize.baseDisplaySize)
let subtextFont = Font.regular(presentationData.listsFontSize.baseDisplaySize * 13.0 / 17.0)
self.textNode.attributedText = NSAttributedString(string: self.textNode.attributedText?.string ?? "", font: textFont, textColor: presentationData.theme.contextMenu.primaryColor)
self.statusNode.attributedText = NSAttributedString(string: self.statusNode.attributedText?.string ?? "", font: subtextFont, textColor: presentationData.theme.contextMenu.secondaryColor)
}
@objc private func buttonPressed() {
self.performAction()
}
func performAction() {
guard let controller = self.getController() else {
return
}
self.item.action(controller, { [weak self] result in
self?.actionSelected(result)
})
}
func setIsHighlighted(_ value: Bool) {
if value {
self.highlightedBackgroundNode.alpha = 1.0
} else {
self.highlightedBackgroundNode.alpha = 0.0
}
}
}
private func stringForRemainingTime(_ duration: Int32, strings: PresentationStrings) -> String {
let days = duration / (3600 * 24)
let hours = duration / 3600
let minutes = duration / 60 % 60
let seconds = duration % 60
let durationString: String
if days > 0 {
let roundDays = round(Double(duration) / (3600.0 * 24.0))
return strings.Conversation_AutoremoveRemainingDays(Int32(roundDays))
} else if hours > 0 {
durationString = String(format: "%d:%02d:%02d", hours, minutes, seconds)
} else {
durationString = String(format: "%d:%02d", minutes, seconds)
}
return strings.Conversation_AutoremoveRemainingTime(durationString).0
}
| 49.936913 | 407 | 0.560815 |
ab85ef56cb22610b6b0784a088ba4a0fdf85889e | 31,190 | //
// Copyright © 2018 Shin Yamamoto. All rights reserved.
//
import UIKit
///
/// FloatingPanel presentation model
///
class FloatingPanel: NSObject, UIGestureRecognizerDelegate, UIScrollViewDelegate {
/* Cause 'terminating with uncaught exception of type NSException' error on Swift Playground
unowned let view: UIView
*/
let surfaceView: FloatingPanelSurfaceView
let backdropView: FloatingPanelBackdropView
var layoutAdapter: FloatingPanelLayoutAdapter
var behavior: FloatingPanelBehavior
weak var scrollView: UIScrollView? {
didSet {
guard let scrollView = scrollView else { return }
scrollView.panGestureRecognizer.addTarget(self, action: #selector(handle(panGesture:)))
scrollBouncable = scrollView.bounces
scrollIndictorVisible = scrollView.showsVerticalScrollIndicator
}
}
weak var userScrollViewDelegate: UIScrollViewDelegate?
var safeAreaInsets: UIEdgeInsets! {
get { return layoutAdapter.safeAreaInsets }
set { layoutAdapter.safeAreaInsets = newValue }
}
unowned let viewcontroller: FloatingPanelController
private(set) var state: FloatingPanelPosition = .tip {
didSet { viewcontroller.delegate?.floatingPanelDidChangePosition(viewcontroller) }
}
private var isBottomState: Bool {
let remains = layoutAdapter.layout.supportedPositions.filter { $0.rawValue > state.rawValue }
return remains.count == 0
}
let panGesture: FloatingPanelPanGestureRecognizer
var isRemovalInteractionEnabled: Bool = false
private var animator: UIViewPropertyAnimator?
private var initialFrame: CGRect = .zero
private var initialScrollOffset: CGPoint = .zero
private var transOffsetY: CGFloat = 0
private var interactionInProgress: Bool = false
// Scroll handling
private var stopScrollDeceleration: Bool = false
private var scrollBouncable = false
private var scrollIndictorVisible = false
// MARK: - Interface
init(_ vc: FloatingPanelController, layout: FloatingPanelLayout, behavior: FloatingPanelBehavior) {
viewcontroller = vc
surfaceView = vc.view as! FloatingPanelSurfaceView
backdropView = FloatingPanelBackdropView()
backdropView.backgroundColor = .black
backdropView.alpha = 0.0
self.layoutAdapter = FloatingPanelLayoutAdapter(surfaceView: surfaceView,
backdropView: backdropView,
layout: layout)
self.behavior = behavior
state = layoutAdapter.layout.initialPosition
panGesture = FloatingPanelPanGestureRecognizer()
if #available(iOS 11.0, *) {
panGesture.name = "FloatingPanelSurface"
}
super.init()
surfaceView.addGestureRecognizer(panGesture)
panGesture.addTarget(self, action: #selector(handle(panGesture:)))
panGesture.delegate = self
}
func setUpViews(in vc: UIViewController) {
unowned let view = vc.view!
view.insertSubview(backdropView, belowSubview: surfaceView)
backdropView.frame = view.bounds
layoutAdapter.prepareLayout(toParent: vc)
}
func move(to: FloatingPanelPosition, animated: Bool, completion: (() -> Void)? = nil) {
move(from: state, to: to, animated: animated, completion: completion)
}
func present(animated: Bool, completion: (() -> Void)? = nil) {
self.layoutAdapter.activateLayout(of: nil)
move(from: nil, to: layoutAdapter.layout.initialPosition, animated: animated, completion: completion)
}
func dismiss(animated: Bool, completion: (() -> Void)? = nil) {
move(from: state, to: nil, animated: animated, completion: completion)
}
private func move(from: FloatingPanelPosition?, to: FloatingPanelPosition?, animated: Bool, completion: (() -> Void)? = nil) {
if to != .full {
lockScrollView()
}
if animated {
let animator: UIViewPropertyAnimator
switch (from, to) {
case (nil, let to?):
animator = behavior.addAnimator(self.viewcontroller, to: to)
case (let from?, let to?):
animator = behavior.moveAnimator(self.viewcontroller, from: from, to: to)
case (let from?, nil):
animator = behavior.removeAnimator(self.viewcontroller, from: from)
case (nil, nil):
fatalError()
}
animator.addAnimations { [weak self] in
guard let self = self else { return }
self.updateLayout(to: to)
if let to = to {
self.state = to
}
}
animator.addCompletion { _ in
completion?()
}
animator.startAnimation()
} else {
self.updateLayout(to: to)
if let to = to {
self.state = to
}
completion?()
}
}
// MARK: - Layout update
private func updateLayout(to target: FloatingPanelPosition?) {
self.layoutAdapter.activateLayout(of: target)
}
private func getBackdropAlpha(with translation: CGPoint) -> CGFloat {
let currentY = getCurrentY(from: initialFrame, with: translation)
let next = directionalPosition(with: translation)
let pre = redirectionalPosition(with: translation)
let nextY = layoutAdapter.positionY(for: next)
let preY = layoutAdapter.positionY(for: pre)
let nextAlpha = layoutAdapter.layout.backdropAlphaFor(position: next)
let preAlpha = layoutAdapter.layout.backdropAlphaFor(position: pre)
if preY == nextY {
return preAlpha
} else {
return preAlpha + max(min(1.0, 1.0 - (nextY - currentY) / (nextY - preY) ), 0.0) * (nextAlpha - preAlpha)
}
}
// MARK: - UIGestureRecognizerDelegate
public func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer,
shouldRecognizeSimultaneouslyWith otherGestureRecognizer: UIGestureRecognizer) -> Bool {
guard gestureRecognizer == panGesture else { return false }
/* log.debug("shouldRecognizeSimultaneouslyWith", otherGestureRecognizer) */
// all gestures of the tracking scroll view should be recognized in parallel
// and handle them in self.handle(panGesture:)
return scrollView?.gestureRecognizers?.contains(otherGestureRecognizer) ?? false
}
public func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldBeRequiredToFailBy otherGestureRecognizer: UIGestureRecognizer) -> Bool {
guard gestureRecognizer == panGesture else { return false }
/* log.debug("shouldBeRequiredToFailBy", otherGestureRecognizer) */
// The tracking scroll view's gestures should begin without waiting for the pan gesture failure.
// `scrollView.gestureRecognizers` can contains the following gestures
// * UIScrollViewDelayedTouchesBeganGestureRecognizer
// * UIScrollViewPanGestureRecognizer (scrollView.panGestureRecognizer)
// * _UIDragAutoScrollGestureRecognizer
// * _UISwipeActionPanGestureRecognizer
// * UISwipeDismissalGestureRecognizer
if let scrollView = scrollView,
let scrollGestureRecognizers = scrollView.gestureRecognizers,
scrollGestureRecognizers.contains(otherGestureRecognizer) {
return false
}
// Long press gesture should begin without waiting for the pan gesture failure.
if otherGestureRecognizer is UILongPressGestureRecognizer {
return false
}
// Do not begin any other gestures until the pan gesture fails.
return true
}
public func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldRequireFailureOf otherGestureRecognizer: UIGestureRecognizer) -> Bool {
guard gestureRecognizer == panGesture else { return false }
log.debug("shouldRequireFailureOf", otherGestureRecognizer)
// Should begin the pan gesture without waiting for the tracking scroll view's gestures.
// `scrollView.gestureRecognizers` can contains the following gestures
// * UIScrollViewDelayedTouchesBeganGestureRecognizer
// * UIScrollViewPanGestureRecognizer (scrollView.panGestureRecognizer)
// * _UIDragAutoScrollGestureRecognizer
// * _UISwipeActionPanGestureRecognizer
// * UISwipeDismissalGestureRecognizer
if let scrollView = scrollView {
// On short contents scroll, `_UISwipeActionPanGestureRecognizer` blocks
// the panel's pan gesture if not returns false
if let scrollGestureRecognizers = scrollView.gestureRecognizers,
scrollGestureRecognizers.contains(otherGestureRecognizer) {
return false
}
}
switch otherGestureRecognizer {
case is UIPanGestureRecognizer,
is UISwipeGestureRecognizer,
is UIRotationGestureRecognizer,
is UIScreenEdgePanGestureRecognizer,
is UIPinchGestureRecognizer:
// Do not begin the pan gesture until these gestures fail
return true
default:
// Should begin the pan gesture witout waiting tap/long press gestures fail
return false
}
}
var grabberAreaFrame: CGRect {
let grabberAreaFrame = CGRect(x: surfaceView.bounds.origin.x,
y: surfaceView.bounds.origin.y,
width: surfaceView.bounds.width,
height: FloatingPanelSurfaceView.topGrabberBarHeight * 2)
return grabberAreaFrame
}
// MARK: - Gesture handling
private let offsetThreshold: CGFloat = 5.0 // Optimal value from testing
@objc func handle(panGesture: UIPanGestureRecognizer) {
log.debug("Gesture >>>>", panGesture)
let velocity = panGesture.velocity(in: panGesture.view)
switch panGesture {
case scrollView?.panGestureRecognizer:
guard let scrollView = scrollView else { return }
log.debug("SrollPanGesture ScrollView.contentOffset >>>", scrollView.contentOffset.y, scrollView.contentSize, scrollView.bounds.size)
// Prevent scoll slip by the top bounce when the scroll view's height is
// less than the content's height
if scrollView.isDecelerating == false, scrollView.contentSize.height > scrollView.bounds.height {
scrollView.bounces = (scrollView.contentOffset.y > offsetThreshold)
}
if surfaceView.frame.minY > layoutAdapter.topY {
switch state {
case .full:
let point = panGesture.location(in: surfaceView)
if grabberAreaFrame.contains(point) {
// Preserve the current content offset in moving from full.
scrollView.contentOffset.y = initialScrollOffset.y
} else {
// Prevent over scrolling in moving from full.
scrollView.contentOffset.y = scrollView.contentOffsetZero.y
}
case .half, .tip:
guard scrollView.isDecelerating == false else {
// Don't fix the scroll offset in animating the panel to half and tip.
// It causes a buggy scrolling deceleration because `state` becomes
// a target position in animating the panel on the interaction from full.
return
}
// Fix the scroll offset in moving the panel from half and tip.
scrollView.contentOffset.y = initialScrollOffset.y
}
// Always hide a scroll indicator at the non-top.
if interactionInProgress {
lockScrollView()
}
} else {
// Always show a scroll indicator at the top.
if interactionInProgress {
unlockScrollView()
}
}
case panGesture:
let translation = panGesture.translation(in: panGesture.view!.superview)
let location = panGesture.location(in: panGesture.view)
log.debug(panGesture.state, ">>>", "translation: \(translation.y), velocity: \(velocity.y)")
if shouldScrollViewHandleTouch(scrollView, point: location, velocity: velocity) {
return
}
if let animator = self.animator, animator.isInterruptible {
animator.stopAnimation(true)
self.animator = nil
}
switch panGesture.state {
case .began:
panningBegan()
case .changed:
if interactionInProgress == false {
startInteraction(with: translation)
}
panningChange(with: translation)
case .ended, .cancelled, .failed:
panningEnd(with: translation, velocity: velocity)
case .possible:
break
}
default:
return
}
}
private func shouldScrollViewHandleTouch(_ scrollView: UIScrollView?, point: CGPoint, velocity: CGPoint) -> Bool {
// When no scrollView, nothing to handle.
guard let scrollView = scrollView else { return false }
// For _UISwipeActionPanGestureRecognizer
if let scrollGestureRecognizers = scrollView.gestureRecognizers {
for gesture in scrollGestureRecognizers {
guard gesture.state == .began || gesture.state == .changed
else { continue }
if gesture != scrollView.panGestureRecognizer {
return true
}
}
}
guard
state == .full, // When not .full, don't scroll.
interactionInProgress == false, // When interaction already in progress, don't scroll.
scrollView.frame.contains(point), // When point not in scrollView, don't scroll.
!grabberAreaFrame.contains(point) // When point within grabber area, don't scroll.
else {
return false
}
log.debug("ScrollView.contentOffset >>>", scrollView.contentOffset.y)
let offset = scrollView.contentOffset.y - scrollView.contentOffsetZero.y
if abs(offset) > offsetThreshold {
return true
}
if scrollView.isDecelerating {
return true
}
if velocity.y < 0 {
return true
}
return false
}
private func panningBegan() {
// A user interaction does not always start from Began state of the pan gesture
// because it can be recognized in scrolling a content in a content view controller.
// So do nothing here.
log.debug("panningBegan")
}
private func panningChange(with translation: CGPoint) {
log.debug("panningChange")
let currentY = getCurrentY(from: initialFrame, with: translation)
var frame = initialFrame
frame.origin.y = currentY
surfaceView.frame = frame
backdropView.alpha = getBackdropAlpha(with: translation)
viewcontroller.delegate?.floatingPanelDidMove(viewcontroller)
}
private func panningEnd(with translation: CGPoint, velocity: CGPoint) {
log.debug("panningEnd")
if interactionInProgress == false {
initialFrame = surfaceView.frame
}
stopScrollDeceleration = (surfaceView.frame.minY > layoutAdapter.topY) // Projecting the dragging to the scroll dragging or not
let targetPosition = self.targetPosition(with: translation, velocity: velocity)
let distance = self.distance(to: targetPosition, with: translation)
endInteraction(for: targetPosition)
if isRemovalInteractionEnabled, isBottomState {
if startRemovalAnimation(with: translation, velocity: velocity, distance: distance) {
return
}
}
viewcontroller.delegate?.floatingPanelDidEndDragging(viewcontroller, withVelocity: velocity, targetPosition: targetPosition)
viewcontroller.delegate?.floatingPanelWillBeginDecelerating(viewcontroller)
startAnimation(to: targetPosition, at: distance, with: velocity)
}
private func startRemovalAnimation(with translation: CGPoint, velocity: CGPoint, distance: CGFloat) -> Bool {
let posY = layoutAdapter.positionY(for: state)
let currentY = getCurrentY(from: initialFrame, with: translation)
let safeAreaBottomY = layoutAdapter.safeAreaBottomY
let vth = behavior.removalVelocity
let pth = max(min(behavior.removalProgress, 1.0), 0.0)
let velocityVector = (distance != 0) ? CGVector(dx: 0, dy: max(min(velocity.y/distance, vth), 0.0)) : .zero
guard (safeAreaBottomY - posY) != 0 else { return false }
guard (currentY - posY) / (safeAreaBottomY - posY) >= pth || velocityVector.dy == vth else { return false }
viewcontroller.delegate?.floatingPanelDidEndDraggingToRemove(viewcontroller, withVelocity: velocity)
let animator = self.behavior.removalInteractionAnimator(self.viewcontroller, with: velocityVector)
animator.addAnimations { [weak self] in
guard let self = self else { return }
self.updateLayout(to: nil)
}
animator.addCompletion({ [weak self] (_) in
guard let self = self else { return }
self.viewcontroller.removePanelFromParent(animated: false)
self.viewcontroller.delegate?.floatingPanelDidEndRemove(self.viewcontroller)
})
animator.startAnimation()
return true
}
private func startInteraction(with translation: CGPoint) {
/* Don't lock a scroll view to show a scroll indicator after hitting the top */
log.debug("startInteraction")
initialFrame = surfaceView.frame
if let scrollView = scrollView {
initialScrollOffset = scrollView.contentOffset
}
transOffsetY = translation.y
viewcontroller.delegate?.floatingPanelWillBeginDragging(viewcontroller)
interactionInProgress = true
}
private func endInteraction(for targetPosition: FloatingPanelPosition) {
log.debug("endInteraction for \(targetPosition)")
interactionInProgress = false
// Prevent to keep a scoll view indicator visible at the half/tip position
if targetPosition != .full {
lockScrollView()
}
}
private func getCurrentY(from rect: CGRect, with translation: CGPoint) -> CGFloat {
let dy = translation.y - transOffsetY
let y = rect.offsetBy(dx: 0.0, dy: dy).origin.y
let topY = layoutAdapter.topY
let topBuffer = layoutAdapter.layout.topInteractionBuffer
let bottomY = layoutAdapter.bottomY
let bottomBuffer = layoutAdapter.layout.bottomInteractionBuffer
if let scrollView = scrollView, scrollView.panGestureRecognizer.state == .changed {
let preY = surfaceView.frame.origin.y
if preY > 0 && preY > y {
return max(topY, min(bottomY, y))
}
}
return max(topY - topBuffer, min(bottomY + bottomBuffer, y))
}
private func startAnimation(to targetPosition: FloatingPanelPosition, at distance: CGFloat, with velocity: CGPoint) {
log.debug("startAnimation", targetPosition, distance, velocity)
let targetY = layoutAdapter.positionY(for: targetPosition)
let velocityVector = (distance != 0) ? CGVector(dx: 0, dy: max(min(velocity.y/distance, 30.0), -30.0)) : .zero
let animator = behavior.interactionAnimator(self.viewcontroller, to: targetPosition, with: velocityVector)
animator.addAnimations { [weak self] in
guard let self = self else { return }
if self.state == targetPosition {
self.surfaceView.frame.origin.y = targetY
self.layoutAdapter.setBackdropAlpha(of: targetPosition)
} else {
self.updateLayout(to: targetPosition)
}
self.state = targetPosition
}
animator.addCompletion { [weak self] pos in
guard let self = self else { return }
guard
self.interactionInProgress == false,
animator == self.animator,
pos == .end
else { return }
self.finishAnimation(at: targetPosition)
}
animator.startAnimation()
self.animator = animator
}
private func finishAnimation(at targetPosition: FloatingPanelPosition) {
log.debug("finishAnimation \(targetPosition)")
self.animator = nil
self.viewcontroller.delegate?.floatingPanelDidEndDecelerating(self.viewcontroller)
stopScrollDeceleration = false
// Don't unlock scroll view in animating view when presentation layer != model layer
if targetPosition == .full {
unlockScrollView()
}
}
private func distance(to targetPosition: FloatingPanelPosition, with translation: CGPoint) -> CGFloat {
let topY = layoutAdapter.topY
let middleY = layoutAdapter.middleY
let bottomY = layoutAdapter.bottomY
let currentY = getCurrentY(from: initialFrame, with: translation)
switch targetPosition {
case .full:
return CGFloat(fabs(Double(currentY - topY)))
case .half:
return CGFloat(fabs(Double(currentY - middleY)))
case .tip:
return CGFloat(fabs(Double(currentY - bottomY)))
}
}
private func directionalPosition(with translation: CGPoint) -> FloatingPanelPosition {
let currentY = getCurrentY(from: initialFrame, with: translation)
let supportedPositions: Set = layoutAdapter.layout.supportedPositions
if supportedPositions.count == 1 {
return state
}
switch supportedPositions {
case [.full, .half]: return translation.y >= 0 ? .half : .full
case [.half, .tip]: return translation.y >= 0 ? .tip : .half
case [.full, .tip]: return translation.y >= 0 ? .tip : .full
default:
let middleY = layoutAdapter.middleY
switch state {
case .full:
if translation.y <= 0 {
return .full
}
return currentY > middleY ? .tip : .half
case .half:
return currentY > middleY ? .tip : .full
case .tip:
if translation.y >= 0 {
return .tip
}
return currentY > middleY ? .half : .full
}
}
}
private func redirectionalPosition(with translation: CGPoint) -> FloatingPanelPosition {
let currentY = getCurrentY(from: initialFrame, with: translation)
let supportedPositions: Set = layoutAdapter.layout.supportedPositions
if supportedPositions.count == 1 {
return state
}
switch supportedPositions {
case [.full, .half]: return translation.y >= 0 ? .full : .half
case [.half, .tip]: return translation.y >= 0 ? .half : .tip
case [.full, .tip]: return translation.y >= 0 ? .full : .tip
default:
let middleY = layoutAdapter.middleY
switch state {
case .full:
return currentY > middleY ? .half : .full
case .half:
return .half
case .tip:
return currentY > middleY ? .tip : .half
}
}
}
// Distance travelled after decelerating to zero velocity at a constant rate.
// Refer to the slides p176 of [Designing Fluid Interfaces](https://developer.apple.com/videos/play/wwdc2018/803/)
private func project(initialVelocity: CGFloat) -> CGFloat {
let decelerationRate = UIScrollView.DecelerationRate.normal.rawValue
return (initialVelocity / 1000.0) * decelerationRate / (1.0 - decelerationRate)
}
private func targetPosition(with translation: CGPoint, velocity: CGPoint) -> (FloatingPanelPosition) {
let currentY = getCurrentY(from: initialFrame, with: translation)
let supportedPositions: Set = layoutAdapter.layout.supportedPositions
if supportedPositions.count == 1 {
return state
}
switch supportedPositions {
case [.full, .half]:
return targetPosition(from: [.full, .half], at: currentY, velocity: velocity)
case [.half, .tip]:
return targetPosition(from: [.half, .tip], at: currentY, velocity: velocity)
case [.full, .tip]:
return targetPosition(from: [.full, .tip], at: currentY, velocity: velocity)
default:
/*
[topY|full]---[th1]---[middleY|half]---[th2]---[bottomY|tip]
*/
let topY = layoutAdapter.topY
let middleY = layoutAdapter.middleY
let bottomY = layoutAdapter.bottomY
let target: FloatingPanelPosition
let forwardYDirection: Bool
switch state {
case .full:
target = .half
forwardYDirection = true
case .half:
if (currentY < middleY) {
target = .full
forwardYDirection = false
} else {
target = .tip
forwardYDirection = true
}
case .tip:
target = .half
forwardYDirection = false
}
let redirectionalProgress = max(min(behavior.redirectionalProgress(viewcontroller, from: state, to: target), 1.0), 0.0)
let th1: CGFloat
let th2: CGFloat
if forwardYDirection {
th1 = topY + (middleY - topY) * redirectionalProgress
th2 = middleY + (bottomY - middleY) * redirectionalProgress
} else {
th1 = middleY - (middleY - topY) * redirectionalProgress
th2 = bottomY - (bottomY - middleY) * redirectionalProgress
}
switch currentY {
case ..<th1:
if project(initialVelocity: velocity.y) >= (middleY - currentY) {
return .half
} else {
return .full
}
case ...middleY:
if project(initialVelocity: velocity.y) <= (topY - currentY) {
return .full
} else {
return .half
}
case ..<th2:
if project(initialVelocity: velocity.y) >= (bottomY - currentY) {
return .tip
} else {
return .half
}
default:
if project(initialVelocity: velocity.y) <= (middleY - currentY) {
return .half
} else {
return .tip
}
}
}
}
private func targetPosition(from positions: [FloatingPanelPosition], at currentY: CGFloat, velocity: CGPoint) -> FloatingPanelPosition {
assert(positions.count == 2)
let top = positions[0]
let bottom = positions[1]
let topY = layoutAdapter.positionY(for: top)
let bottomY = layoutAdapter.positionY(for: bottom)
let target = top == state ? bottom : top
let redirectionalProgress = max(min(behavior.redirectionalProgress(viewcontroller, from: state, to: target), 1.0), 0.0)
let th = topY + (bottomY - topY) * redirectionalProgress
switch currentY {
case ..<th:
if project(initialVelocity: velocity.y) >= (bottomY - currentY) {
return bottom
} else {
return top
}
default:
if project(initialVelocity: velocity.y) <= (topY - currentY) {
return top
} else {
return bottom
}
}
}
// MARK: - ScrollView handling
private func lockScrollView() {
guard let scrollView = scrollView else { return }
scrollView.isDirectionalLockEnabled = true
scrollView.bounces = false
scrollView.showsVerticalScrollIndicator = false
}
private func unlockScrollView() {
guard let scrollView = scrollView else { return }
scrollView.isDirectionalLockEnabled = false
scrollView.bounces = scrollBouncable
scrollView.showsVerticalScrollIndicator = scrollIndictorVisible
}
// MARK: - UIScrollViewDelegate Intermediation
override func responds(to aSelector: Selector!) -> Bool {
return super.responds(to: aSelector) || userScrollViewDelegate?.responds(to: aSelector) == true
}
override func forwardingTarget(for aSelector: Selector!) -> Any? {
if userScrollViewDelegate?.responds(to: aSelector) == true {
return userScrollViewDelegate
} else {
return super.forwardingTarget(for: aSelector)
}
}
func scrollViewDidEndScrollingAnimation(_ scrollView: UIScrollView) {
if state != .full {
initialScrollOffset = scrollView.contentOffset
}
userScrollViewDelegate?.scrollViewDidEndScrollingAnimation?(scrollView)
}
func scrollViewWillEndDragging(_ scrollView: UIScrollView, withVelocity velocity: CGPoint, targetContentOffset: UnsafeMutablePointer<CGPoint>) {
if stopScrollDeceleration {
targetContentOffset.pointee = scrollView.contentOffset
stopScrollDeceleration = false
} else {
userScrollViewDelegate?.scrollViewWillEndDragging?(scrollView, withVelocity: velocity, targetContentOffset: targetContentOffset)
}
}
}
class FloatingPanelPanGestureRecognizer: UIPanGestureRecognizer {
override weak var delegate: UIGestureRecognizerDelegate? {
get {
return super.delegate
}
set {
guard newValue is FloatingPanel else {
let exception = NSException(name: .invalidArgumentException,
reason: "FloatingPanelController's built-in pan gesture recognizer must have its controller as its delegate.",
userInfo: nil)
exception.raise()
return
}
super.delegate = newValue
}
}
}
| 39.183417 | 155 | 0.609202 |
4b54395534a229ef9277616128a51b39d5b364ef | 276 | //
// PrioritizedRequest.swift
// ForYouAndMe
//
// Created by Leonardo Passeri on 30/04/2020.
// Copyright © 2020 Balzo srl. All rights reserved.
//
import Foundation
import RxSwift
struct PrioritizedRequest {
let hasPriority: Bool
let disposable: Disposable
}
| 17.25 | 52 | 0.724638 |
91d6480f2cb7274f8c8bf95494419ad516feb95e | 529 | //
// ViewController.swift
// IAPHelper
//
// Created by [email protected] on 04/24/2017.
// Copyright (c) 2017 [email protected]. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
| 21.16 | 80 | 0.678639 |
e40cb69709b29fc8febbd67895a5e1f489d0c075 | 382 | //
// Blinder.swift
// FinalProject
//
// Created by Zhen on 3/20/18.
// Copyright © 2018 Local Account 436-30. All rights reserved.
//
import Foundation
struct RGBA {
var R: Float
var G: Float
var B: Float
var A: Float
init(R: Float, G: Float, B: Float, A: Float) {
self.R = R
self.G = G
self.B = B
self.A = A
}
}
| 15.916667 | 63 | 0.536649 |
877442bb4d491a1bad910889d00158b03758db38 | 660 | //
// RowWorkoutView.swift
// Workout
//
// Created by blind heitz nathan on 03/03/2022.
//
import SwiftUI
struct RowWorkoutView: View {
let category: Category
let date: String
var body: some View {
VStack {
HStack {
Image(systemName: category.icon)
Text(date)
}
}
}
}
struct RowWorkoutView_Previews: PreviewProvider {
static var previews: some View {
ForEach(Workout.testData) { workout in
RowWorkoutView(category: workout.categogy, date: workout.getFormattedDate())
.previewLayout(.sizeThatFits)
}
}
}
| 20 | 88 | 0.577273 |
89131bdcb539199d8c96337c2b06955fa7bc6639 | 1,360 | //
// AppDelegate.swift
// TableView
//
// Created by Renato F. dos Santos Jr on 15/03/22.
//
import UIKit
@main
class AppDelegate: UIResponder, UIApplicationDelegate {
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
return true
}
// MARK: UISceneSession Lifecycle
func application(_ application: UIApplication, configurationForConnecting connectingSceneSession: UISceneSession, options: UIScene.ConnectionOptions) -> UISceneConfiguration {
// Called when a new scene session is being created.
// Use this method to select a configuration to create the new scene with.
return UISceneConfiguration(name: "Default Configuration", sessionRole: connectingSceneSession.role)
}
func application(_ application: UIApplication, didDiscardSceneSessions sceneSessions: Set<UISceneSession>) {
// Called when the user discards a scene session.
// If any sessions were discarded while the application was not running, this will be called shortly after application:didFinishLaunchingWithOptions.
// Use this method to release any resources that were specific to the discarded scenes, as they will not return.
}
}
| 36.756757 | 179 | 0.744853 |
ff71cbce94bbd8a7763ec638269bfef4f7d21955 | 3,457 | // Copyright 2020 Carton contributors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
import CartonHelpers
import Foundation
import TSCBasic
import WasmTransformer
public final class Builder {
public let mainWasmPath: AbsolutePath
public let pathsToWatch: [AbsolutePath]
private let arguments: [String]
private let flavor: BuildFlavor
private let terminal: InteractiveWriter
private let fileSystem: FileSystem
public init(
arguments: [String],
mainWasmPath: AbsolutePath,
pathsToWatch: [AbsolutePath] = [],
_ flavor: BuildFlavor,
_ fileSystem: FileSystem,
_ terminal: InteractiveWriter
) {
self.arguments = arguments
self.mainWasmPath = mainWasmPath
self.pathsToWatch = pathsToWatch
self.flavor = flavor
self.terminal = terminal
self.fileSystem = fileSystem
}
private func buildWithoutSanitizing(builderArguments: [String]) async throws {
let buildStarted = Date()
try await Process.run(
builderArguments,
loadingMessage: "Compiling...",
parser: nil,
terminal
)
self.terminal.logLookup(
"`swift build` completed in ",
String(format: "%.2f seconds", abs(buildStarted.timeIntervalSinceNow))
)
var transformers: [(inout InputByteStream, inout InMemoryOutputWriter) throws -> ()] = []
if self.flavor.environment != .other {
transformers.append(I64ImportTransformer().transform)
}
switch self.flavor.sanitize {
case .stackOverflow:
transformers.append(StackOverflowSanitizer().transform)
case .none:
break
}
guard !transformers.isEmpty else { return }
let binary = try self.fileSystem.readFileContents(self.mainWasmPath)
let transformStarted = Date()
var inputBinary = binary.contents
for transformer in transformers {
var input = InputByteStream(bytes: inputBinary)
var writer = InMemoryOutputWriter(reservingCapacity: inputBinary.count)
try! transformer(&input, &writer)
inputBinary = writer.bytes()
}
self.terminal.logLookup(
"Binary transformation for Safari compatibility completed in ",
String(format: "%.2f seconds", abs(transformStarted.timeIntervalSinceNow))
)
try self.fileSystem.writeFileContents(self.mainWasmPath, bytes: .init(inputBinary))
}
public func run() async throws {
switch flavor.sanitize {
case .none:
return try await buildWithoutSanitizing(builderArguments: arguments)
case .stackOverflow:
let sanitizerFile =
fileSystem.homeDirectory.appending(components: ".carton", "static", "so_sanitizer.wasm")
var modifiedArguments = arguments
modifiedArguments.append(contentsOf: [
"-Xlinker", sanitizerFile.pathString,
// stack-overflow-sanitizer depends on "--stack-first"
"-Xlinker", "--stack-first",
])
return try await buildWithoutSanitizing(builderArguments: modifiedArguments)
}
}
}
| 31.715596 | 96 | 0.711021 |
fed88e306662e6664c828f07ba8b7d23c5e95749 | 4,845 | //
// StockPositionView.swift
// PaperTrading
//
// Created by Apps4World on 3/5/21.
//
import SwiftUI
/// Shows the details about any stock position
struct StockPositionView: View {
@ObservedObject var manager: StocksDataManager
@State private var frequentRefreshTimer: Timer?
var portfolioPosition: PositionModel?
// MARK: - Main rendering function
var body: some View {
let position = portfolioPosition ?? manager.positions.first(where: { $0.stock == manager.selectedStock?.symbol })
let profit = position?.profitLoss(fromLatestPrice: manager.stockDataModel?.prices.last ?? 0.0) ?? "$0.00"
return VStack {
if portfolioPosition != nil {
CreateDashboardPosition(position)
} else {
CreateStockDetailsPosition(position, profit: profit).padding()
}
}
}
/// Position view for stock details screen
private func CreateStockDetailsPosition(_ position: PositionModel?, profit: String) -> some View {
VStack {
HStack {
VStack(alignment: .leading) {
Text("Your Positions").font(.system(size: 25))
Text(position == nil ? "You don't have any \(manager.selectedStock?.symbol ?? "XYZ") positions" : "See your current position below").opacity(0.60)
}
Spacer()
}
if position != nil {
HStack {
VStack(alignment: .leading) {
Text("Shares").opacity(0.7)
Text("\(position!.sharesCount)")
}
Spacer()
VStack(alignment: .center) {
Text("P&L").opacity(0.7)
Text(profit).bold()
.foregroundColor(profit.contains("-") ? AppConfig.negativeColor : AppConfig.tradeButtonColor)
.lineLimit(1).minimumScaleFactor(0.5)
}
Spacer()
VStack(alignment: .trailing) {
Text("Avg Cost").opacity(0.7)
Text(position!.purchasePrice.dollarAmount)
}
}.padding().background(RoundedRectangle(cornerRadius: 10).foregroundColor(.white))
}
}
}
/// Position view for the dashboard screen
private func CreateDashboardPosition(_ position: PositionModel?) -> some View {
let isStockDown = position!.profitLoss(fromLatestPrice: manager.positionsPrices[position!.stock] ?? position!.purchasePrice).contains("-")
return HStack {
if position?.stockDetails.companyLogoURL != nil {
RemoteImage(imageUrl: position!.stockDetails.companyLogoURL)
.frame(width: 25, height: 25, alignment: .center).cornerRadius(6)
} else {
Image("image_placeholder").resizable().aspectRatio(contentMode: .fill)
.frame(width: 25, height: 25, alignment: .center).cornerRadius(6)
}
Text(position!.stock).bold()
Spacer()
VStack(alignment: .trailing) {
Text(position!.totalPositionValue(fromLatestPrice: manager.positionsPrices[position!.stock] ?? position!.purchasePrice))
HStack {
Image(systemName: isStockDown ? "arrowtriangle.down.fill" : "arrowtriangle.up.fill")
Text(position!.profitLoss(fromLatestPrice: manager.positionsPrices[position!.stock] ?? position!.purchasePrice))
}
.font(.system(size: 15))
.foregroundColor(isStockDown ? AppConfig.negativeColor : AppConfig.tradeButtonColor)
}
}
.padding().background(RoundedRectangle(cornerRadius: 10).foregroundColor(.white))
.onAppear(perform: {
/// Refresh the last price every 1min
frequentRefreshTimer?.invalidate()
frequentRefreshTimer = Timer.scheduledTimer(withTimeInterval: 1, repeats: true, block: { (_) in
manager.fetchLatestPrice(symbol: position!.stock)
})
})
}
}
// MARK: - Render preview UI
struct StockPositionView_Previews: PreviewProvider {
static var previews: some View {
Group {
StockPositionView(manager: StocksDataManager())
.previewLayout(.sizeThatFits)
StockPositionView(manager: StocksDataManager(), portfolioPosition: PositionModel(stock: "XYZ", sharesCount: 10, purchasePrice: 100, stockDetails: StockDetailsModel(symbol: "XYZ", companyName: "XYZ", companyLogoURL: AppConfig.stockIconURL.replacingOccurrences(of: "<S>", with: "mcd"))))
.previewLayout(.sizeThatFits)
}
}
}
| 44.861111 | 297 | 0.578947 |
1a8b5ccc3e73b201d47cca73029ba7f93209a19c | 477 | // This source file is part of the Swift.org open source project
// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
// RUN: not %target-swift-frontend %s -typecheck
struct Q<T where I.c = compose<T> () {
typealias R = {
}
let a {
class d<I : N
| 34.071429 | 79 | 0.725367 |
26fd7432c1a87c430561929889dee20e8f90d5cd | 467 | //
// AppDelegate.swift
// CRNetworkButton
//
// Created by Dmitry Pashinskiy on 05/20/2016.
// Copyright (c) 2016 Dmitry Pashinskiy. All rights reserved.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey : Any]? = nil) -> Bool {
return true
}
}
| 21.227273 | 152 | 0.721627 |
0a265493cc0f9cba4e1a5cc9e2cea68fb5a1e1f0 | 10,454 | //===--- main.swift -------------------------------------------*- swift -*-===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2018 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 is just a driver for performance overview tests.
import TestsUtils
import DriverUtils
import Ackermann
import AngryPhonebook
import AnyHashableWithAClass
import Array2D
import ArrayAppend
import ArrayInClass
import ArrayLiteral
import ArrayOfGenericPOD
import ArrayOfGenericRef
import ArrayOfPOD
import ArrayOfRef
import ArraySetElement
import ArraySubscript
import BinaryFloatingPointConversionFromBinaryInteger
import BinaryFloatingPointProperties
import BitCount
import Breadcrumbs
import BucketSort
import ByteSwap
import COWTree
import COWArrayGuaranteedParameterOverhead
import CString
import CSVParsing
import Calculator
import CaptureProp
import ChaCha
import ChainedFilterMap
import CharacterLiteralsLarge
import CharacterLiteralsSmall
import CharacterProperties
import Chars
import ClassArrayGetter
import Codable
import Combos
import DataBenchmarks
import DeadArray
import DictOfArraysToArrayOfDicts
import DictTest
import DictTest2
import DictTest3
import DictTest4
import DictTest4Legacy
import DictionaryBridge
import DictionaryBridgeToObjC
import DictionaryCompactMapValues
import DictionaryCopy
import DictionaryGroup
import DictionaryKeysContains
import DictionaryLiteral
import DictionaryOfAnyHashableStrings
import DictionaryRemove
import DictionarySubscriptDefault
import DictionarySwap
import Diffing
import DiffingMyers
import DropFirst
import DropLast
import DropWhile
import ErrorHandling
import Exclusivity
import ExistentialPerformance
import Fibonacci
import FindStringNaive
import FlattenList
import FloatingPointParsing
import FloatingPointPrinting
import Hanoi
import Hash
import Histogram
import InsertCharacter
import IntegerParsing
import Integrate
import IterateData
import Join
import LazyFilter
import LinkedList
import LuhnAlgoEager
import LuhnAlgoLazy
import MapReduce
import Memset
import MonteCarloE
import MonteCarloPi
import NibbleSort
import NIOChannelPipeline
import NSDictionaryCastToSwift
import NSError
#if os(macOS) || os(iOS) || os(watchOS) || os(tvOS)
import NSStringConversion
#endif
import NopDeinit
import ObjectAllocation
#if os(macOS) || os(iOS) || os(watchOS) || os(tvOS)
import ObjectiveCBridging
import ObjectiveCBridgingStubs
#if !(SWIFT_PACKAGE || Xcode)
import ObjectiveCNoBridgingStubs
#endif
#endif
import ObserverClosure
import ObserverForwarderStruct
import ObserverPartiallyAppliedMethod
import ObserverUnappliedMethod
import OpaqueConsumingUsers
import OpenClose
import Phonebook
import PointerArithmetics
import PolymorphicCalls
import PopFront
import PopFrontGeneric
import Prefix
import PrefixWhile
import Prims
import PrimsNonStrongRef
import PrimsSplit
import ProtocolDispatch
import ProtocolDispatch2
import Queue
import RC4
import RGBHistogram
import Radix2CooleyTukey
import RandomShuffle
import RandomValues
import RangeAssignment
import RangeIteration
import RangeOverlaps
import RangeReplaceableCollectionPlusDefault
import RecursiveOwnedParameter
import ReduceInto
import RemoveWhere
import ReversedCollections
import RomanNumbers
import SequenceAlgos
import SetTests
import SevenBoom
import Sim2DArray
import SortArrayInClass
import SortIntPyramids
import SortLargeExistentials
import SortLettersInPlace
import SortStrings
import StackPromo
import StaticArray
import StrComplexWalk
import StrToInt
import StringBuilder
import StringComparison
import StringEdits
import StringEnum
import StringInterpolation
import StringMatch
import StringRemoveDupes
import StringReplaceSubrange
import StringTests
import StringWalk
import Substring
import Suffix
import SuperChars
import TwoSum
import TypeFlood
import UTF8Decode
import Walsh
import WordCount
import XorLoop
@inline(__always)
private func registerBenchmark(_ bench: BenchmarkInfo) {
registeredBenchmarks.append(bench)
}
@inline(__always)
private func registerBenchmark<
S : Sequence
>(_ infos: S) where S.Element == BenchmarkInfo {
registeredBenchmarks.append(contentsOf: infos)
}
registerBenchmark(Ackermann)
registerBenchmark(AngryPhonebook)
registerBenchmark(AnyHashableWithAClass)
registerBenchmark(Array2D)
registerBenchmark(ArrayAppend)
registerBenchmark(ArrayInClass)
registerBenchmark(ArrayLiteral)
registerBenchmark(ArrayOfGenericPOD)
registerBenchmark(ArrayOfGenericRef)
registerBenchmark(ArrayOfPOD)
registerBenchmark(ArrayOfRef)
registerBenchmark(ArraySetElement)
registerBenchmark(ArraySubscript)
registerBenchmark(BinaryFloatingPointConversionFromBinaryInteger)
registerBenchmark(BinaryFloatingPointPropertiesBinade)
registerBenchmark(BinaryFloatingPointPropertiesNextUp)
registerBenchmark(BinaryFloatingPointPropertiesUlp)
registerBenchmark(BitCount)
registerBenchmark(Breadcrumbs)
registerBenchmark(BucketSort)
registerBenchmark(ByteSwap)
registerBenchmark(COWTree)
registerBenchmark(COWArrayGuaranteedParameterOverhead)
registerBenchmark(CString)
registerBenchmark(CSVParsing)
registerBenchmark(Calculator)
registerBenchmark(CaptureProp)
registerBenchmark(ChaCha)
registerBenchmark(ChainedFilterMap)
registerBenchmark(CharacterLiteralsLarge)
registerBenchmark(CharacterLiteralsSmall)
registerBenchmark(CharacterPropertiesFetch)
registerBenchmark(CharacterPropertiesStashed)
registerBenchmark(CharacterPropertiesStashedMemo)
registerBenchmark(CharacterPropertiesPrecomputed)
registerBenchmark(Chars)
registerBenchmark(Codable)
registerBenchmark(Combos)
registerBenchmark(ClassArrayGetter)
registerBenchmark(DataBenchmarks)
registerBenchmark(DeadArray)
registerBenchmark(DictOfArraysToArrayOfDicts)
registerBenchmark(Dictionary)
registerBenchmark(Dictionary2)
registerBenchmark(Dictionary3)
registerBenchmark(Dictionary4)
registerBenchmark(Dictionary4Legacy)
registerBenchmark(DictionaryBridge)
registerBenchmark(DictionaryBridgeToObjC)
registerBenchmark(DictionaryCompactMapValues)
registerBenchmark(DictionaryCopy)
registerBenchmark(DictionaryGroup)
registerBenchmark(DictionaryKeysContains)
registerBenchmark(DictionaryLiteral)
registerBenchmark(DictionaryOfAnyHashableStrings)
registerBenchmark(DictionaryRemove)
registerBenchmark(DictionarySubscriptDefault)
registerBenchmark(DictionarySwap)
registerBenchmark(Diffing)
registerBenchmark(DiffingMyers)
registerBenchmark(DropFirst)
registerBenchmark(DropLast)
registerBenchmark(DropWhile)
registerBenchmark(ErrorHandling)
registerBenchmark(Exclusivity)
registerBenchmark(ExistentialPerformance)
registerBenchmark(Fibonacci)
registerBenchmark(FindStringNaive)
registerBenchmark(FlattenListLoop)
registerBenchmark(FlattenListFlatMap)
registerBenchmark(FloatingPointParsing)
registerBenchmark(FloatingPointPrinting)
registerBenchmark(Hanoi)
registerBenchmark(HashTest)
registerBenchmark(Histogram)
registerBenchmark(InsertCharacter)
registerBenchmark(IntegerParsing)
registerBenchmark(IntegrateTest)
registerBenchmark(IterateData)
registerBenchmark(Join)
registerBenchmark(LazyFilter)
registerBenchmark(LinkedList)
registerBenchmark(LuhnAlgoEager)
registerBenchmark(LuhnAlgoLazy)
registerBenchmark(MapReduce)
registerBenchmark(Memset)
registerBenchmark(MonteCarloE)
registerBenchmark(MonteCarloPi)
registerBenchmark(NSDictionaryCastToSwift)
registerBenchmark(NSErrorTest)
#if os(macOS) || os(iOS) || os(watchOS) || os(tvOS)
registerBenchmark(NSStringConversion)
#endif
registerBenchmark(NibbleSort)
registerBenchmark(NIOChannelPipeline)
registerBenchmark(NopDeinit)
registerBenchmark(ObjectAllocation)
#if os(macOS) || os(iOS) || os(watchOS) || os(tvOS)
registerBenchmark(ObjectiveCBridging)
registerBenchmark(ObjectiveCBridgingStubs)
#if !(SWIFT_PACKAGE || Xcode)
registerBenchmark(ObjectiveCNoBridgingStubs)
#endif
#endif
registerBenchmark(ObserverClosure)
registerBenchmark(ObserverForwarderStruct)
registerBenchmark(ObserverPartiallyAppliedMethod)
registerBenchmark(ObserverUnappliedMethod)
registerBenchmark(OpaqueConsumingUsers)
registerBenchmark(OpenClose)
registerBenchmark(Phonebook)
registerBenchmark(PointerArithmetics)
registerBenchmark(PolymorphicCalls)
registerBenchmark(PopFront)
registerBenchmark(PopFrontArrayGeneric)
registerBenchmark(Prefix)
registerBenchmark(PrefixWhile)
registerBenchmark(Prims)
registerBenchmark(PrimsNonStrongRef)
registerBenchmark(PrimsSplit)
registerBenchmark(ProtocolDispatch)
registerBenchmark(ProtocolDispatch2)
registerBenchmark(QueueGeneric)
registerBenchmark(QueueConcrete)
registerBenchmark(RC4Test)
registerBenchmark(RGBHistogram)
registerBenchmark(Radix2CooleyTukey)
registerBenchmark(RandomShuffle)
registerBenchmark(RandomValues)
registerBenchmark(RangeAssignment)
registerBenchmark(RangeIteration)
registerBenchmark(RangeOverlaps)
registerBenchmark(RangeReplaceableCollectionPlusDefault)
registerBenchmark(RecursiveOwnedParameter)
registerBenchmark(ReduceInto)
registerBenchmark(RemoveWhere)
registerBenchmark(ReversedCollections)
registerBenchmark(RomanNumbers)
registerBenchmark(SequenceAlgos)
registerBenchmark(SetTests)
registerBenchmark(SevenBoom)
registerBenchmark(Sim2DArray)
registerBenchmark(SortArrayInClass)
registerBenchmark(SortIntPyramids)
registerBenchmark(SortLargeExistentials)
registerBenchmark(SortLettersInPlace)
registerBenchmark(SortStrings)
registerBenchmark(StackPromo)
registerBenchmark(StaticArrayTest)
registerBenchmark(StrComplexWalk)
registerBenchmark(StrToInt)
registerBenchmark(StringBuilder)
registerBenchmark(StringComparison)
registerBenchmark(StringEdits)
registerBenchmark(StringEnum)
registerBenchmark(StringHashing)
registerBenchmark(StringInterpolation)
registerBenchmark(StringInterpolationSmall)
registerBenchmark(StringInterpolationManySmallSegments)
registerBenchmark(StringMatch)
registerBenchmark(StringNormalization)
registerBenchmark(StringRemoveDupes)
registerBenchmark(StringReplaceSubrange)
registerBenchmark(StringTests)
registerBenchmark(StringWalk)
registerBenchmark(SubstringTest)
registerBenchmark(Suffix)
registerBenchmark(SuperChars)
registerBenchmark(TwoSum)
registerBenchmark(TypeFlood)
registerBenchmark(UTF8Decode)
registerBenchmark(Walsh)
registerBenchmark(WordCount)
registerBenchmark(XorLoop)
main()
| 28.330623 | 80 | 0.878611 |
ab5ce7c6e177d4eb0116d8bf52364089cc3f45cb | 14,921 | //
// AdultStudentDetailsTableViewController.swift
// Academia
//
// Created by Kelly Johnson on 9/26/18.
// Copyright © 2018 DunDak, LLC. All rights reserved.
//
import UIKit
class AdultStudentDetailsTableViewController: UITableViewController, SegueFromSaveProfileNibCellDelegate {
// MARK: - Properties
var kidStudent: KidStudent?
var cells: [MyCells]?
// MARK: - ViewController Lifecycle Functions
override func viewWillAppear(_ animated: Bool) {
tableView.estimatedRowHeight = 80
tableView.rowHeight = 80
}
override func viewDidLoad() {
super.viewDidLoad()
self.title = "Adult Student Profile"
}
// MARK: - SegueFromSaveProfileNibCellDelegate protocol method
func callSegueFromNibCell(nibCellData dataobject: AnyObject) {
self.performSegue(withIdentifier: "initialKidStudentSegue", sender: dataobject)
}
// MARK: - Table view data source
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
guard let cells = cells else { return 0 }
return cells.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
// func nibRegistration(nibName: String, forCellReuseIdentifier: String) -> UINib {
// let nib = UINib(nibName: nibName, bundle: nil)
// self.tableView.register(nib, forCellReuseIdentifier: forCellReuseIdentifier)
// return nib
// }
guard let cells = cells else { return UITableViewCell() }
let myCell = cells[indexPath.row]
let avenirFont = [ NSAttributedStringKey.foregroundColor: UIColor.gray,
NSAttributedStringKey.font: UIFont(name: "Avenir-Medium", size: 24)! ]
// register required cell nibs
let nibProfilePic = UINib(nibName: "ProfilePicCell", bundle: nil)
self.tableView.register(nibProfilePic, forCellReuseIdentifier: "profilePicCell")
let nibKidsBelt = UINib(nibName: "KidsBeltTemplate", bundle: nil)
self.tableView.register(nibKidsBelt, forCellReuseIdentifier: "kidsBeltTemplate")
let nibStatus = UINib(nibName: "StatusCell", bundle: nil)
self.tableView.register(nibStatus, forCellReuseIdentifier: "statusCell")
let nibUsername = UINib(nibName: "UsernameTextFieldCell", bundle: nil)
self.tableView.register(nibUsername, forCellReuseIdentifier: "usernameTextFieldCell")
let nibFirstName = UINib(nibName: "FirstNameTextFieldCell", bundle: nil)
self.tableView.register(nibFirstName, forCellReuseIdentifier: "firstNameTextFieldCell")
let nibLastName = UINib(nibName: "LastNameTextFieldCell", bundle: nil)
self.tableView.register(nibLastName, forCellReuseIdentifier: "lastNameTextFieldCell")
let nibParentGuardian = UINib(nibName: "ParentGuardianTextFieldCell", bundle: nil)
self.tableView.register(nibParentGuardian, forCellReuseIdentifier: "parentGuardianTextFieldCell")
let nibStreetAddress = UINib(nibName: "StreetAddressTextFieldCell", bundle: nil)
self.tableView.register(nibStreetAddress, forCellReuseIdentifier: "streetAddressTextFieldCell")
let nibCity = UINib(nibName: "CityTextFieldCell", bundle: nil)
self.tableView.register(nibCity, forCellReuseIdentifier: "cityTextFieldCell")
let nibState = UINib(nibName: "StateTextFieldCell", bundle: nil)
self.tableView.register(nibState, forCellReuseIdentifier: "stateTextFieldCell")
let nibZipCode = UINib(nibName: "ZipCodeTextFieldCell", bundle: nil)
self.tableView.register(nibZipCode, forCellReuseIdentifier: "zipCodeTextFieldCell")
let nibPhone = UINib(nibName: "PhoneTextFieldCell", bundle: nil)
self.tableView.register(nibPhone, forCellReuseIdentifier: "phoneTextFieldCell")
let nibMobile = UINib(nibName: "MobileTextFieldCell", bundle: nil)
self.tableView.register(nibMobile, forCellReuseIdentifier: "mobileTextFieldCell")
let nibEmail = UINib(nibName: "EmailTextFieldCell", bundle: nil)
self.tableView.register(nibEmail, forCellReuseIdentifier: "emailTextFieldCell")
let nibEmergencyContact = UINib(nibName: "EmergencyContactTextFieldCell", bundle: nil)
self.tableView.register(nibEmergencyContact, forCellReuseIdentifier: "emergencyContactTextFieldCell")
let nibEmergencyContactPhone = UINib(nibName: "EmergencyContactPhoneTextFieldCell", bundle: nil)
self.tableView.register(nibEmergencyContactPhone, forCellReuseIdentifier: "emergencyContactPhoneTextFieldCell")
let nibEmergencyContactRelationship = UINib(nibName: "EmergencyContactRelationshipTextFieldCell", bundle: nil)
self.tableView.register(nibEmergencyContactRelationship, forCellReuseIdentifier: "emergencyContactRelationshipTextFieldCell")
let nibSaveProfile = UINib(nibName: "SaveProfileCell", bundle: nil)
self.tableView.register(nibSaveProfile, forCellReuseIdentifier: "saveProfileCell")
// switch on myCell to setup the tableView
switch myCell {
// use "where" clause to determine distinction between between adult and kid students?
case .beltCell:
if let cell = tableView.dequeueReusableCell(withIdentifier: "kidsBeltTemplate", for: indexPath) as? KidsBeltTableViewCell {
tableView.estimatedRowHeight = 100
tableView.rowHeight = 100
return cell
}
case .cityCell:
if let cell = tableView.dequeueReusableCell(withIdentifier: "cityTextFieldCell", for: indexPath) as? CityTextFieldTableViewCell {
cell.cityTextFieldOutlet.attributedPlaceholder = NSAttributedString(string: "\(myCell.rawValue)", attributes: avenirFont)
tableView.estimatedRowHeight = 80
tableView.rowHeight = 80
return cell
}
case .emailCell:
if let cell = tableView.dequeueReusableCell(withIdentifier: "emailTextFieldCell", for: indexPath) as? EmailTextFieldTableViewCell {
cell.emailTextFieldOutlet.attributedPlaceholder = NSAttributedString(string: "\(myCell.rawValue)", attributes: avenirFont)
tableView.estimatedRowHeight = 80
tableView.rowHeight = 80
return cell
}
case .emergencyContactCell:
if let cell = tableView.dequeueReusableCell(withIdentifier: "emergencyContactTextFieldCell", for: indexPath) as? EmergencyContactTextFieldTableViewCell {
cell.emergencyContactTextFieldOutlet.attributedPlaceholder = NSAttributedString(string: "\(myCell.rawValue)", attributes: avenirFont)
tableView.estimatedRowHeight = 80
tableView.rowHeight = 80
return cell
}
case .emergencyContactPhoneCell:
if let cell = tableView.dequeueReusableCell(withIdentifier: "emergencyContactPhoneTextFieldCell", for: indexPath) as? EmergencyContactPhoneTextFieldTableViewCell {
cell.emergencyContactPhoneTextFieldOutlet.attributedPlaceholder = NSAttributedString(string: "\(myCell.rawValue)", attributes: avenirFont)
tableView.estimatedRowHeight = 80
tableView.rowHeight = 80
return cell
}
case .emergencyContactRelationshipCell:
if let cell = tableView.dequeueReusableCell(withIdentifier: "emergencyContactRelationshipTextFieldCell", for: indexPath) as? EmergencyContactRelationshipTextFieldTableViewCell {
cell.emergencyContactRelationshipTextFieldOutlet.attributedPlaceholder = NSAttributedString(string: "\(myCell.rawValue)", attributes: avenirFont)
tableView.estimatedRowHeight = 80
tableView.rowHeight = 80
return cell
}
case .firstNameCell:
if let cell = tableView.dequeueReusableCell(withIdentifier: "firstNameTextFieldCell", for: indexPath) as? FirstNameTextFieldTableViewCell {
cell.firstNameTextFieldOutlet.attributedPlaceholder = NSAttributedString(string: "\(myCell.rawValue)", attributes: avenirFont)
tableView.estimatedRowHeight = 80
tableView.rowHeight = 80
return cell
}
case .lastNameCell:
if let cell = tableView.dequeueReusableCell(withIdentifier: "lastNameTextFieldCell", for: indexPath) as? LastNameTextFieldTableViewCell {
cell.lastNameTextFieldOutlet.attributedPlaceholder = NSAttributedString(string: "\(myCell.rawValue)", attributes: avenirFont)
tableView.estimatedRowHeight = 80
tableView.rowHeight = 80
return cell
}
case .mobileCell:
if let cell = tableView.dequeueReusableCell(withIdentifier: "mobileTextFieldCell", for: indexPath) as? MobileTextFieldTableViewCell {
cell.mobileTextFieldOutlet.attributedPlaceholder = NSAttributedString(string: "\(myCell.rawValue)", attributes: avenirFont)
tableView.estimatedRowHeight = 80
tableView.rowHeight = 80
return cell
}
case .parentGuardianCell:
if let cell = tableView.dequeueReusableCell(withIdentifier: "parentGuardianTextFieldCell", for: indexPath) as? ParentGuardianTextFieldTableViewCell {
cell.parentGuardianTextFieldOutlet.attributedPlaceholder = NSAttributedString(string: "\(myCell.rawValue)", attributes: avenirFont)
tableView.estimatedRowHeight = 80
tableView.rowHeight = 80
return cell
}
case .phoneCell:
if let cell = tableView.dequeueReusableCell(withIdentifier: "phoneTextFieldCell", for: indexPath) as? PhoneTextFieldTableViewCell {
cell.phoneTextFieldOutlet.attributedPlaceholder = NSAttributedString(string: "\(myCell.rawValue)", attributes: avenirFont)
tableView.estimatedRowHeight = 80
tableView.rowHeight = 80
return cell
}
case .profilePicCell:
if let cell = tableView.dequeueReusableCell(withIdentifier: "profilePicCell", for: indexPath) as? ProfilePicTableViewCell {
tableView.estimatedRowHeight = 200
tableView.rowHeight = 200
return cell
}
case .saveProfileButtonCell:
if let cell = tableView.dequeueReusableCell(withIdentifier: "saveProfileCell", for: indexPath) as? SaveProfileTableViewCell {
cell.delegate = self
tableView.estimatedRowHeight = 80
tableView.rowHeight = 80
return cell
}
case .stateCell:
if let cell = tableView.dequeueReusableCell(withIdentifier: "stateTextFieldCell", for: indexPath) as? StateTextFieldTableViewCell {
cell.stateTextFieldOutlet.attributedPlaceholder = NSAttributedString(string: "\(myCell.rawValue)", attributes: avenirFont)
tableView.estimatedRowHeight = 80
tableView.rowHeight = 80
return cell
}
case .statusCell:
if let cell = tableView.dequeueReusableCell(withIdentifier: "statusCell", for: indexPath) as? StatusTableViewCell {
cell.detailLabelOutlet.text = "PAID - 06/15/2018" // eventually will be date of last successful payment from payment program object
tableView.estimatedRowHeight = 80
tableView.rowHeight = 80
return cell
}
case .streetAddressCell:
if let cell = tableView.dequeueReusableCell(withIdentifier: "streetAddressTextFieldCell", for: indexPath) as? StreetAddressTextFieldTableViewCell {
cell.streetAddressTextFieldOutlet.attributedPlaceholder = NSAttributedString(string: "\(myCell.rawValue)", attributes: avenirFont)
tableView.estimatedRowHeight = 80
tableView.rowHeight = 80
return cell
}
case .usernameCell:
if let cell = tableView.dequeueReusableCell(withIdentifier: "usernameTextFieldCell", for: indexPath) as? UsernameTextFieldTableViewCell {
cell.usernameTextFieldOutlet.attributedPlaceholder = NSAttributedString(string: "\(myCell.rawValue)", attributes: avenirFont)
tableView.estimatedRowHeight = 80
tableView.rowHeight = 80
return cell
}
case .zipCodeCell:
if let cell = tableView.dequeueReusableCell(withIdentifier: "zipCodeTextFieldCell", for: indexPath) as? ZipCodeTextFieldTableViewCell {
cell.zipCodeTextFieldOutlet.attributedPlaceholder = NSAttributedString(string: "\(myCell.rawValue)", attributes: avenirFont)
tableView.estimatedRowHeight = 80
tableView.rowHeight = 80
return cell
}
default: print("\(myCell.rawValue) is not supposeed to be in the owner onboarding workflow, or if is valid, the switch statement in OwnerProfileDetailsTableViewController needs to be updated.")
return UITableViewCell()
}
return UITableViewCell()
}
/*
// 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.
}
*/
}
| 47.670927 | 201 | 0.630923 |
8fb7f4d71574099bf4e3f32aa9cabeb9d875dd0c | 10,770 | //
// SunlightTests.swift
// SunlightTests
//
// Created by Ameir Al-Zoubi on 4/29/20.
// Copyright © 2020 Ameir Al-Zoubi. All rights reserved.
//
import XCTest
@testable import Sunlight
class SunlightTests: XCTestCase {
func date(year: Int, month: Int, day: Int, hours: Double = 0) -> DateComponents {
var cal = Calendar(identifier: Calendar.Identifier.gregorian)
cal.timeZone = TimeZone(identifier: "UTC")!
var comps = DateComponents()
comps.calendar = cal
comps.year = year
comps.month = month
comps.day = day
comps.hour = Int(hours)
comps.minute = Int((hours - floor(hours)) * 60)
return comps
}
func testSolarPosition() {
// values from Astronomical Algorithms page 165
var jd = Astronomical.julianDay(year: 1992, month: 10, day: 13)
var solar = SolarPosition(julianDay: jd)
var T = Astronomical.julianCentury(julianDay: jd)
var L0 = Astronomical.meanSolarLongitude(julianCentury: T)
var ε0 = Astronomical.meanObliquityOfTheEcliptic(julianCentury: T)
let εapp = Astronomical.apparentObliquityOfTheEcliptic(julianCentury: T, meanObliquityOfTheEcliptic: ε0)
let M = Astronomical.meanSolarAnomaly(julianCentury: T)
let C = Astronomical.solarEquationOfTheCenter(julianCentury: T, meanAnomaly: M)
let λ = Astronomical.apparentSolarLongitude(julianCentury: T, meanLongitude: L0)
let δ = solar.declination
let α = solar.rightAscension.unwound()
XCTAssertEqual(T, -0.072183436,
accuracy: 0.00000000001)
XCTAssertEqual(L0.degrees, 201.80720,
accuracy: 0.00001)
XCTAssertEqual(ε0.degrees, 23.44023,
accuracy: 0.00001)
XCTAssertEqual(εapp.degrees, 23.43999,
accuracy: 0.00001)
XCTAssertEqual(M.degrees, 278.99397,
accuracy: 0.00001)
XCTAssertEqual(C.degrees, -1.89732,
accuracy: 0.00001)
// lower accuracy than desired
XCTAssertEqual(λ.degrees, 199.90895,
accuracy: 0.00002)
XCTAssertEqual(δ.degrees, -7.78507,
accuracy: 0.00001)
XCTAssertEqual(α.degrees, 198.38083,
accuracy: 0.00001)
// values from Astronomical Algorithms page 88
jd = Astronomical.julianDay(year: 1987, month: 4, day: 10)
solar = SolarPosition(julianDay: jd)
T = Astronomical.julianCentury(julianDay: jd)
let θ0 = Astronomical.meanSiderealTime(julianCentury: T)
let θapp = solar.apparentSiderealTime
let Ω = Astronomical.ascendingLunarNodeLongitude(julianCentury: T)
ε0 = Astronomical.meanObliquityOfTheEcliptic(julianCentury: T)
L0 = Astronomical.meanSolarLongitude(julianCentury: T)
let Lp = Astronomical.meanLunarLongitude(julianCentury: T)
let ΔΨ = Astronomical.nutationInLongitude(solarLongitude: L0, lunarLongitude: Lp, ascendingNode: Ω)
let Δε = Astronomical.nutationInObliquity(solarLongitude: L0, lunarLongitude: Lp, ascendingNode: Ω)
let ε = Angle(ε0.degrees + Δε)
XCTAssertEqual(θ0.degrees, 197.693195,
accuracy: 0.000001)
XCTAssertEqual(θapp.degrees, 197.6922295833,
accuracy: 0.0001)
// values from Astronomical Algorithms page 148
XCTAssertEqual(Ω.degrees, 11.2531,
accuracy: 0.0001)
XCTAssertEqual(ΔΨ, -0.0010522,
accuracy: 0.0001)
XCTAssertEqual(Δε, 0.0026230556,
accuracy: 0.00001)
XCTAssertEqual(ε0.degrees, 23.4409463889,
accuracy: 0.000001)
XCTAssertEqual(ε.degrees, 23.4435694444,
accuracy: 0.00001)
}
func testAltitudeOfCelestialBody() {
let φ: Angle = 38 + (55 / 60) + (17.0 / 3600)
let δ: Angle = -6 - (43 / 60) - (11.61 / 3600)
let H: Angle = 64.352133
let h = Astronomical.altitudeOfCelestialBody(observerLatitude: φ, declination: δ, localHourAngle: H)
XCTAssertEqual(h.degrees, 15.1249,
accuracy: 0.0001)
}
func testTransitAndHourAngle() {
// values from Astronomical Algorithms page 103
let longitude: Angle = -71.0833
let Θ: Angle = 177.74208
let α1: Angle = 40.68021
let α2: Angle = 41.73129
let α3: Angle = 42.78204
let m0 = Astronomical.approximateTransit(longitude: longitude, siderealTime: Θ, rightAscension: α2)
XCTAssertEqual(m0, 0.81965,
accuracy: 0.00001)
let transit = Astronomical.correctedTransit(approximateTransit: m0, longitude: longitude, siderealTime: Θ, rightAscension: α2, previousRightAscension: α1, nextRightAscension: α3) / 24
XCTAssertEqual(transit, 0.81980,
accuracy: 0.00001)
let δ1: Angle = 18.04761
let δ2: Angle = 18.44092
let δ3: Angle = 18.82742
let rise = Astronomical.correctedHourAngle(approximateTransit: m0, angle: -0.5667, coordinates: Coordinates(latitude: 42.3333, longitude: longitude.degrees), afterTransit: false, siderealTime: Θ,
rightAscension: α2, previousRightAscension: α1, nextRightAscension: α3, declination: δ2, previousDeclination: δ1, nextDeclination: δ3) / 24
XCTAssertEqual(rise, 0.51766,
accuracy: 0.00001)
}
func testSolarTime() {
/*
Comparison values generated from http://aa.usno.navy.mil/rstt/onedaytable?form=1&ID=AA&year=2015&month=7&day=12&state=NC&place=raleigh
*/
let coordinates = Coordinates(latitude: 35 + 47/60, longitude: -78 - 39/60)
let solar = SolarDate(coordinates: coordinates, date: date(year: 2015, month: 7, day: 12, hours: 0))!
let formatter = DateFormatter()
formatter.timeZone = TimeZone(identifier: "America/New_York")
formatter.dateStyle = .short
formatter.timeStyle = .long
let transit = solar.solarNoon
let sunrise = solar.sunrise
let sunset = solar.sunset
let twilightStart = solar.timeForSolarAngle(-6, afterTransit: false)!
let twilightEnd = solar.timeForSolarAngle(-6, afterTransit: true)!
let invalid = solar.timeForSolarAngle(-36, afterTransit: true)
XCTAssertEqual(formatter.string(from: twilightStart), "7/12/15, 5:38:21 AM EDT")
XCTAssertEqual(formatter.string(from: sunrise), "7/12/15, 6:07:54 AM EDT")
XCTAssertEqual(formatter.string(from: transit), "7/12/15, 1:20:14 PM EDT")
XCTAssertEqual(formatter.string(from: sunset), "7/12/15, 8:32:16 PM EDT")
XCTAssertEqual(formatter.string(from: twilightEnd), "7/12/15, 9:01:45 PM EDT")
XCTAssertNil(invalid)
}
func testCalendricalDate() {
// generated from http://aa.usno.navy.mil/data/docs/RS_OneYear.php for KUKUIHAELE, HAWAII
let coordinates = Coordinates(latitude: 20 + 7/60, longitude: -155 - 34/60)
let day1solar = SolarDate(coordinates: coordinates, date: date(year: 2015, month: 4, day: 2, hours: 0))!
let day2solar = SolarDate(coordinates: coordinates, date: date(year: 2015, month: 4, day: 3, hours: 0))!
let day1 = day1solar.sunrise
let day2 = day2solar.sunrise
let formatter = DateFormatter()
formatter.timeZone = TimeZone(identifier: "Pacific/Honolulu")
formatter.dateStyle = .short
formatter.timeStyle = .long
XCTAssertEqual(formatter.string(from: day1), "4/2/15, 6:14:59 AM HST")
XCTAssertEqual(formatter.string(from: day2), "4/3/15, 6:14:08 AM HST")
}
func testInterpolation() {
// values from Astronomical Algorithms page 25
let interpolatedValue = Astronomical.interpolate(value: 0.877366, previousValue: 0.884226, nextValue: 0.870531, factor: 4.35/24)
XCTAssertEqual(interpolatedValue, 0.876125,
accuracy: 0.000001)
let i1 = Astronomical.interpolate(value: 1, previousValue: -1, nextValue: 3, factor: 0.6)
XCTAssertEqual(i1, 2.2, accuracy: 0.000001)
}
func testAngleInterpolation() {
let i1 = Astronomical.interpolateAngles(value: 1, previousValue: -1, nextValue: 3, factor: 0.6)
XCTAssertEqual(i1.degrees, 2.2, accuracy: 0.000001)
let i2 = Astronomical.interpolateAngles(value: 1, previousValue: 359, nextValue: 3, factor: 0.6)
XCTAssertEqual(i2.degrees, 2.2, accuracy: 0.000001)
}
func testJulianDay() {
/*
Comparison values generated from http://aa.usno.navy.mil/data/docs/JulianDate.php
*/
XCTAssertEqual(Astronomical.julianDay(year: 2010, month: 1, day: 2), 2455198.500000)
XCTAssertEqual(Astronomical.julianDay(year: 2011, month: 2, day: 4), 2455596.500000)
XCTAssertEqual(Astronomical.julianDay(year: 2012, month: 3, day: 6), 2455992.500000)
XCTAssertEqual(Astronomical.julianDay(year: 2013, month: 4, day: 8), 2456390.500000)
XCTAssertEqual(Astronomical.julianDay(year: 2014, month: 5, day: 10), 2456787.500000)
XCTAssertEqual(Astronomical.julianDay(year: 2015, month: 6, day: 12), 2457185.500000)
XCTAssertEqual(Astronomical.julianDay(year: 2016, month: 7, day: 14), 2457583.500000)
XCTAssertEqual(Astronomical.julianDay(year: 2017, month: 8, day: 16), 2457981.500000)
XCTAssertEqual(Astronomical.julianDay(year: 2018, month: 9, day: 18), 2458379.500000)
XCTAssertEqual(Astronomical.julianDay(year: 2019, month: 10, day: 20), 2458776.500000)
XCTAssertEqual(Astronomical.julianDay(year: 2020, month: 11, day: 22), 2459175.500000)
XCTAssertEqual(Astronomical.julianDay(year: 2021, month: 12, day: 24), 2459572.500000)
let jdVal = 2457215.67708333
XCTAssertEqual(Astronomical.julianDay(year: 2015, month: 7, day: 12, hours: 4.25), jdVal, accuracy: 0.000001)
var components = DateComponents()
components.year = 2015
components.month = 7
components.day = 12
components.hour = 4
components.minute = 15
XCTAssertEqual(Astronomical.julianDay(dateComponents: components), jdVal, accuracy: 0.000001)
XCTAssertEqual(Astronomical.julianDay(year: 2015, month: 7, day: 12, hours: 8.0), 2457215.833333, accuracy: 0.000001)
XCTAssertEqual(Astronomical.julianDay(year: 1992, month: 10, day: 13, hours: 0.0), 2448908.5, accuracy: 0.000001)
XCTAssertEqual(Astronomical.julianDay(dateComponents: DateComponents()), 1721425.5, accuracy: 0.000001)
}
func testJulianHours() {
let j1 = Astronomical.julianDay(year: 2010, month: 1, day: 3)
let j2 = Astronomical.julianDay(year: 2010, month: 1, day: 1, hours: 48)
XCTAssertEqual(j1, j2)
}
}
| 42.401575 | 203 | 0.656825 |
2023927f600620bac496ea592b448291f46d978c | 2,602 | /*
Copyright (C) 2015 Apple Inc. All Rights Reserved.
See LICENSE.txt for this sample’s licensing information
Abstract:
This file shows an example of implementing the OperationCondition protocol.
*/
import EventKit
/// A condition for verifying access to the user's calendar.
struct CalendarCondition: OperationCondition {
static let name = "Calendar"
static let entityTypeKey = "EKEntityType"
static let isMutuallyExclusive = false
let entityType: EKEntityType
init(entityType: EKEntityType) {
self.entityType = entityType
}
func dependencyForOperation(operation: EQOperation) -> Operation? {
return CalendarPermissionOperation(entityType: entityType)
}
func evaluateForOperation(operation: EQOperation, completion: (OperationConditionResult) -> Void) {
switch EKEventStore.authorizationStatus(for: entityType) {
case .authorized:
completion(.Satisfied)
default:
// We are not authorized to access entities of this type.
let error = NSError(code: .ConditionFailed, userInfo: [
OperationConditionKey: type(of: self).name,
type(of: self).entityTypeKey: entityType.rawValue
])
completion(.Failed(error))
}
}
}
/**
`EKEventStore` takes a while to initialize, so we should create
one and then keep it around for future use, instead of creating
a new one every time a `CalendarPermissionOperation` runs.
*/
private let SharedEventStore = EKEventStore()
/**
A private `Operation` that will request access to the user's Calendar/Reminders,
if it has not already been granted.
*/
private class CalendarPermissionOperation: EQOperation {
let entityType: EKEntityType
init(entityType: EKEntityType) {
self.entityType = entityType
super.init()
addCondition(condition: AlertPresentation())
}
override func execute() {
let status = EKEventStore.authorizationStatus(for: entityType)
switch status {
case .notDetermined:
DispatchQueue.global(qos: .background).async {
// Background Thread
DispatchQueue.main.async {
// Run UI Updates
SharedEventStore.requestAccess(to: self.entityType) { granted, error in
self.finish()
}
}
}
default:
finish()
}
}
}
| 29.568182 | 103 | 0.61837 |
083cc3bc05b5138aeccb182aa5a6b2deb13911fb | 1,760 | //
// Int+FileSize.swift
// Video Player
//
// Created by Venj Chu on 15/11/2.
// Copyright © 2015年 Home. All rights reserved.
//
import Foundation
public extension Int {
var gb: Int {
return self * 1073741824 // 1024 x 1024 x 1024
}
var mb: Int {
return self * 1048576 // 1024 x 1024
}
var kb: Int {
return self * 1024
}
var fileSizeString: String {
var str = ""
if self > 1.gb {
str = String(format: "%.1f GB", arguments: [Double(self) / Double(1.gb)])
}
else if self > 1.mb {
str = String(format: "%.1f MB", arguments: [Double(self) / Double(1.mb)])
}
else if self > 1.kb {
str = String(format: "%.1f KB", arguments: [Double(self) / Double(1.kb)])
}
else {
str = String(format: "%.1f B", arguments: [Double(self)])
}
return str
}
}
public extension CLongLong {
var gb: CLongLong {
return self * 1073741824 // 1024 x 1024 x 1024
}
var mb: CLongLong {
return self * 1048576 // 1024 x 1024
}
var kb: CLongLong {
return self * 1024
}
var fileSizeString: String {
var str = ""
if self > CLongLong(1.gb) {
str = String(format: "%.1f GB", arguments: [Double(self) / Double(1.gb)])
}
else if self > CLongLong(1.mb) {
str = String(format: "%.1f MB", arguments: [Double(self) / Double(1.mb)])
}
else if self > CLongLong(1.kb) {
str = String(format: "%.1f KB", arguments: [Double(self) / Double(1.kb)])
}
else {
str = String(format: "%.1f B", arguments: [Double(self)])
}
return str
}
}
| 24.444444 | 85 | 0.507955 |
ff900bf61889220d1453831d69b02b7dcbb24415 | 782 | //
// UInt8Extensions.swift
// EditorDebuggingFeature
//
// Created by Hoon H. on 2015/01/19.
// Copyright (c) 2015 Eonil. All rights reserved.
//
import Foundation
/// UInt8 value `0xFE` becomes SingleByteHex `(0x0F, 0x0E)`.
typealias SingleByteHex = (UTF8.CodeUnit, UTF8.CodeUnit)
extension UInt8 {
init(lowercaseHex: SingleByteHex) {
func fromASCII(u:U8U) -> UInt8 {
return u < U8U("a") ? u - U8U("0") : u - U8U("a")
}
let a = fromASCII(lowercaseHex.0)
let b = fromASCII(lowercaseHex.1)
self = (a + 0x0F) + b
}
func toLowercaseHex() -> SingleByteHex {
func toASCIIChar(u:UInt8) -> U8U {
return u > 9 ? u + U8U("a") : u + U8U("0")
}
let a = 0xF0 & self - 0x0F
let b = 0x0F & self
return (toASCIIChar(a), toASCIIChar(b))
}
}
| 18.186047 | 60 | 0.620205 |
fb42a66abca1b0a8afaed64cd1d55b62e1e53513 | 468 | import UIKit
protocol AccessibilityInitializing { }
extension UIView: AccessibilityInitializing { }
extension AccessibilityInitializing where Self: UIView {
init<T: RawRepresentable>(_ accessibilityIdentifier: T, configureBlock: ((Self) -> ())? = nil) where T.RawValue == String {
self = Self.init()
self.accessibilityIdentifier = accessibilityIdentifier.rawValue
self.isAccessibilityElement = true
configureBlock?(self)
}
}
| 31.2 | 127 | 0.722222 |
e992d2e8d5a99b646b6adf4f4d65a9d922de5acd | 2,213 | /// Copyright (c) 2019 Razeware 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.
///
/// Notwithstanding the foregoing, you may not use, copy, modify, merge, publish,
/// distribute, sublicense, create a derivative work, and/or sell copies of the
/// Software in any work that is designed, intended, or marketed for pedagogical or
/// instructional purposes related to programming, coding, application development,
/// or information technology. Permission for such use, copying, modification,
/// merger, publication, distribution, sublicensing, creation of derivative works,
/// or sale is expressly withheld.
///
/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
/// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
/// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
/// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
/// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
/// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
/// THE SOFTWARE.
import UIKit
class ErrorPresenter {
static func showError(message: String, on viewController: UIViewController?, dismissAction: ((UIAlertAction) -> Void)? = nil) {
weak var vc = viewController
DispatchQueue.main.async {
let alert = UIAlertController(title: "Error",
message: message,
preferredStyle: .alert)
alert.addAction(UIAlertAction(title: "Dismiss", style: .default, handler: dismissAction))
vc?.present(alert, animated: true)
}
}
}
| 50.295455 | 129 | 0.721645 |
1d42a65fd9f990ac9bd5b5ab9136c61801043760 | 1,213 | import Gloss
import Foundation
import CoreGraphics
struct Image: Imageable, ImageURLThumbnailable, GeminiThumbnailable {
let id: String
let imageFormatString: String
let imageVersions: [String]
let imageSize: CGSize
let aspectRatio: CGFloat?
let geminiToken: String?
let isDefault: Bool
func bestThumbnailWithHeight(height:CGFloat) -> NSURL? {
if let url = geminiThumbnailURLWithHeight(Int(height)) {
return url
}
return bestAvailableThumbnailURL()
}
}
extension Image: Decodable {
init?(json: JSON) {
guard
let idValue: String = "id" <~~ json,
let imageFormatStringValue: String = "image_url" <~~ json,
let imageVersionsValue: [String] = "image_versions" <~~ json
else {
return nil
}
id = idValue
imageFormatString = imageFormatStringValue
imageVersions = imageVersionsValue
geminiToken = "gemini_token" <~~ json
imageSize = CGSize(width: "original_width" <~~ json ?? 1, height: "original_height" <~~ json ?? 1)
aspectRatio = "aspect_ratio" <~~ json
isDefault = "is_default" <~~ json ?? false
}
} | 28.209302 | 106 | 0.625721 |
757d3b21df2485be4764083a1ae7e6a80d1a89a8 | 1,240 | //
// tipHelperUITests.swift
// tipHelperUITests
//
// Created by Ming Lei on 9/7/18.
// Copyright © 2018 Ming Lei. All rights reserved.
//
import XCTest
class tipHelperUITests: XCTestCase {
override func setUp() {
super.setUp()
// Put setup code here. This method is called before the invocation of each test method in the class.
// In UI tests it is usually best to stop immediately when a failure occurs.
continueAfterFailure = false
// UI tests must launch the application that they test. Doing this in setup will make sure it happens for each test method.
XCUIApplication().launch()
// In UI tests it’s important to set the initial state - such as interface orientation - required for your tests before they run. The setUp method is a good place to do this.
}
override func tearDown() {
// Put teardown code here. This method is called after the invocation of each test method in the class.
super.tearDown()
}
func testExample() {
// Use recording to get started writing UI tests.
// Use XCTAssert and related functions to verify your tests produce the correct results.
}
}
| 33.513514 | 182 | 0.66129 |
91a1667a148c983772e5efdb20be662090781b24 | 1,225 | //
// once.swift
// RxSwiftExt
//
// Created by Florent Pillet on 12/04/16.
// Copyright (c) 2016 RxSwiftCommunity https://github.com/RxSwiftCommunity
//
import Foundation
import RxSwift
extension Observable {
/**
Returns an observable sequence that contains a single element. This element will be delivered to the first observer
that subscribes. Further subscriptions to the same observable will get an empty sequence.
In most cases, you want to use `Observable.just()`. This one is really for specific cases where you need to guarantee
unique delivery of a value.
- seealso: [just operator on reactivex.io](http://reactivex.io/documentation/operators/just.html)
- parameter element: Single element in the resulting observable sequence.
- returns: An observable sequence containing the single specified element delivered once.
*/
@warn_unused_result(message="http://git.io/rxs.uo")
public static func once(element: E) -> Observable<E> {
var delivered : UInt32 = 0
return create { observer in
let wasDelivered = OSAtomicOr32OrigBarrier(1, &delivered)
if wasDelivered == 0 {
observer.onNext(element)
}
observer.onCompleted()
return NopDisposable.instance
}
}
}
| 29.878049 | 119 | 0.737959 |
ddb0f1c7c7cf46482d14808693f81f1b885030da | 2,718 | //
// main.swift
// PythonTool
//
// Created by Pedro José Pereira Vieito on 29/1/18.
// Copyright © 2018 Pedro José Pereira Vieito. All rights reserved.
//
import Foundation
import LoggerKit
import CommandLineKit
import PythonKit
let listOption = BoolOption(shortFlag: "l", longFlag: "list", helpMessage: "List installed modules.")
let pathOption = BoolOption(shortFlag: "p", longFlag: "path", helpMessage: "List Python paths.")
let verboseOption = BoolOption(shortFlag: "v", longFlag: "verbose", helpMessage: "Verbose mode.")
let helpOption = BoolOption(shortFlag: "h", longFlag: "help", helpMessage: "Prints a help message.")
let cli = CommandLineKit.CommandLine()
cli.addOptions(listOption, pathOption, verboseOption, helpOption)
do {
try cli.parse(strict: true)
}
catch {
cli.printUsage(error)
exit(EX_USAGE)
}
if helpOption.value {
cli.printUsage()
exit(-1)
}
Logger.logMode = .commandLine
Logger.logLevel = verboseOption.value ? .debug : .info
do {
let pythonVersion = OperatingSystemVersion(
majorVersion: Int(Python.versionInfo.major) ?? 0,
minorVersion: Int(Python.versionInfo.minor) ?? 0,
patchVersion: Int(Python.versionInfo.micro) ?? 0
)
Logger.log(important: "Python \(pythonVersion.shortVersion)")
Logger.log(info: "Version: \(pythonVersion)")
Logger.log(verbose: "Version String: \(Python.version.splitlines()[0])")
let sys = try Python.attemptImport("sys")
Logger.log(verbose: "Executable: \(sys.executable)")
Logger.log(verbose: "Executable Prefix: \(sys.exec_prefix)")
if pathOption.value {
Logger.log(important: "Python Paths (\(sys.path.count))")
if !sys.path.isEmpty {
for searchPath in sys.path {
Logger.log(success: searchPath)
}
}
else {
Logger.log(warning: "No paths available.")
}
}
if listOption.value {
let pkg_resources = try Python.attemptImport("pkg_resources")
let installedModules = Dictionary<String, PythonObject>(pkg_resources.working_set.by_key)!
Logger.log(important: "Python Modules (\(installedModules.count))")
if !installedModules.isEmpty {
let installedModulesArray = installedModules.sorted { $0.key.lowercased() < $1.key.lowercased() }
for (_, moduleReference) in installedModulesArray {
Logger.log(success: "\(moduleReference.key) (\(moduleReference.version))")
}
}
else {
Logger.log(warning: "No modules available.")
}
}
}
catch {
Logger.log(fatalError: error)
}
| 29.868132 | 109 | 0.639441 |
64c5e5a932a5ef48f7149eff9145e58218135e5c | 3,829 | //
// BaseQuestionsSlidingViewController.swift
// ios-app
//
// Copyright © 2017 Testpress. All rights reserved.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
import UIKit
import SlideMenuControllerSwift
protocol SlidingMenuDelegate {
func dismissViewController()
}
protocol QuestionsSlidingMenuDelegate {
func displayQuestions(currentQuestionIndex: Int)
func updateQuestions(_ attemptItems: [AttemptItem])
}
class BaseQuestionsSlidingViewController: SlideMenuController {
@IBOutlet weak var navigationBarItem: UINavigationItem!
var exam: Exam!
var attempt: Attempt!
var courseContent: Content!
var contentAttempt: ContentAttempt!
var slidingMenuDelegate: SlidingMenuDelegate!
var questionsSlidingMenuDelegate: QuestionsSlidingMenuDelegate!
var panelOpened: Bool = false
override func awakeFromNib() {
let mainViewController = self.mainViewController as! BaseQuestionsPageViewController
let leftViewController = self.leftViewController as! BaseQuestionsListViewController
leftViewController.delegate = mainViewController
questionsSlidingMenuDelegate = leftViewController
delegate = self
SlideMenuOptions.contentViewScale = 1.0
SlideMenuOptions.hideStatusBar = false
SlideMenuOptions.panGesturesEnabled = false
SlideMenuOptions.leftViewWidth = self.view.frame.size.width
super.awakeFromNib()
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
let questionsPageViewController = mainViewController as! BaseQuestionsPageViewController
questionsPageViewController.attempt = attempt
questionsPageViewController.exam = exam
questionsPageViewController.courseContent = courseContent
questionsPageViewController.contentAttempt = contentAttempt
questionsPageViewController.parentviewController = self
}
@IBAction func onPressBackButton() {
if panelOpened {
slideMenuController()?.closeLeft()
} else {
slidingMenuDelegate.dismissViewController()
}
}
func showQuestionList() {
panelOpened = true
let questionsPageViewController = mainViewController as! BaseQuestionsPageViewController
questionsSlidingMenuDelegate.displayQuestions(
currentQuestionIndex: questionsPageViewController.getCurrentIndex())
}
}
extension BaseQuestionsSlidingViewController: SlideMenuControllerDelegate {
func leftWillOpen() {
showQuestionList()
}
func leftDidOpen() {
if !panelOpened {
showQuestionList()
}
}
func leftDidClose() {
panelOpened = false
}
}
| 35.785047 | 96 | 0.727344 |
d99af772086519a2a7277e790f52fa56ff2c085e | 4,609 | //
// ExpressionsProcessor.swift
// Swifternalization
//
// Created by Tomasz Szulc on 26/07/15.
// Copyright (c) 2015 Tomasz Szulc. All rights reserved.
//
import Foundation
/**
Swifternalization contains some built-in country-related shared expressions.
Developer can create its own expressions in expressions.json file for
base and preferred languages.
The class is responsible for proper loading the built-in shared ones and
those loaded from project's files. It handles overriding of built-in and loads
those from Base and preferred language version.
It always load base expressions, then looking for language specific.
If in Base are some expressions that overrides built-ins, that's fine.
The class adds developer's custom expressions and adds only those of built-in
that are not contained in the Base.
The same is for preferred languages but also here what is important is that
at first preferred language file expressions are loaded, then if something
different is defined in Base it will be also loaded and then the built-in
expression that differs.
*/
class SharedExpressionsProcessor {
/**
Method takes expression for both Base and preferred language localizations
and also internally loads built-in expressions, combine them and returns
expressions for Base and prefered language.
:param: preferedLanguage A user device's language.
:param: preferedLanguageExpressions Expressions from expressions.json
:param: baseLanguageExpressions Expressions from base section of
expression.json.
:returns: array of shared expressions for Base and preferred language.
*/
class func processSharedExpression(_ preferedLanguage: CountryCode, preferedLanguageExpressions: [SharedExpression], baseLanguageExpressions: [SharedExpression]) -> [SharedExpression] {
/*
Get unique base expressions that are not presented in prefered language
expressions. Those from base will be used in a case when programmer
will ask for string localization and when there is no such expression
in prefered language section defined.
It means two things:
1. Programmer make this expression shared through prefered language
and this is good as base expression.
2. He forgot to define such expression for prefered language.
*/
let uniqueBaseExpressions = baseLanguageExpressions <! preferedLanguageExpressions
// Expressions from json files.
let loadedExpressions = uniqueBaseExpressions + preferedLanguageExpressions
// Load prefered language nad base built-in expressions. Get unique.
let prefBuiltInExpressions = loadBuiltInExpressions(preferedLanguage)
let baseBuiltInExpressions = SharedBaseExpression.allExpressions()
let uniqueBaseBuiltInExpressions = baseBuiltInExpressions <! prefBuiltInExpressions
// Unique built-in expressions made of base + prefered language.
let builtInExpressions = uniqueBaseBuiltInExpressions + prefBuiltInExpressions
/*
To get it done we must get only unique built-in expressions that are not
in loaded expressions.
*/
return loadedExpressions + (builtInExpressions <! loadedExpressions)
}
/**
Method loads built-in framework's built-in expressions for specific language.
:param: language A preferred user's language.
:returns: Shared expressions for specific language. If there is no
expression for passed language empty array is returned.
*/
private class func loadBuiltInExpressions(_ language: CountryCode) -> [SharedExpression] {
switch language {
case "pl": return SharedPolishExpression.allExpressions()
default: return []
}
}
}
precedencegroup SetPrecedence {
higherThan: DefaultPrecedence
}
infix operator <! : SetPrecedence
/**
"Get Unique" operator. It helps in getting unique shared expressions from two arrays.
Content of `lhs` array will be checked in terms on uniqueness. The operator does
check is there is any shared expression in `lhs` that is presented in `rhs`.
If element from `lhs` is not in `rhs` then this element is correct and is returned
in new array which is a result of this operation.
*/
func <! (lhs: [SharedExpression], rhs: [SharedExpression]) -> [SharedExpression] {
var result = lhs
if rhs.count > 0 {
result = lhs.filter({
let tmp = $0
return rhs.filter({$0.identifier == tmp.identifier}).count == 0
})
}
return result
}
| 41.151786 | 189 | 0.72749 |
bb773306eea4f92a8951ad03afcd065cf836dbe7 | 934 | //
// Base.swift
// APSP
//
// Created by Andrew McKnight on 5/6/16.
//
import Foundation
import Graph
/**
`APSPAlgorithm` is a protocol for encapsulating an All-Pairs Shortest Paths algorithm. It provides a single function `apply` that accepts a subclass of `AbstractGraph` and returns an object conforming to `APSPResult`.
*/
public protocol APSPAlgorithm {
associatedtype Q: Hashable
associatedtype P: APSPResult
static func apply(graph: AbstractGraph<Q>) -> P
}
/**
`APSPResult` is a protocol defining functions `distance` and `path`, allowing for opaque queries into the actual data structures that represent the APSP solution according to the algorithm used.
*/
public protocol APSPResult {
associatedtype T: Hashable
func distance(fromVertex from: Vertex<T>, toVertex to: Vertex<T>) -> Double?
func path(fromVertex from: Vertex<T>, toVertex to: Vertex<T>, inGraph graph: AbstractGraph<T>) -> [T]?
}
| 27.470588 | 218 | 0.739829 |
50d5091d44730a90b58c5fafe3f382a00ddf70dd | 4,583 | import UIKit
import RxSwift
import RxCocoa
import Eureka
import iOSKit
import JacKit
fileprivate let jack = Jack.with(levelOfThisFile: .debug)
private struct ViewModel {
// outputs
let tip: Driver<String>
let showButtonEnabled: Driver<Bool>
let showAlert: Driver<(style: UIAlertControllerStyle, layout: String)>
init(
showButtonTap: ControlEvent<Void>,
style: Driver<UIAlertControllerStyle>,
layout: Driver<String>
) {
let parseResult = layout
.distinctUntilChanged()
.map { text -> (tip: String, layout: String?, error: Error?) in
do {
let alertLayout = try AlertLayout(layout: text)
return (ViewModel.tip(for: alertLayout), text, nil)
} catch {
if text.isEmpty {
return ("Try input `Title:Message->OK`", nil, error)
} else {
return (ViewModel.tip(for: error), nil, error)
}
}
}
tip = parseResult.map { $0.tip }
let layout = parseResult
.filter { $0.error == nil }
.map { $0.layout! }
let paramters = Driver.combineLatest(style, layout) {
return (style: $0, layout: $1)
}
showAlert = showButtonTap.asDriver().withLatestFrom(paramters)
showButtonEnabled = parseResult.map { $0.error == nil }
}
static func tip(for alertLayout: AlertLayout) -> String {
func string(for style: UIAlertActionStyle) -> String {
switch style {
case .default: return "default"
case .cancel: return "cancel"
case .destructive: return "destructive"
}
}
var tip = """
Title: \(alertLayout.title ?? "n/a")
Message: \(alertLayout.message ?? "n/a")
Actions:
"""
alertLayout.actions.forEach {
tip.append("\n - \($0.title) @\(string(for: $0.style))")
}
return tip
}
static func tip(for error: Error) -> String {
return """
Error: \(error)
"""
}
}
class AlertVC: FormViewController {
var disposeBag = DisposeBag()
let layout = BehaviorRelay<String>(value: "")
let style = BehaviorRelay<UIAlertControllerStyle>(value: .alert)
fileprivate func setupForm() {
form +++ Section("STYLE")
<<< SegmentedRow<UIAlertControllerStyle>("style") {
$0.options = [.alert, .actionSheet]
$0.value = .alert
$0.displayValueFor = { $0!.caseName.capitalized }
}.onChange { [weak self] row in
guard let ss = self else { return }
if row.value == nil {
jack.failure("Should not be nil")
}
ss.style.accept(row.value ?? .alert)
}
form +++ Section("LAYOUT")
<<< TextAreaRow("layout") {
$0.title = "Alert Layout Format"
$0.placeholder = "Input layout string"
$0.textAreaHeight = .dynamic(initialTextViewHeight: 80)
}.cellUpdate { cell, row in
cell.textView.font = UIFont.systemFont(ofSize: 14)
}.onChange { [weak self] row in
guard let ss = self else { return }
ss.layout.accept(row.value ?? "")
}
form +++ Section("PARSING RESULT")
<<< TextAreaRow("tip") {
$0.textAreaHeight = .dynamic(initialTextViewHeight: 140)
}.cellUpdate { cell, row in
with(cell.textView) { v in
cell.isUserInteractionEnabled = false
v?.font = UIFont.systemFont(ofSize: 14)
v?.backgroundColor = .clear
}
}
}
func setupViewModel() {
let showButton = navigationItem.rightBarButtonItem!
let vm = ViewModel(
showButtonTap: showButton.rx.tap,
style: style.asDriver(),
layout: layout.asDriver()
)
vm.showButtonEnabled.drive(showButton.rx.isEnabled).disposed(by: disposeBag)
vm.tip.drive(
onNext: { [weak self] text in
guard let ss = self else { return }
with(ss.form.rowBy(tag: "tip") as! TextAreaRow) { row in
row.value = text
row.updateCell()
}
}
).disposed(by: disposeBag)
vm.showAlert.asObservable()
.flatMap { param in
return UIAlertController.mdx.present(layout: param.layout, style: param.style)
}
.subscribe (
onNext: {
jack.info("User select action: \($0)")
}
).disposed(by: disposeBag)
}
override func viewDidLoad() {
super.viewDidLoad()
with(navigationItem) { nav in
nav.title = "Alert Layout"
nav.rightBarButtonItem = with(UIBarButtonItem()) { item in
item.title = "Show"
return item
}
}
with(tableView!) { tv in
tv.separatorInset = UIEdgeInsets(top: 0, left: 12, bottom: 0, right: 12)
}
setupForm()
setupViewModel()
}
}
| 25.181319 | 86 | 0.604189 |
e6e76421118b8fb3697abf5a29b750ab1e8d24dc | 1,233 | //
// Contraption.swift
// Mitra
//
// Created by Serge Bouts on 11/16/20.
// Copyright © 2020 iRiZen.com. All rights reserved.
//
import Mitra
/// A fictional device `Contraption` (an example of Mitra's shared memory manager usage)
struct Contraption {
let sharedManager = SharedManager()
// MARK: - Properties (State)
private let sensorReadings = [Property(value: 0),
Property(value: 0),
Property(value: 0)]
private let average = Property<Double>(value: 0.0)
// MARK: - UI
func updateSensor(_ i: Int, value: Int) {
sharedManager.borrow(ArraySliceProperty(sensorReadings[i...i]).rw) { sensor in
sensor.first!.value = value
}
}
@discardableResult
func updateAvarage() -> Double {
sharedManager.borrow(ArraySliceProperty(sensorReadings[...]).ro, average.rw) { readings, average in
average.value = Double(readings.map { $0.value }.reduce(0, +)) / Double(readings.count)
// Alternatively:
// average.value = Double(readings[0].value + readings[1].value + readings[2].value) / Double(readings.count)
return average.value
}
}
}
| 31.615385 | 121 | 0.603406 |
ed643e91826717a96230e3de13ad2e0a33564740 | 1,504 | //
// InvoicePriceComponentType.swift
// Asclepius
// Module: R4
//
// Copyright (c) 2022 Bitmatic Ltd.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
/**
Codes indicating the kind of the price component.
URL: http://hl7.org/fhir/invoice-priceComponentType
ValueSet: http://hl7.org/fhir/ValueSet/invoice-priceComponentType
*/
public enum InvoicePriceComponentType: String, AsclepiusPrimitiveType {
/// the amount is the base price used for calculating the total price before applying surcharges, discount or taxes.
case base
/// the amount is a surcharge applied on the base price.
case surcharge
/// the amount is a deduction applied on the base price.
case deduction
/// the amount is a discount applied on the base price.
case discount
/// the amount is the tax component of the total price.
case tax
/// the amount is of informational character, it has not been applied in the calculation of the total price.
case informational
}
| 33.422222 | 118 | 0.733378 |
e046b19c6ee32db4780342dab4e9859f7729699f | 1,747 | class Solution {
// Solution @ Sergey Leschev, Belarusian State University
// 75. Sort Colors
// Given an array nums with n objects colored red, white, or blue, sort them in-place so that objects of the same color are adjacent, with the colors in the order red, white, and blue.
// We will use the integers 0, 1, and 2 to represent the color red, white, and blue, respectively.
// You must solve this problem without using the library's sort function.
// Sorts colors in-place.
// - Parameter nums: An array with red, white or blue color. The integers 0, 1, and 2
// represent the color red, white, and blue respectively.
// Example 1:
// Input: nums = [2,0,2,1,1,0]
// Output: [0,0,1,1,2,2]
// Example 2:
// Input: nums = [2,0,1]
// Output: [0,1,2]
// Example 3:
// Input: nums = [0]
// Output: [0]
// Example 4:
// Input: nums = [1]
// Output: [1]
// Constraints:
// n == nums.length
// 1 <= n <= 300
// nums[i] is 0, 1, or 2.
// Follow up: Could you come up with a one-pass algorithm using only constant extra space?
// - Complexity:
// - time: O(n), where n is the length of the `nums`.
// - space: O(1), only constant space is used.
func sortColors(_ nums: inout [Int]) {
var zeroIndex = 0
var twoIndex = nums.count - 1
var i = 0
while i <= twoIndex {
if nums[i] == 0, i > zeroIndex {
nums.swapAt(i, zeroIndex)
zeroIndex += 1
} else if nums[i] == 2, i < twoIndex {
nums.swapAt(i, twoIndex)
twoIndex -= 1
} else {
i += 1
}
}
}
} | 28.177419 | 188 | 0.538638 |
794fd473c992ca1df7e129478d2ca5def2b9a350 | 1,431 | //
// LilySwift Library Project
//
// Copyright (c) Watanabe-Denki Inc. and Kengo Watanabe.
// https://wdkk.co.jp/
//
// This software is released under the MIT License.
// https://opensource.org/licenses/mit-license.php
//
#if os(macOS)
import Metal
import QuartzCore
open class LLMetalView : LLView
{
/// Metalレイヤー
public private(set) lazy var metalLayer = CAMetalLayer()
public private(set) var lastDrawable:CAMetalDrawable?
public private(set) var ready:Bool = false
open override var bounds:CGRect {
didSet {
metalLayer.frame = self.bounds
}
}
open override var frame:CGRect {
didSet {
metalLayer.frame = self.bounds
}
}
open override func postSetup() {
super.postSetup()
setupMetal()
}
/// Metalの初期化 / Metal Layerの準備
open func setupMetal() {
self.addSublayer( metalLayer )
metalLayer.device = LLMetalManager.shared.device
metalLayer.pixelFormat = .bgra8Unorm
metalLayer.framebufferOnly = false
metalLayer.frame = self.bounds
metalLayer.contentsScale = LLSystem.retinaScale.cgf
self.ready = true
}
open var drawable:CAMetalDrawable? {
if metalLayer.bounds.width < 1 || metalLayer.bounds.height < 1 { return nil }
lastDrawable = metalLayer.nextDrawable()
return lastDrawable
}
}
#endif
| 24.672414 | 85 | 0.635919 |
bf45b4c3ff30365202238a11f26b6bcea9559e2e | 1,072 | //
// Created by Dmitry Gorin on 02.05.2020.
// Copyright (c) 2020 gordiig. All rights reserved.
//
import Foundation
final class ProfileManager: APIEntityManager {
// MARK: - Singletone
private static var _instance: ProfileManager?
static var instance: ProfileManager {
if _instance == nil {
_instance = ProfileManager()
}
return _instance!
}
private init() {
}
// MARK: - Variables
var entities: [Profile] = []
var requester: ProfileRequester {
ProfileRequester()
}
var currentProfile: Profile? {
get {
Defaults.currentProfile
}
set {
Defaults.currentProfile = newValue
if let newValue = newValue {
self.replace(newValue, with: newValue)
}
}
}
// MARK: - Needed for protocol
func checkEntityWithKeyPath<T>(_ entity: Profile, keyPath: KeyPath<Profile, T>, value: T) -> Bool
where T : Equatable {
return entity[keyPath: keyPath] == value
}
}
| 21.877551 | 101 | 0.578358 |
bfb6a41fca8312dae82261d9e7fa6069c6e17e23 | 19,898 | //
// SUFileManagerTest.swift
// Sparkle
//
// Created by Mayur Pawashe on 9/26/15.
// Copyright © 2015 Sparkle Project. All rights reserved.
//
import XCTest
class SUFileManagerTest: XCTestCase
{
func makeTempFiles(testBlock: (SUFileManager, NSURL, NSURL, NSURL, NSURL, NSURL, NSURL) -> Void)
{
let fileManager = SUFileManager.defaultManager()
let tempDirectoryURL = try! fileManager.makeTemporaryDirectoryWithPreferredName("Sparkle Unit Test Data", appropriateForDirectoryURL: NSURL(fileURLWithPath: NSHomeDirectory()))
defer {
try! fileManager.removeItemAtURL(tempDirectoryURL)
}
let ordinaryFileURL = tempDirectoryURL.URLByAppendingPathComponent("a file written by sparkles unit tests")
try! "foo".dataUsingEncoding(NSUTF8StringEncoding)!.writeToURL(ordinaryFileURL, options: .DataWritingAtomic)
let directoryURL = tempDirectoryURL.URLByAppendingPathComponent("a directory written by sparkles unit tests")
try! NSFileManager.defaultManager().createDirectoryAtURL(directoryURL, withIntermediateDirectories: false, attributes: nil)
let fileInDirectoryURL = directoryURL.URLByAppendingPathComponent("a file inside a directory written by sparkles unit tests")
try! "bar baz".dataUsingEncoding(NSUTF8StringEncoding)!.writeToURL(fileInDirectoryURL, options: .DataWritingAtomic)
let validSymlinkURL = tempDirectoryURL.URLByAppendingPathComponent("symlink test")
try! NSFileManager.defaultManager().createSymbolicLinkAtURL(validSymlinkURL, withDestinationURL: directoryURL)
let invalidSymlinkURL = tempDirectoryURL.URLByAppendingPathComponent("symlink test 2")
try! NSFileManager.defaultManager().createSymbolicLinkAtURL(invalidSymlinkURL, withDestinationURL: tempDirectoryURL.URLByAppendingPathComponent("does not exist"))
testBlock(fileManager, tempDirectoryURL, ordinaryFileURL, directoryURL, fileInDirectoryURL, validSymlinkURL, invalidSymlinkURL)
}
func testMoveFiles()
{
makeTempFiles() { fileManager, rootURL, ordinaryFileURL, directoryURL, fileInDirectoryURL, validSymlinkURL, invalidSymlinkURL in
XCTAssertNil(try? fileManager.moveItemAtURL(ordinaryFileURL, toURL: directoryURL))
XCTAssertNil(try? fileManager.moveItemAtURL(ordinaryFileURL, toURL: directoryURL.URLByAppendingPathComponent("foo").URLByAppendingPathComponent("bar")))
XCTAssertNil(try? fileManager.moveItemAtURL(rootURL.URLByAppendingPathComponent("does not exist"), toURL: directoryURL))
let newFileURL = (ordinaryFileURL.URLByDeletingLastPathComponent?.URLByAppendingPathComponent("new file"))!
try! fileManager.moveItemAtURL(ordinaryFileURL, toURL: newFileURL)
XCTAssertFalse(fileManager._itemExistsAtURL(ordinaryFileURL))
XCTAssertTrue(fileManager._itemExistsAtURL(newFileURL))
let newValidSymlinkURL = (ordinaryFileURL.URLByDeletingLastPathComponent?.URLByAppendingPathComponent("new symlink"))!
try! fileManager.moveItemAtURL(validSymlinkURL, toURL: newValidSymlinkURL)
XCTAssertFalse(fileManager._itemExistsAtURL(validSymlinkURL))
XCTAssertTrue(fileManager._itemExistsAtURL(newValidSymlinkURL))
XCTAssertTrue(fileManager._itemExistsAtURL(directoryURL))
let newInvalidSymlinkURL = (ordinaryFileURL.URLByDeletingLastPathComponent?.URLByAppendingPathComponent("new invalid symlink"))!
try! fileManager.moveItemAtURL(invalidSymlinkURL, toURL: newInvalidSymlinkURL)
XCTAssertFalse(fileManager._itemExistsAtURL(invalidSymlinkURL))
XCTAssertTrue(fileManager._itemExistsAtURL(newValidSymlinkURL))
let newDirectoryURL = (ordinaryFileURL.URLByDeletingLastPathComponent?.URLByAppendingPathComponent("new directory"))!
try! fileManager.moveItemAtURL(directoryURL, toURL: newDirectoryURL)
XCTAssertFalse(fileManager._itemExistsAtURL(directoryURL))
XCTAssertTrue(fileManager._itemExistsAtURL(newDirectoryURL))
XCTAssertFalse(fileManager._itemExistsAtURL(fileInDirectoryURL))
XCTAssertTrue(fileManager._itemExistsAtURL(newDirectoryURL.URLByAppendingPathComponent(fileInDirectoryURL.lastPathComponent!)))
}
}
func testMoveFilesToTrash()
{
makeTempFiles() { fileManager, rootURL, ordinaryFileURL, directoryURL, fileInDirectoryURL, validSymlinkURL, invalidSymlinkURL in
XCTAssertNil(try? fileManager.moveItemAtURLToTrash(rootURL.URLByAppendingPathComponent("does not exist")))
let trashURL = try! NSFileManager.defaultManager().URLForDirectory(.TrashDirectory, inDomain: .UserDomainMask, appropriateForURL: nil, create: false)
try! fileManager.moveItemAtURLToTrash(ordinaryFileURL)
XCTAssertFalse(fileManager._itemExistsAtURL(ordinaryFileURL))
let ordinaryFileTrashURL = trashURL.URLByAppendingPathComponent(ordinaryFileURL.lastPathComponent!)
XCTAssertTrue(fileManager._itemExistsAtURL(ordinaryFileTrashURL))
try! fileManager.removeItemAtURL(ordinaryFileTrashURL)
let validSymlinkTrashURL = trashURL.URLByAppendingPathComponent(validSymlinkURL.lastPathComponent!)
try! fileManager.moveItemAtURLToTrash(validSymlinkURL)
XCTAssertTrue(fileManager._itemExistsAtURL(validSymlinkTrashURL))
XCTAssertTrue(fileManager._itemExistsAtURL(directoryURL))
try! fileManager.removeItemAtURL(validSymlinkTrashURL)
try! fileManager.moveItemAtURLToTrash(directoryURL)
XCTAssertFalse(fileManager._itemExistsAtURL(directoryURL))
XCTAssertFalse(fileManager._itemExistsAtURL(fileInDirectoryURL))
let directoryTrashURL = trashURL.URLByAppendingPathComponent(directoryURL.lastPathComponent!)
XCTAssertTrue(fileManager._itemExistsAtURL(directoryTrashURL))
XCTAssertTrue(fileManager._itemExistsAtURL(directoryTrashURL.URLByAppendingPathComponent(fileInDirectoryURL.lastPathComponent!)))
try! fileManager.removeItemAtURL(directoryTrashURL)
}
}
func testCopyFiles()
{
makeTempFiles() { fileManager, rootURL, ordinaryFileURL, directoryURL, fileInDirectoryURL, validSymlinkURL, invalidSymlinkURL in
XCTAssertNil(try? fileManager.copyItemAtURL(ordinaryFileURL, toURL: directoryURL))
XCTAssertNil(try? fileManager.copyItemAtURL(ordinaryFileURL, toURL: directoryURL.URLByAppendingPathComponent("foo").URLByAppendingPathComponent("bar")))
XCTAssertNil(try? fileManager.copyItemAtURL(rootURL.URLByAppendingPathComponent("does not exist"), toURL: directoryURL))
let newFileURL = (ordinaryFileURL.URLByDeletingLastPathComponent?.URLByAppendingPathComponent("new file"))!
try! fileManager.copyItemAtURL(ordinaryFileURL, toURL: newFileURL)
XCTAssertTrue(fileManager._itemExistsAtURL(ordinaryFileURL))
XCTAssertTrue(fileManager._itemExistsAtURL(newFileURL))
let newSymlinkURL = (ordinaryFileURL.URLByDeletingLastPathComponent?.URLByAppendingPathComponent("new symlink file"))!
try! fileManager.copyItemAtURL(invalidSymlinkURL, toURL: newSymlinkURL)
XCTAssertTrue(fileManager._itemExistsAtURL(newSymlinkURL))
let newDirectoryURL = (ordinaryFileURL.URLByDeletingLastPathComponent?.URLByAppendingPathComponent("new directory"))!
try! fileManager.copyItemAtURL(directoryURL, toURL: newDirectoryURL)
XCTAssertTrue(fileManager._itemExistsAtURL(directoryURL))
XCTAssertTrue(fileManager._itemExistsAtURL(newDirectoryURL))
XCTAssertTrue(fileManager._itemExistsAtURL(fileInDirectoryURL))
XCTAssertTrue(fileManager._itemExistsAtURL(newDirectoryURL.URLByAppendingPathComponent(fileInDirectoryURL.lastPathComponent!)))
}
}
func testRemoveFiles()
{
makeTempFiles() { fileManager, rootURL, ordinaryFileURL, directoryURL, fileInDirectoryURL, validSymlinkURL, invalidSymlinkURL in
XCTAssertNil(try? fileManager.removeItemAtURL(rootURL.URLByAppendingPathComponent("does not exist")))
try! fileManager.removeItemAtURL(ordinaryFileURL)
XCTAssertFalse(fileManager._itemExistsAtURL(ordinaryFileURL))
try! fileManager.removeItemAtURL(validSymlinkURL)
XCTAssertFalse(fileManager._itemExistsAtURL(validSymlinkURL))
XCTAssertTrue(fileManager._itemExistsAtURL(directoryURL))
try! fileManager.removeItemAtURL(directoryURL)
XCTAssertFalse(fileManager._itemExistsAtURL(directoryURL))
XCTAssertFalse(fileManager._itemExistsAtURL(fileInDirectoryURL))
}
}
func testReleaseFilesFromQuarantine()
{
makeTempFiles() { fileManager, rootURL, ordinaryFileURL, directoryURL, fileInDirectoryURL, validSymlinkURL, invalidSymlinkURL in
try! fileManager.releaseItemFromQuarantineAtRootURL(ordinaryFileURL)
try! fileManager.releaseItemFromQuarantineAtRootURL(directoryURL)
try! fileManager.releaseItemFromQuarantineAtRootURL(validSymlinkURL)
let quarantineData = "does not really matter what is here".cStringUsingEncoding(NSUTF8StringEncoding)!
let quarantineDataLength = Int(strlen(quarantineData))
XCTAssertEqual(0, setxattr(ordinaryFileURL.path!, SUAppleQuarantineIdentifier, quarantineData, quarantineDataLength, 0, XATTR_CREATE))
XCTAssertGreaterThan(getxattr(ordinaryFileURL.path!, SUAppleQuarantineIdentifier, nil, 0, 0, XATTR_NOFOLLOW), 0)
try! fileManager.releaseItemFromQuarantineAtRootURL(ordinaryFileURL)
XCTAssertEqual(-1, getxattr(ordinaryFileURL.path!, SUAppleQuarantineIdentifier, nil, 0, 0, XATTR_NOFOLLOW))
XCTAssertEqual(0, setxattr(directoryURL.path!, SUAppleQuarantineIdentifier, quarantineData, quarantineDataLength, 0, XATTR_CREATE))
XCTAssertGreaterThan(getxattr(directoryURL.path!, SUAppleQuarantineIdentifier, nil, 0, 0, XATTR_NOFOLLOW), 0)
XCTAssertEqual(0, setxattr(fileInDirectoryURL.path!, SUAppleQuarantineIdentifier, quarantineData, quarantineDataLength, 0, XATTR_CREATE))
XCTAssertGreaterThan(getxattr(fileInDirectoryURL.path!, SUAppleQuarantineIdentifier, nil, 0, 0, XATTR_NOFOLLOW), 0)
// Extended attributes can't be set on symbolic links currently
try! fileManager.releaseItemFromQuarantineAtRootURL(validSymlinkURL)
XCTAssertGreaterThan(getxattr(directoryURL.path!, SUAppleQuarantineIdentifier, nil, 0, 0, XATTR_NOFOLLOW), 0)
XCTAssertEqual(-1, getxattr(validSymlinkURL.path!, SUAppleQuarantineIdentifier, nil, 0, 0, XATTR_NOFOLLOW))
try! fileManager.releaseItemFromQuarantineAtRootURL(directoryURL)
XCTAssertEqual(-1, getxattr(directoryURL.path!, SUAppleQuarantineIdentifier, nil, 0, 0, XATTR_NOFOLLOW))
XCTAssertEqual(-1, getxattr(fileInDirectoryURL.path!, SUAppleQuarantineIdentifier, nil, 0, 0, XATTR_NOFOLLOW))
}
}
func groupIDAtPath(path: String) -> gid_t
{
let attributes = try! NSFileManager.defaultManager().attributesOfItemAtPath(path)
let groupID = attributes[NSFileGroupOwnerAccountID] as! NSNumber
return groupID.unsignedIntValue
}
// Only the super user can alter user IDs, so changing user IDs is not tested here
// Instead we try to change the group ID - we just have to be a member of that group
func testAlterFilesGroupID()
{
makeTempFiles() { fileManager, rootURL, ordinaryFileURL, directoryURL, fileInDirectoryURL, validSymlinkURL, invalidSymlinkURL in
XCTAssertNil(try? fileManager.changeOwnerAndGroupOfItemAtRootURL(ordinaryFileURL, toMatchURL: rootURL.URLByAppendingPathComponent("does not exist")))
XCTAssertNil(try? fileManager.changeOwnerAndGroupOfItemAtRootURL(rootURL.URLByAppendingPathComponent("does not exist"), toMatchURL: ordinaryFileURL))
let everyoneGroup = getgrnam("everyone")
let everyoneGroupID = everyoneGroup.memory.gr_gid
let staffGroup = getgrnam("staff")
let staffGroupID = staffGroup.memory.gr_gid
XCTAssertNotEqual(staffGroupID, everyoneGroupID)
XCTAssertEqual(staffGroupID, self.groupIDAtPath(ordinaryFileURL.path!))
XCTAssertEqual(staffGroupID, self.groupIDAtPath(directoryURL.path!))
XCTAssertEqual(staffGroupID, self.groupIDAtPath(fileInDirectoryURL.path!))
XCTAssertEqual(staffGroupID, self.groupIDAtPath(validSymlinkURL.path!))
try! fileManager.changeOwnerAndGroupOfItemAtRootURL(fileInDirectoryURL, toMatchURL: ordinaryFileURL)
try! fileManager.changeOwnerAndGroupOfItemAtRootURL(ordinaryFileURL, toMatchURL: ordinaryFileURL)
try! fileManager.changeOwnerAndGroupOfItemAtRootURL(validSymlinkURL, toMatchURL: ordinaryFileURL)
XCTAssertEqual(staffGroupID, self.groupIDAtPath(ordinaryFileURL.path!))
XCTAssertEqual(staffGroupID, self.groupIDAtPath(directoryURL.path!))
XCTAssertEqual(staffGroupID, self.groupIDAtPath(validSymlinkURL.path!))
XCTAssertEqual(0, chown(ordinaryFileURL.path!, getuid(), everyoneGroupID))
XCTAssertEqual(everyoneGroupID, self.groupIDAtPath(ordinaryFileURL.path!))
try! fileManager.changeOwnerAndGroupOfItemAtRootURL(fileInDirectoryURL, toMatchURL: ordinaryFileURL)
XCTAssertEqual(everyoneGroupID, self.groupIDAtPath(fileInDirectoryURL.path!))
try! fileManager.changeOwnerAndGroupOfItemAtRootURL(fileInDirectoryURL, toMatchURL: directoryURL)
XCTAssertEqual(staffGroupID, self.groupIDAtPath(fileInDirectoryURL.path!))
try! fileManager.changeOwnerAndGroupOfItemAtRootURL(validSymlinkURL, toMatchURL: ordinaryFileURL)
XCTAssertEqual(everyoneGroupID, self.groupIDAtPath(validSymlinkURL.path!))
try! fileManager.changeOwnerAndGroupOfItemAtRootURL(directoryURL, toMatchURL: ordinaryFileURL)
XCTAssertEqual(everyoneGroupID, self.groupIDAtPath(directoryURL.path!))
XCTAssertEqual(everyoneGroupID, self.groupIDAtPath(fileInDirectoryURL.path!))
}
}
func testUpdateFileModificationTime()
{
makeTempFiles() { fileManager, rootURL, ordinaryFileURL, directoryURL, fileInDirectoryURL, validSymlinkURL, invalidSymlinkURL in
XCTAssertNil(try? fileManager.updateModificationAndAccessTimeOfItemAtURL(rootURL.URLByAppendingPathComponent("does not exist")))
let oldOrdinaryFileAttributes = try! NSFileManager.defaultManager().attributesOfItemAtPath(ordinaryFileURL.path!)
let oldDirectoryAttributes = try! NSFileManager.defaultManager().attributesOfItemAtPath(directoryURL.path!)
let oldValidSymlinkAttributes = try! NSFileManager.defaultManager().attributesOfItemAtPath(validSymlinkURL.path!)
sleep(1); // wait for clock to advance
try! fileManager.updateModificationAndAccessTimeOfItemAtURL(ordinaryFileURL)
try! fileManager.updateModificationAndAccessTimeOfItemAtURL(directoryURL)
try! fileManager.updateModificationAndAccessTimeOfItemAtURL(validSymlinkURL)
let newOrdinaryFileAttributes = try! NSFileManager.defaultManager().attributesOfItemAtPath(ordinaryFileURL.path!)
XCTAssertGreaterThan((newOrdinaryFileAttributes[NSFileModificationDate] as! NSDate).timeIntervalSinceDate(oldOrdinaryFileAttributes[NSFileModificationDate] as! NSDate), 0)
let newDirectoryAttributes = try! NSFileManager.defaultManager().attributesOfItemAtPath(directoryURL.path!)
XCTAssertGreaterThan((newDirectoryAttributes[NSFileModificationDate] as! NSDate).timeIntervalSinceDate(oldDirectoryAttributes[NSFileModificationDate] as! NSDate), 0)
let newSymlinkAttributes = try! NSFileManager.defaultManager().attributesOfItemAtPath(validSymlinkURL.path!)
XCTAssertGreaterThan((newSymlinkAttributes[NSFileModificationDate] as! NSDate).timeIntervalSinceDate(oldValidSymlinkAttributes[NSFileModificationDate] as! NSDate), 0)
}
}
func testFileExists()
{
makeTempFiles() { fileManager, rootURL, ordinaryFileURL, directoryURL, fileInDirectoryURL, validSymlinkURL, invalidSymlinkURL in
XCTAssertTrue(fileManager._itemExistsAtURL(ordinaryFileURL))
XCTAssertTrue(fileManager._itemExistsAtURL(directoryURL))
XCTAssertFalse(fileManager._itemExistsAtURL(rootURL.URLByAppendingPathComponent("does not exist")))
var isOrdinaryFileDirectory: ObjCBool = false
XCTAssertTrue(fileManager._itemExistsAtURL(ordinaryFileURL, isDirectory: &isOrdinaryFileDirectory) && !isOrdinaryFileDirectory)
var isDirectoryADirectory: ObjCBool = false
XCTAssertTrue(fileManager._itemExistsAtURL(directoryURL, isDirectory: &isDirectoryADirectory) && isDirectoryADirectory)
XCTAssertFalse(fileManager._itemExistsAtURL(rootURL.URLByAppendingPathComponent("does not exist"), isDirectory: nil))
XCTAssertTrue(fileManager._itemExistsAtURL(validSymlinkURL))
var validSymlinkIsADirectory: ObjCBool = false
XCTAssertTrue(fileManager._itemExistsAtURL(validSymlinkURL, isDirectory: &validSymlinkIsADirectory) && !validSymlinkIsADirectory)
// Symlink should still exist even if it doesn't point to a file that exists
XCTAssertTrue(fileManager._itemExistsAtURL(invalidSymlinkURL))
var invalidSymlinkIsADirectory: ObjCBool = false
XCTAssertTrue(fileManager._itemExistsAtURL(invalidSymlinkURL, isDirectory: &invalidSymlinkIsADirectory) && !invalidSymlinkIsADirectory)
}
}
func testMakeDirectory()
{
makeTempFiles() { fileManager, rootURL, ordinaryFileURL, directoryURL, fileInDirectoryURL, validSymlinkURL, invalidSymlinkURL in
XCTAssertNil(try? fileManager.makeDirectoryAtURL(ordinaryFileURL))
XCTAssertNil(try? fileManager.makeDirectoryAtURL(directoryURL))
XCTAssertNil(try? fileManager.makeDirectoryAtURL(rootURL.URLByAppendingPathComponent("this should").URLByAppendingPathComponent("be a failure")))
let newDirectoryURL = rootURL.URLByAppendingPathComponent("new test directory")
XCTAssertFalse(fileManager._itemExistsAtURL(newDirectoryURL))
try! fileManager.makeDirectoryAtURL(newDirectoryURL)
var isDirectory: ObjCBool = false
XCTAssertTrue(fileManager._itemExistsAtURL(newDirectoryURL, isDirectory: &isDirectory))
try! fileManager.removeItemAtURL(directoryURL)
XCTAssertNil(try? fileManager.makeDirectoryAtURL(validSymlinkURL))
}
}
func testAcquireBadAuthorization()
{
let fileManager = SUFileManager.defaultManager()
XCTAssertNil(try? fileManager._acquireAuthorization())
}
}
| 62.769716 | 184 | 0.726003 |
09c304318001bd1713ee145ce9ce2ccd75e579eb | 4,328 | //
// DJGlobalMethods.swift
// DJExtension
//
// Created by David Jia on 16/8/2017.
// Copyright © 2017 David Jia. All rights reserved.
//
import UIKit
import SnapKit
public let lineColor = dj_hexColor("EDEDED")
// MARK: - init method
extension UIView {
/// create a view with background color
@discardableResult
public convenience init (backgroundColor: UIColor) {
self.init()
self.backgroundColor = backgroundColor
}
/// create a view with background color and super view
@discardableResult
public convenience init (backgroundColor: UIColor, superView: UIView, closure: ((ConstraintMaker) -> Void)) {
self.init()
self.backgroundColor = backgroundColor
superView.addSubview(self)
self.snp.makeConstraints(closure)
}
/// create a view with super view
@discardableResult
public convenience init (superView: UIView, closure: ((ConstraintMaker) -> Void)) {
self.init()
superView.addSubview(self)
self.snp.makeConstraints(closure)
}
}
// MARK: - instance method
extension UIView {
public func dj_addTopLine(color: UIColor = lineColor, leftOffset: CGFloat = 0, rightOffset: CGFloat = 0, height: CGFloat = 0.5) {
UIView(backgroundColor: color, superView: self) { (make) in
make.left.equalTo(self.snp.left).offset(leftOffset)
make.right.equalTo(self.snp.right).offset(-rightOffset)
make.top.equalTo(self.snp.top)
make.height.equalTo(height)
}
}
public func dj_addBottomLine(color: UIColor = lineColor, leftOffset: CGFloat = 0, rightOffset: CGFloat = 0, height: CGFloat = 0.5) {
let line = UIView(backgroundColor: color, superView: self) { (make) in
make.left.equalTo(self.snp.left).offset(leftOffset)
make.right.equalTo(self.snp.right).offset(-rightOffset)
make.bottom.equalTo(self.snp.bottom)
make.height.equalTo(height)
}
line.tag = 100001
}
public func dj_removeBottomLine() {
subviews.forEach { (view) in
if view.tag == 100001 {
view.removeFromSuperview()
}
}
}
/// add blank view for iPhone X
public func dj_addBlankView(isHasTopLine: Bool = false) {
if dj_isIPhoneX() {
let blankView = UIView(backgroundColor: djWhite, superView: self) { (make) in
make.left.right.bottom.equalTo(self)
make.height.equalTo(34)
}
if isHasTopLine {
blankView.dj_addTopLine()
}
}
}
}
extension UIView {
/// set corner radius
public func dj_setCornerRadius(radius: CGFloat, borderWidth: CGFloat = 0.5, borderColor: UIColor? = nil) {
layer.cornerRadius = radius
layer.masksToBounds = true
if let color = borderColor {
layer.borderWidth = borderWidth
layer.borderColor = color.cgColor
}
}
}
extension UIView {
// add shadow
public func dj_addShadow() {
layer.masksToBounds = false
layer.shadowColor = djBlack.cgColor
layer.shadowOpacity = 0.1
layer.shadowOffset = CGSize(width: 0, height: 1)
layer.shadowRadius = 3
}
}
extension UIView {
/// remove all subviews
public func dj_removeAllSubviews() {
subviews.forEach { (subView) in
subView.removeFromSuperview()
}
}
/// get parent viewController
public func dj_getParentViewController() -> UIViewController? {
var next:UIView? = self
repeat{
if let nextResponder = next?.next, nextResponder.isKind(of: UIViewController.self) {
return (nextResponder as! UIViewController)
}
next = next?.superview
} while next != nil
return nil
}
}
extension UIView {
// add tap gesture to a view
public func dj_addTapGesture(_ target: Any?, action: Selector?) {
addGestureRecognizer(UITapGestureRecognizer(target: target, action: action))
}
}
| 27.392405 | 136 | 0.589187 |
220f3e7ccc12e7f1374633d1edabe6c8188d9a4c | 22,674 | //
// CLChatInputToolBar.swift
// Potato
//
// Created by AUG on 2019/10/22.
//
import UIKit
import SnapKit
import Photos
protocol CLChatInputToolBarDelegate: class {
///键盘发送文字
func inputBarWillSendText(text: String)
///键盘发送图片
func inputBarWillSendImage(images: [(image: UIImage, asset: PHAsset)])
///键盘将要显示
func inputBarWillShowKeyboard()
///键盘将要隐藏
func inputBarWillHiddenKeyboard()
///开始录音
func inputBarStartRecord()
///取消录音
func inputBarCancelRecord()
///结束录音
func inputBarFinishRecord(duration: TimeInterval, file: Data)
}
extension CLChatInputToolBarDelegate {
///键盘发送文字
func inputBarWillSendText(text: String) {
}
///键盘发送图片
func inputBarWillSendImage(images: [(image: UIImage, asset: PHAsset)]) {
}
///键盘将要显示
func inputBarWillShowKeyboard() {
}
///键盘将要隐藏
func inputBarWillHiddenKeyboard() {
}
///开始录音
func inputBarStartRecord() {
}
///取消录音
func inputBarCancelRecord() {
}
///结束录音
func inputBarFinishRecord(duration: TimeInterval, file: Data) {
}
}
class CLChatInputToolBar: UIView {
///内容视图
private lazy var contentView: UIView = {
let contentView = UIView()
return contentView
}()
///顶部线条
private lazy var topLineView: UIView = {
let topLineView = UIView()
topLineView.backgroundColor = .hexColor(with: "#DADADA")
return topLineView
}()
///顶部工具条
private lazy var topToolBar: UIView = {
let topToolBar = UIView()
topToolBar.backgroundColor = .hexColor(with: "#F6F6F6")
return topToolBar
}()
///中间内容视图
private lazy var middleSpaceView: UIView = {
let middleSpaceView = UIView()
middleSpaceView.backgroundColor = .hexColor(with: "#F6F6F6")
return middleSpaceView
}()
///底部安全区域
private lazy var bottomSafeView: UIView = {
let bottomSafeView = UIView()
bottomSafeView.backgroundColor = .hexColor(with: "#F6F6F6")
return bottomSafeView
}()
///图片按钮
private lazy var moreButton: UIButton = {
let view = UIButton()
view.expandClickEdgeInsets = UIEdgeInsets(top: 10, left: 5, bottom: 10, right: 5)
view.adjustsImageWhenHighlighted = false
view.setBackgroundImage(UIImage.init(named: "addIcon"), for: .normal)
view.setBackgroundImage(UIImage.init(named: "addIcon"), for: .selected)
view.addTarget(self, action: #selector(photoButtonAction), for: .touchUpInside)
return view
}()
///表情按钮
private lazy var emojiButton: UIButton = {
let view = UIButton()
view.expandClickEdgeInsets = UIEdgeInsets(top: 10, left: 5, bottom: 10, right: 5)
view.adjustsImageWhenHighlighted = false
view.setBackgroundImage(UIImage.init(named: "facialIcon"), for: .normal)
view.setBackgroundImage(UIImage.init(named: "facialIcon"), for: .selected)
view.addTarget(self, action: #selector(emojiButtonAction), for: .touchUpInside)
return view
}()
///录音按钮
private lazy var recordButton: UIButton = {
let view = UIButton()
view.expandClickEdgeInsets = UIEdgeInsets(top: 10, left: 5, bottom: 10, right: 5)
view.adjustsImageWhenHighlighted = false
view.setBackgroundImage(UIImage.init(named: "voiceIcon"), for: .normal)
view.setBackgroundImage(UIImage.init(named: "voiceIcon"), for: .selected)
view.addTarget(self, action: #selector(recordButtonAction), for: .touchUpInside)
return view
}()
///发送按钮
private lazy var sendButton: UIButton = {
let view = UIButton()
view.expandClickEdgeInsets = UIEdgeInsets(top: 10, left: 5, bottom: 10, right: 5)
view.isHidden = true
view.adjustsImageWhenHighlighted = false
view.setBackgroundImage(UIImage.init(named: "sendIcon"), for: .normal)
view.setBackgroundImage(UIImage.init(named: "sendIcon"), for: .selected)
view.addTarget(self, action: #selector(sendButtonAction), for: .touchUpInside)
return view
}()
///输入框
private lazy var textView: CLChatTextView = {
let view = CLChatTextView()
view.layer.cornerRadius = 5
view.clipsToBounds = true
view.backgroundColor = .white
view.autocapitalizationType = .none
view.enablesReturnKeyAutomatically = true
view.layoutManager.allowsNonContiguousLayout = false
view.scrollsToTop = false
view.delegate = self
view.returnKeyType = .send
view.autocorrectionType = .no
view.textColor = .black
view.textContainerInset = UIEdgeInsets(top: 8, left: 8, bottom:8, right: 8)
view.textContainer.lineFragmentPadding = 0
view.textViewHeightChangeCallBack = {[weak self] (height) in
self?.textViewHeightChange(height: height)
}
view.textDidChangeCallBack = {[weak self](text) in
self?.isHiddenSend = text.isEmpty || (text).isValidAllEmpty()
}
return view
}()
///表情view
private lazy var emojiView: CLChatEmojiView = {
let view = CLChatEmojiView()
view.backgroundColor = .hexColor(with: "EEEEED")
view.autoresizesSubviews = false
view.didSelectEmojiCallBack = {[weak self] (emoji) in
guard let strongSelf = self else {
return
}
if let selectedTextRange = strongSelf.textView.selectedTextRange {
strongSelf.textView .replace(selectedTextRange, withText: emoji)
}
}
view.didSelectDeleteCallBack = {[weak self] in
guard let strongSelf = self else {
return
}
DispatchQueue.main.async {
strongSelf.textView.deleteBackward()
}
}
return view
}()
///图片view
private lazy var photoView: CLChatPhotoView = {
let view = CLChatPhotoView()
view.backgroundColor = .hexColor(with: "EEEEED")
view.sendImageCallBack = {[weak self] (images) in
self?.delegate?.inputBarWillSendImage(images: images)
}
return view
}()
///录音
private lazy var recordView: CLChatRecordView = {
let view = CLChatRecordView()
view.backgroundColor = .hexColor(with: "#EEEEED")
view.startRecorderCallBack = {[weak self] in
self?.delegate?.inputBarStartRecord()
}
view.cancelRecorderCallBack = {[weak self] in
self?.delegate?.inputBarCancelRecord()
}
view.finishRecorderCallBack = {[weak self] (duration, data) in
self?.delegate?.inputBarFinishRecord(duration: duration, file: data)
}
return view
}()
///是否弹出键盘
private (set) var isShowKeyboard: Bool = false {
willSet {
if isShowKeyboard != newValue {
if newValue == true {
delegate?.inputBarWillShowKeyboard()
}else {
delegate?.inputBarWillHiddenKeyboard()
}
}
}
}
///是否隐藏发送按钮
private var isHiddenSend: Bool = true {
didSet {
if isHiddenSend != oldValue {
sendButton.isHidden = isHiddenSend
recordButton.isHidden = !isHiddenSend
let animateView = isHiddenSend ? recordButton : sendButton
animateView.transform = CGAffineTransform(scaleX: 0.8, y: 0.8)
UIView.animate(withDuration: 0.5, delay: 0, usingSpringWithDamping: 0.5, initialSpringVelocity: 0.8, options: .curveEaseOut, animations: {
animateView.transform = CGAffineTransform(scaleX: 1.0, y: 1.0)
}, completion: nil)
}
}
}
///第一次显示
private var isFristShowEmoji: Bool = true
///是否显示图片键盘
private var isShowPhotoKeyboard: Bool = false {
willSet {
if isShowPhotoKeyboard != newValue {
photoKeyboard(show: newValue)
}
}
}
///是否显示表情键盘
private var isShowEmojiKeyboard: Bool = false
///是否显示录音键盘
private var isShowVoiceKeyboard: Bool = false {
willSet {
if isShowVoiceKeyboard != newValue {
voiceKeyboard(show: newValue)
}
}
}
///是否显示文字键盘
private var isShowTextKeyboard: Bool = false
///是否正在旋转
private var isTransition: Bool = false
///输入框默认大小
private var textViewDefaultHeight: CGFloat {
get {
return CGFloat(ceilf(Float(textFont.lineHeight + textView.textContainerInset.top + textView.textContainerInset.bottom)))
}
}
///输入框改变后大小
private var textViewChangedHeight: CGFloat = 0.0
///输入框大小
var textViewHeight: CGFloat {
get {
return max(textViewDefaultHeight, textViewChangedHeight)
}
}
///初始高度
var toolBarDefaultHeight: CGFloat {
get {
return textViewDefaultHeight + 15 + 15 + safeAreaEdgeInsets().bottom
}
}
///文字大小
var textFont: UIFont = UIFont.systemFont(ofSize: 15) {
didSet {
textView.font = textFont
}
}
///最大行数
var maxNumberOfLines: Int = 5 {
didSet {
textView.maxNumberOfLines = maxNumberOfLines
}
}
///占位文字
var placeholder: String = "" {
didSet {
textView.placeholder = placeholder
}
}
///占位文字颜色
var placeholderColor: UIColor = .hexColor(with: "0x5C5C71") {
didSet {
textView.textColor = placeholderColor
}
}
///代理
weak var delegate: CLChatInputToolBarDelegate?
override init(frame: CGRect) {
super.init(frame: frame)
initUI()
makeConstraints()
addNotification()
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
deinit {
NotificationCenter.default.removeObserver(self)
}
}
//MARK: - JmoVxia---初始化
extension CLChatInputToolBar {
private func initUI() {
backgroundColor = .hexColor(with: "#F6F6F6")
addSubview(contentView)
addSubview(topLineView)
contentView.addSubview(topToolBar)
contentView.addSubview(middleSpaceView)
contentView.addSubview(bottomSafeView)
topToolBar.addSubview(moreButton)
topToolBar.addSubview(emojiButton)
topToolBar.addSubview(recordButton)
topToolBar.addSubview(sendButton)
topToolBar.addSubview(textView)
}
private func makeConstraints() {
contentView.snp.makeConstraints { (make) in
make.top.bottom.equalTo(self)
if #available(iOS 11.0, *) {
make.left.equalTo(safeAreaLayoutGuide.snp.left)
make.right.equalTo(safeAreaLayoutGuide.snp.right)
} else {
make.left.equalTo(self.snp.left)
make.right.equalTo(self.snp.right)
}
}
topLineView.snp.makeConstraints { (make) in
make.top.right.left.equalToSuperview()
make.height.equalTo(1)
}
topToolBar.snp.makeConstraints { (make) in
make.top.left.right.equalTo(contentView)
}
middleSpaceView.snp.makeConstraints { (make) in
make.top.equalTo(topToolBar.snp.bottom)
make.left.right.equalTo(contentView)
make.height.equalTo(0)
}
bottomSafeView.snp.makeConstraints { (make) in
make.top.equalTo(middleSpaceView.snp.bottom)
make.left.right.bottom.equalTo(contentView)
make.height.equalTo(safeAreaEdgeInsets().bottom)
}
moreButton.snp.makeConstraints { (make) in
make.left.equalTo(12)
make.width.height.equalTo(textViewHeight - 8)
make.bottom.equalTo(textView.snp.bottom).offset(-4)
}
emojiButton.snp.makeConstraints { (make) in
make.left.equalTo(moreButton.snp.right).offset(12)
make.width.height.equalTo(textViewHeight - 8)
make.bottom.equalTo(textView.snp.bottom).offset(-4)
}
recordButton.snp.makeConstraints { (make) in
make.right.equalTo(-12)
make.width.height.equalTo(textViewHeight - 8)
make.bottom.equalTo(textView.snp.bottom).offset(-4)
}
sendButton.snp.makeConstraints { (make) in
make.edges.equalTo(recordButton)
}
textView.snp.makeConstraints { (make) in
make.left.equalTo(emojiButton.snp.right).offset(12)
make.right.equalTo(recordButton.snp.left).offset(-12)
make.height.equalTo(textViewHeight)
make.top.equalTo(15)
make.bottom.equalTo(topToolBar.snp.bottom).offset(-15)
}
}
private func addNotification() {
NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillShow(notification:)), name: UIResponder.keyboardWillShowNotification, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillHide(notification:)), name: UIResponder.keyboardWillHideNotification, object: nil)
}
}
//MARK: - JmoVxia---键盘监听
extension CLChatInputToolBar {
@objc private func keyboardWillShow(notification: Notification) {
guard let userInfo = notification.userInfo, let keyboardRect = userInfo[UIResponder.keyboardFrameEndUserInfoKey] as? CGRect, let duration = userInfo[UIResponder.keyboardAnimationDurationUserInfoKey] as? TimeInterval, let options = userInfo[UIResponder.keyboardAnimationCurveUserInfoKey] as? NSInteger else {return}
var keyboardHeight: CGFloat = keyboardRect.height - safeAreaEdgeInsets().bottom
if isShowEmojiKeyboard {
keyboardHeight = emojiView.height - safeAreaEdgeInsets().bottom
}
if isShowPhotoKeyboard {
keyboardHeight = photoView.height - safeAreaEdgeInsets().bottom
}
if isShowVoiceKeyboard {
keyboardHeight = recordView.height - safeAreaEdgeInsets().bottom
}
middleSpaceView.snp.updateConstraints { (make) in
make.height.equalTo(keyboardHeight)
}
UIView.animate(withDuration: duration, delay: 0, options: UIView.AnimationOptions(rawValue: UIView.AnimationOptions.RawValue(options)), animations: {
self.superview?.setNeedsLayout()
self.superview?.layoutIfNeeded()
})
}
@objc private func keyboardWillHide(notification: Notification) {
guard let userInfo = notification.userInfo, let duration = userInfo[UIResponder.keyboardAnimationDurationUserInfoKey] as? TimeInterval, let options = userInfo[UIResponder.keyboardAnimationCurveUserInfoKey] as? NSInteger else {return}
if isShowPhotoKeyboard || isShowVoiceKeyboard || isTransition {
return
}
isShowEmojiKeyboard = false
middleSpaceView.snp.updateConstraints { (make) in
make.height.equalTo(0)
}
UIView.animate(withDuration: duration, delay: 0, options:UIView.AnimationOptions(rawValue: UIView.AnimationOptions.RawValue(options)) , animations: {
self.superview?.setNeedsLayout()
self.superview?.layoutIfNeeded()
}, completion: { (_) in
self.textView.inputView = nil;
})
}
}
//MARK: - JmoVxia---UI改变
extension CLChatInputToolBar {
private func textViewHeightChange(height: CGFloat) {
textViewChangedHeight = height
textView.snp.updateConstraints { (make) in
make.height.equalTo(height)
}
}
}
//MARK: - JmoVxia---按钮点击事件
extension CLChatInputToolBar {
@objc private func photoButtonAction() {
isShowEmojiKeyboard = false
isShowVoiceKeyboard = false
contentView.addSubview(photoView)
if isShowPhotoKeyboard == false {
isShowPhotoKeyboard = true
textViewResignFirstResponder()
textView.inputView = nil
}else {
isShowPhotoKeyboard = false
isShowEmojiKeyboard = textView.inputView == emojiView
isShowTextKeyboard = !isShowEmojiKeyboard
textViewBecomeFirstResponder()
}
}
@objc private func recordButtonAction() {
isShowEmojiKeyboard = false
isShowPhotoKeyboard = false
contentView.addSubview(recordView)
if isShowVoiceKeyboard == false {
isShowVoiceKeyboard = true
textViewResignFirstResponder()
textView.inputView = nil
}else {
isShowVoiceKeyboard = false
isShowEmojiKeyboard = textView.inputView == emojiView
isShowTextKeyboard = !isShowEmojiKeyboard
textViewBecomeFirstResponder()
}
}
@objc private func emojiButtonAction() {
isShowPhotoKeyboard = false
isShowVoiceKeyboard = false
if isShowEmojiKeyboard == false {
textView.inputView = emojiView
}else {
textView.inputView = nil
}
isShowEmojiKeyboard = !isShowEmojiKeyboard
textViewBecomeFirstResponder()
if isFristShowEmoji {
isFristShowEmoji = false
textView.reloadInputViews()
}else {
UIView.animate(withDuration: 0.25) {
self.textView.reloadInputViews()
}
}
}
@objc private func sendButtonAction() {
if !(textView.text).isValidAllEmpty() {
delegate?.inputBarWillSendText(text: textView.text)
textView.text = ""
}
}
private func keyboardChange() {
isShowKeyboard = isShowPhotoKeyboard || isShowEmojiKeyboard || isShowVoiceKeyboard || isShowTextKeyboard
}
private func photoKeyboard(show: Bool) {
contentView.addSubview(photoView)
if show {
photoView.snp.remakeConstraints { (make) in
make.left.right.equalTo(contentView)
make.height.equalTo(photoView.height)
make.top.equalTo(contentView.snp.bottom)
}
setNeedsLayout()
layoutIfNeeded()
UIView.animate(withDuration: 0.25) {
self.photoView.snp.remakeConstraints { (make) in
make.left.right.equalTo(self.contentView)
make.height.equalTo(self.photoView.height)
make.top.equalTo(self.contentView.snp.bottom).offset(-self.photoView.height)
}
self.middleSpaceView.snp.updateConstraints { (make) in
make.height.equalTo(self.photoView.height - safeAreaEdgeInsets().bottom)
}
self.superview?.setNeedsLayout()
self.superview?.layoutIfNeeded()
}
}else {
UIView.animate(withDuration: 0.25) {
self.photoView.snp.updateConstraints { (make) in
make.top.equalTo(self.contentView.snp.bottom)
}
self.superview?.setNeedsLayout()
self.superview?.layoutIfNeeded()
}
}
}
private func voiceKeyboard(show: Bool) {
contentView.addSubview(recordView)
if show {
recordView.snp.remakeConstraints { (make) in
make.left.right.equalTo(contentView)
make.height.equalTo(recordView.height)
make.top.equalTo(contentView.snp.bottom)
}
setNeedsLayout()
layoutIfNeeded()
UIView.animate(withDuration: 0.25) {
self.recordView.snp.remakeConstraints { (make) in
make.left.right.equalTo(self.contentView)
make.height.equalTo(self.recordView.height)
make.top.equalTo(self.contentView.snp.bottom).offset(-self.recordView.height)
}
self.middleSpaceView.snp.updateConstraints { (make) in
make.height.equalTo(self.recordView.height - safeAreaEdgeInsets().bottom)
}
self.superview?.setNeedsLayout()
self.superview?.layoutIfNeeded()
}
}else {
UIView.animate(withDuration: 0.25) {
self.recordView.snp.updateConstraints { (make) in
make.top.equalTo(self.contentView.snp.bottom)
}
self.superview?.setNeedsLayout()
self.superview?.layoutIfNeeded()
}
}
}
private func textViewBecomeFirstResponder() {
textView.becomeFirstResponder()
isShowEmojiKeyboard = textView.inputView == emojiView
isShowTextKeyboard = !isShowEmojiKeyboard
keyboardChange()
}
private func textViewResignFirstResponder() {
textView.resignFirstResponder()
isShowTextKeyboard = false
keyboardChange()
}
}
//MARK: - JmoVxia---对外接口
extension CLChatInputToolBar {
///控制器将要旋转
func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) {
isTransition = true
coordinator.animate(alongsideTransition: nil) { (_) in
self.isTransition = false
}
emojiView.viewWillTransition(to: size, with: coordinator)
}
///隐藏键盘
func dismissKeyboard() {
isShowPhotoKeyboard = false
isShowEmojiKeyboard = false
isShowVoiceKeyboard = false
middleSpaceView.snp.updateConstraints { (make) in
make.height.equalTo(0)
}
UIView.animate(withDuration: 0.25, animations: {
self.superview?.setNeedsLayout()
self.superview?.layoutIfNeeded()
}) { (_) in
self.photoView.hiddenAlbumContentView()
}
textViewResignFirstResponder()
}
}
extension CLChatInputToolBar: UITextViewDelegate {
func textViewShouldBeginEditing(_ textView: UITextView) -> Bool {
isShowPhotoKeyboard = false
isShowVoiceKeyboard = false
return true
}
func textViewDidBeginEditing(_ textView: UITextView) {
textViewBecomeFirstResponder()
}
func textViewDidEndEditing(_ textView: UITextView) {
textViewResignFirstResponder()
}
func textView(_ textView: UITextView, shouldChangeTextIn range: NSRange, replacementText text: String) -> Bool {
if text == "\n" {
sendButtonAction()
return false
}
return true
}
}
| 36.68932 | 322 | 0.614845 |
64cec61fa5561ba2f05a889b818fa6c2468feec6 | 708 | //
// SettingsViewController.swift
// SoloProjectFireBase
//
// Created by Olimpia on 2/26/19.
// Copyright © 2019 Olimpia. All rights reserved.
//
import UIKit
class SettingsViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
/*
// 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.destination.
// Pass the selected object to the new view controller.
}
*/
}
| 22.83871 | 106 | 0.670904 |
720409027ba98139b9281f68b6750daa613de18a | 7,379 | // DO NOT EDIT.
//
// Generated by the Swift generator plugin for the protocol buffer compiler.
// Source: tron.proto
//
// For information on using the generated types, please see the documentation:
// https://github.com/apple/swift-protobuf/
import Foundation
import SwiftProtobuf
// If the compiler emits an error on this type, it is because this file
// was generated by a version of the `protoc` Swift plug-in that is
// incompatible with the version of SwiftProtobuf to which you are linking.
// Please ensure that your are building against the same version of the API
// that was used to generate this file.
fileprivate struct _GeneratedWithProtocGenSwiftVersion: SwiftProtobuf.ProtobufAPIVersionCheck {
struct _2: SwiftProtobuf.ProtobufAPIVersion_2 {}
typealias Version = _2
}
public struct Tronapi_TronTxInput {
// SwiftProtobuf.Message conformance is added in an extension below. See the
// `Message` and `Message+*Additions` files in the SwiftProtobuf library for
// methods supported on all messages.
public var rawData: String = String()
public var unknownFields = SwiftProtobuf.UnknownStorage()
public init() {}
}
public struct Tronapi_TronTxOutput {
// SwiftProtobuf.Message conformance is added in an extension below. See the
// `Message` and `Message+*Additions` files in the SwiftProtobuf library for
// methods supported on all messages.
public var signature: String = String()
public var unknownFields = SwiftProtobuf.UnknownStorage()
public init() {}
}
public struct Tronapi_TronMessageInput {
// SwiftProtobuf.Message conformance is added in an extension below. See the
// `Message` and `Message+*Additions` files in the SwiftProtobuf library for
// methods supported on all messages.
public var message: String = String()
public var isHex: Bool = false
public var isTronHeader: Bool = false
public var unknownFields = SwiftProtobuf.UnknownStorage()
public init() {}
}
public struct Tronapi_TronMessageOutput {
// SwiftProtobuf.Message conformance is added in an extension below. See the
// `Message` and `Message+*Additions` files in the SwiftProtobuf library for
// methods supported on all messages.
public var signature: String = String()
public var unknownFields = SwiftProtobuf.UnknownStorage()
public init() {}
}
// MARK: - Code below here is support for the SwiftProtobuf runtime.
fileprivate let _protobuf_package = "tronapi"
extension Tronapi_TronTxInput: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding {
public static let protoMessageName: String = _protobuf_package + ".TronTxInput"
public static let _protobuf_nameMap: SwiftProtobuf._NameMap = [
2: .standard(proto: "raw_data"),
]
public mutating func decodeMessage<D: SwiftProtobuf.Decoder>(decoder: inout D) throws {
while let fieldNumber = try decoder.nextFieldNumber() {
switch fieldNumber {
case 2: try decoder.decodeSingularStringField(value: &self.rawData)
default: break
}
}
}
public func traverse<V: SwiftProtobuf.Visitor>(visitor: inout V) throws {
if !self.rawData.isEmpty {
try visitor.visitSingularStringField(value: self.rawData, fieldNumber: 2)
}
try unknownFields.traverse(visitor: &visitor)
}
public static func ==(lhs: Tronapi_TronTxInput, rhs: Tronapi_TronTxInput) -> Bool {
if lhs.rawData != rhs.rawData {return false}
if lhs.unknownFields != rhs.unknownFields {return false}
return true
}
}
extension Tronapi_TronTxOutput: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding {
public static let protoMessageName: String = _protobuf_package + ".TronTxOutput"
public static let _protobuf_nameMap: SwiftProtobuf._NameMap = [
1: .same(proto: "signature"),
]
public mutating func decodeMessage<D: SwiftProtobuf.Decoder>(decoder: inout D) throws {
while let fieldNumber = try decoder.nextFieldNumber() {
switch fieldNumber {
case 1: try decoder.decodeSingularStringField(value: &self.signature)
default: break
}
}
}
public func traverse<V: SwiftProtobuf.Visitor>(visitor: inout V) throws {
if !self.signature.isEmpty {
try visitor.visitSingularStringField(value: self.signature, fieldNumber: 1)
}
try unknownFields.traverse(visitor: &visitor)
}
public static func ==(lhs: Tronapi_TronTxOutput, rhs: Tronapi_TronTxOutput) -> Bool {
if lhs.signature != rhs.signature {return false}
if lhs.unknownFields != rhs.unknownFields {return false}
return true
}
}
extension Tronapi_TronMessageInput: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding {
public static let protoMessageName: String = _protobuf_package + ".TronMessageInput"
public static let _protobuf_nameMap: SwiftProtobuf._NameMap = [
2: .same(proto: "message"),
4: .standard(proto: "is_hex"),
5: .standard(proto: "is_tron_header"),
]
public mutating func decodeMessage<D: SwiftProtobuf.Decoder>(decoder: inout D) throws {
while let fieldNumber = try decoder.nextFieldNumber() {
switch fieldNumber {
case 2: try decoder.decodeSingularStringField(value: &self.message)
case 4: try decoder.decodeSingularBoolField(value: &self.isHex)
case 5: try decoder.decodeSingularBoolField(value: &self.isTronHeader)
default: break
}
}
}
public func traverse<V: SwiftProtobuf.Visitor>(visitor: inout V) throws {
if !self.message.isEmpty {
try visitor.visitSingularStringField(value: self.message, fieldNumber: 2)
}
if self.isHex != false {
try visitor.visitSingularBoolField(value: self.isHex, fieldNumber: 4)
}
if self.isTronHeader != false {
try visitor.visitSingularBoolField(value: self.isTronHeader, fieldNumber: 5)
}
try unknownFields.traverse(visitor: &visitor)
}
public static func ==(lhs: Tronapi_TronMessageInput, rhs: Tronapi_TronMessageInput) -> Bool {
if lhs.message != rhs.message {return false}
if lhs.isHex != rhs.isHex {return false}
if lhs.isTronHeader != rhs.isTronHeader {return false}
if lhs.unknownFields != rhs.unknownFields {return false}
return true
}
}
extension Tronapi_TronMessageOutput: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding {
public static let protoMessageName: String = _protobuf_package + ".TronMessageOutput"
public static let _protobuf_nameMap: SwiftProtobuf._NameMap = [
1: .same(proto: "signature"),
]
public mutating func decodeMessage<D: SwiftProtobuf.Decoder>(decoder: inout D) throws {
while let fieldNumber = try decoder.nextFieldNumber() {
switch fieldNumber {
case 1: try decoder.decodeSingularStringField(value: &self.signature)
default: break
}
}
}
public func traverse<V: SwiftProtobuf.Visitor>(visitor: inout V) throws {
if !self.signature.isEmpty {
try visitor.visitSingularStringField(value: self.signature, fieldNumber: 1)
}
try unknownFields.traverse(visitor: &visitor)
}
public static func ==(lhs: Tronapi_TronMessageOutput, rhs: Tronapi_TronMessageOutput) -> Bool {
if lhs.signature != rhs.signature {return false}
if lhs.unknownFields != rhs.unknownFields {return false}
return true
}
}
| 35.995122 | 137 | 0.739125 |
e96c5d0ad60d9fcbe342bdb3556ceb178c2b6c13 | 2,261 | //
// AppDelegate.swift
// quickui
//
// Created by kaygro on 04/13/2020.
// Copyright (c) 2020 kaygro. All rights reserved.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
let menu = MainMenuFactory.MakeMainMenu()
self.window = UIWindow(frame: UIScreen.main.bounds)
window?.rootViewController = menu
window?.makeKeyAndVisible()
return true
}
func applicationWillResignActive(_ application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}
func applicationDidEnterBackground(_ application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(_ application: UIApplication) {
// Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(_ application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(_ application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}
}
| 45.22 | 285 | 0.754091 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.