repo_name
stringlengths 6
91
| path
stringlengths 8
968
| copies
stringclasses 202
values | size
stringlengths 2
7
| content
stringlengths 61
1.01M
| license
stringclasses 15
values | hash
stringlengths 32
32
| line_mean
float64 6
99.8
| line_max
int64 12
1k
| alpha_frac
float64 0.3
0.91
| ratio
float64 2
9.89
| autogenerated
bool 1
class | config_or_test
bool 2
classes | has_no_keywords
bool 2
classes | has_few_assignments
bool 1
class |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
damoyan/BYRClient
|
FromScratch/View/UIViewExtension.swift
|
1
|
804
|
//
// UIViewExtension.swift
// FromScratch
//
// Created by Yu Pengyang on 12/23/15.
// Copyright © 2015 Yu Pengyang. All rights reserved.
//
import UIKit
extension UIView {
@IBInspectable
var borderWidth: CGFloat {
get {
return layer.borderWidth
}
set {
layer.borderWidth = newValue
}
}
@IBInspectable
var borderColor: UIColor? {
get {
return layer.borderColor == nil ? nil : UIColor(CGColor: layer.borderColor!)
}
set {
layer.borderColor = newValue?.CGColor
}
}
@IBInspectable
var cornerRadius: CGFloat {
get {
return layer.cornerRadius
}
set {
layer.cornerRadius = newValue
}
}
}
|
mit
|
f577ed4dd278ad56e2dbe69e1cf2fee0
| 18.585366 | 88 | 0.533001 | 4.668605 | false | false | false | false |
wireapp/wire-ios
|
Wire-iOS/Sources/UserInterface/UserProfile/ProfileViewControllerViewModel.swift
|
1
|
8906
|
//
// Wire
// Copyright (C) 2019 Wire Swiss GmbH
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see http://www.gnu.org/licenses/.
//
import Foundation
import WireDataModel
import WireSystem
import WireSyncEngine
private let zmLog = ZMSLog(tag: "ProfileViewControllerViewModel")
enum ProfileViewControllerContext {
case search
case groupConversation
case oneToOneConversation
case deviceList
/// when opening from a URL scheme, not linked to a specific conversation
case profileViewer
}
final class ProfileViewControllerViewModel: NSObject {
let user: UserType
let conversation: ZMConversation?
let viewer: UserType
let context: ProfileViewControllerContext
let classificationProvider: ClassificationProviding?
weak var delegate: ProfileViewControllerDelegate? {
didSet {
backButtonTitleDelegate = delegate as? BackButtonTitleDelegate
}
}
weak var backButtonTitleDelegate: BackButtonTitleDelegate?
private var observerToken: Any?
weak var viewModelDelegate: ProfileViewControllerViewModelDelegate?
init(user: UserType,
conversation: ZMConversation?,
viewer: UserType,
context: ProfileViewControllerContext,
classificationProvider: ClassificationProviding? = ZMUserSession.shared()
) {
self.user = user
self.conversation = conversation
self.viewer = viewer
self.context = context
self.classificationProvider = classificationProvider
super.init()
if let userSession = ZMUserSession.shared() {
observerToken = UserChangeInfo.add(observer: self, for: user, in: userSession)
}
}
var classification: SecurityClassification {
classificationProvider?.classification(with: [user]) ?? .none
}
var hasLegalHoldItem: Bool {
return user.isUnderLegalHold || conversation?.isUnderLegalHold == true
}
var shouldShowVerifiedShield: Bool {
return user.isVerified && context != .deviceList
}
var hasUserClientListTab: Bool {
return context != .search &&
context != .profileViewer
}
var userSet: UserSet {
return UserSet(arrayLiteral: user)
}
var incomingRequestFooterHidden: Bool {
return !user.isPendingApprovalBySelfUser
}
var blockTitle: String? {
return BlockResult.title(for: user)
}
var allBlockResult: [BlockResult] {
return BlockResult.all(isBlocked: user.isBlocked)
}
func cancelConnectionRequest(completion: @escaping Completion) {
self.user.cancelConnectionRequest { [weak self] error in
if let error = error as? ConnectToUserError {
self?.viewModelDelegate?.presentError(error)
} else {
completion()
}
}
}
func toggleBlocked() {
if user.isBlocked {
user.accept { [weak self] error in
if let error = error as? LocalizedError {
self?.viewModelDelegate?.presentError(error)
}
}
} else {
user.block { [weak self] error in
if let error = error as? LocalizedError {
self?.viewModelDelegate?.presentError(error)
}
}
}
}
func openOneToOneConversation() {
var conversation: ZMConversation?
ZMUserSession.shared()?.enqueue({
conversation = self.user.oneToOneConversation
}, completionHandler: {
guard let conversation = conversation else { return }
self.delegate?.profileViewController(self.viewModelDelegate as? ProfileViewController,
wantsToNavigateTo: conversation)
})
}
// MARK: - Action Handlers
func archiveConversation() {
transitionToListAndEnqueue {
self.conversation?.isArchived.toggle()
}
}
func handleBlockAndUnblock() {
switch context {
case .search:
/// stay on this VC and let user to decise what to do next
enqueueChanges(toggleBlocked)
default:
transitionToListAndEnqueue { self.toggleBlocked() }
}
}
// MARK: - Notifications
func updateMute(enableNotifications: Bool) {
ZMUserSession.shared()?.enqueue {
self.conversation?.mutedMessageTypes = enableNotifications ? .none : .all
// update the footer view to display the correct mute/unmute button
self.viewModelDelegate?.updateFooterViews()
}
}
func handleNotificationResult(_ result: NotificationResult) {
if let mutedMessageTypes = result.mutedMessageTypes {
ZMUserSession.shared()?.perform {
self.conversation?.mutedMessageTypes = mutedMessageTypes
}
}
}
// MARK: Delete Contents
func handleDeleteResult(_ result: ClearContentResult) {
guard case .delete(leave: let leave) = result else { return }
transitionToListAndEnqueue {
self.conversation?.clearMessageHistory()
if leave {
self.conversation?.removeOrShowError(participant: SelfUser.current)
}
}
}
// MARK: - Helpers
func transitionToListAndEnqueue(leftViewControllerRevealed: Bool = true, _ block: @escaping () -> Void) {
ZClientViewController.shared?.transitionToList(animated: true,
leftViewControllerRevealed: leftViewControllerRevealed) {
self.enqueueChanges(block)
}
}
func enqueueChanges(_ block: @escaping () -> Void) {
ZMUserSession.shared()?.enqueue(block)
}
// MARK: - Factories
func makeUserNameDetailViewModel() -> UserNameDetailViewModel {
// TODO: add addressBookEntry to ZMUser
return UserNameDetailViewModel(user: user, fallbackName: user.name ?? "", addressBookName: (user as? ZMUser)?.addressBookEntry?.cachedName)
}
var profileActionsFactory: ProfileActionsFactory {
return ProfileActionsFactory(user: user, viewer: viewer, conversation: conversation, context: context)
}
// MARK: Connect
func sendConnectionRequest() {
user.connect { [weak self] error in
if let error = error as? ConnectToUserError {
self?.viewModelDelegate?.presentError(error)
}
self?.viewModelDelegate?.updateFooterViews()
}
}
func acceptConnectionRequest() {
user.accept { [weak self] error in
if let error = error as? ConnectToUserError {
self?.viewModelDelegate?.presentError(error)
} else {
self?.user.refreshData()
self?.viewModelDelegate?.updateFooterViews()
}
}
}
func ignoreConnectionRequest() {
user.ignore { [weak self] error in
if let error = error as? ConnectToUserError {
self?.viewModelDelegate?.presentError(error)
} else {
self?.viewModelDelegate?.returnToPreviousScreen()
}
}
}
}
extension ProfileViewControllerViewModel: ZMUserObserver {
func userDidChange(_ note: UserChangeInfo) {
if note.trustLevelChanged {
viewModelDelegate?.updateShowVerifiedShield()
}
if note.legalHoldStatusChanged {
viewModelDelegate?.setupNavigationItems()
}
if note.nameChanged {
viewModelDelegate?.updateTitleView()
}
if note.user.isAccountDeleted || note.connectionStateChanged {
viewModelDelegate?.updateFooterViews()
}
}
}
extension ProfileViewControllerViewModel: BackButtonTitleDelegate {
func suggestedBackButtonTitle(for controller: ProfileViewController?) -> String? {
return user.name?.uppercasedWithCurrentLocale
}
}
protocol ProfileViewControllerViewModelDelegate: AnyObject {
func updateShowVerifiedShield()
func setupNavigationItems()
func updateFooterViews()
func updateTitleView()
func returnToPreviousScreen()
func presentError(_ error: LocalizedError)
}
|
gpl-3.0
|
8583824d6893f016259db439285f3518
| 30.469965 | 147 | 0.636762 | 5.329743 | false | false | false | false |
developerY/Active-Learning-Swift-2.0_OLD
|
ActiveLearningSwift2.playground/Pages/Optional.xcplaygroundpage/Contents.swift
|
3
|
7170
|
//: [Previous](@previous)
//: ------------------------------------------------------------------------------------------------
//: Things to know:
//:
//: * An optional value is a stored value that can either hold a value or "no value at all"
//:
//: * This is similar to assigning a stored value to "nil" but Optionals work with any type of
//: stored value, including Int, Bool, etc.
//: ------------------------------------------------------------------------------------------------
//: An optional declaration adds a "?" immediately after the explicit type. The following line
//: defines a value 'someOptional' that can either hold an Int or no value at all. In this case
//: we set an optional Int value to .None (similar to nil)
let someOptional: Int? = .None
//: Let's try to convert a String to an Int
//:
//: Using the String's toInt() method, we'll try to convert a string to a numeric value. Since not
//: all strings can be converted to an Integer, the toInt() returns an optional, "Int?". This way
//: we can recognize failed conversions without having to trap exceptions or use other arcane
//: methods to recognize the failure.
//:
//: Here's an optional in action
let notNumber = "abc"
let failedConversion = Int(notNumber)
//: Notice how failedConversion is 'nil', even though it's an Int
failedConversion
//: Let's carry on with a successful conversion
let possibleNumber = "123"
var optionalConvertedNumber = Int(possibleNumber)
//: This one worked
optionalConvertedNumber
//: If we assign it to a constant, the type of that constant will be an Optional Int (Int?)
let unwrapped = optionalConvertedNumber //: 'unwrapped' is another optional
//: ------------------------------------------------------------------------------------------------
//: Alternate syntax for Optionals
//:
//: The use of a "?" for the syntax of an optional is syntactic sugar for the use of the Generic
//: Optional type defined in Swift's standard library. We haven't gotten into Generics yet, but
//: let's not let that stop us from learning this little detail.
//:
//: These two lines are of equivalent types:
let optionalA: String? = .None
let optionalB: Optional<String> = .None
//: ------------------------------------------------------------------------------------------------
//: Unwrapping
//:
//: The difference between Int and Int? is important. Optionals essentially "wrap" their contents
//: which means that Int and Int? are two different types (with the latter being wrapped in an
//: optional.
//:
//: We can't explicity convert to an Int because that's not the same as an Int?. The following
//: line won't compile:
//:
//: let unwrappedInt: Int = optionalConvertedNumber
//: One way to do this is to "force unwrap" the value using the "!" symbol, like this:
let unwrappedInt = optionalConvertedNumber!
//: Implicit unwrapping isn't very safe because if the optional doesn't hold a value, it will
//: generate a runtime error. To verify that is's safe, you can check the optional with an if
//: statement.
if optionalConvertedNumber != .None
{
//: It's now safe to force-unwrap because we KNOW it has a value
let anotherUnwrappedInt = optionalConvertedNumber!
}
else
{
//: The optional holds "no value"
"Nothing to see here, go away"
}
//: ------------------------------------------------------------------------------------------------
//: Optional Binding
//:
//: We can conditionally store the unwrapped value to a stored value if the optional holds a value.
//:
//: In the following block, we'll optionally bind the Int value to a constant named 'intValue'
if let intValue = optionalConvertedNumber
{
//: No need to use the "!" suffix as intValue is not optional
intValue
//: In fact, since 'intValue' is an Int (not an Int?) we can't use the force-unwrap. This line
//: of code won't compile:
//: intValue!
}
else
{
//: Note that 'intValue' doesn't exist in this "else" scope
"No value"
}
//: We can still use optional binding to bind to another optional value, if we do so explicitly
//: by specifying the type of the stored value that we're binding to.
if let optionalIntValue:Int? = optionalConvertedNumber
{
// 'optionalIntValue' is still an optional, but it's known to be safe. We can still check
// it here, though, because it's still an optional. If it weren't optional, this if statement
// wouldn't compile:
if optionalIntValue != .None
{
// 'optionalIntValue' is optional, so we still use the force-unwrap here:
"intValue is optional, but has the value \(optionalIntValue!)"
}
}
//: Setting an optional to 'nil' sets it to be contain "no value"
optionalConvertedNumber = nil
//: Now if we check it, we see that it holds no value:
if optionalConvertedNumber != .None
{
"optionalConvertedNumber holds a value (\(optionalConvertedNumber))! (this should not happen)"
}
else
{
"optionalConvertedNumber holds no value"
}
//: We can also try optional binding on an empty optional
if let optionalIntValue = optionalConvertedNumber
{
"optionalIntValue holds a value (\(optionalIntValue))! (this should not happen)"
}
else
{
"optionalIntValue holds no value"
}
//: Because of the introduction of optionals, you can no longer use nil for non-optional
//: variables or constants.
//:
//: The following line will not compile
//:
//: var failure: String = nil //: Won't compile
//: The following line will compile, because the String is optional
var noString: String? = nil
//: If we create an optional without an initializer, it is automatically initialized to nil. In
//: future sections, we'll learn that all values must be initialized before they are used. Because
//: of this behavior, this variable is considered initialized, even though it holds no value:
var emptyOptional: String?
//: Another way to implicitly unwrap an optional is during declaration of a new stored value
//:
//: Here, we create an optional that we are pretty sure will always hold a value, so we give Swift
//: permission to automatically unwrap it whenever it needs to.
//:
//: Note the type, "String!"
var assumedString: String! = "An implicitly unwrapped optional string"
//: Although assumedString is still an optional (and can be treated as one), it will also
//: automatically unwrap if we try to use it like a normal String.
//:
//: Note that we perform no unwrapping in order to assign the value to a normal String
let copyOfAssumedString: String = assumedString
//: Since assumedString is still an optional, we can still set it to nil. This is dangerous to do
//: because we assumed it is always going to hold a value (and we gave permission to automatically
//: unwrap it.) So by doing this, we are taking a risk:
assumedString = nil
//: BE SURE that your implicitly unwrapped optionals actually hold values!
//:
//: The following line will compile, but will generate a runtime error because of the automatic
//: unwrapping.
//:
//: let errorString: String = assumedString
//: Like any other optional, we can still check if it holds a value:
if assumedString != nil
{
"We have a value"
}
else
{
"No value"
}
//: [Next](@next)
|
apache-2.0
|
b92fe9deae2e8c53ad4c5f4cf2fddafb
| 36.736842 | 100 | 0.671688 | 4.484053 | false | false | false | false |
magicien/GLTFSceneKit
|
Sample/iOS/GameViewController.swift
|
1
|
2312
|
//
// GameViewController.swift
// GLTFSceneKitSampler
//
// Created by magicien on 2017/08/26.
// Copyright © 2017年 DarkHorse. All rights reserved.
//
import UIKit
import QuartzCore
import SceneKit
import GLTFSceneKit
class GameViewController: UIViewController {
var gameView: SCNView? {
get { return self.view as? SCNView }
}
var scene: SCNScene?
override func viewDidLoad() {
super.viewDidLoad()
var scene: SCNScene
do {
let sceneSource = try GLTFSceneSource(named: "art.scnassets/GlassVase/Wayfair-GlassVase-BCHH2364.glb")
scene = try sceneSource.scene()
} catch {
print("\(error.localizedDescription)")
return
}
self.setScene(scene)
self.gameView!.autoenablesDefaultLighting = true
// allows the user to manipulate the camera
self.gameView!.allowsCameraControl = true
// show statistics such as fps and timing information
self.gameView!.showsStatistics = true
// configure the view
self.gameView!.backgroundColor = UIColor.gray
self.gameView!.delegate = self
}
func setScene(_ scene: SCNScene) {
// set the scene to the view
self.gameView!.scene = scene
self.scene = scene
//to give nice reflections :)
scene.lightingEnvironment.contents = "art.scnassets/shinyRoom.jpg"
scene.lightingEnvironment.intensity = 2;
}
override var shouldAutorotate: Bool {
return true
}
override var prefersStatusBarHidden: Bool {
return true
}
override var supportedInterfaceOrientations: UIInterfaceOrientationMask {
if UIDevice.current.userInterfaceIdiom == .phone {
return .allButUpsideDown
} else {
return .all
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Release any cached data, images, etc that aren't in use.
}
}
extension GameViewController: SCNSceneRendererDelegate {
func renderer(_ renderer: SCNSceneRenderer, didApplyAnimationsAtTime time: TimeInterval) {
self.scene?.rootNode.updateVRMSpringBones(time: time)
}
}
|
mit
|
c3985f8ca3e361ed4e667ecdff8bdd56
| 25.848837 | 114 | 0.62971 | 5.085903 | false | false | false | false |
lawrnce/PopUpCollectionView
|
Example/PopUpCollectionView/ViewController.swift
|
1
|
2874
|
//
// ViewController.swift
// PopUpCollectionView
//
// Created by Lawrence Tran on 03/31/2016.
// Copyright (c) 2016 Lawrence Tran. All rights reserved.
//
import UIKit
import FLAnimatedImage
import PopUpCollectionView
class ViewController: UIViewController {
@IBOutlet weak var popUpCollectionView: PopUpCollectionView!
fileprivate var shouldHideStatusBar: Bool = false
fileprivate var demoData: [FLAnimatedImage]!
override func viewDidLoad() {
super.viewDidLoad()
self.popUpCollectionView.delegate = self
self.popUpCollectionView.dataSource = self
self.demoData = [FLAnimatedImage]()
// setup demo data
for index in 0...10 {
let gifPath = Bundle.main.url(forResource: "\(index)", withExtension: "gif")
let data = try? Data(contentsOf: gifPath!)
let gif = FLAnimatedImage(gifData: data!)
self.demoData.append(gif!)
self.popUpCollectionView.reloadData()
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
override var prefersStatusBarHidden : Bool {
return self.shouldHideStatusBar
}
}
extension ViewController: PopUpCollectionViewDataSource {
func popUpCollectionView(_ popUpCollectionView: PopUpCollectionView, numberOfItemsInSection section: Int) -> Int {
return self.demoData.count
}
func popUpCollectionView(_ popUpCollectionView: PopUpCollectionView, contentViewAtIndexPath indexPath: IndexPath) -> UIView {
let animatedImageView = FLAnimatedImageView(frame: CGRect.zero)
animatedImageView.contentMode = .scaleAspectFill
animatedImageView.animatedImage = self.demoData[indexPath.row]
animatedImageView.sizeToFit()
animatedImageView.startAnimating()
return animatedImageView
}
func popUpCollectionView(_ popUpCollectionView: PopUpCollectionView, infoViewForItemAtIndexPath indexPath: IndexPath) -> UIView {
let label = UILabel(frame: CGRect.zero)
label.textAlignment = .center
label.baselineAdjustment = .alignCenters
label.text = "Info for \(indexPath.row)"
label.font = UIFont(name: "Avenir", size: 24.0)
label.frame = CGRect(x: 0, y: 0, width: UIScreen.main.bounds.width, height: 100)
return label
}
}
extension ViewController: PopUpCollectionViewDelegate {
func popUpCollectionView(_ popUpCollectionView: PopUpCollectionView, sizeForItemAtIndexPath indexPath: IndexPath) -> CGSize {
return self.demoData[indexPath.row].size
}
func setStatusBarHidden(_ hidden: Bool) {
self.shouldHideStatusBar = hidden
setNeedsStatusBarAppearanceUpdate()
}
}
|
agpl-3.0
|
b61e749a93139c11911bb98f9d771038
| 32.811765 | 133 | 0.682672 | 5.332096 | false | false | false | false |
Olinguito/YoIntervengoiOS
|
Yo Intervengo/Helpers/Components/Connection.swift
|
1
|
4689
|
//
// Connection.swift
// Yo Intervengo
//
// Created by Jorge Raul Ovalle Zuleta on 2/5/15.
// Copyright (c) 2015 Olinguito. All rights reserved.
//
import UIKit
import Foundation
class Connection: NSObject {
let db = SQLiteDB.sharedInstance()
override init() {
super.init()
}
//GET CATEGGORY
func getCategoryByDBId(idDB:Int) -> Category {
var category = Category()
let data = db.query("select a.id as idSub, a.name as nameSub, a.apiID as APISub, b.id as idCat, b.name as nameCat, b.icon as icon, b.apiID as APICat from subcategory a,category b where a.category = b.id and a.id = \(idDB)")
let row = data[0]
if let _id = row["idSub"] {
category.id = _id.asInt()
}
if let icon = row["icon"] {
category.slug = icon.asString()
category.icon = icon.asString()
}
if let name = row["nameSub"] {
category.name = name.asString()
}
if let api = row["APISub"]{
category.idAPI = api.asString()
}
if let _idCat = row["idCat"]{
category.parentId = _idCat.asInt()
}
if let nameCat = row["nameCat"]{
category.parentName = nameCat.asString()
}
if let apiCat = row["apiID"]{
category.parentAPI = apiCat.asString()
}
return category
}
// GET CATEGORIES
func getCategory(id:Int) -> Category{
var returnArray = NSMutableArray()
let data = db.query("SELECT * FROM Category where id = \(id)")
let row = data[0]
var category = Category()
if let _id = row["id"] {
category.id = _id.asInt()
}
if let name = row["name"] {
category.name = name.asString()
}
if let image = row["icon"] {
category.icon = image.asString()
}
return category
}
// GET CATEGORIES
func getCategories(report:Bool) -> NSMutableArray{
var returnArray = NSMutableArray()
let data = db.query("SELECT * FROM Category ORDER BY _order")
for key in data{
var city: Dictionary<String, String> = [:]
if let _id = key["id"] {
city["ID"] = _id.asString()
}
if let name = key["name"] {
city["NAME"] = name.asString()
}
if let image = key["icon"] {
city["ICON"] = report ? "btn_reporte_" + image.asString() : "btn_solicitud_" + image.asString()
}
returnArray.addObject(city)
}
return returnArray
}
// GET SUBCATEGORIES
func getSubcategories(idCategory:Int) -> NSMutableArray{
var returnArray = NSMutableArray()
let data = db.query("SELECT * FROM subcategory where category = \(idCategory)")
for key in data{
var category = Category()
if let id = key["id"] {
category.id = id.asInt()
}
if let name = key["name"] {
category.name = name.asString()
}
returnArray.addObject(category)
}
return returnArray
}
// GET LINKS
func getLinks() -> NSMutableArray{
var returnArray = NSMutableArray()
let data = db.query("SELECT * FROM links")
for key in data{
var links: Dictionary<String, String> = [:]
if let _id = key["id"] {
links["ID"] = _id.asString()
}
if let name = key["name"] {
links["NAME"] = name.asString()
}
if let icon = key["icon"] {
links["ICON"] = "btn_add_links_" + icon.asString()
links["BG"] = "bg_links_" + icon.asString()
}
returnArray.addObject(links)
}
return returnArray
}
//GET ESPECIFIC LINK
func getLinkByID(index:Int) -> NSMutableArray{
var returnArray = NSMutableArray()
let query = "SELECT * FROM link where \(index)"
let data = db.query(query)
for key in data{
var links: Dictionary<String, String> = [:]
if let _id = key["id"] {
links["ID"] = _id.asString()
}
if let name = key["name"] {
links["NAME"] = name.asString()
}
if let icon = key["icon"] {
links["ICON"] = "bg_links_" + icon.asString()
}
returnArray.addObject(links)
}
return returnArray
}
}
|
mit
|
9339e4342036669fa459ac6ca847fc15
| 29.448052 | 232 | 0.497334 | 4.262727 | false | false | false | false |
swojtyna/starsview
|
StarsView/StarsView/RequestOperation.swift
|
1
|
1299
|
//
// RequestOperation.swift
// StarsView
//
// Created by Sebastian Wojtyna on 03/09/16.
// Copyright © 2016 Sebastian Wojtyna. All rights reserved.
//
import Foundation
class RequestOperation: BaseOperation {
//MARK: Properties
private var completionHandler: (NSData?, NSURLResponse?, NSError?) -> Void = { _ in }
private var session: NSURLSession
private var request: NSURLRequest
private var task: NSURLSessionDataTask?
//MARK: Initializers method
init(session: NSURLSession = NSURLSession.sharedSession(), request: NSURLRequest, completionHandler: (NSData?, NSURLResponse?, NSError?) -> Void) {
self.completionHandler = completionHandler
self.session = session
self.request = request
super.init()
}
//MARK: NSOperation method
override func cancel() {
super.cancel()
self.task?.cancel()
}
//MARK: BaseOperation method
override func execute() {
task = session.dataTaskWithRequest(request, completionHandler: { [weak self] (data, response, error) in
guard let strongSelf = self else {
return
}
strongSelf.completionHandler(data, response, error)
strongSelf.finish()
})
task?.resume()
}
}
|
agpl-3.0
|
2b2909129198c685d3835b049b150e4e
| 24.96 | 151 | 0.640986 | 4.935361 | false | false | false | false |
Egibide-DAM/swift
|
02_ejemplos/06_tipos_personalizados/05_subindices/02_ejemplo_matriz.playground/Contents.swift
|
1
|
920
|
struct Matrix {
let rows: Int, columns: Int
var grid: [Double]
init(rows: Int, columns: Int) {
self.rows = rows
self.columns = columns
grid = Array(repeating: 0.0, count: rows * columns)
}
func indexIsValid(row: Int, column: Int) -> Bool {
return row >= 0 && row < rows && column >= 0 && column < columns
}
subscript(row: Int, column: Int) -> Double {
get {
assert(indexIsValid(row: row, column: column), "Index out of range")
return grid[(row * columns) + column]
}
set {
assert(indexIsValid(row: row, column: column), "Index out of range")
grid[(row * columns) + column] = newValue
}
}
}
var matrix = Matrix(rows: 2, columns: 2)
matrix[0, 1] = 1.5
matrix[1, 0] = 3.2
let someValue = matrix[2, 2]
// this triggers an assert, because [2, 2] is outside of the matrix bounds
|
apache-2.0
|
4ad45cb7b8aa44500adcbd26f8c6b28e
| 29.666667 | 80 | 0.56413 | 3.622047 | false | false | false | false |
simonbs/Emcee
|
LastFMKit/Models/Asset.swift
|
1
|
855
|
//
// Asset.swift
// Emcee
//
// Created by Simon Støvring on 31/03/15.
// Copyright (c) 2015 SimonBS. All rights reserved.
//
import Foundation
import SwiftyJSON
public class Asset {
public enum Size: String {
case Small = "small"
case Medium = "medium"
case Large = "large"
case ExtraLarge = "extralarge"
case Mega = "mega"
}
public let size: Size
public let url: NSURL
public var rank: Int {
switch size {
case .Small:
return 0
case .Medium:
return 1
case .Large:
return 2
case .ExtraLarge:
return 3
case .Mega:
return 4
}
}
init(json: JSON) {
size = Size(rawValue: json["size"].stringValue)!
url = json["#text"].URL!
}
}
|
mit
|
25e8f7a135f8da00aa33f958b1dcfcd5
| 18.431818 | 56 | 0.51171 | 4.047393 | false | false | false | false |
JohnEstropia/CoreStore
|
Sources/From+Querying.swift
|
1
|
54136
|
//
// From+Querying.swift
// CoreStore
//
// Copyright © 2018 John Rommel Estropia
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
//
import Foundation
import CoreData
// MARK: - From
extension From {
/**
Creates a `FetchChainBuilder` that starts with the specified `Where` clause
- parameter clause: the `Where` clause to create a `FetchChainBuilder` with
- returns: a `FetchChainBuilder` that starts with the specified `Where` clause
*/
public func `where`(_ clause: Where<O>) -> FetchChainBuilder<O> {
return self.fetchChain(appending: clause)
}
/**
Creates a `FetchChainBuilder` that `AND`s the specified `Where` clauses. Use this overload if the compiler cannot infer the types when chaining multiple `&&` operators.
- parameter clauses: the `Where` clauses to create a `FetchChainBuilder` with
- returns: a `FetchChainBuilder` that `AND`s the specified `Where` clauses
*/
public func `where`(combineByAnd clauses: Where<O>...) -> FetchChainBuilder<O> {
return self.fetchChain(appending: clauses.combinedByAnd())
}
/**
Creates a `FetchChainBuilder` that `OR`s the specified `Where` clauses. Use this overload if the compiler cannot infer the types when chaining multiple `||` operators.
- parameter clauses: the `Where` clauses to create a `FetchChainBuilder` with
- returns: a `FetchChainBuilder` that `OR`s the specified `Where` clauses
*/
public func `where`(combineByOr clauses: Where<O>...) -> FetchChainBuilder<O> {
return self.fetchChain(appending: clauses.combinedByOr())
}
/**
Creates a `FetchChainBuilder` with a predicate using the specified string format and arguments
- parameter format: the format string for the predicate
- parameter args: the arguments for `format`
- returns: a `FetchChainBuilder` with a predicate using the specified string format and arguments
*/
public func `where`(
format: String,
_ args: Any...
) -> FetchChainBuilder<O> {
return self.fetchChain(appending: Where<O>(format, argumentArray: args))
}
/**
Creates a `FetchChainBuilder` with a predicate using the specified string format and arguments
- parameter format: the format string for the predicate
- parameter argumentArray: the arguments for `format`
- returns: a `FetchChainBuilder` with a predicate using the specified string format and arguments
*/
public func `where`(
format: String,
argumentArray: [Any]?
) -> FetchChainBuilder<O> {
return self.fetchChain(appending: Where<O>(format, argumentArray: argumentArray))
}
/**
Creates a `FetchChainBuilder` that starts with the specified `OrderBy` clause.
- parameter clause: the `OrderBy` clause to create a `FetchChainBuilder` with
- returns: a `FetchChainBuilder` that starts with the specified `OrderBy` clause
*/
public func orderBy(_ clause: OrderBy<O>) -> FetchChainBuilder<O> {
return self.fetchChain(appending: clause)
}
/**
Creates a `FetchChainBuilder` with a series of `SortKey`s
- parameter sortKey: a single `SortKey`
- parameter sortKeys: a series of other `SortKey`s
- returns: a `FetchChainBuilder` with a series of `SortKey`s
*/
public func orderBy(
_ sortKey: OrderBy<O>.SortKey,
_ sortKeys: OrderBy<O>.SortKey...
) -> FetchChainBuilder<O> {
return self.fetchChain(appending: OrderBy<O>([sortKey] + sortKeys))
}
/**
Creates a `FetchChainBuilder` with a series of `SortKey`s
- parameter sortKeys: a series of `SortKey`s
- returns: a `FetchChainBuilder` with a series of `SortKey`s
*/
public func orderBy(_ sortKeys: [OrderBy<O>.SortKey]) -> FetchChainBuilder<O> {
return self.fetchChain(appending: OrderBy<O>(sortKeys))
}
/**
Creates a `FetchChainBuilder` with a closure where the `NSFetchRequest` may be configured
- parameter fetchRequest: the block to customize the `NSFetchRequest`
- returns: a `FetchChainBuilder` with closure where the `NSFetchRequest` may be configured
*/
public func tweak(_ fetchRequest: @escaping (NSFetchRequest<NSFetchRequestResult>) -> Void) -> FetchChainBuilder<O> {
return self.fetchChain(appending: Tweak(fetchRequest))
}
/**
Creates a `FetchChainBuilder` and immediately appending a `FetchClause`
- parameter clause: the `FetchClause` to add to the `FetchChainBuilder`
- returns: a `FetchChainBuilder` containing the specified `FetchClause`
*/
public func appending(_ clause: FetchClause) -> FetchChainBuilder<O> {
return self.fetchChain(appending: clause)
}
/**
Creates a `FetchChainBuilder` and immediately appending a series of `FetchClause`s
- parameter clauses: the `FetchClause`s to add to the `FetchChainBuilder`
- returns: a `FetchChainBuilder` containing the specified `FetchClause`s
*/
public func appending<S: Sequence>(contentsOf clauses: S) -> FetchChainBuilder<O> where S.Element == FetchClause {
return self.fetchChain(appending: clauses)
}
/**
Creates a `QueryChainBuilder` that starts with the specified `Select` clause
- parameter clause: the `Select` clause to create a `QueryChainBuilder` with
- returns: a `QueryChainBuilder` that starts with the specified `Select` clause
*/
public func select<R>(_ clause: Select<O, R>) -> QueryChainBuilder<O, R> {
return .init(
from: self,
select: clause,
queryClauses: []
)
}
/**
Creates a `QueryChainBuilder` that starts with a `Select` clause created from the specified `SelectTerm`s
- parameter resultType: the generic `SelectResultType` for the `Select` clause
- parameter selectTerm: a `SelectTerm`
- parameter selectTerms: a series of `SelectTerm`s
- returns: a `QueryChainBuilder` that starts with a `Select` clause created from the specified `SelectTerm`s
*/
public func select<R>(
_ resultType: R.Type,
_ selectTerm: SelectTerm<O>,
_ selectTerms: SelectTerm<O>...
) -> QueryChainBuilder<O, R> {
return self.select(resultType, [selectTerm] + selectTerms)
}
/**
Creates a `QueryChainBuilder` that starts with a `Select` clause created from the specified `SelectTerm`s
- parameter resultType: the generic `SelectResultType` for the `Select` clause
- parameter selectTerms: a series of `SelectTerm`s
- returns: a `QueryChainBuilder` that starts with a `Select` clause created from the specified `SelectTerm`s
*/
public func select<R>(
_ resultType: R.Type,
_ selectTerms: [SelectTerm<O>]
) -> QueryChainBuilder<O, R> {
return .init(
from: self,
select: .init(selectTerms),
queryClauses: []
)
}
/**
Creates a `SectionMonitorChainBuilder` that starts with the `SectionBy` to use to group `ListMonitor` objects into sections
- parameter clause: the `SectionBy` to be used by the `ListMonitor`
- returns: a `SectionMonitorChainBuilder` that is sectioned by the specified key path
*/
public func sectionBy(_ clause: SectionBy<O>) -> SectionMonitorChainBuilder<O> {
return .init(
from: self,
sectionBy: clause,
fetchClauses: []
)
}
/**
Creates a `SectionMonitorChainBuilder` with the key path to use to group `ListMonitor` objects into sections
- parameter sectionKeyPath: the key path to use to group the objects into sections
- returns: a `SectionMonitorChainBuilder` that is sectioned by the specified key path
*/
public func sectionBy(_ sectionKeyPath: KeyPathString) -> SectionMonitorChainBuilder<O> {
return self.sectionBy(sectionKeyPath, sectionIndexTransformer: { _ in nil })
}
/**
Creates a `SectionMonitorChainBuilder` with the key path to use to group `ListMonitor` objects into sections, and a closure to transform the value for the key path to an appropriate section index title
- Important: Some utilities (such as `ListMonitor`s) may keep `SectionBy`s in memory and may thus introduce retain cycles if reference captures are not handled properly.
- parameter sectionKeyPath: the key path to use to group the objects into sections
- parameter sectionIndexTransformer: a closure to transform the value for the key path to an appropriate section index title
- returns: a `SectionMonitorChainBuilder` that is sectioned by the specified key path
*/
public func sectionBy(
_ sectionKeyPath: KeyPathString,
sectionIndexTransformer: @escaping (_ sectionName: String?) -> String?
) -> SectionMonitorChainBuilder<O> {
return .init(
from: self,
sectionBy: .init(
sectionKeyPath,
sectionIndexTransformer: sectionIndexTransformer
),
fetchClauses: []
)
}
// MARK: Private
private func fetchChain(appending clause: FetchClause) -> FetchChainBuilder<O> {
return .init(from: self, fetchClauses: [clause])
}
private func fetchChain<S: Sequence>(appending clauses: S) -> FetchChainBuilder<O> where S.Element == FetchClause {
return .init(from: self, fetchClauses: Array(clauses))
}
// MARK: Deprecated
@available(*, deprecated, renamed: "sectionBy(_:sectionIndexTransformer:)")
public func sectionBy(
_ sectionKeyPath: KeyPathString,
_ sectionIndexTransformer: @escaping (_ sectionName: String?) -> String?
) -> SectionMonitorChainBuilder<O> {
return self.sectionBy(
sectionKeyPath,
sectionIndexTransformer: sectionIndexTransformer
)
}
}
// MARK: - From where O: NSManagedObject
extension From where O: NSManagedObject {
/**
Creates a `QueryChainBuilder` that starts with a `Select` clause created from the specified key path
- parameter keyPath: the keyPath to query the value for
- returns: a `QueryChainBuilder` that starts with a `Select` clause created from the specified key path
*/
public func select<R>(_ keyPath: KeyPath<O, R>) -> QueryChainBuilder<O, R> {
return self.select(R.self, [SelectTerm<O>.attribute(keyPath)])
}
/**
Creates a `SectionMonitorChainBuilder` with the key path to use to group `ListMonitor` objects into sections
- parameter sectionKeyPath: the `KeyPath` to use to group the objects into sections
- returns: a `SectionMonitorChainBuilder` that is sectioned by the specified key path
*/
public func sectionBy<T>(_ sectionKeyPath: KeyPath<O, T>) -> SectionMonitorChainBuilder<O> {
return self.sectionBy(
sectionKeyPath._kvcKeyPathString!,
sectionIndexTransformer: { _ in nil }
)
}
/**
Creates a `SectionMonitorChainBuilder` with the key path to use to group `ListMonitor` objects into sections, and a closure to transform the value for the key path to an appropriate section index title
- Important: Some utilities (such as `ListMonitor`s) may keep `SectionBy`s in memory and may thus introduce retain cycles if reference captures are not handled properly.
- parameter sectionKeyPath: the `KeyPath` to use to group the objects into sections
- parameter sectionIndexTransformer: a closure to transform the value for the key path to an appropriate section index title
- returns: a `SectionMonitorChainBuilder` that is sectioned by the specified key path
*/
public func sectionBy<T>(
_ sectionKeyPath: KeyPath<O, T>,
sectionIndexTransformer: @escaping (_ sectionName: String?) -> String?
) -> SectionMonitorChainBuilder<O> {
return self.sectionBy(
sectionKeyPath._kvcKeyPathString!,
sectionIndexTransformer: sectionIndexTransformer
)
}
// MARK: Deprecated
@available(*, deprecated, renamed: "sectionBy(_:sectionIndexTransformer:)")
public func sectionBy<T>(
_ sectionKeyPath: KeyPath<O, T>,
_ sectionIndexTransformer: @escaping (_ sectionName: String?) -> String?
) -> SectionMonitorChainBuilder<O> {
return self.sectionBy(
sectionKeyPath._kvcKeyPathString!,
sectionIndexTransformer: sectionIndexTransformer
)
}
}
// MARK: - From where O: CoreStoreObject
extension From where O: CoreStoreObject {
/**
Creates a `FetchChainBuilder` that starts with the specified `Where` clause
- parameter clause: a closure that returns a `Where` clause
- returns: a `FetchChainBuilder` that starts with the specified `Where` clause
*/
public func `where`<T: AnyWhereClause>(_ clause: (O) -> T) -> FetchChainBuilder<O> {
return self.fetchChain(appending: clause(O.meta))
}
/**
Creates a `QueryChainBuilder` that starts with a `Select` clause created from the specified key path
- parameter keyPath: the keyPath to query the value for
- returns: a `QueryChainBuilder` that starts with a `Select` clause created from the specified key path
*/
public func select<R>(_ keyPath: KeyPath<O, ValueContainer<O>.Required<R>>) -> QueryChainBuilder<O, R> {
return self.select(R.self, [SelectTerm<O>.attribute(keyPath)])
}
/**
Creates a `QueryChainBuilder` that starts with a `Select` clause created from the specified key path
- parameter keyPath: the keyPath to query the value for
- returns: a `QueryChainBuilder` that starts with a `Select` clause created from the specified key path
*/
public func select<R>(_ keyPath: KeyPath<O, ValueContainer<O>.Optional<R>>) -> QueryChainBuilder<O, R> {
return self.select(R.self, [SelectTerm<O>.attribute(keyPath)])
}
/**
Creates a `QueryChainBuilder` that starts with a `Select` clause created from the specified key path
- parameter keyPath: the keyPath to query the value for
- returns: a `QueryChainBuilder` that starts with a `Select` clause created from the specified key path
*/
public func select<R>(_ keyPath: KeyPath<O, TransformableContainer<O>.Required<R>>) -> QueryChainBuilder<O, R> {
return self.select(R.self, [SelectTerm<O>.attribute(keyPath)])
}
/**
Creates a `QueryChainBuilder` that starts with a `Select` clause created from the specified key path
- parameter keyPath: the keyPath to query the value for
- returns: a `QueryChainBuilder` that starts with a `Select` clause created from the specified key path
*/
public func select<R>(_ keyPath: KeyPath<O, TransformableContainer<O>.Optional<R>>) -> QueryChainBuilder<O, R> {
return self.select(R.self, [SelectTerm<O>.attribute(keyPath)])
}
/**
Creates a `SectionMonitorChainBuilder` with the key path to use to group `ListMonitor` objects into sections
- parameter sectionKeyPath: the `KeyPath` to use to group the objects into sections
- returns: a `SectionMonitorChainBuilder` that is sectioned by the specified key path
*/
public func sectionBy<T>(_ sectionKeyPath: KeyPath<O, FieldContainer<O>.Stored<T>>) -> SectionMonitorChainBuilder<O> {
return self.sectionBy(
O.meta[keyPath: sectionKeyPath].keyPath,
sectionIndexTransformer: { _ in nil }
)
}
/**
Creates a `SectionMonitorChainBuilder` with the key path to use to group `ListMonitor` objects into sections
- parameter sectionKeyPath: the `KeyPath` to use to group the objects into sections
- returns: a `SectionMonitorChainBuilder` that is sectioned by the specified key path
*/
public func sectionBy<T>(_ sectionKeyPath: KeyPath<O, FieldContainer<O>.Virtual<T>>) -> SectionMonitorChainBuilder<O> {
return self.sectionBy(
O.meta[keyPath: sectionKeyPath].keyPath,
sectionIndexTransformer: { _ in nil }
)
}
/**
Creates a `SectionMonitorChainBuilder` with the key path to use to group `ListMonitor` objects into sections
- parameter sectionKeyPath: the `KeyPath` to use to group the objects into sections
- returns: a `SectionMonitorChainBuilder` that is sectioned by the specified key path
*/
public func sectionBy<T>(_ sectionKeyPath: KeyPath<O, FieldContainer<O>.Coded<T>>) -> SectionMonitorChainBuilder<O> {
return self.sectionBy(
O.meta[keyPath: sectionKeyPath].keyPath,
sectionIndexTransformer: { _ in nil }
)
}
/**
Creates a `SectionMonitorChainBuilder` with the key path to use to group `ListMonitor` objects into sections
- parameter sectionKeyPath: the `KeyPath` to use to group the objects into sections
- returns: a `SectionMonitorChainBuilder` that is sectioned by the specified key path
*/
public func sectionBy<T>(_ sectionKeyPath: KeyPath<O, ValueContainer<O>.Required<T>>) -> SectionMonitorChainBuilder<O> {
return self.sectionBy(
O.meta[keyPath: sectionKeyPath].keyPath,
sectionIndexTransformer: { _ in nil }
)
}
/**
Creates a `SectionMonitorChainBuilder` with the key path to use to group `ListMonitor` objects into sections
- parameter sectionKeyPath: the `KeyPath` to use to group the objects into sections
- returns: a `SectionMonitorChainBuilder` that is sectioned by the specified key path
*/
public func sectionBy<T>(_ sectionKeyPath: KeyPath<O, ValueContainer<O>.Optional<T>>) -> SectionMonitorChainBuilder<O> {
return self.sectionBy(
O.meta[keyPath: sectionKeyPath].keyPath,
sectionIndexTransformer: { _ in nil }
)
}
/**
Creates a `SectionMonitorChainBuilder` with the key path to use to group `ListMonitor` objects into sections
- parameter sectionKeyPath: the `KeyPath` to use to group the objects into sections
- returns: a `SectionMonitorChainBuilder` that is sectioned by the specified key path
*/
public func sectionBy<T>(_ sectionKeyPath: KeyPath<O, TransformableContainer<O>.Required<T>>) -> SectionMonitorChainBuilder<O> {
return self.sectionBy(
O.meta[keyPath: sectionKeyPath].keyPath,
sectionIndexTransformer: { _ in nil }
)
}
/**
Creates a `SectionMonitorChainBuilder` with the key path to use to group `ListMonitor` objects into sections
- parameter sectionKeyPath: the `KeyPath` to use to group the objects into sections
- returns: a `SectionMonitorChainBuilder` that is sectioned by the specified key path
*/
public func sectionBy<T>(_ sectionKeyPath: KeyPath<O, TransformableContainer<O>.Optional<T>>) -> SectionMonitorChainBuilder<O> {
return self.sectionBy(
O.meta[keyPath: sectionKeyPath].keyPath,
sectionIndexTransformer: { _ in nil }
)
}
/**
Creates a `SectionMonitorChainBuilder` with the key path to use to group `ListMonitor` objects into sections, and a closure to transform the value for the key path to an appropriate section index title
- Important: Some utilities (such as `ListMonitor`s) may keep `SectionBy`s in memory and may thus introduce retain cycles if reference captures are not handled properly.
- parameter sectionKeyPath: the `KeyPath` to use to group the objects into sections
- parameter sectionIndexTransformer: a closure to transform the value for the key path to an appropriate section index title
- returns: a `SectionMonitorChainBuilder` that is sectioned by the specified key path
*/
public func sectionBy<T>(
_ sectionKeyPath: KeyPath<O, FieldContainer<O>.Stored<T>>,
sectionIndexTransformer: @escaping (_ sectionName: String?) -> String?
) -> SectionMonitorChainBuilder<O> {
return self.sectionBy(
O.meta[keyPath: sectionKeyPath].keyPath,
sectionIndexTransformer: sectionIndexTransformer
)
}
/**
Creates a `SectionMonitorChainBuilder` with the key path to use to group `ListMonitor` objects into sections, and a closure to transform the value for the key path to an appropriate section index title
- Important: Some utilities (such as `ListMonitor`s) may keep `SectionBy`s in memory and may thus introduce retain cycles if reference captures are not handled properly.
- parameter sectionKeyPath: the `KeyPath` to use to group the objects into sections
- parameter sectionIndexTransformer: a closure to transform the value for the key path to an appropriate section index title
- returns: a `SectionMonitorChainBuilder` that is sectioned by the specified key path
*/
public func sectionBy<T>(
_ sectionKeyPath: KeyPath<O, FieldContainer<O>.Virtual<T>>,
sectionIndexTransformer: @escaping (_ sectionName: String?) -> String?
) -> SectionMonitorChainBuilder<O> {
return self.sectionBy(
O.meta[keyPath: sectionKeyPath].keyPath,
sectionIndexTransformer: sectionIndexTransformer
)
}
/**
Creates a `SectionMonitorChainBuilder` with the key path to use to group `ListMonitor` objects into sections, and a closure to transform the value for the key path to an appropriate section index title
- Important: Some utilities (such as `ListMonitor`s) may keep `SectionBy`s in memory and may thus introduce retain cycles if reference captures are not handled properly.
- parameter sectionKeyPath: the `KeyPath` to use to group the objects into sections
- parameter sectionIndexTransformer: a closure to transform the value for the key path to an appropriate section index title
- returns: a `SectionMonitorChainBuilder` that is sectioned by the specified key path
*/
public func sectionBy<T>(
_ sectionKeyPath: KeyPath<O, FieldContainer<O>.Coded<T>>,
sectionIndexTransformer: @escaping (_ sectionName: String?) -> String?
) -> SectionMonitorChainBuilder<O> {
return self.sectionBy(
O.meta[keyPath: sectionKeyPath].keyPath,
sectionIndexTransformer: sectionIndexTransformer
)
}
/**
Creates a `SectionMonitorChainBuilder` with the key path to use to group `ListMonitor` objects into sections, and a closure to transform the value for the key path to an appropriate section index title
- Important: Some utilities (such as `ListMonitor`s) may keep `SectionBy`s in memory and may thus introduce retain cycles if reference captures are not handled properly.
- parameter sectionKeyPath: the `KeyPath` to use to group the objects into sections
- parameter sectionIndexTransformer: a closure to transform the value for the key path to an appropriate section index title
- returns: a `SectionMonitorChainBuilder` that is sectioned by the specified key path
*/
public func sectionBy<T>(
_ sectionKeyPath: KeyPath<O, ValueContainer<O>.Required<T>>,
sectionIndexTransformer: @escaping (_ sectionName: String?) -> String?
) -> SectionMonitorChainBuilder<O> {
return self.sectionBy(
O.meta[keyPath: sectionKeyPath].keyPath,
sectionIndexTransformer: sectionIndexTransformer
)
}
/**
Creates a `SectionMonitorChainBuilder` with the key path to use to group `ListMonitor` objects into sections, and a closure to transform the value for the key path to an appropriate section index title
- Important: Some utilities (such as `ListMonitor`s) may keep `SectionBy`s in memory and may thus introduce retain cycles if reference captures are not handled properly.
- parameter sectionKeyPath: the `KeyPath` to use to group the objects into sections
- parameter sectionIndexTransformer: a closure to transform the value for the key path to an appropriate section index title
- returns: a `SectionMonitorChainBuilder` that is sectioned by the specified key path
*/
public func sectionBy<T>(
_ sectionKeyPath: KeyPath<O, ValueContainer<O>.Optional<T>>,
sectionIndexTransformer: @escaping (_ sectionName: String?) -> String?
) -> SectionMonitorChainBuilder<O> {
return self.sectionBy(
O.meta[keyPath: sectionKeyPath].keyPath,
sectionIndexTransformer: sectionIndexTransformer
)
}
/**
Creates a `SectionMonitorChainBuilder` with the key path to use to group `ListMonitor` objects into sections, and a closure to transform the value for the key path to an appropriate section index title
- Important: Some utilities (such as `ListMonitor`s) may keep `SectionBy`s in memory and may thus introduce retain cycles if reference captures are not handled properly.
- parameter sectionKeyPath: the `KeyPath` to use to group the objects into sections
- parameter sectionIndexTransformer: a closure to transform the value for the key path to an appropriate section index title
- returns: a `SectionMonitorChainBuilder` that is sectioned by the specified key path
*/
public func sectionBy<T>(
_ sectionKeyPath: KeyPath<O, TransformableContainer<O>.Required<T>>,
sectionIndexTransformer: @escaping (_ sectionName: String?) -> String?
) -> SectionMonitorChainBuilder<O> {
return self.sectionBy(
O.meta[keyPath: sectionKeyPath].keyPath,
sectionIndexTransformer: sectionIndexTransformer
)
}
/**
Creates a `SectionMonitorChainBuilder` with the key path to use to group `ListMonitor` objects into sections, and a closure to transform the value for the key path to an appropriate section index title
- Important: Some utilities (such as `ListMonitor`s) may keep `SectionBy`s in memory and may thus introduce retain cycles if reference captures are not handled properly.
- parameter sectionKeyPath: the `KeyPath` to use to group the objects into sections
- parameter sectionIndexTransformer: a closure to transform the value for the key path to an appropriate section index title
- returns: a `SectionMonitorChainBuilder` that is sectioned by the specified key path
*/
public func sectionBy<T>(
_ sectionKeyPath: KeyPath<O, TransformableContainer<O>.Optional<T>>,
sectionIndexTransformer: @escaping (_ sectionName: String?) -> String?
) -> SectionMonitorChainBuilder<O> {
return self.sectionBy(
O.meta[keyPath: sectionKeyPath].keyPath,
sectionIndexTransformer: sectionIndexTransformer
)
}
// MARK: Deprecated
@available(*, deprecated, renamed: "sectionBy(_:sectionIndexTransformer:)")
public func sectionBy<T>(
_ sectionKeyPath: KeyPath<O, FieldContainer<O>.Stored<T>>,
_ sectionIndexTransformer: @escaping (_ sectionName: String?) -> String?
) -> SectionMonitorChainBuilder<O> {
return self.sectionBy(
sectionKeyPath,
sectionIndexTransformer: sectionIndexTransformer
)
}
@available(*, deprecated, renamed: "sectionBy(_:sectionIndexTransformer:)")
public func sectionBy<T>(
_ sectionKeyPath: KeyPath<O, FieldContainer<O>.Virtual<T>>,
_ sectionIndexTransformer: @escaping (_ sectionName: String?) -> String?
) -> SectionMonitorChainBuilder<O> {
return self.sectionBy(
sectionKeyPath,
sectionIndexTransformer: sectionIndexTransformer
)
}
@available(*, deprecated, renamed: "sectionBy(_:sectionIndexTransformer:)")
public func sectionBy<T>(
_ sectionKeyPath: KeyPath<O, FieldContainer<O>.Coded<T>>,
_ sectionIndexTransformer: @escaping (_ sectionName: String?) -> String?
) -> SectionMonitorChainBuilder<O> {
return self.sectionBy(
sectionKeyPath,
sectionIndexTransformer: sectionIndexTransformer
)
}
@available(*, deprecated, renamed: "sectionBy(_:sectionIndexTransformer:)")
public func sectionBy<T>(
_ sectionKeyPath: KeyPath<O, ValueContainer<O>.Required<T>>,
_ sectionIndexTransformer: @escaping (_ sectionName: String?) -> String?
) -> SectionMonitorChainBuilder<O> {
return self.sectionBy(
sectionKeyPath,
sectionIndexTransformer: sectionIndexTransformer
)
}
@available(*, deprecated, renamed: "sectionBy(_:sectionIndexTransformer:)")
public func sectionBy<T>(
_ sectionKeyPath: KeyPath<O, ValueContainer<O>.Optional<T>>,
_ sectionIndexTransformer: @escaping (_ sectionName: String?) -> String?
) -> SectionMonitorChainBuilder<O> {
return self.sectionBy(
sectionKeyPath,
sectionIndexTransformer: sectionIndexTransformer
)
}
@available(*, deprecated, renamed: "sectionBy(_:sectionIndexTransformer:)")
public func sectionBy<T>(
_ sectionKeyPath: KeyPath<O, TransformableContainer<O>.Required<T>>,
_ sectionIndexTransformer: @escaping (_ sectionName: String?) -> String?
) -> SectionMonitorChainBuilder<O> {
return self.sectionBy(
sectionKeyPath,
sectionIndexTransformer: sectionIndexTransformer
)
}
@available(*, deprecated, renamed: "sectionBy(_:sectionIndexTransformer:)")
public func sectionBy<T>(
_ sectionKeyPath: KeyPath<O, TransformableContainer<O>.Optional<T>>,
_ sectionIndexTransformer: @escaping (_ sectionName: String?) -> String?
) -> SectionMonitorChainBuilder<O> {
return self.sectionBy(
sectionKeyPath,
sectionIndexTransformer: sectionIndexTransformer
)
}
}
// MARK: - FetchChainBuilder
extension FetchChainBuilder {
/**
Adds a `Where` clause to the `FetchChainBuilder`
- parameter clause: a `Where` clause to add to the fetch builder
- returns: a new `FetchChainBuilder` containing the `Where` clause
*/
public func `where`(_ clause: Where<O>) -> FetchChainBuilder<O> {
return self.fetchChain(appending: clause)
}
/**
Creates a `FetchChainBuilder` that `AND`s the specified `Where` clauses. Use this overload if the compiler cannot infer the types when chaining multiple `&&` operators.
- parameter clauses: the `Where` clauses to create a `FetchChainBuilder` with
- returns: a `FetchChainBuilder` that `AND`s the specified `Where` clauses
*/
public func `where`(combineByAnd clauses: Where<O>...) -> FetchChainBuilder<O> {
return self.fetchChain(appending: clauses.combinedByAnd())
}
/**
Creates a `FetchChainBuilder` that `OR`s the specified `Where` clauses. Use this overload if the compiler cannot infer the types when chaining multiple `||` operators.
- parameter clauses: the `Where` clauses to create a `FetchChainBuilder` with
- returns: a `FetchChainBuilder` that `OR`s the specified `Where` clauses
*/
public func `where`(combineByOr clauses: Where<O>...) -> FetchChainBuilder<O> {
return self.fetchChain(appending: clauses.combinedByOr())
}
/**
Adds a `Where` clause to the `FetchChainBuilder`
- parameter format: the format string for the predicate
- parameter args: the arguments for `format`
- returns: a new `FetchChainBuilder` containing the `Where` clause
*/
public func `where`(format: String, _ args: Any...) -> FetchChainBuilder<O> {
return self.fetchChain(appending: Where<O>(format, argumentArray: args))
}
/**
Adds a `Where` clause to the `FetchChainBuilder`
- parameter format: the format string for the predicate
- parameter argumentArray: the arguments for `format`
- returns: a new `FetchChainBuilder` containing the `Where` clause
*/
public func `where`(format: String, argumentArray: [Any]?) -> FetchChainBuilder<O> {
return self.fetchChain(appending: Where<O>(format, argumentArray: argumentArray))
}
/**
Adds an `OrderBy` clause to the `FetchChainBuilder`
- parameter clause: the `OrderBy` clause to add
- returns: a new `FetchChainBuilder` containing the `OrderBy` clause
*/
public func orderBy(_ clause: OrderBy<O>) -> FetchChainBuilder<O> {
return self.fetchChain(appending: clause)
}
/**
Adds an `OrderBy` clause to the `FetchChainBuilder`
- parameter sortKey: a single `SortKey`
- parameter sortKeys: a series of other `SortKey`s
- returns: a new `FetchChainBuilder` containing the `OrderBy` clause
*/
public func orderBy(_ sortKey: OrderBy<O>.SortKey, _ sortKeys: OrderBy<O>.SortKey...) -> FetchChainBuilder<O> {
return self.fetchChain(appending: OrderBy<O>([sortKey] + sortKeys))
}
/**
Adds an `OrderBy` clause to the `FetchChainBuilder`
- parameter sortKeys: a series of `SortKey`s
- returns: a new `FetchChainBuilder` containing the `OrderBy` clause
*/
public func orderBy(_ sortKeys: [OrderBy<O>.SortKey]) -> FetchChainBuilder<O> {
return self.fetchChain(appending: OrderBy<O>(sortKeys))
}
/**
Adds a `Tweak` clause to the `FetchChainBuilder` with a closure where the `NSFetchRequest` may be configured
- parameter fetchRequest: the block to customize the `NSFetchRequest`
- returns: a new `FetchChainBuilder` containing the `Tweak` clause
*/
public func tweak(_ fetchRequest: @escaping (NSFetchRequest<NSFetchRequestResult>) -> Void) -> FetchChainBuilder<O> {
return self.fetchChain(appending: Tweak(fetchRequest))
}
/**
Appends a `FetchClause` to the `FetchChainBuilder`
- parameter clause: the `FetchClause` to add to the `FetchChainBuilder`
- returns: a new `FetchChainBuilder` containing the `FetchClause`
*/
public func appending(_ clause: FetchClause) -> FetchChainBuilder<O> {
return self.fetchChain(appending: clause)
}
/**
Appends a series of `FetchClause`s to the `FetchChainBuilder`
- parameter clauses: the `FetchClause`s to add to the `FetchChainBuilder`
- returns: a new `FetchChainBuilder` containing the `FetchClause`s
*/
public func appending<S: Sequence>(contentsOf clauses: S) -> FetchChainBuilder<O> where S.Element == FetchClause {
return self.fetchChain(appending: clauses)
}
// MARK: Private
private func fetchChain(appending clause: FetchClause) -> FetchChainBuilder<O> {
return .init(
from: self.from,
fetchClauses: self.fetchClauses + [clause]
)
}
private func fetchChain<S: Sequence>(appending clauses: S) -> FetchChainBuilder<O> where S.Element == FetchClause {
return .init(
from: self.from,
fetchClauses: self.fetchClauses + Array(clauses)
)
}
}
// MARK: - FetchChainBuilder where O: CoreStoreObject
extension FetchChainBuilder where O: CoreStoreObject {
public func `where`<T: AnyWhereClause>(_ clause: (O) -> T) -> FetchChainBuilder<O> {
return self.fetchChain(appending: clause(O.meta))
}
}
// MARK: - QueryChainBuilder
extension QueryChainBuilder {
/**
Adds a `Where` clause to the `QueryChainBuilder`
- parameter clause: a `Where` clause to add to the query builder
- returns: a new `QueryChainBuilder` containing the `Where` clause
*/
public func `where`(_ clause: Where<O>) -> QueryChainBuilder<O, R> {
return self.queryChain(appending: clause)
}
/**
Creates a `FetchChainBuilder` that `AND`s the specified `Where` clauses. Use this overload if the compiler cannot infer the types when chaining multiple `&&` operators.
- parameter clauses: the `Where` clauses to create a `FetchChainBuilder` with
- returns: a `FetchChainBuilder` that `AND`s the specified `Where` clauses
*/
public func `where`(combineByAnd clauses: Where<O>...) -> QueryChainBuilder<O, R> {
return self.queryChain(appending: clauses.combinedByAnd())
}
/**
Creates a `FetchChainBuilder` that `OR`s the specified `Where` clauses. Use this overload if the compiler cannot infer the types when chaining multiple `||` operators.
- parameter clauses: the `Where` clauses to create a `FetchChainBuilder` with
- returns: a `FetchChainBuilder` that `OR`s the specified `Where` clauses
*/
public func `where`(combineByOr clauses: Where<O>...) -> QueryChainBuilder<O, R> {
return self.queryChain(appending: clauses.combinedByOr())
}
/**
Adds a `Where` clause to the `QueryChainBuilder`
- parameter format: the format string for the predicate
- parameter args: the arguments for `format`
- returns: a new `QueryChainBuilder` containing the `Where` clause
*/
public func `where`(format: String, _ args: Any...) -> QueryChainBuilder<O, R> {
return self.queryChain(appending: Where<O>(format, argumentArray: args))
}
/**
Adds a `Where` clause to the `QueryChainBuilder`
- parameter format: the format string for the predicate
- parameter argumentArray: the arguments for `format`
- returns: a new `QueryChainBuilder` containing the `Where` clause
*/
public func `where`(format: String, argumentArray: [Any]?) -> QueryChainBuilder<O, R> {
return self.queryChain(appending: Where<O>(format, argumentArray: argumentArray))
}
/**
Adds an `OrderBy` clause to the `QueryChainBuilder`
- parameter clause: the `OrderBy` clause to add
- returns: a new `QueryChainBuilder` containing the `OrderBy` clause
*/
public func orderBy(_ clause: OrderBy<O>) -> QueryChainBuilder<O, R> {
return self.queryChain(appending: clause)
}
/**
Adds an `OrderBy` clause to the `QueryChainBuilder`
- parameter sortKey: a single `SortKey`
- parameter sortKeys: a series of other `SortKey`s
- returns: a new `QueryChainBuilder` containing the `OrderBy` clause
*/
public func orderBy(_ sortKey: OrderBy<O>.SortKey, _ sortKeys: OrderBy<O>.SortKey...) -> QueryChainBuilder<O, R> {
return self.queryChain(appending: OrderBy<O>([sortKey] + sortKeys))
}
/**
Adds an `OrderBy` clause to the `QueryChainBuild`
- parameter sortKeys: a series of `SortKey`s
- returns: a new `QueryChainBuilder` containing the `OrderBy` clause
*/
public func orderBy(_ sortKeys: [OrderBy<O>.SortKey]) -> QueryChainBuilder<O, R> {
return self.queryChain(appending: OrderBy<O>(sortKeys))
}
/**
Adds a `Tweak` clause to the `QueryChainBuilder` with a closure where the `NSFetchRequest` may be configured
- parameter fetchRequest: the block to customize the `NSFetchRequest`
- returns: a new `QueryChainBuilder` containing the `Tweak` clause
*/
public func tweak(_ fetchRequest: @escaping (NSFetchRequest<NSFetchRequestResult>) -> Void) -> QueryChainBuilder<O, R> {
return self.queryChain(appending: Tweak(fetchRequest))
}
/**
Adds a `GroupBy` clause to the `QueryChainBuilder`
- parameter clause: a `GroupBy` clause to add to the query builder
- returns: a new `QueryChainBuilder` containing the `GroupBy` clause
*/
public func groupBy(_ clause: GroupBy<O>) -> QueryChainBuilder<O, R> {
return self.queryChain(appending: clause)
}
/**
Adds a `GroupBy` clause to the `QueryChainBuilder`
- parameter keyPath: a key path to group the query results with
- parameter keyPaths: other key paths to group the query results with
- returns: a new `QueryChainBuilder` containing the `GroupBy` clause
*/
public func groupBy(_ keyPath: KeyPathString, _ keyPaths: KeyPathString...) -> QueryChainBuilder<O, R> {
return self.groupBy(GroupBy<O>([keyPath] + keyPaths))
}
/**
Adds a `GroupBy` clause to the `QueryChainBuilder`
- parameter keyPaths: a series of key paths to group the query results with
- returns: a new `QueryChainBuilder` containing the `GroupBy` clause
*/
public func groupBy(_ keyPaths: [KeyPathString]) -> QueryChainBuilder<O, R> {
return self.queryChain(appending: GroupBy<O>(keyPaths))
}
/**
Appends a `QueryClause` to the `QueryChainBuilder`
- parameter clause: the `QueryClause` to add to the `QueryChainBuilder`
- returns: a new `QueryChainBuilder` containing the `QueryClause`
*/
public func appending(_ clause: QueryClause) -> QueryChainBuilder<O, R> {
return self.queryChain(appending: clause)
}
/**
Appends a series of `QueryClause`s to the `QueryChainBuilder`
- parameter clauses: the `QueryClause`s to add to the `QueryChainBuilder`
- returns: a new `QueryChainBuilder` containing the `QueryClause`s
*/
public func appending<S: Sequence>(contentsOf clauses: S) -> QueryChainBuilder<O, R> where S.Element == QueryClause {
return self.queryChain(appending: clauses)
}
// MARK: Private
private func queryChain(appending clause: QueryClause) -> QueryChainBuilder<O, R> {
return .init(
from: self.from,
select: self.select,
queryClauses: self.queryClauses + [clause]
)
}
private func queryChain<S: Sequence>(appending clauses: S) -> QueryChainBuilder<O, R> where S.Element == QueryClause {
return .init(
from: self.from,
select: self.select,
queryClauses: self.queryClauses + Array(clauses)
)
}
}
// MARK: - QueryChainBuilder where O: NSManagedObject
extension QueryChainBuilder where O: NSManagedObject {
/**
Adds a `GroupBy` clause to the `QueryChainBuilder`
- parameter keyPath: a key path to group the query results with
- returns: a new `QueryChainBuilder` containing the `GroupBy` clause
*/
public func groupBy<T>(_ keyPath: KeyPath<O, T>) -> QueryChainBuilder<O, R> {
return self.groupBy(GroupBy<O>(keyPath))
}
}
// MARK: - QueryChainBuilder where O: CoreStoreObject
extension QueryChainBuilder where O: CoreStoreObject {
/**
Adds a `Where` clause to the `QueryChainBuilder`
- parameter clause: a `Where` clause to add to the query builder
- returns: a new `QueryChainBuilder` containing the `Where` clause
*/
public func `where`<T: AnyWhereClause>(_ clause: (O) -> T) -> QueryChainBuilder<O, R> {
return self.queryChain(appending: clause(O.meta))
}
/**
Adds a `GroupBy` clause to the `QueryChainBuilder`
- parameter keyPath: a key path to group the query results with
- returns: a new `QueryChainBuilder` containing the `GroupBy` clause
*/
public func groupBy<T>(_ keyPath: KeyPath<O, FieldContainer<O>.Stored<T>>) -> QueryChainBuilder<O, R> {
return self.groupBy(GroupBy<O>(keyPath))
}
/**
Adds a `GroupBy` clause to the `QueryChainBuilder`
- parameter keyPath: a key path to group the query results with
- returns: a new `QueryChainBuilder` containing the `GroupBy` clause
*/
public func groupBy<T>(_ keyPath: KeyPath<O, FieldContainer<O>.Virtual<T>>) -> QueryChainBuilder<O, R> {
return self.groupBy(GroupBy<O>(keyPath))
}
/**
Adds a `GroupBy` clause to the `QueryChainBuilder`
- parameter keyPath: a key path to group the query results with
- returns: a new `QueryChainBuilder` containing the `GroupBy` clause
*/
public func groupBy<T>(_ keyPath: KeyPath<O, FieldContainer<O>.Coded<T>>) -> QueryChainBuilder<O, R> {
return self.groupBy(GroupBy<O>(keyPath))
}
/**
Adds a `GroupBy` clause to the `QueryChainBuilder`
- parameter keyPath: a key path to group the query results with
- returns: a new `QueryChainBuilder` containing the `GroupBy` clause
*/
public func groupBy<T>(_ keyPath: KeyPath<O, ValueContainer<O>.Required<T>>) -> QueryChainBuilder<O, R> {
return self.groupBy(GroupBy<O>(keyPath))
}
/**
Adds a `GroupBy` clause to the `QueryChainBuilder`
- parameter keyPath: a key path to group the query results with
- returns: a new `QueryChainBuilder` containing the `GroupBy` clause
*/
public func groupBy<T>(_ keyPath: KeyPath<O, ValueContainer<O>.Optional<T>>) -> QueryChainBuilder<O, R> {
return self.groupBy(GroupBy<O>(keyPath))
}
/**
Adds a `GroupBy` clause to the `QueryChainBuilder`
- parameter keyPath: a key path to group the query results with
- returns: a new `QueryChainBuilder` containing the `GroupBy` clause
*/
public func groupBy<T>(_ keyPath: KeyPath<O, TransformableContainer<O>.Required<T>>) -> QueryChainBuilder<O, R> {
return self.groupBy(GroupBy<O>(keyPath))
}
/**
Adds a `GroupBy` clause to the `QueryChainBuilder`
- parameter keyPath: a key path to group the query results with
- returns: a new `QueryChainBuilder` containing the `GroupBy` clause
*/
public func groupBy<T>(_ keyPath: KeyPath<O, TransformableContainer<O>.Optional<T>>) -> QueryChainBuilder<O, R> {
return self.groupBy(GroupBy<O>(keyPath))
}
}
// MARK: - SectionMonitorChainBuilder
extension SectionMonitorChainBuilder {
/**
Adds a `Where` clause to the `SectionMonitorChainBuilder`
- parameter clause: a `Where` clause to add to the fetch builder
- returns: a new `SectionMonitorChainBuilder` containing the `Where` clause
*/
public func `where`(_ clause: Where<O>) -> SectionMonitorChainBuilder<O> {
return self.sectionMonitorChain(appending: clause)
}
/**
Creates a `FetchChainBuilder` that `AND`s the specified `Where` clauses. Use this overload if the compiler cannot infer the types when chaining multiple `&&` operators.
- parameter clauses: the `Where` clauses to create a `FetchChainBuilder` with
- returns: a `FetchChainBuilder` that `AND`s the specified `Where` clauses
*/
public func `where`(combineByAnd clauses: Where<O>...) -> SectionMonitorChainBuilder<O> {
return self.sectionMonitorChain(appending: clauses.combinedByAnd())
}
/**
Creates a `FetchChainBuilder` that `OR`s the specified `Where` clauses. Use this overload if the compiler cannot infer the types when chaining multiple `||` operators.
- parameter clauses: the `Where` clauses to create a `FetchChainBuilder` with
- returns: a `FetchChainBuilder` that `OR`s the specified `Where` clauses
*/
public func `where`(combineByOr clauses: Where<O>...) -> SectionMonitorChainBuilder<O> {
return self.sectionMonitorChain(appending: clauses.combinedByOr())
}
/**
Adds a `Where` clause to the `SectionMonitorChainBuilder`
- parameter format: the format string for the predicate
- parameter args: the arguments for `format`
- returns: a new `SectionMonitorChainBuilder` containing the `Where` clause
*/
public func `where`(format: String, _ args: Any...) -> SectionMonitorChainBuilder<O> {
return self.sectionMonitorChain(appending: Where<O>(format, argumentArray: args))
}
/**
Adds a `Where` clause to the `SectionMonitorChainBuilder`
- parameter format: the format string for the predicate
- parameter argumentArray: the arguments for `format`
- returns: a new `SectionMonitorChainBuilder` containing the `Where` clause
*/
public func `where`(format: String, argumentArray: [Any]?) -> SectionMonitorChainBuilder<O> {
return self.sectionMonitorChain(appending: Where<O>(format, argumentArray: argumentArray))
}
/**
Adds an `OrderBy` clause to the `SectionMonitorChainBuilder`
- parameter clause: the `OrderBy` clause to add
- returns: a new `SectionMonitorChainBuilder` containing the `OrderBy` clause
*/
public func orderBy(_ clause: OrderBy<O>) -> SectionMonitorChainBuilder<O> {
return self.sectionMonitorChain(appending: clause)
}
/**
Adds an `OrderBy` clause to the `SectionMonitorChainBuilder`
- parameter sortKey: a single `SortKey`
- parameter sortKeys: a series of other `SortKey`s
- returns: a new `SectionMonitorChainBuilder` containing the `OrderBy` clause
*/
public func orderBy(_ sortKey: OrderBy<O>.SortKey, _ sortKeys: OrderBy<O>.SortKey...) -> SectionMonitorChainBuilder<O> {
return self.sectionMonitorChain(appending: OrderBy<O>([sortKey] + sortKeys))
}
/**
Adds an `OrderBy` clause to the `SectionMonitorChainBuilder`
- parameter sortKeys: a series of `SortKey`s
- returns: a new `SectionMonitorChainBuilder` containing the `OrderBy` clause
*/
public func orderBy(_ sortKeys: [OrderBy<O>.SortKey]) -> SectionMonitorChainBuilder<O> {
return self.sectionMonitorChain(appending: OrderBy<O>(sortKeys))
}
/**
Adds a `Tweak` clause to the `SectionMonitorChainBuilder` with a closure where the `NSFetchRequest` may be configured
- parameter fetchRequest: the block to customize the `NSFetchRequest`
- returns: a new `SectionMonitorChainBuilder` containing the `Tweak` clause
*/
public func tweak(_ fetchRequest: @escaping (NSFetchRequest<NSFetchRequestResult>) -> Void) -> SectionMonitorChainBuilder<O> {
return self.sectionMonitorChain(appending: Tweak(fetchRequest))
}
/**
Appends a `QueryClause` to the `SectionMonitorChainBuilder`
- parameter clause: the `QueryClause` to add to the `SectionMonitorChainBuilder`
- returns: a new `SectionMonitorChainBuilder` containing the `QueryClause`
*/
public func appending(_ clause: FetchClause) -> SectionMonitorChainBuilder<O> {
return self.sectionMonitorChain(appending: clause)
}
/**
Appends a series of `QueryClause`s to the `SectionMonitorChainBuilder`
- parameter clauses: the `QueryClause`s to add to the `SectionMonitorChainBuilder`
- returns: a new `SectionMonitorChainBuilder` containing the `QueryClause`s
*/
public func appending<S: Sequence>(contentsOf clauses: S) -> SectionMonitorChainBuilder<O> where S.Element == FetchClause {
return self.sectionMonitorChain(appending: clauses)
}
// MARK: Private
private func sectionMonitorChain(appending clause: FetchClause) -> SectionMonitorChainBuilder<O> {
return .init(
from: self.from,
sectionBy: self.sectionBy,
fetchClauses: self.fetchClauses + [clause]
)
}
private func sectionMonitorChain<S: Sequence>(appending clauses: S) -> SectionMonitorChainBuilder<O> where S.Element == FetchClause {
return .init(
from: self.from,
sectionBy: self.sectionBy,
fetchClauses: self.fetchClauses + Array(clauses)
)
}
}
// MARK: - SectionMonitorChainBuilder where O: CoreStoreObject
extension SectionMonitorChainBuilder where O: CoreStoreObject {
/**
Adds a `Where` clause to the `SectionMonitorChainBuilder`
- parameter clause: a `Where` clause to add to the fetch builder
- returns: a new `SectionMonitorChainBuilder` containing the `Where` clause
*/
public func `where`<T: AnyWhereClause>(_ clause: (O) -> T) -> SectionMonitorChainBuilder<O> {
return self.sectionMonitorChain(appending: clause(O.meta))
}
}
|
mit
|
8083bd06fc462e1dc2b79e5f6d0ff131
| 38.746696 | 206 | 0.663046 | 4.638023 | false | false | false | false |
knutnyg/ios-iou
|
iou/DefaultLoginViewController.swift
|
1
|
7256
|
import Foundation
import FBSDKCoreKit
import FBSDKLoginKit
import SwiftValidator
class DefaultLoginViewController: UIViewController, ValidationDelegate{
var forgotPasswordButton:UIButton!
var signInButton:UIButton!
var usernameTextField:UITextField!
var passwordTextField:UITextField!
var usernameTextFieldErrorLabel:UILabel!
var passwordTextFieldErrorLabel:UILabel!
var validator:Validator!
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = UIColor.whiteColor()
setupNavigationBar()
forgotPasswordButton = createButton("Forgot password", font: UIFont(name: "HelveticaNeue",size: 22)!)
signInButton = createButton("Sign in!", font: UIFont(name: "HelveticaNeue",size: 22)!)
usernameTextField = createTextField("username")
passwordTextField = createTextField("password")
passwordTextField.secureTextEntry = true
usernameTextFieldErrorLabel = createLabel("")
usernameTextFieldErrorLabel.translatesAutoresizingMaskIntoConstraints = false
usernameTextFieldErrorLabel.hidden = true
view.addSubview(usernameTextFieldErrorLabel)
passwordTextFieldErrorLabel = createLabel("")
passwordTextFieldErrorLabel.translatesAutoresizingMaskIntoConstraints = false
passwordTextFieldErrorLabel.hidden = true
view.addSubview(passwordTextFieldErrorLabel)
forgotPasswordButton.addTarget(self, action: "forgotPasswordButtonPressed:", forControlEvents: .TouchUpInside)
signInButton.addTarget(self, action: "signInButtonPressed:", forControlEvents: .TouchUpInside)
validator = Validator()
validator.registerField(usernameTextField, errorLabel: usernameTextFieldErrorLabel, rules: [RequiredRule(), EmailRule(message: "Invalid email")])
validator.registerField(passwordTextField, errorLabel: passwordTextFieldErrorLabel, rules: [RequiredRule()])
let views = ["forgotPasswordButton":forgotPasswordButton, "signInButton":signInButton, "usernameTextField":usernameTextField,"passwordTextField":passwordTextField, "usernameErrorLabel":usernameTextFieldErrorLabel, "passwordErrorLabel":passwordTextFieldErrorLabel]
view.addSubview(forgotPasswordButton)
view.addSubview(signInButton)
view.addSubview(usernameTextField)
view.addSubview(passwordTextField)
view.addSubview(usernameTextFieldErrorLabel)
view.addSubview(passwordTextFieldErrorLabel)
view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|-100-[usernameTextField(60)]-40-[passwordTextField(60)]", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: views))
view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:[passwordTextField(60)]-40-[signInButton(60)]", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: views))
view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:[passwordTextField(60)]-40-[forgotPasswordButton(60)]", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: views))
view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|-20-[usernameTextField]-20-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: views))
view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|-20-[passwordTextField]-20-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: views))
view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|-[signInButton]", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: views))
view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:[forgotPasswordButton]-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: views))
view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:[usernameErrorLabel]-[usernameTextField]", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: views))
view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:[usernameErrorLabel]-20-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: views))
view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:[passwordErrorLabel]-[passwordTextField]", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: views))
view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:[passwordErrorLabel]-20-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: views))
}
func signInButtonPressed(sender:UIButton){
clearValidationErrors()
validator.validate(self)
}
func forgotPasswordButtonPressed(sender:UIButton){
let vc = ForgotPasswordViewController()
vc.delegate = self
navigationController?.pushViewController(vc, animated: true)
}
func setupNavigationBar(){
// let font = UIFont(name: "Verdana", size:22)!
// let attributes:[String : AnyObject] = [NSFontAttributeName: font, NSForegroundColorAttributeName: UIColor.whiteColor()]
navigationItem.title = "Log In"
// navigationController!.navigationBar.titleTextAttributes = attributes
let verticalOffset = 1.5 as CGFloat;
navigationController?.navigationBar.setTitleVerticalPositionAdjustment(verticalOffset, forBarMetrics: UIBarMetrics.Default)
}
func validationSuccessful() {
let username = usernameTextField.text
let password = passwordTextField.text
guard let un = username, let pw = password else {
return
}
API.defaultLogIn(un, password: pw)
.onSuccess{ token in
API.accessToken = token
//Store key to disk:
let defaults = NSUserDefaults.standardUserDefaults()
defaults.setValue(token, forKey: "DefaultAccessToken")
defaults.synchronize()
let vc = MainViewController()
self.navigationController?.pushViewController(vc, animated: true)
}
.onFailure{ error in
let alertController = UIAlertController(title: "", message:
"Unable to log in\nPlease verify your credentials", preferredStyle: UIAlertControllerStyle.Alert)
alertController.addAction(UIAlertAction(title: "Dismiss", style: UIAlertActionStyle.Default,handler: nil))
self.presentViewController(alertController, animated: true, completion: nil)
}
}
func validationFailed(errors:[UITextField:ValidationError]) {
// turn the fields to red
for (field, error) in validator.errors {
field.layer.borderColor = UIColor.redColor().CGColor
field.layer.borderWidth = 1.0
error.errorLabel?.text = error.errorMessage // works if you added labels
error.errorLabel?.hidden = false
}
}
func clearValidationErrors(){
usernameTextField.layer.borderWidth = 0.0
usernameTextFieldErrorLabel.hidden = true
passwordTextField.layer.borderWidth = 0.0
passwordTextFieldErrorLabel.hidden = true
}
}
|
bsd-2-clause
|
ffeb098d58ddbcf39948585f5ad20d6f
| 49.041379 | 271 | 0.725469 | 5.932952 | false | false | false | false |
Yuanjihua1/SwiftyORM
|
SwiftyORM/SQLite.swift
|
1
|
18939
|
//
// SQLite.swift
// PerfectLib
//
// Created by Kyle Jessup on 7/14/15.
// Copyright (C) 2015 PerfectlySoft, Inc.
//
//===----------------------------------------------------------------------===//
//
// This source file is part of the Perfect.org open source project
//
// Copyright (c) 2015 - 2016 PerfectlySoft Inc. and the Perfect project authors
// Licensed under Apache License v2.0
//
// See http://perfect.org/licensing.html for license information
//
//===----------------------------------------------------------------------===//
//
//import SQLite3
#if os(Linux)
import SwiftGlibc
#endif
import CSQLite
/// This enum type indicates an exception when dealing with a SQLite database
public enum SQLiteError : Error {
/// A SQLite error code and message.
case Error(code: Int, msg: String)
}
/// A SQLite database
public class SQLite {
let path: String
var sqlite3 = OpaquePointer(bitPattern: 0)
/// Create or open a SQLite database given a file path.
///
/// - parameter path: String path to SQLite database
/// - parameter readOnly: Optional, Bool flag for read/write setting, defaults to false
/// - throws: SQLiteError
public init(_ path: String, readOnly: Bool = false, busyTimeoutMillis: Int = 1000) throws {
self.path = path
let flags = readOnly ? SQLITE_OPEN_READONLY : SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE
let res = sqlite3_open_v2(path, &self.sqlite3, flags, nil)
if res != SQLITE_OK {
throw SQLiteError.Error(code: Int(res), msg: "Unable to open database "+path)
}
sqlite3_busy_timeout(self.sqlite3, Int32(busyTimeoutMillis))
}
/// Close the SQLite database.
public func close() {
if self.sqlite3 != nil {
sqlite3_close(self.sqlite3)
self.sqlite3 = nil
}
}
/// Close the SQLite database.
public func close<T>(after: (SQLite) -> T) -> T {
defer {
close()
}
return after(self)
}
deinit {
close()
}
/// Compile the SQL statement.
///
/// - returns: A SQLiteStmt object representing the compiled statement.
public func prepare(statement stat: String) throws -> SQLiteStmt {
var statPtr = OpaquePointer(bitPattern: 0)
let tail = UnsafeMutablePointer<UnsafePointer<Int8>?>(nil as OpaquePointer?)
let res = sqlite3_prepare_v2(self.sqlite3, stat, Int32(stat.utf8.count), &statPtr, tail)
try checkRes(res)
return SQLiteStmt(db: self.sqlite3, stat: statPtr)
}
/// Returns the value of `sqlite3_last_insert_rowid`.
///
/// - returns: Int last inserted row ID
public func lastInsertRowID() -> Int {
let res = sqlite3_last_insert_rowid(self.sqlite3)
return Int(res)
}
/// Returns the value of `sqlite3_total_changes`.
///
/// - returns: Int total changes
public func totalChanges() -> Int {
let res = sqlite3_total_changes(self.sqlite3)
return Int(res)
}
/// Returns the value of `sqlite3_changes`.
///
/// - returns: Int number of changes
public func changes() -> Int {
let res = sqlite3_changes(self.sqlite3)
return Int(res)
}
/// Returns the value of `sqlite3_errcode`.
///
/// - returns: Int error code
public func errCode() -> Int {
let res = sqlite3_errcode(self.sqlite3)
return Int(res)
}
/// Returns the value of `sqlite3_errmsg`.
///
/// - returns: String error message
public func errMsg() -> String {
return String(validatingUTF8: sqlite3_errmsg(self.sqlite3))!
}
/// Execute the given statement. Assumes there will be no parameter binding or resulting row data.
///
/// - parameter statement: String statement to be executed
/// - throws: ()
public func execute(statement: String) throws {
try forEachRow(statement: statement, doBindings: { (SQLiteStmt) throws -> () in () }) {
(SQLiteStmt) -> () in
// nothing
}
}
/// Execute the given statement. Calls the provided callback one time for parameter binding. Assumes there will be no resulting row data.
///
/// - parameter statement: String statement to be executed
/// - parameter doBindings: Block used for bindings
/// - throws: ()
public func execute(statement: String, doBindings: (SQLiteStmt) throws -> ()) throws {
try forEachRow(statement: statement, doBindings: doBindings) {
(SQLiteStmt) -> () in
// nothing
}
}
/// Execute the given statement `count` times. Calls the provided callback on each execution for parameter binding. Assumes there will be no resulting row data.
///
/// - parameter statement: String statement to be executed
/// - parameter count: Int number of times to execute
/// - parameter doBindings: Block to be executed for binding on each call
/// - throws: ()
public func execute(statement: String, count: Int, doBindings: (SQLiteStmt, Int) throws -> ()) throws {
let stat = try prepare(statement: statement)
defer { stat.finalize() }
for idx in 1...count {
try doBindings(stat, idx)
try forEachRowBody(stat: stat) {
(SQLiteStmt) -> () in
// nothing
}
let _ = try stat.reset()
}
}
/// Executes a BEGIN, calls the provided closure and executes a ROLLBACK if an exception occurs or a COMMIT if no exception occurs.
///
/// - parameter closure: Block to be executed inside transaction
/// - throws: ErrorType
public func doWithTransaction(closure: () throws -> ()) throws {
try execute(statement: "BEGIN")
do {
try closure()
try execute(statement: "COMMIT")
} catch let e {
try execute(statement: "ROLLBACK")
throw e
}
}
/// Executes the statement and calls the closure for each resulting row.
///
/// - parameter statement: String statement to be executed
/// - parameter handleRow: Block to be executed for each row
/// - throws: ()
public func forEachRow(statement: String, handleRow: (SQLiteStmt, Int) throws -> ()) throws {
let stat = try prepare(statement: statement)
defer { stat.finalize() }
try forEachRowBody(stat: stat, handleRow: handleRow)
}
/// Executes the statement, calling `doBindings` to handle parameter bindings and calling `handleRow` for each resulting row.
///
/// - parameter statement: String statement to be executed
/// - parameter doBindings: Block to perform bindings on statement
/// - parameter handleRow: Block to execute for each row
/// - throws: ()
public func forEachRow(statement: String, doBindings: (SQLiteStmt) throws -> (), handleRow: (SQLiteStmt, Int) throws -> ()) throws {
let stat = try prepare(statement: statement)
defer { stat.finalize() }
try doBindings(stat)
try forEachRowBody(stat: stat, handleRow: handleRow)
}
func forEachRowBody(stat: SQLiteStmt, handleRow: (SQLiteStmt, Int) throws -> ()) throws {
var r = stat.step()
guard r == SQLITE_ROW || r == SQLITE_DONE else {
try checkRes(r)
return
}
var rowNum = 1
while r == SQLITE_ROW {
try handleRow(stat, rowNum)
rowNum += 1
r = stat.step()
}
}
func miniSleep(millis: Int) {
var tv = timeval()
tv.tv_sec = millis / 1000
#if os(Linux)
tv.tv_usec = Int((millis % 1000) * 1000)
#else
tv.tv_usec = Int32((millis % 1000) * 1000)
#endif
select(0, nil, nil, nil, &tv)
}
func checkRes(_ res: Int32) throws {
try checkRes(Int(res))
}
func checkRes(_ res: Int) throws {
if res != Int(SQLITE_OK) {
throw SQLiteError.Error(code: res, msg: String(validatingUTF8: sqlite3_errmsg(self.sqlite3))!)
}
}
}
/// A compiled SQLite statement
public class SQLiteStmt {
let db: OpaquePointer?
var stat: OpaquePointer?
typealias sqlite_destructor = @convention(c) (UnsafeMutableRawPointer?) -> Void
init(db: OpaquePointer?, stat: OpaquePointer?) {
self.db = db
self.stat = stat
}
/// Close or "finalize" the statement.
public func close() {
finalize()
}
/// Close the statement.
public func finalize() {
if self.stat != nil {
sqlite3_finalize(self.stat!)
self.stat = nil
}
}
/// Advance to the next row.
public func step() -> Int32 {
guard self.stat != nil else {
return SQLITE_MISUSE
}
return sqlite3_step(self.stat!)
}
/// Bind the Double value to the indicated parameter.
///
/// - parameter position: Int position of binding
/// - parameter d: Double to be bound
/// - throws: ()
public func bind(position: Int, _ d: Double) throws {
try checkRes(sqlite3_bind_double(self.stat!, Int32(position), d))
}
/// Bind the Int32 value to the indicated parameter.
///
/// - parameter position: Int position of binding
/// - parameter i: Int32 to be bound
/// - throws: ()
public func bind(position: Int, _ i: Int32) throws {
try checkRes(sqlite3_bind_int(self.stat!, Int32(position), Int32(i)))
}
/// Bind the Int value to the indicated parameter.
///
/// - parameter position: Int position of binding
/// - parameter i: Int to be bound
/// - throws: ()
public func bind(position: Int, _ i: Int) throws {
try checkRes(sqlite3_bind_int64(self.stat!, Int32(position), Int64(i)))
}
/// Bind the Int64 value to the indicated parameter.
///
/// - parameter position: Int position of binding
/// - parameter i: Int64 to be bound
/// - throws: ()
public func bind(position: Int, _ i: Int64) throws {
try checkRes(sqlite3_bind_int64(self.stat!, Int32(position), i))
}
/// Bind the String value to the indicated parameter.
///
/// - parameter position: Int position of binding
/// - parameter s: String to be bound
/// - throws: ()
public func bind(position: Int, _ s: String) throws {
try checkRes(sqlite3_bind_text(self.stat!, Int32(position), s, Int32(s.utf8.count), unsafeBitCast(OpaquePointer(bitPattern: -1), to: sqlite_destructor.self)))
}
/// Bind the [Int8] blob value to the indicated parameter.
///
/// - parameter position: Int position of binding
/// - parameter b: [Int8] blob to be bound
/// - throws: ()
public func bind(position: Int, _ b: [Int8]) throws {
try checkRes(sqlite3_bind_blob(self.stat!, Int32(position), b, Int32(b.count), unsafeBitCast(OpaquePointer(bitPattern: -1), to: sqlite_destructor.self)))
}
/// Bind the [UInt8] blob value to the indicated parameter.
///
/// - parameter position: Int position of binding
/// - parameter b: [UInt8] blob to be bound
/// - throws: ()
public func bind(position: Int, _ b: [UInt8]) throws {
try checkRes(sqlite3_bind_blob(self.stat!, Int32(position), b, Int32(b.count), unsafeBitCast(OpaquePointer(bitPattern: -1), to: sqlite_destructor.self)))
}
/// Bind a blob of `count` zero values to the indicated parameter.
///
/// - parameter position: Int position of binding
/// - parameter count: Int number of zero values in blob to be bound
/// - throws: ()
public func bindZeroBlob(position: Int, count: Int) throws {
try checkRes(sqlite3_bind_zeroblob(self.stat!, Int32(position), Int32(count)))
}
/// Bind a null to the indicated parameter.
///
/// - parameter position: Int position of binding
/// - throws: ()
public func bindNull(position: Int) throws {
try checkRes(sqlite3_bind_null(self.stat!, Int32(position)))
}
/// Bind the Double value to the indicated parameter.
///
/// - parameter name: String name of binding
/// - parameter d: Double to be bound
/// - throws: ()
public func bind(name: String, _ d: Double) throws {
try checkRes(sqlite3_bind_double(self.stat!, Int32(bindParameterIndex(name: name)), d))
}
/// Bind the Int32 value to the indicated parameter.
///
/// - parameter name: String name of binding
/// - parameter i: Int32 to be bound
/// - throws: ()
public func bind(name: String, _ i: Int32) throws {
try checkRes(sqlite3_bind_int(self.stat!, Int32(bindParameterIndex(name: name)), Int32(i)))
}
/// Bind the Int value to the indicated parameter.
///
/// - parameter name: String name of binding
/// - parameter i: Int to be bound
/// - throws: ()
public func bind(name: String, _ i: Int) throws {
try checkRes(sqlite3_bind_int64(self.stat!, Int32(bindParameterIndex(name: name)), Int64(i)))
}
/// Bind the Int64 value to the indicated parameter.
///
/// - parameter name: String name of binding
/// - parameter i: Int64 to be bound
/// - throws: ()
public func bind(name: String, _ i: Int64) throws {
try checkRes(sqlite3_bind_int64(self.stat!, Int32(bindParameterIndex(name: name)), i))
}
/// Bind the String value to the indicated parameter.
///
/// - parameter name: String name of binding
/// - parameter s: String to be bound
/// - throws: ()
public func bind(name: String, _ s: String) throws {
try checkRes(sqlite3_bind_text(self.stat!, Int32(bindParameterIndex(name: name)), s, Int32(s.utf8.count), unsafeBitCast(OpaquePointer(bitPattern: -1), to: sqlite_destructor.self)))
}
/// Bind the [Int8] blob value to the indicated parameter.
///
/// - parameter name: String name of binding
/// - parameter b: [Int8] blob to be bound
/// - throws: ()
public func bind(name: String, _ b: [Int8]) throws {
try checkRes(sqlite3_bind_text(self.stat!, Int32(bindParameterIndex(name: name)), b, Int32(b.count), unsafeBitCast(OpaquePointer(bitPattern: -1), to: sqlite_destructor.self)))
}
/// Bind a blob of `count` zero values to the indicated parameter.
///
/// - parameter name: String name of binding
/// - parameter count: Int number of zero values in blob to be bound
/// - throws: ()
public func bindZeroBlob(name: String, count: Int) throws {
try checkRes(sqlite3_bind_zeroblob(self.stat!, Int32(bindParameterIndex(name: name)), Int32(count)))
}
/// Bind a null to the indicated parameter.
///
/// - parameter name: String name of binding
/// - throws: ()
public func bindNull(name: String) throws {
try checkRes(sqlite3_bind_null(self.stat!, Int32(bindParameterIndex(name: name))))
}
/// Returns the index for the named parameter.
///
/// - parameter name: String name of binding
/// - throws: ()
/// - returns: Int index of parameter
public func bindParameterIndex(name: String) throws -> Int {
let idx = sqlite3_bind_parameter_index(self.stat!, name)
guard idx != 0 else {
throw SQLiteError.Error(code: Int(SQLITE_MISUSE), msg: "The indicated bind parameter name was not found.")
}
return Int(idx)
}
/// Resets the SQL statement.
///
/// - returns: Int result
public func reset() throws -> Int {
let res = sqlite3_reset(self.stat!)
try checkRes(res)
return Int(res)
}
/// Return the number of columns in mthe result set.
///
/// - returns: Int count of columns in result set
public func columnCount() -> Int {
let res = sqlite3_column_count(self.stat!)
return Int(res)
}
/// Returns the name for the indicated column.
///
/// - parameter position: Int position of column
/// - returns: String name of column
public func columnName(position: Int) -> String {
return String(validatingUTF8: sqlite3_column_name(self.stat!, Int32(position)))!
}
/// Returns the name of the declared type for the indicated column.
///
/// - parameter position: Int position of column
/// - returns: String name of declared type
public func columnDeclType(position: Int) -> String {
return String(validatingUTF8: sqlite3_column_decltype(self.stat!, Int32(position)))!
}
/// Returns the blob data for the indicated column.
///
/// - parameter position: Int position of column
/// - returns: [Int8] blob
public func columnBlob(position: Int) -> [Int8] {
let vp = sqlite3_column_blob(self.stat!, Int32(position))
let vpLen = Int(sqlite3_column_bytes(self.stat!, Int32(position)))
guard vpLen > 0 else {
return [Int8]()
}
var ret = [Int8]()
if var bytesPtr = vp?.bindMemory(to: Int8.self, capacity: vpLen) {
for _ in 0..<vpLen {
ret.append(bytesPtr.pointee)
bytesPtr = bytesPtr.successor()
}
}
return ret
}
/// Returns the Double value for the indicated column.
///
/// - parameter: Int position of column
/// - returns: Double value for column
public func columnDouble(position: Int) -> Double {
return Double(sqlite3_column_double(self.stat!, Int32(position)))
}
/// Returns the Int value for the indicated column.
///
/// - parameter: Int position of column
/// - returns: Int value for column
public func columnInt(position: Int) -> Int {
return Int(sqlite3_column_int64(self.stat!, Int32(position)))
}
/// Returns the Int32 value for the indicated column.
///
/// - parameter: Int position of column
/// - returns: Int32 value for column
public func columnInt32(position: Int) -> Int32 {
return sqlite3_column_int(self.stat!, Int32(position))
}
/// Returns the Int64 value for the indicated column.
///
/// - parameter: Int position of column
/// - returns: Int64 value for column
public func columnInt64(position: Int) -> Int64 {
return sqlite3_column_int64(self.stat!, Int32(position))
}
/// Returns the String value for the indicated column.
///
/// - parameter: Int position of column
/// - returns: String value for column
public func columnText(position: Int) -> String {
if let res = sqlite3_column_text(self.stat!, Int32(position)) {
return res.withMemoryRebound(to: Int8.self, capacity: 0) {
String(validatingUTF8: $0) ?? ""
}
}
return ""
}
/// Returns the type for the indicated column.
///
/// - parameter: Int position of column
/// - returns: Int32
public func columnType(position: Int) -> Int32 {
return sqlite3_column_type(self.stat!, Int32(position))
}
/// Test if the indicated column is an integer
///
/// - parameter: Int position of column
/// - returns: Bool
public func isInteger(position: Int) -> Bool {
return SQLITE_INTEGER == columnType(position: position)
}
/// Test if the indicated column is a Float
///
/// - parameter: Int position of column
/// - returns: Bool
public func isFloat(position: Int) -> Bool {
return SQLITE_FLOAT == columnType(position: position)
}
/// Test if the indicated column is Text
///
/// - parameter: Int position of column
/// - returns: Bool
public func isText(position: Int) -> Bool {
return SQLITE_TEXT == columnType(position: position)
}
/// Test if the indicated column is a Blob
///
/// - parameter: Int position of column
/// - returns: Bool
public func isBlob(position: Int) -> Bool {
return SQLITE_BLOB == columnType(position: position)
}
/// Test if the indicated column is NULL
///
/// - parameter: Int position of column
/// - returns: Bool
public func isNull(position: Int) -> Bool {
return SQLITE_NULL == columnType(position: position)
}
func checkRes(_ res: Int32) throws {
try checkRes(Int(res))
}
func checkRes(_ res: Int) throws {
if res != Int(SQLITE_OK) {
throw SQLiteError.Error(code: res, msg: String(validatingUTF8: sqlite3_errmsg(self.db!))!)
}
}
deinit {
finalize()
}
}
|
mit
|
335f8d54b9d472c99f966a47cea4669c
| 30.304132 | 182 | 0.656106 | 3.55195 | false | false | false | false |
geocore/geocore-swift
|
GeocoreKit/Geocore.swift
|
1
|
31847
|
//
// Geocore.swift
// GeocoreKit
//
// Created by Purbo Mohamad on 2017/02/10.
// Copyright © 2017 Geocore. All rights reserved.
//
import Foundation
import Alamofire
import SwiftyJSON
import PromiseKit
// MARK: - Constants
fileprivate struct GeocoreConstants {
fileprivate static let bundleKeyBaseURL = "GeocoreBaseURL"
fileprivate static let bundleKeyProjectID = "GeocoreProjectId"
fileprivate static let httpHeaderAccessTokenName = "Geocore-Access-Token"
}
/// GeocoreKit error code.
///
/// - invalidState: Unexpected internal state. Possibly a bug.
/// - invalidServerResponse: Unexpected server response. Possibly a bug.
/// - unexpectedResponse: Unexpected response format. Possibly a bug.
/// - serverError: Server returns an error.
/// - tokenUndefined: Token is unavailable. Possibly the library is left uninitialized or user is not logged in.
/// - unauthorizedAccess: Access to the specified resource is forbidden. Possibly the user is not logged in.
/// - invalidParameter: One of the parameter passed to the API is invalid.
/// - networkError: Underlying network library produces an error.
public enum GeocoreError: Error {
case invalidState
case invalidServerResponse(statusCode: Int)
case unexpectedResponse(message: String)
case serverError(code: String, message: String)
case tokenUndefined
case unauthorizedAccess
case invalidParameter(message: String)
case networkError(error: Error)
case otherError(error: Error)
}
/// GeocoreError.invalidServerResponse code for locally generated errors.
///
/// - unavailable: No information available about the error. Possibly a bug.
/// - unexpectedResponse: Server returns unexpected (unstructured) response. Possibly a bug.
public enum GeocoreServerResponse: Int {
case unavailable = -1
case unexpectedResponse = -2
case emptyResponse = -3
}
// MARK: - Helper extensions
fileprivate extension Alamofire.URLEncoding {
/// Almost like URLEncoding's encode, except that this will ALWAYS encode the parameters as URL query parameters
fileprivate func geocoreEncode(_ urlRequest: URLRequestConvertible, with parameters: Parameters?) throws -> URLRequest {
var urlRequest = try urlRequest.asURLRequest()
guard let parameters = parameters else { return urlRequest }
guard let url = urlRequest.url else {
throw AFError.parameterEncodingFailed(reason: .missingURL)
}
if var urlComponents = URLComponents(url: url, resolvingAgainstBaseURL: false), !parameters.isEmpty {
let percentEncodedQuery = (urlComponents.percentEncodedQuery.map { $0 + "&" } ?? "") + geocoreQuery(parameters)
urlComponents.percentEncodedQuery = percentEncodedQuery
urlRequest.url = urlComponents.url
}
return urlRequest
}
/// A copy of URLEncoding's query, but it's declared as private
private func geocoreQuery(_ parameters: [String: Any]) -> String {
var components: [(String, String)] = []
for key in parameters.keys.sorted(by: <) {
let value = parameters[key]!
components += queryComponents(fromKey: key, value: value)
}
return components.map { "\($0)=\($1)" }.joined(separator: "&")
}
}
/// Alamofire's SessionManager extended so that a request can have both URL-encoded parameters and JSON-encoded body
fileprivate extension Alamofire.SessionManager {
@discardableResult
fileprivate func requestWithParametersAndBody(
_ url: URLConvertible,
method: HTTPMethod = .get,
parameters: Parameters? = nil,
body: Parameters? = nil,
headers: HTTPHeaders? = nil) throws -> DataRequest {
// if both parameters & body are defined: JSON encoding for the body, URL encoding for parameters
// if only parameters is defined: URL encoding for parameters
// if only body is defined: JSON encoding for body
if let parameters = parameters, let body = body {
let originalURLRequest = try URLRequest(url: url, method: method, headers: headers)
var encodedURLRequest = try URLEncoding.default.geocoreEncode(originalURLRequest, with: parameters)
let data = try JSONSerialization.data(withJSONObject: body, options: [])
// force JSON encoding
encodedURLRequest.setValue("application/json; charset=utf-8", forHTTPHeaderField: "Content-Type")
encodedURLRequest.httpBody = data
return request(encodedURLRequest)
} else if let parameters = parameters {
let originalURLRequest = try URLRequest(url: url, method: method, headers: headers)
var encodedURLRequest = try URLEncoding.default.geocoreEncode(originalURLRequest, with: parameters)
// force JSON encoding
encodedURLRequest.setValue("application/json; charset=utf-8", forHTTPHeaderField: "Content-Type")
return request(encodedURLRequest)
//return request(url, method: method, parameters: parameters, encoding: URLEncoding.default, headers: headers)
} else if let body = body {
return request(url, method: method, parameters: body, encoding: JSONEncoding.default, headers: headers)
} else {
return request(url, method: method, parameters: parameters, encoding: JSONEncoding.default, headers: headers)
}
}
}
// MARK: - Base structures
/// Representing an object that can be initialized from JSON data.
public protocol GeocoreInitializableFromJSON {
init(_ json: JSON)
}
/// Representing an object that can be serialized to JSON.
public protocol GeocoreSerializableToJSON {
func asDictionary() -> [String: Any]
}
/// Representing an object can be identified
public protocol GeocoreIdentifiable: GeocoreInitializableFromJSON, GeocoreSerializableToJSON {
var sid: Int64? { get set }
var id: String? { get set }
}
/// A wrapper for raw JSON value returned by Geocore service.
open class GeocoreGenericResult: GeocoreInitializableFromJSON {
private(set) public var json: JSON
public required init(_ json: JSON) {
self.json = json
}
}
/// A wrapper for count request returned by Geocore service.
open class GeocoreGenericCountResult: GeocoreInitializableFromJSON {
private(set) public var count: Int?
public required init(_ json: JSON) {
self.count = json["count"].int
}
}
/// Geographical point in WGS84.
public struct GeocorePoint: GeocoreSerializableToJSON, GeocoreInitializableFromJSON {
public var latitude: Float?
public var longitude: Float?
public init() {
}
public init(latitude: Float?, longitude: Float?) {
self.latitude = latitude
self.longitude = longitude
}
public init(_ json: JSON) {
self.latitude = json["latitude"].float
self.longitude = json["longitude"].float
}
public func asDictionary() -> [String: Any] {
if let latitude = self.latitude, let longitude = self.longitude {
return ["latitude": latitude, "longitude": longitude]
} else {
return [String: Any]()
}
}
}
/// Representing a result returned by Geocore service.
///
/// - success: Containing value of the result.
/// - failure: Containing an error.
public enum GeocoreResult<T> {
case success(T)
case failure(GeocoreError)
public init(_ value: T) {
self = .success(value)
}
public init(_ error: GeocoreError) {
self = .failure(error)
}
public var failed: Bool {
switch self {
case .failure(_):
return true
default:
return false
}
}
public var error: GeocoreError? {
switch self {
case .failure(let error):
return error
default:
return nil
}
}
public var value: T? {
switch self {
case .success(let value):
return value
default:
return nil
}
}
public func propagate(toFulfillment fulfill: @escaping (T) -> Void, rejection reject: @escaping (Error) -> Void) -> Void {
switch self {
case .success(let value):
fulfill(value)
case .failure(let error):
reject(error)
}
}
}
// MARK: - Main class
/// Main singleton class for accessing Geocore.
open class Geocore {
/// Singleton instance.
public static let sharedInstance = Geocore()
/// Default Geocore date formatter
public static let geocoreDateFormatter = DateFormatter.dateFormatterForGeocore()
/// Currently used Geocore base URL.
public private(set) var baseURL: String?
/// Currently used Geocore project ID.
public private(set) var projectId: String?
/// Currently logged in user ID (if logged in).
public private(set) var userId: String?
/// Access token of currently logged in user (if logged in).
public var token: String?
private init() {
baseURL = Bundle.main.object(forInfoDictionaryKey: GeocoreConstants.bundleKeyBaseURL) as? String
projectId = Bundle.main.object(forInfoDictionaryKey: GeocoreConstants.bundleKeyProjectID) as? String
}
public func setup(baseURL: String, projectId: String) -> Geocore {
self.baseURL = baseURL;
self.projectId = projectId;
return self;
}
// MARK: Internal low-level methods
private func buildUrl(_ servicePath: String) throws -> String {
if let baseURL = self.baseURL {
return baseURL + servicePath
} else {
throw GeocoreError.invalidState
}
}
private func extractMultipartInfoFrom(_ body: Alamofire.Parameters? = nil) -> (fileContents: Data, fileName: String, fieldName: String, mimeType: String)? {
if let fileContents = body?["$fileContents"] as? Data {
if let fileName = body?["$fileName"] as? String, let fieldName = body?["$fieldName"] as? String, let mimeType = body?["$mimeType"] as? String {
return (fileContents, fileName, fieldName, mimeType)
}
}
return nil
}
private func validateUploadRequest(_ body: Alamofire.Parameters? = nil) -> Bool {
if let _ = body?["$fileContents"] as? Data {
// uploading file, make sure all required parameters are specified as well
if let _ = body?["$fileName"] as? String, let _ = body?["$fieldName"] as? String, let _ = body?["$mimeType"] as? String {
return true
} else {
return false
}
} else {
return true
}
}
private func buildRequestCompletionHandler(onSuccess: @escaping (JSON) -> Void,
onError: @escaping (GeocoreError) -> Void) -> ((Alamofire.DataResponse<Data>) -> Void) {
return { (response: Alamofire.DataResponse<Data>) -> Void in
if let error = response.error {
print("[ERROR] \(error)")
onError(.networkError(error: error))
} else if let statusCode = response.response?.statusCode {
switch statusCode {
case 200:
if let data = response.data {
if let json = try? JSON(data: data) {
if let status = json["status"].string {
if status == "success" {
onSuccess(json["result"])
} else {
onError(.serverError(
code: json["code"].string ?? "",
message: json["message"].string ?? ""))
}
} else {
onError(.invalidServerResponse(
statusCode: GeocoreServerResponse.unexpectedResponse.rawValue))
}
} else {
onError(.invalidServerResponse(
statusCode: GeocoreServerResponse.unexpectedResponse.rawValue))
}
} else {
// shouldn't happen
onError(.invalidServerResponse(
statusCode: GeocoreServerResponse.emptyResponse.rawValue))
}
case 403:
onError(.unauthorizedAccess)
default:
onError(.invalidServerResponse(statusCode: statusCode))
}
} else {
onError(.invalidServerResponse(
statusCode: GeocoreServerResponse.unavailable.rawValue))
}
}
}
private func request(
_ url: String,
method: Alamofire.HTTPMethod,
parameters: Alamofire.Parameters?,
body: Alamofire.Parameters?,
requestCompletionHandler: @escaping (Alamofire.DataResponse<Data>) -> Void) throws {
if !validateUploadRequest(body) {
// file supposed to be uploaded but file info not provided.
throw GeocoreError.invalidParameter(message: "Parameter for file upload incomplete")
} else {
if let token = self.token {
if let multipartInfo = self.extractMultipartInfoFrom(body) {
// multipart request
try Alamofire.upload(
multipartFormData: { multipartFormData in
multipartFormData.append(
multipartInfo.fileContents,
withName: multipartInfo.fieldName,
fileName: multipartInfo.fileName,
mimeType: multipartInfo.mimeType)
},
with: URLRequest(url: url, method: method, headers: [GeocoreConstants.httpHeaderAccessTokenName: token]),
encodingCompletion: { encodingResult in
switch encodingResult {
case .success(let upload, _, _):
upload.responseData(completionHandler: requestCompletionHandler)
case .failure(let encodingError):
print(encodingError)
}
})
} else {
// Alamofire request with token
try Alamofire.SessionManager.default
.requestWithParametersAndBody(
url,
method: method,
parameters: parameters,
body: body,
headers: [GeocoreConstants.httpHeaderAccessTokenName: token])
.responseData(completionHandler: requestCompletionHandler)
}
} else {
// Alamofire request with no token
try Alamofire.SessionManager.default
.requestWithParametersAndBody(
url,
method: method,
parameters: parameters,
body: body)
.responseData(completionHandler: requestCompletionHandler)
}
}
}
/// Generic request
///
/// - Parameters:
/// - path: Path relative to base API URL.
/// - method: HTTP method
/// - parameters: URL query parameters
/// - body: HTTP body
/// - onSuccess: handler called when request is successful
/// - onError: handler called when there is an error
private func request(
_ path: String,
method: Alamofire.HTTPMethod,
parameters: Alamofire.Parameters?,
body: Alamofire.Parameters?,
onSuccess: @escaping (JSON) -> Void,
onError: @escaping (GeocoreError) -> Void) {
do {
try request(
buildUrl(path),
method: method,
parameters: parameters,
body: body,
requestCompletionHandler: buildRequestCompletionHandler(onSuccess: onSuccess, onError: onError))
} catch {
onError(.otherError(error: error))
}
}
/// Request resulting a single result of type T.
///
/// - Parameters:
/// - path: Path relative to base API URL.
/// - method: HTTP method
/// - parameters: URL query parameters
/// - body: HTTP body
/// - callback: callback to be called when there is a single result of type T or error.
private func request<T: GeocoreInitializableFromJSON>(
path: String,
method: Alamofire.HTTPMethod,
parameters: Alamofire.Parameters?,
body: Alamofire.Parameters?,
callback: @escaping (GeocoreResult<T>) -> Void) {
request(path,
method: method,
parameters: parameters,
body: body,
onSuccess: { json in callback(GeocoreResult(T(json))) },
onError: { error in callback(.failure(error)) })
}
/// Request resulting multiple result in an array of objects of type T
///
/// - Parameters:
/// - path: Path relative to base API URL.
/// - method: HTTP method
/// - parameters: URL query parameters
/// - body: HTTP body
/// - callback: callback to be called when there is an array of result of type T or error.
private func request<T: GeocoreInitializableFromJSON>(
_ path: String,
method: Alamofire.HTTPMethod,
parameters: Alamofire.Parameters?,
body: Alamofire.Parameters?,
callback: @escaping (GeocoreResult<[T]>) -> Void) {
request(path,
method: method,
parameters: parameters,
body: body,
onSuccess: { json in
if let result = json.array {
callback(GeocoreResult(result.map { T($0) }))
} else {
callback(GeocoreResult([]))
}
},
onError: { error in callback(.failure(error)) })
}
// MARK: HTTP methods: GET, POST, DELETE, PUT
/// Do an HTTP GET request expecting one result of type T
///
/// - Parameters:
/// - path: Path relative to base API URL.
/// - parameters: URL query parameters
/// - callback: callback to be called when there is a single result of type T or error.
public func GET<T: GeocoreInitializableFromJSON>(
_ path: String,
parameters: Alamofire.Parameters? = nil,
callback: @escaping (GeocoreResult<T>) -> Void) {
request(path: path, method: .get, parameters: parameters, body: nil, callback: callback)
}
/// Promise a single result of type T from an HTTP GET request.
///
/// - Parameters:
/// - path: Path relative to base API URL.
/// - parameters: URL query parameters
/// - Returns: Promise for a single result of type T.
public func promisedGET<T: GeocoreInitializableFromJSON>(
_ path: String,
parameters: Alamofire.Parameters? = nil) -> Promise<T> {
return Promise { (fulfill, reject) in
self.GET(path, parameters: parameters) {
result in result.propagate(toFulfillment: fulfill, rejection: reject)
}
}
}
/// Do an HTTP GET request expecting an multiple result in an array of objects of type T
///
/// - Parameters:
/// - path: Path relative to base API URL.
/// - parameters: URL query parameters
/// - callback: callback to be called when there is an array of multiple result of type T or error.
func GET<T: GeocoreInitializableFromJSON>(
_ path: String,
parameters: Alamofire.Parameters? = nil,
callback: @escaping (GeocoreResult<[T]>) -> Void) {
request(path, method: .get, parameters: parameters, body: nil, callback: callback)
}
/// Promise multiple result of type T from an HTTP GET request.
///
/// - Parameters:
/// - path: Path relative to base API URL.
/// - parameters: URL query parameters
/// - Returns: Promise for a multiple result of type T.
func promisedGET<T: GeocoreInitializableFromJSON>(
_ path: String,
parameters: Alamofire.Parameters? = nil) -> Promise<[T]> {
return Promise { (fulfill, reject) in
self.GET(path, parameters: parameters) {
result in result.propagate(toFulfillment: fulfill, rejection: reject)
}
}
}
/// Do an HTTP POST request expecting one result of type T
///
/// - Parameters:
/// - path: Path relative to base API URL.
/// - parameters: URL query parameters
/// - body: HTTP body
/// - callback: callback to be called when there is a single result of type T or error.
func POST<T: GeocoreInitializableFromJSON>(
_ path: String,
parameters: Alamofire.Parameters? = nil,
body: Alamofire.Parameters? = nil,
callback: @escaping (GeocoreResult<T>) -> Void) {
request(path: path, method: .post, parameters: parameters, body: body, callback: callback)
}
/// Do an HTTP POST request expecting an multiple result in an array of objects of type T
///
/// - Parameters:
/// - path: Path relative to base API URL.
/// - parameters: URL query parameters
/// - body: HTTP body
/// - callback: callback to be called when there is an array of multiple result of type T or error.
func POST<T: GeocoreInitializableFromJSON>(
_ path: String,
parameters: Alamofire.Parameters? = nil,
body: Alamofire.Parameters? = nil,
callback: @escaping (GeocoreResult<[T]>) -> Void) {
request(path, method: .post, parameters: parameters, body: body, callback: callback)
}
/// Do an HTTP POST file upload expecting one result of type T
///
/// - Parameters:
/// - path: Path relative to base API URL.
/// - parameters: URL query parameters
/// - fieldName: Uploaded data field name
/// - fileName: Uploaded data file name
/// - mimeType: Uploaded data MIME type
/// - fileContents: Data to be uploaded
/// - callback: callback to be called when there is a single result of type T or error.
func uploadPOST<T: GeocoreInitializableFromJSON>(
_ path: String,
parameters: Alamofire.Parameters? = nil,
fieldName: String,
fileName: String,
mimeType: String,
fileContents: Data,
callback: @escaping (GeocoreResult<T>) -> Void) {
POST(path,
parameters: parameters,
body: [
"$fileContents": fileContents,
"$fileName": fileName,
"$fieldName": fieldName,
"$mimeType": mimeType],
callback: callback)
}
/**
Promise a single result of type T from an HTTP POST request.
*/
/// Promise a single result of type T from an HTTP POST request.
///
/// - Parameters:
/// - path: Path relative to base API URL.
/// - parameters: URL query parameters
/// - body: HTTP body
/// - Returns: Promise for a single result of type T.
func promisedPOST<T: GeocoreInitializableFromJSON>(
_ path: String,
parameters: Alamofire.Parameters? = nil,
body: Alamofire.Parameters? = nil) -> Promise<T> {
return Promise { (fulfill, reject) in
self.POST(path, parameters: parameters, body: body) { result in
result.propagate(toFulfillment: fulfill, rejection: reject)
}
}
}
/// Promise multiple results of type T from an HTTP POST request.
///
/// - Parameters:
/// - path: Path relative to base API URL.
/// - parameters: URL query parameters
/// - body: HTTP body
/// - Returns: Promise for a multiple result of type T.
func promisedPOST<T: GeocoreInitializableFromJSON>(
_ path: String,
parameters: Alamofire.Parameters? = nil,
body: Alamofire.Parameters? = nil) -> Promise<[T]> {
return Promise { (fulfill, reject) in
self.POST(path, parameters: parameters, body: body) { result in
result.propagate(toFulfillment: fulfill, rejection: reject)
}
}
}
/// Promise one result of type T from an file upload request.
///
/// - Parameters:
/// - path: Path relative to base API URL.
/// - parameters: URL query parameters
/// - fieldName: Uploaded data field name
/// - fileName: Uploaded data file name
/// - mimeType: Uploaded data MIME type
/// - fileContents: Data to be uploaded
/// - Returns: Promise for a single result of type T.
func promisedUploadPOST<T: GeocoreInitializableFromJSON>(
_ path: String,
parameters: Alamofire.Parameters? = nil,
fieldName: String,
fileName: String,
mimeType: String,
fileContents: Data) -> Promise<T> {
return self.promisedPOST(path, parameters: parameters, body: ["$fileContents": fileContents, "$fileName": fileName, "$fieldName": fieldName, "$mimeType": mimeType])
}
/// Do an HTTP DELETE request expecting one result of type T
///
/// - Parameters:
/// - path: Path relative to base API URL.
/// - parameters: URL query parameters
/// - callback: callback to be called when there is a single result of type T or error.
func DELETE<T: GeocoreInitializableFromJSON>(
_ path: String,
parameters: Alamofire.Parameters? = nil,
callback: @escaping (GeocoreResult<T>) -> Void) {
request(path: path, method: .delete, parameters: parameters, body: nil, callback: callback)
}
/// Promise a single result of type T from an HTTP DELETE request.
///
/// - Parameters:
/// - path: Path relative to base API URL.
/// - parameters: URL query parameters
/// - Returns: Promise for a single result of type T.
func promisedDELETE<T: GeocoreInitializableFromJSON>(
_ path: String,
parameters: Alamofire.Parameters? = nil) -> Promise<T> {
return Promise { (fulfill, reject) in
self.DELETE(path, parameters: parameters) { result in
result.propagate(toFulfillment: fulfill, rejection: reject)
}
}
}
// MARK: User management methods (callback version)
/**
Login to Geocore with callback.
- parameter userId: User's ID to be submitted.
- parameter password: Password for authorizing user.
- parameter callback: Closure to be called when the token string or an error is returned.
*/
/// Login to Geocore with callback.
///
/// - Parameters:
/// - userId: User's ID to be submitted.
/// - password: Password for authorizing user.
/// - alternateIdIndex: alternate ID
/// - callback: Closure to be called when the token string or an error is returned.
public func login(
userId: String,
password: String,
alternateIdIndex: Int = 0,
callback: @escaping (GeocoreResult<String>) -> Void) {
var params: Alamofire.Parameters = ["id": userId, "password": password, "project_id": self.projectId!]
if alternateIdIndex > 0 {
params["alt"] = String(alternateIdIndex)
}
// make sure we're logged out, otherwise the logic in requestBuilder will break!
self.logout()
POST("/auth", parameters: params, body: nil) { (result: GeocoreResult<GeocoreGenericResult>) -> Void in
switch result {
case .success(let value):
self.token = value.json["token"].string
if let token = self.token {
self.userId = userId
callback(GeocoreResult(token))
} else {
callback(.failure(GeocoreError.invalidState))
}
case .failure(let error):
callback(.failure(error))
}
}
}
public func loginWithDefaultUser(_ callback: @escaping (GeocoreResult<String>) -> Void) {
// login using default id & password
self.login(userId: GeocoreUser.defaultId(), password: GeocoreUser.defaultPassword(), alternateIdIndex: 0) { result in
switch result {
case .success(_):
callback(result)
case .failure(let error):
// oops! try to register first
switch error {
case .serverError(let code, _):
if code == "Auth.0001" {
// not registered, register the default user first
GeocoreUserOperation().register(user: GeocoreUser.defaultUser(), callback: { result in
switch result {
case .success(_):
// successfully registered, now login again
self.login(
userId: GeocoreUser.defaultId(),
password: GeocoreUser.defaultPassword(),
alternateIdIndex: 0) { result in
callback(result)
}
case .failure(let error):
callback(.failure(error))
}
});
} else {
// unexpected error
callback(.failure(error))
}
default:
// unexpected error
callback(.failure(error))
}
}
}
}
// MARK: User management methods (promise version)
/// Promise to login to Geocore.
///
/// - Parameters:
/// - userId: User's ID to be submitted.
/// - password: Password for authorizing user.
/// - alternateIdIndex: alternate ID
/// - Returns: Promise for token when login is successful.
public func login(userId: String, password: String, alternateIdIndex: Int = 0) -> Promise<String> {
return Promise { (fulfill, reject) in
self.login(userId: userId, password: password, alternateIdIndex: alternateIdIndex) { result in
result.propagate(toFulfillment: fulfill, rejection: reject)
}
}
}
/// Promise to login to Geocore with default user.
///
/// - Returns: Promise for token when login is successful.
public func loginWithDefaultUser() -> Promise<String> {
return Promise { (fulfill, reject) in
self.loginWithDefaultUser { result in
result.propagate(toFulfillment: fulfill, rejection: reject)
}
}
}
/// Logout from Geocore.
public func logout() {
self.token = nil
self.userId = nil
}
}
|
apache-2.0
|
f180b16911125af0bbbc5e76fb1d2da2
| 37.648058 | 172 | 0.575928 | 5.032554 | false | false | false | false |
velyan/Mark
|
Mark/HelpController.swift
|
1
|
2858
|
//
// HelpController.swift
// Mark
//
// Created by Velislava Yanchina on 10/24/16.
// Copyright © 2016 Velislava Yanchina. All rights reserved.
//
import Foundation
fileprivate enum Strings {
static let installation = "Installation"
static let keyBindingsSetup = "Key Bindings Setup"
static let howToSetUp = "HOW TO SETUP"
static let howToUse = "HOW TO USE"
static let markExtension = "Mark"
static let installationDescription = "1. Open System Preferences\n2. Select Extensions > Xcode Source Editor\n3. Enable Mark"
static let keyBindingsDescription = "1. Open Xcode > Preferences\n2. Select Key Bindings from the top bar\n3. Filter by \"mark\" and double tap the result to edit key bindings"
static let markDescription = "When in Xcode select Editor > Mark > Mark All or Mark Selected"
}
fileprivate enum Resources {
static let installation = (name: "system_prefs_demo", extension: "mov")
static let keyBindings = (name: "key_bindings_demo", extension: "mov")
static let mark = (name: "mark_full_demo", extension: "mov")
}
fileprivate enum Contents {
static let installation = Content(title: Strings.installation,
description: Strings.installationDescription,
resource: Resources.installation)
static let keyBindings = Content(title: Strings.keyBindingsSetup,
description: Strings.keyBindingsDescription,
resource: Resources.keyBindings)
static let mark = Content(title: Strings.markExtension,
description: Strings.markDescription,
resource: Resources.mark)
}
protocol HelpControllerDelegate: class {
func reloadContent(content: Content)
}
class HelpController {
weak var delegate: HelpControllerDelegate?
lazy var data = [HeaderNavigationItem(title: Strings.howToSetUp),
NavigationItem(title: Strings.installation),
NavigationItem(title: Strings.keyBindingsSetup),
HeaderNavigationItem(title: Strings.howToUse),
NavigationItem(title: Strings.markExtension)] as [Any]
public func action(forItem item: NavigationItemProtocol) {
if let content = content(forNavigationItem: item) {
delegate?.reloadContent(content: content)
}
}
func content(forNavigationItem item: NavigationItemProtocol) -> Content? {
if item.title == Strings.installation {
return Contents.installation
}
else if item.title == Strings.keyBindingsSetup {
return Contents.keyBindings
}
else if item.title == Strings.markExtension {
return Contents.mark
}
return nil
}
}
|
mit
|
a6c8cc7be66a90b9ea42aff1d74520d9
| 39.239437 | 180 | 0.645782 | 4.817875 | false | false | false | false |
SoneeJohn/WWDC
|
ConfCore/LiveVideosAdapter.swift
|
1
|
1156
|
//
// LiveVideosAdapter.swift
// WWDC
//
// Created by Guilherme Rambo on 15/02/17.
// Copyright © 2017 Guilherme Rambo. All rights reserved.
//
import Foundation
import SwiftyJSON
private enum LiveVideoKeys: String, JSONSubscriptType {
case sessionId, tvosUrl
var jsonKey: JSONKey {
return JSONKey.key(rawValue)
}
}
final class LiveVideosAdapter: Adapter {
typealias InputType = JSON
typealias OutputType = SessionAsset
func adapt(_ input: JSON) -> Result<SessionAsset, AdapterError> {
guard let sessionId = input[LiveVideoKeys.sessionId].string else {
return .error(.missingKey(LiveVideoKeys.sessionId))
}
guard let url = input[LiveVideoKeys.tvosUrl].string else {
return .error(.missingKey(LiveVideoKeys.tvosUrl))
}
let asset = SessionAsset()
// Live assets are always for the current year
asset.year = Calendar.current.component(.year, from: Date())
asset.sessionId = sessionId
asset.rawAssetType = SessionAssetType.liveStreamVideo.rawValue
asset.remoteURL = url
return .success(asset)
}
}
|
bsd-2-clause
|
32f38f54cb34d3817e7a07e67b4a14a3
| 25.860465 | 74 | 0.670996 | 4.547244 | false | false | false | false |
GreatfeatServices/gf-mobile-app
|
olivin-esguerra/ios-exam/Pods/RxSwift/RxSwift/Observables/Implementations/Merge.swift
|
37
|
13377
|
//
// Merge.swift
// RxSwift
//
// Created by Krunoslav Zaher on 3/28/15.
// Copyright © 2015 Krunoslav Zaher. All rights reserved.
//
import Foundation
// MARK: Limited concurrency version
class MergeLimitedSinkIter<S: ObservableConvertibleType, O: ObserverType>
: ObserverType
, LockOwnerType
, SynchronizedOnType where S.E == O.E {
typealias E = O.E
typealias DisposeKey = CompositeDisposable.DisposeKey
typealias Parent = MergeLimitedSink<S, O>
private let _parent: Parent
private let _disposeKey: DisposeKey
var _lock: NSRecursiveLock {
return _parent._lock
}
init(parent: Parent, disposeKey: DisposeKey) {
_parent = parent
_disposeKey = disposeKey
}
func on(_ event: Event<E>) {
synchronizedOn(event)
}
func _synchronized_on(_ event: Event<E>) {
switch event {
case .next:
_parent.forwardOn(event)
case .error:
_parent.forwardOn(event)
_parent.dispose()
case .completed:
_parent._group.remove(for: _disposeKey)
if let next = _parent._queue.dequeue() {
_parent.subscribe(next, group: _parent._group)
}
else {
_parent._activeCount = _parent._activeCount - 1
if _parent._stopped && _parent._activeCount == 0 {
_parent.forwardOn(.completed)
_parent.dispose()
}
}
}
}
}
class MergeLimitedSink<S: ObservableConvertibleType, O: ObserverType>
: Sink<O>
, ObserverType
, LockOwnerType
, SynchronizedOnType where S.E == O.E {
typealias E = S
typealias QueueType = Queue<S>
fileprivate let _maxConcurrent: Int
let _lock = NSRecursiveLock()
// state
fileprivate var _stopped = false
fileprivate var _activeCount = 0
fileprivate var _queue = QueueType(capacity: 2)
fileprivate let _sourceSubscription = SingleAssignmentDisposable()
fileprivate let _group = CompositeDisposable()
init(maxConcurrent: Int, observer: O, cancel: Cancelable) {
_maxConcurrent = maxConcurrent
let _ = _group.insert(_sourceSubscription)
super.init(observer: observer, cancel: cancel)
}
func run(_ source: Observable<S>) -> Disposable {
let _ = _group.insert(_sourceSubscription)
let disposable = source.subscribe(self)
_sourceSubscription.setDisposable(disposable)
return _group
}
func subscribe(_ innerSource: E, group: CompositeDisposable) {
let subscription = SingleAssignmentDisposable()
let key = group.insert(subscription)
if let key = key {
let observer = MergeLimitedSinkIter(parent: self, disposeKey: key)
let disposable = innerSource.asObservable().subscribe(observer)
subscription.setDisposable(disposable)
}
}
func on(_ event: Event<E>) {
synchronizedOn(event)
}
func _synchronized_on(_ event: Event<E>) {
switch event {
case .next(let value):
let subscribe: Bool
if _activeCount < _maxConcurrent {
_activeCount += 1
subscribe = true
}
else {
_queue.enqueue(value)
subscribe = false
}
if subscribe {
self.subscribe(value, group: _group)
}
case .error(let error):
forwardOn(.error(error))
dispose()
case .completed:
if _activeCount == 0 {
forwardOn(.completed)
dispose()
}
else {
_sourceSubscription.dispose()
}
_stopped = true
}
}
}
class MergeLimited<S: ObservableConvertibleType> : Producer<S.E> {
private let _source: Observable<S>
private let _maxConcurrent: Int
init(source: Observable<S>, maxConcurrent: Int) {
_source = source
_maxConcurrent = maxConcurrent
}
override func run<O: ObserverType>(_ observer: O, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where O.E == S.E {
let sink = MergeLimitedSink<S, O>(maxConcurrent: _maxConcurrent, observer: observer, cancel: cancel)
let subscription = sink.run(_source)
return (sink: sink, subscription: subscription)
}
}
// MARK: Merge
final class MergeBasicSink<S: ObservableConvertibleType, O: ObserverType> : MergeSink<S, S, O> where O.E == S.E {
override init(observer: O, cancel: Cancelable) {
super.init(observer: observer, cancel: cancel)
}
override func performMap(_ element: S) throws -> S {
return element
}
}
// MARK: flatMap
final class FlatMapSink<SourceType, S: ObservableConvertibleType, O: ObserverType> : MergeSink<SourceType, S, O> where O.E == S.E {
typealias Selector = (SourceType) throws -> S
private let _selector: Selector
init(selector: @escaping Selector, observer: O, cancel: Cancelable) {
_selector = selector
super.init(observer: observer, cancel: cancel)
}
override func performMap(_ element: SourceType) throws -> S {
return try _selector(element)
}
}
final class FlatMapWithIndexSink<SourceType, S: ObservableConvertibleType, O: ObserverType> : MergeSink<SourceType, S, O> where O.E == S.E {
typealias Selector = (SourceType, Int) throws -> S
private var _index = 0
private let _selector: Selector
init(selector: @escaping Selector, observer: O, cancel: Cancelable) {
_selector = selector
super.init(observer: observer, cancel: cancel)
}
override func performMap(_ element: SourceType) throws -> S {
return try _selector(element, try incrementChecked(&_index))
}
}
// MARK: FlatMapFirst
final class FlatMapFirstSink<SourceType, S: ObservableConvertibleType, O: ObserverType> : MergeSink<SourceType, S, O> where O.E == S.E {
typealias Selector = (SourceType) throws -> S
private let _selector: Selector
override var subscribeNext: Bool {
return _group.count == MergeNoIterators
}
init(selector: @escaping Selector, observer: O, cancel: Cancelable) {
_selector = selector
super.init(observer: observer, cancel: cancel)
}
override func performMap(_ element: SourceType) throws -> S {
return try _selector(element)
}
}
// It's value is one because initial source subscription is always in CompositeDisposable
private let MergeNoIterators = 1
class MergeSinkIter<SourceType, S: ObservableConvertibleType, O: ObserverType> : ObserverType where O.E == S.E {
typealias Parent = MergeSink<SourceType, S, O>
typealias DisposeKey = CompositeDisposable.DisposeKey
typealias E = O.E
private let _parent: Parent
private let _disposeKey: DisposeKey
init(parent: Parent, disposeKey: DisposeKey) {
_parent = parent
_disposeKey = disposeKey
}
func on(_ event: Event<E>) {
switch event {
case .next(let value):
_parent._lock.lock(); defer { _parent._lock.unlock() } // lock {
_parent.forwardOn(.next(value))
// }
case .error(let error):
_parent._lock.lock(); defer { _parent._lock.unlock() } // lock {
_parent.forwardOn(.error(error))
_parent.dispose()
// }
case .completed:
_parent._group.remove(for: _disposeKey)
// If this has returned true that means that `Completed` should be sent.
// In case there is a race who will sent first completed,
// lock will sort it out. When first Completed message is sent
// it will set observer to nil, and thus prevent further complete messages
// to be sent, and thus preserving the sequence grammar.
if _parent._stopped && _parent._group.count == MergeNoIterators {
_parent._lock.lock(); defer { _parent._lock.unlock() } // lock {
_parent.forwardOn(.completed)
_parent.dispose()
// }
}
}
}
}
class MergeSink<SourceType, S: ObservableConvertibleType, O: ObserverType>
: Sink<O>
, ObserverType where O.E == S.E {
typealias ResultType = O.E
typealias Element = SourceType
fileprivate let _lock = NSRecursiveLock()
fileprivate var subscribeNext: Bool {
return true
}
// state
fileprivate let _group = CompositeDisposable()
fileprivate let _sourceSubscription = SingleAssignmentDisposable()
fileprivate var _stopped = false
override init(observer: O, cancel: Cancelable) {
super.init(observer: observer, cancel: cancel)
}
func performMap(_ element: SourceType) throws -> S {
abstractMethod()
}
func on(_ event: Event<SourceType>) {
switch event {
case .next(let element):
if !subscribeNext {
return
}
do {
let value = try performMap(element)
subscribeInner(value.asObservable())
}
catch let e {
forwardOn(.error(e))
dispose()
}
case .error(let error):
_lock.lock(); defer { _lock.unlock() } // lock {
forwardOn(.error(error))
dispose()
// }
case .completed:
_lock.lock(); defer { _lock.unlock() } // lock {
_stopped = true
if _group.count == MergeNoIterators {
forwardOn(.completed)
dispose()
}
else {
_sourceSubscription.dispose()
}
//}
}
}
func subscribeInner(_ source: Observable<O.E>) {
let iterDisposable = SingleAssignmentDisposable()
if let disposeKey = _group.insert(iterDisposable) {
let iter = MergeSinkIter(parent: self, disposeKey: disposeKey)
let subscription = source.subscribe(iter)
iterDisposable.setDisposable(subscription)
}
}
func run(_ source: Observable<SourceType>) -> Disposable {
let _ = _group.insert(_sourceSubscription)
let subscription = source.subscribe(self)
_sourceSubscription.setDisposable(subscription)
return _group
}
}
// MARK: Producers
final class FlatMap<SourceType, S: ObservableConvertibleType>: Producer<S.E> {
typealias Selector = (SourceType) throws -> S
private let _source: Observable<SourceType>
private let _selector: Selector
init(source: Observable<SourceType>, selector: @escaping Selector) {
_source = source
_selector = selector
}
override func run<O: ObserverType>(_ observer: O, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where O.E == S.E {
let sink = FlatMapSink(selector: _selector, observer: observer, cancel: cancel)
let subscription = sink.run(_source)
return (sink: sink, subscription: subscription)
}
}
final class FlatMapWithIndex<SourceType, S: ObservableConvertibleType>: Producer<S.E> {
typealias Selector = (SourceType, Int) throws -> S
private let _source: Observable<SourceType>
private let _selector: Selector
init(source: Observable<SourceType>, selector: @escaping Selector) {
_source = source
_selector = selector
}
override func run<O: ObserverType>(_ observer: O, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where O.E == S.E {
let sink = FlatMapWithIndexSink<SourceType, S, O>(selector: _selector, observer: observer, cancel: cancel)
let subscription = sink.run(_source)
return (sink: sink, subscription: subscription)
}
}
final class FlatMapFirst<SourceType, S: ObservableConvertibleType>: Producer<S.E> {
typealias Selector = (SourceType) throws -> S
private let _source: Observable<SourceType>
private let _selector: Selector
init(source: Observable<SourceType>, selector: @escaping Selector) {
_source = source
_selector = selector
}
override func run<O: ObserverType>(_ observer: O, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where O.E == S.E {
let sink = FlatMapFirstSink<SourceType, S, O>(selector: _selector, observer: observer, cancel: cancel)
let subscription = sink.run(_source)
return (sink: sink, subscription: subscription)
}
}
final class Merge<S: ObservableConvertibleType> : Producer<S.E> {
private let _source: Observable<S>
init(source: Observable<S>) {
_source = source
}
override func run<O: ObserverType>(_ observer: O, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where O.E == S.E {
let sink = MergeBasicSink<S, O>(observer: observer, cancel: cancel)
let subscription = sink.run(_source)
return (sink: sink, subscription: subscription)
}
}
|
apache-2.0
|
fa04fcd87e4aca0d08e8c38c80ce0f1a
| 30.54717 | 140 | 0.600628 | 4.683473 | false | false | false | false |
Draveness/NightNight
|
NightNight/Classes/UIKit/UISlider+Mixed.swift
|
1
|
2292
|
//
// UISlider+Mixed.swift
// Pods
//
// Created by Draveness.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE
// FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
// DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
// OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
//
import Foundation
public extension UISlider {
var mixedMinimumTrackTintColor: MixedColor? {
get { return getMixedColor(&Keys.minimumTrackTintColor) }
set {
minimumTrackTintColor = newValue?.unfold()
setMixedColor(&Keys.minimumTrackTintColor, value: newValue)
}
}
var mixedMaximumTrackTintColor: MixedColor? {
get { return getMixedColor(&Keys.maximumTrackTintColor) }
set {
maximumTrackTintColor = newValue?.unfold()
setMixedColor(&Keys.maximumTrackTintColor, value: newValue)
}
}
var mixedThumbTintColor: MixedColor? {
get { return getMixedColor(&Keys.thumbTintColor) }
set {
thumbTintColor = newValue?.unfold()
setMixedColor(&Keys.thumbTintColor, value: newValue)
}
}
override func _updateCurrentStatus() {
super._updateCurrentStatus()
if let mixedMinimumTrackTintColor = mixedMinimumTrackTintColor {
minimumTrackTintColor = mixedMinimumTrackTintColor.unfold()
}
if let mixedMaximumTrackTintColor = mixedMaximumTrackTintColor {
maximumTrackTintColor = mixedMaximumTrackTintColor.unfold()
}
if let mixedThumbTintColor = mixedThumbTintColor {
thumbTintColor = mixedThumbTintColor.unfold()
}
}
}
|
mit
|
993f1913879e95182a5cc11b5f65eff4
| 33.727273 | 82 | 0.67452 | 5.116071 | false | false | false | false |
yonaskolb/SwagGen
|
Sources/Swagger/Schema/GroupSchema.swift
|
1
|
927
|
import JSONUtilities
public struct GroupSchema {
public let schemas: [Schema]
public let discriminator: Discriminator?
public let type: GroupType
public enum GroupType {
case all
case one
case any
var propertyName: String {
switch self {
case .all: return "allOf"
case .one: return "oneOf"
case .any: return "anyOf"
}
}
}
public init(schemas: [Schema], discriminator: Discriminator? = nil, type: GroupType) {
self.schemas = schemas
self.discriminator = discriminator
self.type = type
}
}
extension GroupSchema {
public init(jsonDictionary: JSONDictionary, type: GroupType) throws {
self.type = type
schemas = try jsonDictionary.json(atKeyPath: .key(type.propertyName))
discriminator = jsonDictionary.json(atKeyPath: "discriminator")
}
}
|
mit
|
6dcfd07fa7ac1b358177e847b11548ec
| 24.75 | 90 | 0.613808 | 4.803109 | false | false | false | false |
cegiela/DragAndDropPod
|
DragAndDrop/Classes/DDView.swift
|
1
|
2522
|
//
// DDView.swift
// Pods
//
// Created by Mat Cegiela on 5/13/17.
//
//
import UIKit
//public protocol DDViewDelegate {
//
// func ddView(_ ddView: UIView, itemForDragAttemptAt point: CGPoint, transitView: UIView) -> DDItem?
// func ddView(_ ddView: UIView, canDrag item: DDItem) -> Bool
//}
public class DDView: UIView {
public var dragAndDropDelegate: DDItemDelegate?
public let dragAndDropGestureRecogniser = UILongPressGestureRecognizer()
public var activeDragAndDropItem: DDItem?
override init(frame: CGRect) {
super.init(frame: frame)
configureAfterInit()
}
public required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
configureAfterInit()
}
func configureAfterInit() {
dragAndDropGestureRecogniser.addTarget(self, action: #selector(DDView.gestureUpdate(_:)))
dragAndDropGestureRecogniser.minimumPressDuration = 0.3
self.addGestureRecognizer(dragAndDropGestureRecogniser)
}
func gestureUpdate(_ gesture: UILongPressGestureRecognizer) {
if gesture.state == .began {
let location = gesture.location(in: self)
beginPossibleDragAndDrop(location)
}
activeDragAndDropItem?.updateWithGesture(gesture)
if gesture.state == .ended {
activeDragAndDropItem = nil
}
}
func beginPossibleDragAndDrop(_ location: CGPoint) {
if let ddDelegate = dragAndDropDelegate, let transitView = self.snapshotView(afterScreenUpdates: false) {
let superview = DDView.rootSuperviewFor(self)
let center = self.superview?.convert(self.center, to: superview)
transitView.center = center ?? CGPoint()
let item = DDItem(transitView: transitView, sharedSuperview: superview, delegate: ddDelegate)
if ddDelegate.ddItemCanDrag(item, originView: self) {
activeDragAndDropItem = item
}
}
}
public func activeDragUpdate(_ item: DDItem) {
///auto-scroll if needed
}
}
extension DDView {
class func rootSuperviewFor(_ view: UIView) -> UIView {
if let superview = view.superview {
if type(of: superview) == UIView.self {
return rootSuperviewFor(superview)
} else {
return view
}
} else {
return view
}
}
}
|
mit
|
df0cebde756865d3705fa6994f562707
| 27.659091 | 113 | 0.611023 | 4.840691 | false | false | false | false |
ranacquat/fish
|
Shared/ServiceController.swift
|
1
|
1977
|
//
// ServiceController.swift
// KYCMobile
//
// Created by Jan ATAC on 24/10/2016.
// Copyright © 2016 Vialink. All rights reserved.
//
import Foundation
class ServiceController {
let directoryURL:URL = NSURL(fileURLWithPath: NSTemporaryDirectory()).appendingPathComponent(ProcessInfo.processInfo.globallyUniqueString, isDirectory: true)!
func check(document:Document, success:@escaping (Score) -> Void, failure:@escaping(Error)-> Void){
Service().check(document: document,success:{results in
success(Score(with:results))
},failure:{ error in
print(error)
failure(error)
})
}
func createTmpStore(){
do {
try FileManager.default.createDirectory(at: directoryURL, withIntermediateDirectories: true, attributes: nil)
} catch {
print("ERROR IN CREATING TMP STORE")
}
}
// STORE THE DOC IN /TMP DIRECTORY
func storeTmp(document:Document){
let identifier = ProcessInfo.processInfo.globallyUniqueString
let fileName = String(format: "%@_%@", identifier, "document.txt")
let directory = NSTemporaryDirectory()
let writePath = directory.appending(fileName)
document.info["URL"] = writePath
document.info["NAME"] = fileName
NSKeyedArchiver.archiveRootObject(document, toFile: writePath)
}
func getTmp(document:Document)->Document{
let documentUnarchived:Document = NSKeyedUnarchiver.unarchiveObject(withFile: document.info["URL"] as! String ) as! Document
return documentUnarchived
}
func cleanTmpStore(){
do {
try FileManager.default.removeItem(at: directoryURL)
} catch {
print("ERROR IN CLEANING TMP STORAGE")
}
}
func getTmpImage()->NSData{
return NSData()
}
}
|
mit
|
429a2249189c3de1157ea2abe43c669e
| 29.875 | 162 | 0.611842 | 4.855037 | false | false | false | false |
RocketChat/Rocket.Chat.iOS
|
Rocket.Chat/External/RCEmojiKit/EmojiSearcher.swift
|
1
|
1067
|
//
// EmojiSearcher.swift
// Rocket.Chat
//
// Created by Matheus Cardoso on 1/9/18.
// Copyright © 2018 Rocket.Chat. All rights reserved.
//
import Foundation
public typealias EmojiSearchResult = (emoji: Emoji, suggestion: String)
open class EmojiSearcher {
public let emojis: [Emoji]
public init(emojis: [Emoji]) {
self.emojis = emojis
}
public func search(shortname: String, custom: [Emoji] = []) -> [EmojiSearchResult] {
return (emojis + custom).compactMap { emoji -> EmojiSearchResult? in
if let suggestion = emoji.shortname.contains(shortname) ? emoji.shortname : emoji.alternates.filter({ $0.contains(shortname) }).first {
return (emoji: emoji, suggestion: suggestion.contains(":") ? suggestion : ":\(suggestion):")
}
return nil
}.sorted {
($0.suggestion.count - shortname.count) < ($1.suggestion.count - shortname.count)
}
}
}
public extension EmojiSearcher {
public static let standard = EmojiSearcher(emojis: Emojione.all)
}
|
mit
|
b0ef16a25834149ee4a2caeb10cf695c
| 29.457143 | 147 | 0.642589 | 4.022642 | false | false | false | false |
zzxuxu/TestKitchen
|
TestKitchen/TestKitchen/Classes/Common/UILabel+Common.swift
|
1
|
634
|
//
// UILabel+Common.swift
// TestKitchen
//
// Created by 王健旭 on 2016/10/21.
// Copyright © 2016年 王健旭. All rights reserved.
//
import Foundation
import UIKit
extension UILabel {
class func createLabel(text: String?,textAlignment: NSTextAlignment?, font: UIFont?)->UILabel {
let label = UILabel()
if let tmpText = text {
label.text = tmpText
}
if let tmpAlignment = textAlignment {
label.textAlignment = tmpAlignment
}
if let tmpFont = font {
label.font = tmpFont
}
return label
}
}
|
mit
|
acc9f6482bee2af16ccb180d8b0351f1
| 14.475 | 99 | 0.570275 | 4.298611 | false | false | false | false |
onthetall/OTTLocationManager
|
OTTLocationManager/OTTLocationSearchTable.swift
|
1
|
1869
|
//
// OTTLocationSearchTable.swift
// OTTLocationManager
//
// Created by JERRY LIU on 8/9/2016.
// Copyright © 2016 OTT. All rights reserved.
//
import Foundation
import MapKit
protocol OTTLocationSearchTableDelegate: class {
func didSelect(annotation: MKAnnotation)
}
class OTTLocationSearchTable: UITableViewController {
weak var delegate: OTTLocationSearchTableDelegate?
var results: [MKAnnotation] = []
}
extension OTTLocationSearchTable : UISearchResultsUpdating {
func updateSearchResultsForSearchController(searchController: UISearchController) {
guard let searchQuery = searchController.searchBar.text else { return }
OTTLocationManager().geocodeDitu(searchQuery, apiKey: nil, successBlock: {(results) in
self.results = results
self.tableView.reloadData()
}, errorBlock: {(error) in
print("[OTTLocationSearchTable updateSearchResults] error: \(error)")
})
}
}
extension OTTLocationSearchTable {
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return results.count
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("cell")!
let selectedItem = results[indexPath.row]
cell.textLabel?.text = selectedItem.title ?? "no name"
cell.detailTextLabel?.text = selectedItem.subtitle ?? "no address"
return cell
}
override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
let selectedItem = results[indexPath.row]
delegate?.didSelect(selectedItem)
dismissViewControllerAnimated(true, completion: nil)
}
}
|
mit
|
b79d3308d671879312ce8cfb8245556f
| 31.789474 | 118 | 0.695396 | 5.203343 | false | false | false | false |
emilstahl/swift
|
test/SILGen/availability_query.swift
|
10
|
2392
|
// RUN: %target-swift-frontend -emit-silgen %s | FileCheck %s
// REQUIRES: OS=macosx
// CHECK: [[MAJOR:%.*]] = integer_literal $Builtin.Word, 10
// CHECK: [[MINOR:%.*]] = integer_literal $Builtin.Word, 9
// CHECK: [[PATCH:%.*]] = integer_literal $Builtin.Word, 8
// CHECK: [[FUNC:%.*]] = function_ref @_TFs26_stdlib_isOSVersionAtLeastFTBwBwBw_Bi1_ : $@convention(thin) (Builtin.Word, Builtin.Word, Builtin.Word) -> Builtin.Int1
// CHECK: [[QUERY_RESULT:%.*]] = apply [[FUNC]]([[MAJOR]], [[MINOR]], [[PATCH]]) : $@convention(thin) (Builtin.Word, Builtin.Word, Builtin.Word) -> Builtin.Int1
if #available(OSX 10.9.8, iOS 7.1, *) {
}
// CHECK: [[MAJOR:%.*]] = integer_literal $Builtin.Word, 10
// CHECK: [[MINOR:%.*]] = integer_literal $Builtin.Word, 9
// CHECK: [[PATCH:%.*]] = integer_literal $Builtin.Word, 0
// CHECK: [[FUNC:%.*]] = function_ref @_TFs26_stdlib_isOSVersionAtLeastFTBwBwBw_Bi1_ : $@convention(thin) (Builtin.Word, Builtin.Word, Builtin.Word) -> Builtin.Int1
// CHECK: [[QUERY_RESULT:%.*]] = apply [[FUNC]]([[MAJOR]], [[MINOR]], [[PATCH]]) : $@convention(thin) (Builtin.Word, Builtin.Word, Builtin.Word) -> Builtin.Int1
// Since we are compiling for an unmentioned platform (OS X), we check against the minimum
// deployment target, which is 10.9
if #available(iOS 7.1, *) {
}
// CHECK: [[MAJOR:%.*]] = integer_literal $Builtin.Word, 10
// CHECK: [[MINOR:%.*]] = integer_literal $Builtin.Word, 10
// CHECK: [[PATCH:%.*]] = integer_literal $Builtin.Word, 0
// CHECK: [[QUERY_FUNC:%.*]] = function_ref @_TFs26_stdlib_isOSVersionAtLeastFTBwBwBw_Bi1_ : $@convention(thin) (Builtin.Word, Builtin.Word, Builtin.Word) -> Builtin.Int1
// CHECK: [[QUERY_RESULT:%.*]] = apply [[QUERY_FUNC]]([[MAJOR]], [[MINOR]], [[PATCH]]) : $@convention(thin) (Builtin.Word, Builtin.Word, Builtin.Word) -> Builtin.Int1
if #available(OSX 10.10, *) {
}
// CHECK: [[MAJOR:%.*]] = integer_literal $Builtin.Word, 10
// CHECK: [[MINOR:%.*]] = integer_literal $Builtin.Word, 0
// CHECK: [[PATCH:%.*]] = integer_literal $Builtin.Word, 0
// CHECK: [[QUERY_FUNC:%.*]] = function_ref @_TFs26_stdlib_isOSVersionAtLeastFTBwBwBw_Bi1_ : $@convention(thin) (Builtin.Word, Builtin.Word, Builtin.Word) -> Builtin.Int1
// CHECK: [[QUERY_RESULT:%.*]] = apply [[QUERY_FUNC]]([[MAJOR]], [[MINOR]], [[PATCH]]) : $@convention(thin) (Builtin.Word, Builtin.Word, Builtin.Word) -> Builtin.Int1
if #available(OSX 10, *) {
}
|
apache-2.0
|
95642e4c3184fe32a2bf425ff9b303db
| 61.947368 | 170 | 0.647575 | 3.340782 | false | false | false | false |
tehprofessor/SwiftyFORM
|
Example/DatePicker/DatePickerLocaleViewController.swift
|
1
|
2941
|
// MIT license. Copyright (c) 2014 SwiftyFORM. All rights reserved.
import UIKit
import SwiftyFORM
class DatePickerLocaleViewController: FormViewController {
lazy var datePicker_time_currentLocale: DatePickerFormItem = {
let instance = DatePickerFormItem()
instance.title("Time")
instance.datePickerMode = .Time
return instance
}()
lazy var datePicker_date_currentLocale: DatePickerFormItem = {
let instance = DatePickerFormItem()
instance.title("Date")
instance.datePickerMode = .Date
return instance
}()
lazy var datePicker_dateAndTime_currentLocale: DatePickerFormItem = {
let instance = DatePickerFormItem()
instance.title("DateAndTime")
instance.datePickerMode = .DateAndTime
return instance
}()
lazy var datePicker_time_da_DK: DatePickerFormItem = {
let instance = DatePickerFormItem()
instance.title("Time")
instance.datePickerMode = .Time
instance.locale = NSLocale(localeIdentifier: "da_DK")
return instance
}()
lazy var datePicker_date_da_DK: DatePickerFormItem = {
let instance = DatePickerFormItem()
instance.title("Date")
instance.datePickerMode = .Date
instance.locale = NSLocale(localeIdentifier: "da_DK")
return instance
}()
lazy var datePicker_dateAndTime_da_DK: DatePickerFormItem = {
let instance = DatePickerFormItem()
instance.title("DateAndTime")
instance.datePickerMode = .DateAndTime
instance.locale = NSLocale(localeIdentifier: "da_DK")
return instance
}()
lazy var datePicker_time_zh_CN: DatePickerFormItem = {
let instance = DatePickerFormItem()
instance.title("Time")
instance.datePickerMode = .Time
instance.locale = NSLocale(localeIdentifier: "zh_CN")
return instance
}()
lazy var datePicker_date_zh_CN: DatePickerFormItem = {
let instance = DatePickerFormItem()
instance.title("Date")
instance.datePickerMode = .Date
instance.locale = NSLocale(localeIdentifier: "zh_CN")
return instance
}()
lazy var datePicker_dateAndTime_zh_CN: DatePickerFormItem = {
let instance = DatePickerFormItem()
instance.title("DateAndTime")
instance.datePickerMode = .DateAndTime
instance.locale = NSLocale(localeIdentifier: "zh_CN")
return instance
}()
override func populate(builder: FormBuilder) {
builder.navigationTitle = "DatePicker & Locale"
builder.toolbarMode = .Simple
builder.demo_showInfo("Demonstration of\nUIDatePicker with locale")
builder += SectionHeaderTitleFormItem().title("Current locale")
builder += datePicker_time_currentLocale
builder += datePicker_date_currentLocale
builder += datePicker_dateAndTime_currentLocale
builder += SectionHeaderTitleFormItem().title("da_DK")
builder += datePicker_time_da_DK
builder += datePicker_date_da_DK
builder += datePicker_dateAndTime_da_DK
builder += SectionHeaderTitleFormItem().title("zh_CN")
builder += datePicker_time_zh_CN
builder += datePicker_date_zh_CN
builder += datePicker_dateAndTime_zh_CN
}
}
|
mit
|
efcfbef0a943ef71e0019561abc6dff0
| 29.957895 | 70 | 0.747705 | 4.079057 | false | false | false | false |
ZhangHangwei/100_days_Swift
|
Project_24&25&26/Project_16/ViewController.swift
|
1
|
1953
|
//
// ViewController.swift
// Project_16
//
// Created by 章航伟 on 06/02/2017.
// Copyright © 2017 Harvie. All rights reserved.
//
import UIKit
class ViewController: UICollectionViewController {
fileprivate var images = [String]()
override func viewDidLoad() {
super.viewDidLoad()
for _ in 0..<20 {
let random = arc4random() % 9 + 1
let imageName = String(random)
images.append(imageName)
}
setupCollectionView()
}
fileprivate func setupCollectionView() {
let collectionViewLayout = collectionView?.collectionViewLayout as! UICollectionViewFlowLayout
collectionViewLayout.minimumLineSpacing = 0.0
collectionViewLayout.minimumInteritemSpacing = 0.0
let width = collectionView!.bounds.width / 3.0
collectionViewLayout.itemSize = CGSize(width: width, height: width)
}
}
extension ViewController {
override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return images.count
}
override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "PhotoCell", for: indexPath) as! PhotoCell
cell.image.image = UIImage(named: images[indexPath.row])
return cell
}
override func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
performSegue(withIdentifier: "ShowDetialVC", sender: images[indexPath.row])
}
}
extension ViewController {
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "ShowDetialVC" {
let VC = segue.destination as! DetailViewController
VC.imageName = sender as! String
}
}
}
|
mit
|
c4193c1ef7d483ed989c39881fe806de
| 30.387097 | 130 | 0.668551 | 5.331507 | false | false | false | false |
andreyFreeman/EasyCoreData
|
Demo/EasyCoreDataDemo/EasyCoreData/ManagedObjectContext.swift
|
1
|
9546
|
//
// ManagedObjectContext.swift
// EasyCoreData
//
// Created by Andrey Kladov on 02/04/15.
// Copyright (c) 2015 Andrey Kladov. All rights reserved.
//
import Foundation
import CoreData
public extension NSManagedObjectContext {
private struct StaticStorage {
static weak var customMainThreadManagedObjectContext: NSManagedObjectContext!
}
/**
if you are going to use your own NSManagedObjectContext, but still want to use NSManagedObjectContext and NSManagedObject extensions, you can setup it here
**Warning! Weak reference will be stored. Stored NSManagedObjectContext will be overwritten by 'EasyCoreData.setup()' call**
- parameter context: context you would like to use as a main thread context with this EasyCoreData extensions. *
*/
public class func setupMainThreadManagedObjectContext(context: NSManagedObjectContext!) {
StaticStorage.customMainThreadManagedObjectContext = context
}
}
public extension NSManagedObjectContext {
/**
Main NSManagedObjectContext will be returned. See EasyCoreData.sharedInstance.mainThreadManagedObjectContext for more information.
If method setupMainThreadManagedObjectContext was used, custom NSManagedObjectContext will be returned
*/
class var mainThreadContext: NSManagedObjectContext! {
return StaticStorage.customMainThreadManagedObjectContext ?? EasyCoreData.sharedInstance.mainThreadManagedObjectContext
}
/**
tempolorary child NSManagedObjectContext for mainThreadContext will be returned
*/
class var temporaryMainThreadContext: NSManagedObjectContext! { return mainThreadContext.createChildContext() }
}
public extension NSManagedObjectContext {
/**
Creates a new instance of NSManagedObject subclass with given type
- returns: created object of given type T or nil
*/
func createEntity<T: NSManagedObject>() -> T! {
return T(entity: T.entityDescription(inContext: self), insertIntoManagedObjectContext: self)
}
}
public extension NSManagedObjectContext {
/**
Must be used for creation, updating or deletion of instances of NSManagedObject subclasses in the background. All changed will be saved to all parent contexts as well
- parameter saveFunction: The function will be called to perform changes. All changes must be done in the localContext which is passed to this function as a parameter
- parameter completion: The function will be called on the Main thread once save operation finished. Can update UI here
*/
func saveDataInBackground(saveFunction: (localContext: NSManagedObjectContext) -> Void, completion: (() -> Void)?) {
let context = createChildContext(.PrivateQueueConcurrencyType)
context.performBlock {
saveFunction(localContext: context)
switch context.hasChanges {
case true: context.saveWithCompletion(completion)
default: dispatch_async(dispatch_get_main_queue()) { _ in completion?() }
}
}
}
/**
Must be used for creation, updating or deletion of instances of NSManagedObject subclasses in the background. All changes will be saved to all parent contexts as well
- parameter saveFunction: The function will be called to perform changes. All changes must be done in the localContext which is passed to this function as a parameter
- parameter completion: The function will be called on the Main thread once save operation finished. Can update UI here
*/
class func saveDataInBackground(saveFunction: (localContext: NSManagedObjectContext) -> Void, completion: (() -> Void)?) {
mainThreadContext.saveDataInBackground(saveFunction, completion: completion)
}
/**
Save current NSManagedObject state and merge changes into parent NSManagedObjectContent if exists
- parameter completion: The function will be called once save operation finished
*/
func saveWithCompletion(completion:(() -> Void)?) {
performBlock {
do {
try self.save()
switch self.parentContext {
case .Some(let context): context.saveWithCompletion(completion)
default: dispatch_async(dispatch_get_main_queue()) { _ in completion?(); return }
}
} catch let error as NSError {
logTextIfDebug("\(error)")
completion?()
} catch {
fatalError()
}
}
}
/**
Must be used for creation, updating or deletion of NSManagedObject subclasses instances on the Main thread
- parameter saveFunction: The function will be called to perform changes
*/
class func saveDataWithBlock(saveFunction: () -> Void) {
mainThreadContext.performBlockAndWait {
saveFunction()
do { try self.mainThreadContext.save(); do {
try self.mainThreadContext.parentContext?.save()
} catch let error as NSError {
logTextIfDebug("\(error)")
}
} catch let error as NSError {
logTextIfDebug("\(error)")
} catch {
fatalError()
}
}
}
}
public extension NSManagedObjectContext {
/**
Creates a new instance of NSManagedObjectContext which is child for the current one
- parameter concurrencyType: concurrency type of the new NSManagedObjectContext. The default value is MainQueueConcurrencyType
- returns: a new instance is NSManagedObjectContext
*/
func createChildContext(concurrencyType: NSManagedObjectContextConcurrencyType = .MainQueueConcurrencyType) -> NSManagedObjectContext {
let context = NSManagedObjectContext(concurrencyType: concurrencyType)
context.parentContext = self
return context
}
}
public extension NSManagedObjectContext {
/**
Fetches the instances of NSManagedObject subclasses from CoreData storage
- parameter entity: type of NSManagedObject subclass
- parameter predicate: default value is nil
- parameter sortDescriptors: default value is nil
- returns: array of objects given type T or empty array
*/
func fetchObjects<T: NSManagedObject>(entity: T.Type, predicate: NSPredicate? = nil, sortDescriptors: [NSSortDescriptor]? = nil, fetchLimit: Int? = nil, fetchBatchSize: Int? = nil) -> [T] {
let request = NSFetchRequest(entityName: entity.entityName)
request.sortDescriptors = sortDescriptors
request.predicate = predicate
if let limit = fetchLimit { request.fetchLimit = limit }
if let batchSize = fetchBatchSize { request.fetchBatchSize = batchSize }
do {
guard let items = try executeFetchRequest(request) as? [T] else { return [T]() }
return items
} catch let error as NSError {
logTextIfDebug("executeFetchRequest error: \(error)")
}
return [T]()
}
/**
Fetches the instance of NSManagedObject subclass from CoreData storage
- parameter entity: type of NSManagedObject subclass
- parameter predicate: default values is nil
- parameter sortDescriptors: The default value is nil
- returns: optional object or nil of given type T
*/
func fetchFirstOne<T: NSManagedObject>(entity: T.Type, predicate: NSPredicate? = nil, sortDescriptors: [NSSortDescriptor]? = nil) -> T? {
return fetchObjects(entity, predicate: predicate, sortDescriptors: sortDescriptors, fetchLimit: 1).first
}
}
public extension NSManagedObjectContext {
/**
Fetches NSManagedObject instance from other context in current
- parameter entity: The instance of NSManagedObject for lookup in context
- returns: The instance is NSManagedObject in the current context
*/
func entityFromOtherContext<T: NSManagedObject>(entity: T) -> T? {
return objectWithID(entity.objectID) as? T
}
}
@available(iOS 8.0, *)
public extension NSManagedObjectContext {
/**
Fetches the instances of NSManagedObject subclasses from CoreData storage asynchronously
- parameter entity: type of the objects needs to be fetched
- parameter predicate: default values is nil
- parameter sortDescriptors: The default value is nil
- returns: array of objects given type T or empty array
*/
func fetchObjectsAsynchronously<T: NSManagedObject>(entity: T.Type, predicate: NSPredicate? = nil, sortDescriptors: [NSSortDescriptor]? = nil, completion: (([T]) -> Void)?) {
let request = NSFetchRequest(entityName: entity.entityName)
request.sortDescriptors = sortDescriptors
request.predicate = predicate
let asyncRequest = NSAsynchronousFetchRequest(fetchRequest: request) { result in
var results = [T]()
if let res = result.finalResult as? [T] { results = res }
completion?(results)
}
performBlock {
do {
try self.executeRequest(asyncRequest)
} catch let error as NSError {
logTextIfDebug("fetchObjectsAsynchronously error: \(error)")
} catch {
fatalError()
}
}
}
}
|
mit
|
008f7c77ce1a107abb4d303e2a0ea11c
| 37.035857 | 193 | 0.667295 | 5.705918 | false | false | false | false |
tomasharkema/HoelangTotTrein2.iOS
|
HoelangTotTrein2/Services/NotificationService.swift
|
1
|
3773
|
//
// NotificationService.swift
// HoelangTotTrein2
//
// Created by Tomas Harkema on 24-01-16.
// Copyright © 2016 Tomas Harkema. All rights reserved.
//
import API
import Bindable
import Core
import UIKit
import UserNotifications
class NotificationService: NSObject {
private let transferService: TransferService
private let dataStore: DataStore
private let preferenceStore: PreferenceStore
private let apiService: ApiService
private var currentGeofence: GeofenceModel? {
didSet {
guard let currentGeofence = currentGeofence,
currentGeofence.type == .overstap,
preferenceStore.appSettings.contains(.transferNotificationEnabled)
else {
return
}
notify(for: currentGeofence)
}
}
init(transferService: TransferService, dataStore: DataStore, preferenceStore: PreferenceStore, apiService: ApiService) {
self.transferService = transferService
self.dataStore = dataStore
self.preferenceStore = preferenceStore
self.apiService = apiService
super.init()
start()
}
private func start() {
bind(\.currentGeofence, to: transferService.geofence)
}
fileprivate func fireNotification(_ identifier: String, title: String, body: String, categoryIdentifier: String?, userInfo: [String: Any]?) {
let content = UNMutableNotificationContent()
content.title = title
content.body = body
if let categoryIdentifier = categoryIdentifier {
content.categoryIdentifier = categoryIdentifier
}
if let userInfo = userInfo {
content.userInfo = userInfo
}
content.sound = UNNotificationSound.default
let request = UNNotificationRequest(identifier: identifier, content: content, trigger: nil)
let center = UNUserNotificationCenter.current()
center.add(request, withCompletionHandler: nil)
}
fileprivate func secondsToStringOffset(_ date: Date) -> String {
let components = Calendar.current.dateComponents([.minute, .second], from: Date(), to: date)
guard let minutes = components.minute, let seconds = components.second else {
return "0:00"
}
return String(format: "%02d:%02d", minutes, seconds)
}
fileprivate func notify(for model: GeofenceModel) {
assert(Thread.isMainThread)
guard let time = model.stop.time else {
return
}
switch model.type {
case .start:
let timeString = secondsToStringOffset(time)
do {
fireNotification(
"io.harkema.notification.start",
title: R.string.localization.startNotificationTitle(),
body: R.string.localization.startNotificationBody(timeString, model.stop.halt?.plannedDepartureTrack ?? ""),
categoryIdentifier: "nextStationNotification",
userInfo: ["geofenceModel": try model.encodeJson()]
)
} catch {
print("ERROR \(error)")
}
case .tussenStation:
break
case .overstap:
do {
guard time > Date() else {
return
}
let timeString = secondsToStringOffset(time)
fireNotification(
"io.harkema.notification.overstap",
title: R.string.localization.transferNotificationTitle(),
body: R.string.localization.transferNotificationBody(model.stop.halt?.plannedDepartureTrack ?? "", timeString),
categoryIdentifier: "nextStationNotification",
userInfo: ["geofenceModel": try model.encodeJson()]
)
} catch {
print("Error: \(error)")
}
case .end:
fireNotification(
"io.harkema.notification.end",
title: R.string.localization.endNotificationTitle(),
body: R.string.localization.endNotificationBody(),
categoryIdentifier: nil,
userInfo: nil
)
}
}
}
|
mit
|
1b8657f87cd1b3d188c5284756e83bf7
| 28.24031 | 143 | 0.677625 | 4.633907 | false | false | false | false |
mzp/OctoEye
|
Sources/Preferences/Mock.swift
|
1
|
1076
|
//
// Mock.swift
// OctoEye
//
// Created by mzp on 2017/08/02.
// Copyright © 2017 mzp. All rights reserved.
//
import UIKit
internal class Mock {
private static var firstResponse: Bool = true
static func setup() {
if ProcessInfo.processInfo.arguments.contains("setAccessToken") {
Authentication.accessToken = "mock-access-token"
}
if ProcessInfo.processInfo.arguments.contains("clearAccessToken") {
Authentication.accessToken = nil
}
}
static func httpResponse() -> String {
let response: String
if firstResponse {
response = ProcessInfo.processInfo.environment["httpResponse"] ?? ""
firstResponse = false
} else {
response = ProcessInfo.processInfo.environment["httpResponse_later"] ??
ProcessInfo.processInfo.environment["httpResponse"] ??
""
}
return response
}
static var enabled: Bool {
return ProcessInfo.processInfo.arguments.contains("setAccessToken")
}
}
|
mit
|
b69669e7a13c5ab19e57790f79893cd4
| 26.564103 | 83 | 0.615814 | 5 | false | false | false | false |
Mashape/httpsnippet
|
test/fixtures/output/swift/nsurlsession/full.swift
|
2
|
901
|
import Foundation
let headers = [
"cookie": "foo=bar; bar=baz",
"accept": "application/json",
"content-type": "application/x-www-form-urlencoded"
]
let postData = NSMutableData(data: "foo=bar".data(using: String.Encoding.utf8)!)
let request = NSMutableURLRequest(url: NSURL(string: "http://mockbin.com/har?foo=bar&foo=baz&baz=abc&key=value")! as URL,
cachePolicy: .useProtocolCachePolicy,
timeoutInterval: 10.0)
request.httpMethod = "POST"
request.allHTTPHeaderFields = headers
request.httpBody = postData as Data
let session = URLSession.shared
let dataTask = session.dataTask(with: request as URLRequest, completionHandler: { (data, response, error) -> Void in
if (error != nil) {
print(error)
} else {
let httpResponse = response as? HTTPURLResponse
print(httpResponse)
}
})
dataTask.resume()
|
mit
|
08daeb6f51d3bdd175268b170182847b
| 31.178571 | 121 | 0.667037 | 3.969163 | false | false | false | false |
thebnich/firefox-ios
|
Client/Extensions/UIAlertControllerExtensions.swift
|
7
|
3737
|
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
import UIKit
typealias UIAlertActionCallback = (UIAlertAction) -> Void
// MARK: - Extension methods for building specific UIAlertController instances used across the app
extension UIAlertController {
/**
Builds the Alert view that asks the user if they wish to opt into crash reporting.
- parameter sendReportCallback: Send report option handler
- parameter alwaysSendCallback: Always send option handler
- parameter dontSendCallback: Dont send option handler
- parameter neverSendCallback: Never send option handler
- returns: UIAlertController for opting into crash reporting after a crash occurred
*/
class func crashOptInAlert(
sendReportCallback sendReportCallback: UIAlertActionCallback,
alwaysSendCallback: UIAlertActionCallback,
dontSendCallback: UIAlertActionCallback) -> UIAlertController {
let alert = UIAlertController(
title: NSLocalizedString("Oops! Firefox crashed", comment: "Title for prompt displayed to user after the app crashes"),
message: NSLocalizedString("Send a crash report so Mozilla can fix the problem?", comment: "Message displayed in the crash dialog above the buttons used to select when sending reports"),
preferredStyle: UIAlertControllerStyle.Alert
)
let sendReport = UIAlertAction(
title: NSLocalizedString("Send Report", comment: "Used as a button label for crash dialog prompt"),
style: UIAlertActionStyle.Default,
handler: sendReportCallback
)
let alwaysSend = UIAlertAction(
title: NSLocalizedString("Always Send", comment: "Used as a button label for crash dialog prompt"),
style: UIAlertActionStyle.Default,
handler: alwaysSendCallback
)
let dontSend = UIAlertAction(
title: NSLocalizedString("Don't Send", comment: "Used as a button label for crash dialog prompt"),
style: UIAlertActionStyle.Default,
handler: dontSendCallback
)
alert.addAction(sendReport)
alert.addAction(alwaysSend)
alert.addAction(dontSend)
return alert
}
/**
Builds the Alert view that asks the user if they wish to restore their tabs after a crash.
- parameter okayCallback: Okay option handler
- parameter noCallback: No option handler
- returns: UIAlertController for asking the user to restore tabs after a crash
*/
class func restoreTabsAlert(okayCallback okayCallback: UIAlertActionCallback, noCallback: UIAlertActionCallback) -> UIAlertController {
let alert = UIAlertController(
title: NSLocalizedString("Well, this is embarrassing.", comment: "Restore Tabs Prompt Title"),
message: NSLocalizedString("Looks like Firefox crashed previously. Would you like to restore your tabs?", comment: "Restore Tabs Prompt Description"),
preferredStyle: UIAlertControllerStyle.Alert
)
let noOption = UIAlertAction(
title: NSLocalizedString("No", comment: "Restore Tabs Negative Action"),
style: UIAlertActionStyle.Cancel,
handler: noCallback
)
let okayOption = UIAlertAction(
title: NSLocalizedString("Okay", comment: "Restore Tabs Affirmative Action"),
style: UIAlertActionStyle.Default,
handler: okayCallback
)
alert.addAction(okayOption)
alert.addAction(noOption)
return alert
}
}
|
mpl-2.0
|
58b6bec1dd6e67014204fe4eeb0b999d
| 40.988764 | 198 | 0.689591 | 5.679331 | false | false | false | false |
wordpress-mobile/WordPress-iOS
|
WordPress/Classes/Services/CommentService+Replies.swift
|
1
|
4379
|
/// Encapsulates actions related to fetching reply comments.
///
extension CommentService {
/// Fetches the current user's latest reply ID for the specified `parentID`.
/// In case if there are no replies found, the success block will still be called with value 0.
///
/// - Parameters:
/// - parentID: The ID of the parent comment.
/// - siteID: The ID of the site containing the parent comment.
/// - accountService: Service dependency to fetch the current user's dotcom ID.
/// - success: Closure called when the fetch succeeds.
/// - failure: Closure called when the fetch fails.
func getLatestReplyID(for parentID: Int,
siteID: Int,
accountService: AccountService? = nil,
success: @escaping (Int) -> Void,
failure: @escaping (Error?) -> Void) {
guard let remote = restRemote(forSite: NSNumber(value: siteID)) else {
DDLogError("Unable to create a REST remote to fetch comment replies.")
failure(nil)
return
}
guard let userID = getCurrentUserID(accountService: accountService)?.intValue else {
DDLogError("Unable to find the current user's dotcom ID to fetch comment replies.")
failure(nil)
return
}
// If the current user does not have permission to the site, the `author` endpoint parameter is not permitted.
// Therefore, fetch all replies and filter for the current user here.
remote.getCommentsV2(for: siteID, parameters: [.parent: parentID]) { remoteComments in
// Filter for comments authored by the current user, and return the most recent commentID (if any).
success(remoteComments
.filter { $0.authorID == userID }
.sorted { $0.date > $1.date }.first?.commentID ?? 0)
} failure: { error in
failure(error)
}
}
/// Update the visibility of the comment's replies on the comment thread.
/// Note that this only applies to comments fetched from the Reader Comments section (i.e. has a reference to the `ReaderPost`).
///
/// - Parameters:
/// - ancestorComment: The ancestor comment that will have its reply comments iterated.
/// - completion: The block executed after the replies are updated.
func updateRepliesVisibility(for ancestorComment: Comment, completion: (() -> Void)? = nil) {
guard let context = ancestorComment.managedObjectContext,
let post = ancestorComment.post as? ReaderPost,
let comments = post.comments as? Set<Comment> else {
completion?()
return
}
let isVisible = (ancestorComment.status == CommentStatusType.approved.description)
// iterate over the ancestor comment's descendants and update their visibility for the comment thread.
//
// the hierarchy property stores ancestral info by storing a string version of its comment ID hierarchy,
// e.g.: "0000000012.0000000025.00000000035". The idea is to check if the ancestor comment's ID exists in the hierarchy.
// as an optimization, skip checking the hierarchy when the comment is the direct child of the ancestor comment.
context.perform {
comments.filter { comment in
comment.parentID == ancestorComment.commentID
|| comment.hierarchy
.split(separator: ".")
.compactMap({ Int32($0) })
.contains(ancestorComment.commentID)
}.forEach { childComment in
childComment.visibleOnReader = isVisible
}
ContextManager.shared.save(context)
DispatchQueue.main.async {
completion?()
}
}
}
}
private extension CommentService {
/// Returns the current user's dotcom ID.
///
/// - Parameter accountService: The service used to fetch the default `WPAccount`.
/// - Returns: The current user's dotcom ID if exists, or nil otherwise.
func getCurrentUserID(accountService: AccountService? = nil) -> NSNumber? {
return try? WPAccount.lookupDefaultWordPressComAccount(in: managedObjectContext)?.userID
}
}
|
gpl-2.0
|
cf39b329e4becfff3538af4c30f2eda8
| 47.655556 | 132 | 0.619319 | 5.163915 | false | false | false | false |
realm/SwiftLint
|
Source/SwiftLintFramework/Rules/Style/OptionalEnumCaseMatchingRule.swift
|
1
|
8960
|
import SwiftSyntax
struct OptionalEnumCaseMatchingRule: SwiftSyntaxCorrectableRule, ConfigurationProviderRule, OptInRule {
var configuration = SeverityConfiguration(.warning)
init() {}
static let description = RuleDescription(
identifier: "optional_enum_case_matching",
name: "Optional Enum Case Match",
description: "Matching an enum case against an optional enum without '?' is supported on Swift 5.1 and above.",
kind: .style,
minSwiftVersion: .fiveDotOne,
nonTriggeringExamples: [
Example("""
switch foo {
case .bar: break
case .baz: break
default: break
}
"""),
Example("""
switch foo {
case (.bar, .baz): break
case (.bar, _): break
case (_, .baz): break
default: break
}
"""),
Example("""
switch (x, y) {
case (.c, _?):
break
case (.c, nil):
break
case (_, _):
break
}
"""),
// https://github.com/apple/swift/issues/61817
Example("""
switch bool {
case true?:
break
case false?:
break
case .none:
break
}
""", excludeFromDocumentation: true)
],
triggeringExamples: [
Example("""
switch foo {
case .bar↓?: break
case .baz: break
default: break
}
"""),
Example("""
switch foo {
case Foo.bar↓?: break
case .baz: break
default: break
}
"""),
Example("""
switch foo {
case .bar↓?, .baz↓?: break
default: break
}
"""),
Example("""
switch foo {
case .bar↓? where x > 1: break
case .baz: break
default: break
}
"""),
Example("""
switch foo {
case (.bar↓?, .baz↓?): break
case (.bar↓?, _): break
case (_, .bar↓?): break
default: break
}
""")
],
corrections: [
Example("""
switch foo {
case .bar↓?: break
case .baz: break
default: break
}
"""): Example("""
switch foo {
case .bar: break
case .baz: break
default: break
}
"""),
Example("""
switch foo {
case Foo.bar↓?: break
case .baz: break
default: break
}
"""): Example("""
switch foo {
case Foo.bar: break
case .baz: break
default: break
}
"""),
Example("""
switch foo {
case .bar↓?, .baz↓?: break
default: break
}
"""): Example("""
switch foo {
case .bar, .baz: break
default: break
}
"""),
Example("""
switch foo {
case .bar↓? where x > 1: break
case .baz: break
default: break
}
"""): Example("""
switch foo {
case .bar where x > 1: break
case .baz: break
default: break
}
"""),
Example("""
switch foo {
case (.bar↓?, .baz↓?): break
case (.bar↓?, _): break
case (_, .bar↓?): break
default: break
}
"""): Example("""
switch foo {
case (.bar, .baz): break
case (.bar, _): break
case (_, .bar): break
default: break
}
""")
]
)
func makeVisitor(file: SwiftLintFile) -> ViolationsSyntaxVisitor {
Visitor(viewMode: .sourceAccurate)
}
func makeRewriter(file: SwiftLintFile) -> ViolationsSyntaxRewriter? {
Rewriter(
locationConverter: file.locationConverter,
disabledRegions: disabledRegions(file: file)
)
}
}
private extension OptionalEnumCaseMatchingRule {
final class Visitor: ViolationsSyntaxVisitor {
override func visitPost(_ node: CaseItemSyntax) {
guard let pattern = node.pattern.as(ExpressionPatternSyntax.self) else {
return
}
if let expression = pattern.expression.as(OptionalChainingExprSyntax.self),
!expression.expression.isDiscardAssignmentOrBoolLiteral {
violations.append(expression.questionMark.positionAfterSkippingLeadingTrivia)
} else if let expression = pattern.expression.as(TupleExprSyntax.self) {
let optionalChainingExpressions = expression.optionalChainingExpressions()
for optionalChainingExpression in optionalChainingExpressions {
violations.append(optionalChainingExpression.questionMark.positionAfterSkippingLeadingTrivia)
}
}
}
}
final class Rewriter: SyntaxRewriter, ViolationsSyntaxRewriter {
private(set) var correctionPositions: [AbsolutePosition] = []
let locationConverter: SourceLocationConverter
let disabledRegions: [SourceRange]
init(locationConverter: SourceLocationConverter, disabledRegions: [SourceRange]) {
self.locationConverter = locationConverter
self.disabledRegions = disabledRegions
}
override func visit(_ node: CaseItemSyntax) -> CaseItemSyntax {
guard
let pattern = node.pattern.as(ExpressionPatternSyntax.self),
pattern.expression.is(OptionalChainingExprSyntax.self) || pattern.expression.is(TupleExprSyntax.self),
!node.isContainedIn(regions: disabledRegions, locationConverter: locationConverter)
else {
return super.visit(node)
}
if let expression = pattern.expression.as(OptionalChainingExprSyntax.self),
!expression.expression.isDiscardAssignmentOrBoolLiteral {
let violationPosition = expression.questionMark.positionAfterSkippingLeadingTrivia
correctionPositions.append(violationPosition)
let newExpression = ExprSyntax(expression.withQuestionMark(nil))
let newPattern = PatternSyntax(pattern.withExpression(newExpression))
let newNode = node
.withPattern(newPattern)
.withWhereClause(node.whereClause?.withLeadingTrivia(expression.questionMark.trailingTrivia))
return super.visit(newNode)
} else if let expression = pattern.expression.as(TupleExprSyntax.self) {
var newExpression = expression
for (index, element) in expression.elementList.enumerated() {
guard
let optionalChainingExpression = element.expression.as(OptionalChainingExprSyntax.self),
!optionalChainingExpression.expression.is(DiscardAssignmentExprSyntax.self)
else {
continue
}
let violationPosition = optionalChainingExpression.questionMark.positionAfterSkippingLeadingTrivia
correctionPositions.append(violationPosition)
let newElementExpression = ExprSyntax(optionalChainingExpression.withQuestionMark(nil))
let newElement = element.withExpression(newElementExpression)
newExpression.elementList = newExpression.elementList
.replacing(childAt: index, with: newElement)
}
let newPattern = PatternSyntax(pattern.withExpression(ExprSyntax(newExpression)))
let newNode = node.withPattern(newPattern)
return super.visit(newNode)
}
return super.visit(node)
}
}
}
private extension TupleExprSyntax {
func optionalChainingExpressions() -> [OptionalChainingExprSyntax] {
elementList
.compactMap { $0.expression.as(OptionalChainingExprSyntax.self) }
.filter { !$0.expression.isDiscardAssignmentOrBoolLiteral }
}
}
private extension ExprSyntax {
var isDiscardAssignmentOrBoolLiteral: Bool {
`is`(DiscardAssignmentExprSyntax.self) || `is`(BooleanLiteralExprSyntax.self)
}
}
|
mit
|
fc6d41c347620ce25cb09d473c14f1a4
| 33.455598 | 119 | 0.518153 | 5.851803 | false | false | false | false |
congncif/SiFUtilities
|
Example/Pods/Boardy/Boardy/Core/Utils/DebugLog.swift
|
1
|
3173
|
//
// Logger.swift
// Boardy
//
// Created by NGUYEN CHI CONG on 5/26/21.
//
import Foundation
#if canImport(UIComposable)
import UIComposable
#endif
enum DebugLog {
static func logActivation(icon: String = "🚀 [Activation]", source: IdentifiableBoard, destination: IdentifiableBoard, data: Any?) {
#if DEBUG
if Environment.boardyLogEnabled {
print("\(icon) Boardy Log:")
print(" 🌏 [\(String(describing: type(of: source)))] ➤ \(source.identifier.rawValue)")
print(" 🎯 [\(String(describing: type(of: destination)))] ➤ \(destination.identifier.rawValue)")
if let data = data {
print(" 📦 [\(String(describing: type(of: data)))] ➤ \(data)")
}
}
#endif
}
static func logActivity(source: IdentifiableBoard, data: Any?) {
#if DEBUG
if Environment.boardyLogEnabled {
var icon: String = "🍁"
var destination: BoardID?
var rawData: Any?
switch data {
case let model as BoardInputModel:
icon += " [Next To Board]"
destination = model.identifier
rawData = model.option
case is BoardFlowAction:
icon += " [Broadcast Action]"
rawData = data
case let cmd as BoardCommandModel:
icon += " [Send Command]"
destination = cmd.identifier
rawData = cmd.data
#if canImport(UIComposable)
case let element as UIElementAction:
switch element {
case let .update(element: elm):
icon += " [Update UI Element]"
destination = BoardID(elm.identifier)
case let .reload(identifier: id):
icon += " [Reload UI Element]"
destination = BoardID(id)
case let .removeContent(identifier: id):
icon += " [Remove UI Element content]"
destination = BoardID(id)
case let .updateConfiguration(identifier: id, configuration: config):
icon += " [Remove UI Element content]"
destination = BoardID(id)
rawData = config
}
#endif
default:
icon += " [Send Out]"
rawData = data
}
print("\(icon) Boardy Log:")
print(" 🍀 [\(String(describing: type(of: source)))] ➤ \(source.identifier.rawValue)")
if let motherboard = source.delegate as? IdentifiableBoard {
print(" 🎯 [\(String(describing: type(of: motherboard)))] ➤ \(motherboard.identifier.rawValue)")
}
if let dest = destination {
print(" 💐 [\(String(describing: type(of: dest)))] ➤ \(dest.rawValue)")
}
if let logData = rawData {
print(" 🌾 [\(String(describing: type(of: logData)))] ➤ \(logData)")
}
}
#endif
}
}
|
mit
|
7ffc974e137cd6af1e86b0c309d2dc7c
| 35.418605 | 135 | 0.500639 | 4.752656 | false | false | false | false |
AntonTheDev/CoreFlightAnimation
|
CoreFlightAnimation/CoreFlightAnimationDemo/Source/FAAnimation/FABasicAnimation.swift
|
1
|
6669
|
//
// FAAnimation.swift
// FlightAnimator
//
// Created by Anton Doudarev on 2/24/16.
// Copyright © 2016 Anton Doudarev. All rights reserved.
//
import Foundation
import UIKit
//MARK: - FABasicAnimation
public class FABasicAnimation : CAKeyframeAnimation {
public var toValue: AnyObject?
public var fromValue: AnyObject?
public var easingFunction : FAEasing = .Linear
public var isPrimary : Bool = false
internal var interpolator : FAInterpolator?
public weak var animatingLayer : CALayer?
public var animationKey : String?
public var startTime : CFTimeInterval?
public var isTimeRelative = true
public var progessValue : CGFloat = 0.0
public var triggerOnRemoval : Bool = false
public var autoreverse : Bool = false
public var autoreverseCount: Int = 1
public var autoreverseDelay: NSTimeInterval = 1.0
public var autoreverseEasing: Bool = false
internal var _autoreverseActiveCount: Int = 1
internal var _autoreverseConfigured: Bool = false
required public init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
initializeInitialValues()
}
override public init() {
super.init()
initializeInitialValues()
}
public convenience init(keyPath path: String?) {
self.init()
keyPath = path
initializeInitialValues()
}
internal func initializeInitialValues() {
CALayer.swizzleAddAnimation()
calculationMode = kCAAnimationLinear
fillMode = kCAFillModeForwards
removedOnCompletion = true
values = [AnyObject]()
}
override public func copyWithZone(zone: NSZone) -> AnyObject {
let animation = super.copyWithZone(zone) as! FABasicAnimation
animation.animationKey = animationKey
animation.animatingLayer = animatingLayer
animation.startTime = startTime
animation.interpolator = interpolator
animation.easingFunction = easingFunction
animation.toValue = toValue
animation.fromValue = fromValue
animation.isPrimary = isPrimary
animation.autoreverse = autoreverse
animation.autoreverseCount = autoreverseCount
animation.autoreverseDelay = autoreverseDelay
animation.autoreverseEasing = autoreverseEasing
animation._autoreverseConfigured = _autoreverseConfigured
animation._autoreverseActiveCount = _autoreverseActiveCount
return animation
}
final public func configureAnimation(withLayer layer: CALayer?) {
animatingLayer = layer
}
/// Not Ready for Prime Time, being declared as private
/// Adjusts animation based on the progress form 0 - 1
/*
private func scrubToProgress(progress : CGFloat) {
animatingLayer?.speed = 0.0
animatingLayer?.timeOffset = CFTimeInterval(duration * Double(progress))
}
*/
}
//MARK: - Synchronization Logic
internal extension FABasicAnimation {
func synchronize(relativeTo animation : FABasicAnimation? = nil) {
synchronizeFromValue()
guard let toValue = toValue, fromValue = fromValue else {
return
}
interpolator = FAInterpolator(toValue, fromValue, relativeTo : animation?.fromValue)
// adjustSpringVelocityIfNeeded(relativeTo : animation)
let config = interpolator?.interpolatedConfigurationFor(self, relativeTo: animation)
easingFunction = config!.easing
duration = config!.duration
values = config!.values
}
func synchronizeFromValue() {
if keyPath == "transform" {
print("Stop")
}
if let presentationLayer = (animatingLayer?.presentationLayer() as? CALayer),
let presentationValue = presentationLayer.anyValueForKeyPath(keyPath!) {
if let currentValue = presentationValue as? CGPoint {
fromValue = NSValue(CGPoint : currentValue)
} else if let currentValue = presentationValue as? CGSize {
fromValue = NSValue(CGSize : currentValue)
} else if let currentValue = presentationValue as? CGRect {
fromValue = NSValue(CGRect : currentValue)
} else if let currentValue = presentationValue as? CGFloat {
fromValue = NSNumber(float : Float(currentValue))
} else if let currentValue = presentationValue as? CATransform3D {
fromValue = NSValue(CATransform3D : currentValue)
} else if let currentValue = typeCastCGColor(presentationValue) {
fromValue = currentValue
}
}
}
func adjustSpringVelocityIfNeeded(relativeTo animation : FABasicAnimation?) {
guard easingFunction.isSpring() == true else {
return
}
if easingFunction.isSpring() {
if let adjustedEasing = interpolator?.adjustedVelocitySpring(easingFunction, relativeTo : animation) {
easingFunction = adjustedEasing
}
}
}
internal func convertTimingFunction() {
print("timingFunction has no effect, converting to 'easingFunction' property\n")
switch timingFunction?.valueForKey("name") as! String {
case kCAMediaTimingFunctionEaseIn:
easingFunction = .InCubic
case kCAMediaTimingFunctionEaseOut:
easingFunction = .OutCubic
case kCAMediaTimingFunctionEaseInEaseOut:
easingFunction = .InOutCubic
default:
easingFunction = .SmoothStep
}
}
}
//MARK: - Animation Progress Values
internal extension FABasicAnimation {
func valueProgress() -> CGFloat {
if let presentationValue = (animatingLayer?.presentationLayer() as? CALayer)?.anyValueForKeyPath(keyPath!),
let interpolator = interpolator {
return interpolator.valueProgress(presentationValue)
}
return 0.0
}
func timeProgress() -> CGFloat {
if let presentationLayer = animatingLayer?.presentationLayer() {
let currentTime = presentationLayer.convertTime(CACurrentMediaTime(), toLayer: nil)
let difference = currentTime - startTime!
return CGFloat(round(100 * (difference / duration))/100)
}
return 0.0
}
}
|
mit
|
d30fbe995c798b8f7349febb98373986
| 31.686275 | 115 | 0.627774 | 5.589271 | false | false | false | false |
CherishSmile/ZYBase
|
ZYBaseDemo/SubVCS/AorKDemoVC.swift
|
1
|
4775
|
//
// AorKDemoVC.swift
// ZYBase
//
// Created by Mzywx on 2017/2/24.
// Copyright © 2017年 Mzywx. All rights reserved.
//
import UIKit
private let url = "http://112.74.176.225/a/location/location/andriod_zy"
private let animaleUrl = "http://img.qq1234.org/uploads/allimg/150709/8_150709170804_7.jpg"
class UnitModel: ZYDataModel {
var isNewRecord:String!
var locName:String!
var locAddress:String!
required init(fromJson json: JSON!) {
super .init(fromJson: json)
isNewRecord = json["isNewRecord"].stringValue
locName = json["locName"].stringValue
locAddress = json["locAddress"].stringValue
}
}
class AorKDemoVC: BaseTabVC , UITableViewDelegate , UITableViewDataSource,UIScrollViewDelegate,DZNEmptyDataSetSource,DZNEmptyDataSetDelegate{
var dataArr:Array<UnitModel> = []
lazy var unitTab:UITableView = {
let tab = UITableView(frame: .zero, style: .grouped)
tab.backgroundColor = .clear
tab.delegate = self
tab.dataSource = self
tab.emptyDataSetSource = self
tab.emptyDataSetDelegate = self
return tab
}()
override func viewDidLoad() {
super.viewDidLoad()
self.view.addSubview(unitTab)
unitTab.snp.makeConstraints { (make) in
make.left.right.bottom.top.equalToSuperview()
}
unowned let weakSelf = self
setRefresh(refreshView: unitTab, refreshType: .headerAndFooter, headerRefresh: {
weakSelf.requestServes()
}, footerRefresh: {
weakSelf.perform(#selector(weakSelf.endFootRefresh), with: nil, afterDelay: 3)
})
setSearch(searchView: unitTab, location: .tabHeader, resultVC: nil)
requestServes()
}
func endHeadRefresh() {
stopRefresh(refreshType: .header)
}
func endFootRefresh() {
stopRefresh(refreshType: .footer)
}
func requestServes() {
let netModel = ZYNetModel.init(para: nil, data: UnitModel.self, map: nil, urlString: url, header: nil)
showProgress(title: "正在加载...", superView: self.view, hudMode: .indeterminate, delay: -1)
ZYNetWork.ZYPOST(netModel: netModel, success: { (isSuccess, model) in
dismissProgress()
self.endHeadRefresh()
let rootModel = model as! ZYRootModel
let modelArr = rootModel.data as! Array<UnitModel>
self.dataArr = modelArr
self.unitTab.reloadData()
}) { (isFail, res) in
}
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return dataArr.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cellID = "cellId"
var cell = tableView.dequeueReusableCell(withIdentifier: cellID)
if cell==nil {
cell = UITableViewCell.init(style: .subtitle, reuseIdentifier: cellID)
}
cell?.imageView?.kf.setImage(with: URL(string: animaleUrl), placeholder: #imageLiteral(resourceName: "moji_logo"))
cell?.textLabel?.text = dataArr[indexPath.row].locName
cell?.detailTextLabel?.text = dataArr[indexPath.row].locAddress
return cell!
}
func scrollViewWillBeginDragging(_ scrollView: UIScrollView) {
if let bgview = unitTab.value(forKey: "_tableHeaderBackgroundView") {
(bgview as? UIView)?.backgroundColor = .clear
}
}
//MARK: DZNEmptyDataSetDelegate
/**
* 返回标题文字
*/
func title(forEmptyDataSet scrollView: UIScrollView) -> NSAttributedString? {
let title = "暂无数据"
return NSAttributedString(string: title, attributes: [NSFontAttributeName:getFont(16)])
}
/**
* 返回详情文字
*/
func description(forEmptyDataSet scrollView: UIScrollView) -> NSAttributedString? {
let description = "请稍后重试"
return NSAttributedString(string: description, attributes: [NSFontAttributeName:getFont(14)])
}
/**
* 返回图片
*/
func image(forEmptyDataSet scrollView: UIScrollView) -> UIImage? {
return nil
}
//MARK: DZNEmptyDataSetSource
func emptyDataSetShouldDisplay(_ scrollView: UIScrollView) -> Bool {
return true
}
func emptyDataSetShouldAllowScroll(_ scrollView: UIScrollView) -> Bool {
return true
}
func emptyDataSet(_ scrollView: UIScrollView, didTap view: UIView) {
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
|
mit
|
1b3e90de1abdb23637ba6a53ae919930
| 30.218543 | 141 | 0.634705 | 4.558994 | false | false | false | false |
smdls/C0
|
C0/Cut.swift
|
1
|
99354
|
/*
Copyright 2017 S
This file is part of C0.
C0 is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
C0 is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with C0. If not, see <http://www.gnu.org/licenses/>.
*/
import Foundation
import AppKit.NSColor
import AppKit.NSFont
struct SceneDefaults {
static let roughColor = NSColor(red: 0, green: 0.5, blue: 1, alpha: 0.15).cgColor
static let subRoughColor = NSColor(red: 0, green: 0.5, blue: 1, alpha: 0.1).cgColor
static let previousColor = NSColor(red: 1, green: 0, blue: 0, alpha: 0.1).cgColor
static let subPreviousColor = NSColor(red: 1, green: 0.2, blue: 0.2, alpha: 0.025).cgColor
static let previousSkinColor = SceneDefaults.previousColor.copy(alpha: 1)!
static let subPreviousSkinColor = SceneDefaults.subPreviousColor.copy(alpha: 0.08)!
static let nextColor = NSColor(red: 0.2, green: 0.8, blue: 0, alpha: 0.1).cgColor
static let subNextColor = NSColor(red: 0.4, green: 1, blue: 0, alpha: 0.025).cgColor
static let nextSkinColor = SceneDefaults.nextColor.copy(alpha: 1)!
static let subNextSkinColor = SceneDefaults.subNextColor.copy(alpha: 0.08)!
static let selectionColor = NSColor(red: 0.1, green: 0.7, blue: 1, alpha: 1).cgColor
static let subSelectionColor = NSColor(red: 0.8, green: 0.95, blue: 1, alpha: 0.6).cgColor
static let subSelectionSkinColor = SceneDefaults.subSelectionColor.copy(alpha: 0.3)!
static let selectionSkinLineColor = SceneDefaults.subSelectionColor.copy(alpha: 1.0)!
static let editMaterialColor = NSColor(red: 1, green: 0.5, blue: 0, alpha: 0.2).cgColor
static let editMaterialColorColor = NSColor(red: 1, green: 0.75, blue: 0, alpha: 0.2).cgColor
static let cellBorderNormalColor = NSColor(white: 0, alpha: 0.15).cgColor
static let cellBorderColor = NSColor(white: 0, alpha: 0.15).cgColor
static let cellIndicationNormalColor = SceneDefaults.selectionColor.copy(alpha: 0.9)!
static let cellIndicationColor = SceneDefaults.selectionColor.copy(alpha: 0.4)!
static let controlPointInColor = Defaults.contentColor.cgColor
static let controlPointOutColor = Defaults.editColor.cgColor
static let editControlPointInColor = NSColor(red: 1, green: 0, blue: 0, alpha: 0.8).cgColor
static let editControlPointOutColor = NSColor(red: 1, green: 0.5, blue: 0.5, alpha: 0.3).cgColor
static let contolLineInColor = NSColor(red: 1, green: 0.5, blue: 0.5, alpha: 0.3).cgColor
static let contolLineOutColor = NSColor(red: 1, green: 0, blue: 0, alpha: 0.3).cgColor
static let editLineColor = NSColor(red: 1, green: 0, blue: 0, alpha: 0.8).cgColor
static let moveZColor = NSColor(red: 1, green: 0, blue: 0, alpha: 1).cgColor
static let cameraColor = NSColor(red: 0.7, green: 0.6, blue: 0, alpha: 1).cgColor
static let cameraBorderColor = NSColor(red: 1, green: 0, blue: 0, alpha: 0.5).cgColor
static let cutBorderColor = NSColor(red: 0.3, green: 0.46, blue: 0.7, alpha: 0.5).cgColor
static let cutSubBorderColor = NSColor(white: 1, alpha: 0.5).cgColor
static let backgroundColor = NSColor(red: 1, green: 1, blue: 1, alpha: 1).cgColor
static let strokeLineWidth = 0.75.cf, strokeLineColor = NSColor(white: 0, alpha: 1).cgColor
static let playBorderColor = NSColor(white: 0.3, alpha: 1).cgColor
static let speechBorderColor = NSColor(white: 0, alpha: 1).cgColor
static let speechFillColor = NSColor(white: 1, alpha: 1).cgColor
static let speechFont = NSFont.boldSystemFont(ofSize: 25) as CTFont
}
final class Scene: NSObject, NSCoding {
var cameraFrame: CGRect {
didSet {
affineTransform = viewTransform.affineTransform(with: cameraFrame)
}
}
var frameRate: Int, time: Int, material: Material, isShownPrevious: Bool, isShownNext: Bool, soundItem: SoundItem
var viewTransform: ViewTransform {
didSet {
affineTransform = viewTransform.affineTransform(with: cameraFrame)
}
}
private(set) var affineTransform: CGAffineTransform?
init(cameraFrame: CGRect = CGRect(x: 0, y: 0, width: 640, height: 360), frameRate: Int = 24, time: Int = 0, material: Material = Material(), isShownPrevious: Bool = false, isShownNext: Bool = false, soundItem: SoundItem = SoundItem(), viewTransform: ViewTransform = ViewTransform()) {
self.cameraFrame = cameraFrame
self.frameRate = frameRate
self.time = time
self.material = material
self.isShownPrevious = isShownPrevious
self.isShownNext = isShownNext
self.soundItem = soundItem
self.viewTransform = viewTransform
affineTransform = viewTransform.affineTransform(with: cameraFrame)
super.init()
}
static let dataType = "C0.Scene.1", cameraFrameKey = "0", frameRateKey = "1", timeKey = "2", materialKey = "3", isShownPreviousKey = "4", isShownNextKey = "5", soundItemKey = "7", viewTransformKey = "6"
init?(coder: NSCoder) {
cameraFrame = coder.decodeRect(forKey: Scene.cameraFrameKey)
frameRate = coder.decodeInteger(forKey: Scene.frameRateKey)
time = coder.decodeInteger(forKey: Scene.timeKey)
material = coder.decodeObject(forKey: Scene.materialKey) as? Material ?? Material()
isShownPrevious = coder.decodeBool(forKey: Scene.isShownPreviousKey)
isShownNext = coder.decodeBool(forKey: Scene.isShownNextKey)
soundItem = coder.decodeObject(forKey: Scene.soundItemKey) as? SoundItem ?? SoundItem()
viewTransform = coder.decodeStruct(forKey: Scene.viewTransformKey) ?? ViewTransform()
affineTransform = viewTransform.affineTransform(with: cameraFrame)
super.init()
}
func encode(with coder: NSCoder) {
coder.encode(cameraFrame, forKey: Scene.cameraFrameKey)
coder.encode(frameRate, forKey: Scene.frameRateKey)
coder.encode(time, forKey: Scene.timeKey)
coder.encode(material, forKey: Scene.materialKey)
coder.encode(isShownPrevious, forKey: Scene.isShownPreviousKey)
coder.encode(isShownNext, forKey: Scene.isShownNextKey)
coder.encode(soundItem, forKey: Scene.soundItemKey)
coder.encodeStruct(viewTransform, forKey: Scene.viewTransformKey)
}
func convertTime(frameTime ft: Int) -> TimeInterval {
return TimeInterval(ft)/TimeInterval(frameRate)
}
func convertFrameTime(time t: TimeInterval) -> Int {
return Int(t*TimeInterval(frameRate))
}
var secondTime: (second: Int, frame: Int) {
let second = time/frameRate
return (second, time - second*frameRate)
}
}
struct ViewTransform: ByteCoding {
var position = CGPoint(), scale = 1.0.cf, rotation = 0.0.cf, isFlippedHorizontal = false
var isIdentity: Bool {
return position == CGPoint() && scale == 1 && rotation == 0
}
func affineTransform(with bounds: CGRect) -> CGAffineTransform? {
if scale == 1 && rotation == 0 && position == CGPoint() && !isFlippedHorizontal {
return nil
}
var affine = CGAffineTransform.identity
affine = affine.translatedBy(x: bounds.midX + position.x, y: bounds.midY + position.y)
affine = affine.rotated(by: rotation)
affine = affine.scaledBy(x: scale, y: scale)
affine = affine.translatedBy(x: -bounds.midX, y: -bounds.midY)
if isFlippedHorizontal {
affine = affine.flippedHorizontal(by: bounds.width)
}
return affine
}
}
struct DrawInfo {
let scale: CGFloat, cameraScale: CGFloat, invertScale: CGFloat, invertCameraScale: CGFloat, rotation: CGFloat
init(scale: CGFloat = 1, cameraScale: CGFloat = 1, rotation: CGFloat = 0) {
if scale == 0 || cameraScale == 0 {
fatalError()
}
self.scale = scale
self.cameraScale = cameraScale
self.invertScale = 1/scale
self.invertCameraScale = 1/cameraScale
self.rotation = rotation
}
}
final class Cut: NSObject, NSCoding, Copying {
enum ViewType: Int32 {
case edit, editPoint, editLine, editTransform, editMoveZ, editMaterial, editingMaterial, preview
}
enum TransformViewType {
case scale, rotation, none
}
struct Camera {
let transform: Transform, wigglePhase: CGFloat, affineTransform: CGAffineTransform?
init(bounds: CGRect, time: Int, groups: [Group]) {
var position = CGPoint(), scale = CGSize(), rotation = 0.0.cf, wiggleSize = CGSize(), hz = 0.0.cf, phase = 0.0.cf, transformCount = 0.0
for group in groups {
if let t = group.transformItem?.transform {
position.x += t.position.x
position.y += t.position.y
scale.width += t.scale.width
scale.height += t.scale.height
rotation += t.rotation
wiggleSize.width += t.wiggle.maxSize.width
wiggleSize.height += t.wiggle.maxSize.height
hz += t.wiggle.hz
phase += group.wigglePhaseWith(time: time, lastHz: t.wiggle.hz)
transformCount += 1
}
}
if transformCount > 0 {
let invertTransformCount = 1/transformCount.cf
let wiggle = Wiggle(maxSize: wiggleSize, hz: hz*invertTransformCount)
transform = Transform(position: position, scale: scale, rotation: rotation, wiggle: wiggle)
wigglePhase = phase*invertTransformCount
affineTransform = transform.isEmpty ? nil : transform.affineTransform(with: bounds)
} else {
transform = Transform()
wigglePhase = 0
affineTransform = nil
}
}
}
var rootCell: Cell, groups: [Group]
var editGroup: Group {
didSet {
for cellItem in oldValue.cellItems {
cellItem.cell.isLocked = true
}
for cellItem in editGroup.cellItems {
cellItem.cell.isLocked = false
}
}
}
var time = 0 {
didSet {
for group in groups {
group.update(withTime: time)
}
updateCamera()
}
}
var timeLength: Int {
didSet {
for group in groups {
group.timeLength = timeLength
}
}
}
var cameraBounds: CGRect {
didSet {
updateCamera()
}
}
private(set) var camera: Camera, cells: [Cell]
func updateCamera() {
camera = Camera(bounds: cameraBounds, time: time, groups: groups)
}
func insertCell(_ cellItem: CellItem, in parents: [(cell: Cell, index: Int)], _ group: Group) {
if !cellItem.cell.children.isEmpty {
fatalError()
}
if cellItem.keyGeometries.count != group.keyframes.count {
fatalError()
}
if cells.contains(cellItem.cell) || group.cellItems.contains(cellItem) {
fatalError()
}
for parent in parents {
parent.cell.children.insert(cellItem.cell, at: parent.index)
}
cells.append(cellItem.cell)
group.cellItems.append(cellItem)
}
func insertCells(_ cellItems: [CellItem], rootCell: Cell, at index: Int, in parent: Cell, _ group: Group) {
for cell in rootCell.children.reversed() {
parent.children.insert(cell, at: index)
}
for cellItem in cellItems {
if cellItem.keyGeometries.count != group.keyframes.count {
fatalError()
}
if cells.contains(cellItem.cell) || group.cellItems.contains(cellItem) {
fatalError()
}
cells.append(cellItem.cell)
group.cellItems.append(cellItem)
}
}
func removeCell(_ cellItem: CellItem, in parents: [(cell: Cell, index: Int)], _ group: Group) {
if !cellItem.cell.children.isEmpty {
fatalError()
}
for parent in parents {
parent.cell.children.remove(at: parent.index)
}
cells.remove(at: cells.index(of: cellItem.cell)!)
group.cellItems.remove(at: group.cellItems.index(of: cellItem)!)
}
func removeCells(_ cellItems: [CellItem], rootCell: Cell, in parent: Cell, _ group: Group) {
for cell in rootCell.children {
parent.children.remove(at: parent.children.index(of: cell)!)
}
for cellItem in cellItems {
cells.remove(at: cells.index(of: cellItem.cell)!)
group.cellItems.remove(at: group.cellItems.index(of: cellItem)!)
}
}
struct CellRemoveManager {
let groupAndCellItems: [(group: Group, cellItems: [CellItem])]
let rootCell: Cell
let parents: [(cell: Cell, index: Int)]
func contains(_ cellItem: CellItem) -> Bool {
for gac in groupAndCellItems {
if gac.cellItems.contains(cellItem) {
return true
}
}
return false
}
}
func cellRemoveManager(with cellItem: CellItem) -> CellRemoveManager {
var cells = [cellItem.cell]
cellItem.cell.depthFirstSearch(duplicate: false, handler: { parent, cell in
let parents = rootCell.parents(with: cell)
if parents.count == 1 {
cells.append(cell)
}
})
var groupAndCellItems = [(group: Group, cellItems: [CellItem])]()
for group in groups {
var cellItems = [CellItem]()
cells = cells.filter {
if let removeCellItem = group.cellItem(with: $0) {
cellItems.append(removeCellItem)
return false
}
return true
}
if !cellItems.isEmpty {
groupAndCellItems.append((group, cellItems))
}
}
if groupAndCellItems.isEmpty {
fatalError()
}
return CellRemoveManager(groupAndCellItems: groupAndCellItems, rootCell: cellItem.cell, parents: rootCell.parents(with: cellItem.cell))
}
func insertCell(with crm: CellRemoveManager) {
for parent in crm.parents {
parent.cell.children.insert(crm.rootCell, at: parent.index)
}
for gac in crm.groupAndCellItems {
for cellItem in gac.cellItems {
if cellItem.keyGeometries.count != gac.group.keyframes.count {
fatalError()
}
if cells.contains(cellItem.cell) || gac.group.cellItems.contains(cellItem) {
fatalError()
}
cells.append(cellItem.cell)
gac.group.cellItems.append(cellItem)
}
}
}
func removeCell(with crm: CellRemoveManager) {
for parent in crm.parents {
parent.cell.children.remove(at: parent.index)
}
for gac in crm.groupAndCellItems {
for cellItem in gac.cellItems {
cells.remove(at: cells.index(of: cellItem.cell)!)
gac.group.cellItems.remove(at: gac.group.cellItems.index(of: cellItem)!)
}
}
}
init(rootCell: Cell = Cell(material: Material(color: HSLColor.white)), groups: [Group] = [Group](), editGroup: Group = Group(), time: Int = 0, timeLength: Int = 24, cameraBounds: CGRect = CGRect(x: 0, y: 0, width: 640, height: 360)) {
self.rootCell = rootCell
self.groups = groups.isEmpty ? [editGroup] : groups
self.editGroup = editGroup
self.time = time
self.timeLength = timeLength
self.cameraBounds = cameraBounds
editGroup.timeLength = timeLength
self.camera = Camera(bounds: cameraBounds, time: time, groups: groups)
self.cells = groups.reduce([Cell]()) { $0 + $1.cells }
super.init()
}
init(rootCell: Cell, groups: [Group], editGroup: Group, time: Int, timeLength: Int, cameraBounds: CGRect, cells: [Cell]) {
self.rootCell = rootCell
self.groups = groups
self.editGroup = editGroup
self.time = time
self.timeLength = timeLength
self.cameraBounds = cameraBounds
self.cells = cells
self.camera = Camera(bounds: cameraBounds, time: time, groups: groups)
super.init()
}
private init(rootCell: Cell, groups: [Group], editGroup: Group, time: Int, timeLength: Int, cameraBounds: CGRect, cells: [Cell], camera: Camera) {
self.rootCell = rootCell
self.groups = groups
self.editGroup = editGroup
self.time = time
self.timeLength = timeLength
self.cameraBounds = cameraBounds
self.cells = cells
self.camera = camera
super.init()
}
static let dataType = "C0.Cut.1", rootCellKey = "0", groupsKey = "1", editGroupKey = "2", timeKey = "3", timeLengthKey = "4", cameraBoundsKey = "5", cellsKey = "6"
init?(coder: NSCoder) {
rootCell = coder.decodeObject(forKey: Cut.rootCellKey) as? Cell ?? Cell()
groups = coder.decodeObject(forKey: Cut.groupsKey) as? [Group] ?? []
editGroup = coder.decodeObject(forKey: Cut.editGroupKey) as? Group ?? Group()
time = coder.decodeInteger(forKey: Cut.timeKey)
timeLength = coder.decodeInteger(forKey: Cut.timeLengthKey)
cameraBounds = coder.decodeRect(forKey: Cut.cameraBoundsKey)
cells = coder.decodeObject(forKey: Cut.cellsKey) as? [Cell] ?? []
camera = Camera(bounds: cameraBounds, time: time, groups: groups)
super.init()
}
func encode(with coder: NSCoder) {
coder.encode(rootCell, forKey: Cut.rootCellKey)
coder.encode(groups, forKey: Cut.groupsKey)
coder.encode(editGroup, forKey: Cut.editGroupKey)
coder.encode(time, forKey: Cut.timeKey)
coder.encode(timeLength, forKey: Cut.timeLengthKey)
coder.encode(cameraBounds, forKey: Cut.cameraBoundsKey)
coder.encode(cells, forKey: Cut.cellsKey)
}
var cellIDDictionary: [UUID: Cell] {
var dic = [UUID: Cell]()
for cell in cells {
dic[cell.id] = cell
}
return dic
}
var materialCellIDs: [MaterialCellID] {
get {
var materialCellIDDictionary = [UUID: MaterialCellID]()
for cell in cells {
if let mci = materialCellIDDictionary[cell.material.id] {
mci.cellIDs.append(cell.id)
} else {
materialCellIDDictionary[cell.material.id] = MaterialCellID(material: cell.material, cellIDs: [cell.id])
}
}
return Array(materialCellIDDictionary.values)
}
set {
let cellIDDictionary = self.cellIDDictionary
for materialCellID in newValue {
for cellId in materialCellID.cellIDs {
cellIDDictionary[cellId]?.material = materialCellID.material
}
}
}
}
var deepCopy: Cut {
let copyRootCell = rootCell.deepCopy, copyCells = cells.map { $0.deepCopy }, copyGroups = groups.map() { $0.deepCopy }
let copyGroup = copyGroups[groups.index(of: editGroup)!]
rootCell.resetCopyedCell()
return Cut(rootCell: copyRootCell, groups: copyGroups, editGroup: copyGroup, time: time, timeLength: timeLength, cameraBounds: cameraBounds, cells: copyCells, camera: camera)
}
var allEditSelectionCellItemsWithNotEmptyGeometry: [CellItem] {
return groups.reduce([CellItem]()) {
$0 + $1.editSelectionCellItemsWithNotEmptyGeometry
}
}
var allEditSelectionCellsWithNotEmptyGeometry: [Cell] {
return groups.reduce([Cell]()) {
$0 + $1.editSelectionCellsWithNotEmptyGeometry
}
}
var editGroupIndex: Int {
return groups.index(of: editGroup) ?? 0
}
func selectionCellAndLines(with point: CGPoint, usingLock: Bool = true) -> [(cell: Cell, geometry: Geometry, lines: [Line])] {
if usingLock {
let allEditSelectionCells = editGroup.editSelectionCellsWithNotEmptyGeometry
for selectionCell in allEditSelectionCells {
if selectionCell.contains(point) {
return allEditSelectionCellsWithNotEmptyGeometry.flatMap {
$0.geometry.isEmpty ? nil : ($0, $0.geometry, $0.lines)
}
}
}
} else {
let allEditSelectionCells = allEditSelectionCellsWithNotEmptyGeometry
for selectionCell in allEditSelectionCells {
if selectionCell.contains(point) {
return allEditSelectionCells.flatMap {
$0.geometry.isEmpty ? nil : ($0, $0.geometry, $0.lines)
}
}
}
}
let hitCells = rootCell.cells(at: point, usingLock: usingLock)
if let cell = hitCells.first {
return [(cell, cell.geometry, cell.lines)]
} else {
return []
}
}
enum IndicationCellType {
case none, indication, selection
}
func indicationCellsTuple(with point: CGPoint, usingLock: Bool = true) -> (cells: [Cell], type: IndicationCellType) {
if usingLock {
let allEditSelectionCells = editGroup.editSelectionCellsWithNotEmptyGeometry
for selectionCell in allEditSelectionCells {
if selectionCell.contains(point) {
return (allEditSelectionCellsWithNotEmptyGeometry, .selection)
}
}
} else {
let allEditSelectionCells = allEditSelectionCellsWithNotEmptyGeometry
for selectionCell in allEditSelectionCells {
if selectionCell.contains(point) {
return (allEditSelectionCells, .selection)
}
}
}
let hitCells = rootCell.cells(at: point, usingLock: usingLock)
if let cell = hitCells.first {
return ([cell], .indication)
} else {
return ([], .none)
}
}
func group(with cell: Cell) -> Group {
for group in groups {
if group.contains(cell) {
return group
}
}
fatalError()
}
func groupAndCellItem(with cell: Cell) -> (group: Group, cellItem: CellItem) {
for group in groups {
if let cellItem = group.cellItem(with: cell) {
return (group, cellItem)
}
}
fatalError()
}
@nonobjc func group(with cellItem: CellItem) -> Group {
for group in groups {
if group.contains(cellItem) {
return group
}
}
fatalError()
}
func isInterpolatedKeyframe(with group: Group) -> Bool {
let keyIndex = group.loopedKeyframeIndex(withTime: time)
return group.editKeyframe.interpolation != .none && keyIndex.interValue != 0 && keyIndex.index != group.keyframes.count - 1
}
var maxTime: Int {
return groups.reduce(0) {
max($0, $1.keyframes.last?.time ?? 0)
}
}
func maxTimeWithOtherGroup(_ group: Group) -> Int {
return groups.reduce(0) {
$1 !== group ? max($0, $1.keyframes.last?.time ?? 0) : $0
}
}
func cellItem(at point: CGPoint, with group: Group) -> CellItem? {
if let cell = rootCell.atPoint(point) {
let gc = groupAndCellItem(with: cell)
return gc.group == group ? gc.cellItem : nil
} else {
return nil
}
}
func lines(_ fromCells: [(cell: Cell, lineIndexes: [Int])]) -> [Line] {
var lines = [Line]()
for fromCell in fromCells {
for j in fromCell.lineIndexes {
lines.append(fromCell.cell.lines[j])
}
}
return lines
}
var imageBounds: CGRect {
return groups.reduce(rootCell.imageBounds) { $0.unionNotEmpty($1.imageBounds) }
}
func nearestEditPoint(_ point: CGPoint) -> (drawing: Drawing?, cellItem: CellItem?, geometry: Geometry?, line: Line, lineIndex: Int, pointIndex: Int, controlLineIndex: Int, oldPoint: CGPoint)? {
var minD = CGFloat.infinity, lineIndex = 0, pointIndex = 0, minLine: Line?
func nearestEditPoint(from lines: [Line]) -> Bool {
var isNearest = false
for (j, line) in lines.enumerated() {
line.allEditPoints() { p, i, stop in
let d = hypot2(point.x - p.x, point.y - p.y)
if d < minD {
minD = d
minLine = line
lineIndex = j
pointIndex = i
isNearest = true
}
}
}
return isNearest
}
var drawing: Drawing?, cell: Cell?, geometry: Geometry?
rootCell.allCells { aCell, stop in
if aCell.isEditable && nearestEditPoint(from: aCell.geometry.lines) {
cell = aCell
geometry = aCell.geometry
}
}
if nearestEditPoint(from: editGroup.drawingItem.drawing.lines) {
drawing = editGroup.drawingItem.drawing
cell = nil
geometry = nil
}
if let minLine = minLine {
func nearestControlLineIndex(line: Line) ->Int {
var minD = CGFloat.infinity, minIndex = 0
for i in 0 ..< line.points.count - 1 {
let d = point.distance(line.points[i].mid(line.points[i + 1]))
if d < minD {
minD = d
minIndex = i
}
}
return minIndex
}
if let cell = cell {
return (drawing, groupAndCellItem(with: cell).cellItem, geometry, minLine, lineIndex, pointIndex, nearestControlLineIndex(line: minLine), minLine.points[pointIndex])
} else {
return (drawing, nil, geometry, minLine, lineIndex, pointIndex, nearestControlLineIndex(line: minLine), minLine.points[pointIndex])
}
} else {
return nil
}
}
func nearestVertex(_ point: CGPoint) -> (drawing: Drawing?, cellItem: CellItem?, geometry: Geometry?, line: Line, otherLine: Line?, index: Int, otherIndex: Int, isFirst: Bool, isOtherFirst: Bool, oldPoint: CGPoint)? {
var minD = CGFloat.infinity, vertex: (line: Line, otherLine: Line?, index: Int, otherIndex: Int, isFirst: Bool, isOtherFirst: Bool, oldPoint: CGPoint)?
func nearestVertex(from lines: [Line]) -> Bool {
var j = lines.count - 1, isNearest = false
if var oldLine = lines.last {
for (i, line) in lines.enumerated() {
let lp = oldLine.lastPoint, fp = line.firstPoint
if lp != fp {
let d = hypot2(point.x - lp.x, point.y - lp.y)
if d < minD {
minD = d
vertex = (oldLine, nil, j, i, false, false, lp)
isNearest = true
}
}
let d = hypot2(point.x - fp.x, point.y - fp.y)
if d < minD {
minD = d
vertex = (line, lp != fp ? nil : oldLine, i, j, true, false, fp)
isNearest = true
}
oldLine = line
j = i
}
}
return isNearest
}
var drawing: Drawing?, cell: Cell?, geometry: Geometry?
rootCell.allCells { aCell, stop in
if aCell.isEditable && nearestVertex(from: aCell.geometry.lines) {
cell = aCell
geometry = aCell.geometry
}
}
if nearestVertex(from: editGroup.drawingItem.drawing.lines) {
drawing = editGroup.drawingItem.drawing
cell = nil
geometry = nil
}
if let v = vertex {
if let cell = cell {
return (drawing, groupAndCellItem(with: cell).cellItem, geometry, v.line, v.otherLine, v.index, v.otherIndex, v.isFirst, v.isOtherFirst, v.oldPoint)
} else {
return (drawing, nil, geometry, v.line, v.otherLine, v.index, v.otherIndex, v.isFirst, v.isOtherFirst, v.oldPoint)
}
} else {
return nil
}
}
func draw(_ scene: Scene, viewType: Cut.ViewType = .preview, editMaterial: Material? = nil, moveZCell: Cell? = nil, isShownPrevious: Bool = false, isShownNext: Bool = false, with di: DrawInfo, in ctx: CGContext) {
if viewType == .preview && camera.transform.wiggle.isMove {
let p = camera.transform.wiggle.newPosition(CGPoint(), phase: camera.wigglePhase/scene.frameRate.cf)
ctx.translateBy(x: p.x, y: p.y)
}
if let affine = camera.affineTransform {
ctx.saveGState()
ctx.concatenate(affine)
drawContents(scene, viewType: viewType, editMaterial: editMaterial, moveZCell: moveZCell, isShownPrevious: isShownPrevious, isShownNext: isShownNext, with: di, in: ctx)
ctx.restoreGState()
} else {
drawContents(scene, viewType: viewType, editMaterial: editMaterial, moveZCell: moveZCell, isShownPrevious: isShownPrevious, isShownNext: isShownNext, with: di, in: ctx)
}
if viewType != .preview {
drawCamera(cameraBounds, in: ctx)
}
for group in groups {
if let text = group.textItem?.text {
text.draw(bounds: cameraBounds, in: ctx)
}
}
}
private func drawContents(_ scene: Scene, viewType: Cut.ViewType, editMaterial: Material?, moveZCell: Cell?, isShownPrevious: Bool, isShownNext: Bool, with di: DrawInfo, in ctx: CGContext) {
let isEdit = viewType != .preview && viewType != .editMaterial && viewType != .editingMaterial
drawRootCell(isEdit: isEdit, with: editMaterial,di, in: ctx)
if isEdit {
for group in groups {
if !group.isHidden {
group.drawSelectionCells(opacity: group != editGroup ? 0.5 : 1, isDrawEdit: group == editGroup, with: di, in: ctx)
}
}
if !editGroup.isHidden {
editGroup.drawPreviousNext(isShownPrevious: isShownPrevious, isShownNext: isShownNext, time: time, with: di, in: ctx)
editGroup.drawSkinEditCell(with: di, in: ctx)
if let moveZCell = moveZCell {
drawZCell(zCell: moveZCell, in: ctx)
}
}
}
drawGroups(isEdit: isEdit, with: di, in: ctx)
}
private func drawRootCell(isEdit: Bool, with editMaterial: Material?, _ di: DrawInfo, in ctx: CGContext) {
if isEdit {
var isTransparency = false
for child in rootCell.children {
if isTransparency {
if !child.isLocked {
ctx.endTransparencyLayer()
ctx.restoreGState()
isTransparency = false
}
}
else if child.isLocked {
ctx.saveGState()
ctx.setAlpha(0.5)
ctx.beginTransparencyLayer(auxiliaryInfo: nil)
isTransparency = true
}
child.drawEdit(with: editMaterial, di, in: ctx)
}
if isTransparency {
ctx.endTransparencyLayer()
ctx.restoreGState()
}
} else {
for child in rootCell.children {
child.draw(with: di, in: ctx)
}
}
}
private func drawGroups(isEdit: Bool, with di: DrawInfo, in ctx: CGContext) {
if isEdit {
for group in groups {
if !group.isHidden {
if group === editGroup {
group.drawingItem.drawEdit(with: di, in: ctx)
} else {
ctx.setAlpha(0.08)
group.drawingItem.drawEdit(with: di, in: ctx)
ctx.setAlpha(1)
}
}
}
} else {
var alpha = 1.0.cf
for group in groups {
if !group.isHidden {
ctx.setAlpha(alpha)
group.drawingItem.draw(with: di, in: ctx)
}
alpha = max(alpha*0.4, 0.25)
}
ctx.setAlpha(1)
}
}
private func drawZCell(zCell: Cell, in ctx: CGContext) {
rootCell.depthFirstSearch(duplicate: true, handler: { parent, cell in
if cell === zCell, let index = parent.children.index(of: cell) {
if !parent.isEmptyGeometry {
parent.clip(in: ctx) {
Cell.drawCellPaths(cells: Array(parent.children[index + 1 ..< parent.children.count]), color: SceneDefaults.moveZColor, in: ctx)
}
} else {
Cell.drawCellPaths(cells: Array(parent.children[index + 1 ..< parent.children.count]), color: SceneDefaults.moveZColor, in: ctx)
}
}
})
}
private func drawCamera(_ cameraBounds: CGRect, in ctx: CGContext) {
ctx.setLineWidth(1)
if camera.transform.wiggle.isMove {
let maxSize = camera.transform.wiggle.maxSize
drawCameraBorder(bounds: cameraBounds.insetBy(dx: -maxSize.width, dy: -maxSize.height), inColor: SceneDefaults.cameraBorderColor, outColor: SceneDefaults.cutSubBorderColor, in: ctx)
}
for group in groups {
let keyframeIndex = group.loopedKeyframeIndex(withTime: time)
if keyframeIndex.index > 0 {
if let t = group.transformItem?.keyTransforms[keyframeIndex.index - 1], !t.isEmpty {
}
} else if keyframeIndex.index < group.keyframes.count - 1 {
if let t = group.transformItem?.keyTransforms[keyframeIndex.index + 1], !t.isEmpty {
}
}
}
drawCameraBorder(bounds: cameraBounds, inColor: SceneDefaults.cutBorderColor, outColor: SceneDefaults.cutSubBorderColor, in: ctx)
}
private func drawCameraBorder(bounds: CGRect, inColor: CGColor, outColor: CGColor, in ctx: CGContext) {
ctx.setStrokeColor(inColor)
ctx.stroke(bounds.insetBy(dx: -0.5, dy: -0.5))
ctx.setStrokeColor(outColor)
ctx.stroke(bounds.insetBy(dx: -1.5, dy: -1.5))
}
func drawStrokeLine(_ line: Line, lineColor: CGColor, lineWidth: CGFloat, in ctx: CGContext) {
if let affine = camera.affineTransform {
ctx.saveGState()
ctx.concatenate(affine)
}
ctx.setFillColor(lineColor)
line.draw(size: lineWidth, in: ctx)
if camera.affineTransform != nil {
ctx.restoreGState()
}
}
private func drawPadding(_ scene: Scene, bounds: CGRect, cameraAffineTransform t: CGAffineTransform?, color: CGColor, in ctx: CGContext) {
let transformedCameraBounds: CGRect
if let t = t {
transformedCameraBounds = cameraBounds.applying(t)
} else {
transformedCameraBounds = cameraBounds
}
ctx.setFillColor(color)
ctx.addRect(bounds)
ctx.addRect(transformedCameraBounds)
ctx.fillPath(using: .evenOdd)
}
func drawTransparentCellLines(lineIndicationCells: [Cell], viewAffineTransform t: CGAffineTransform?, with di: DrawInfo, in ctx: CGContext) {
if let t = t {
ctx.saveGState()
ctx.concatenate(t)
}
ctx.setLineWidth(di.invertScale)
ctx.setStrokeColor(SceneDefaults.cellBorderColor)
for cell in lineIndicationCells {
if !cell.isLocked && !cell.isHidden {
cell.addPath(in: ctx)
}
}
ctx.strokePath()
if t != nil {
ctx.restoreGState()
}
}
struct EditPoint {
var line: Line, pointIndex: Int, controlLineIndex: Int
}
struct EditLine {
var line: Line, otherLine: Line?, isFirst: Bool, isOtherFirst: Bool
}
private let editPointRadius = 0.5.cf, lineEditPointRadius = 1.5.cf, pointEditPointRadius = 3.0.cf
func drawEditPointsWith(editPoint: EditPoint?, indicationCells: [Cell], drawingIndicationLines: [Line], viewAffineTransform t: CGAffineTransform?, _ di: DrawInfo, in ctx: CGContext) {
if let editPoint = editPoint {
let line = editPoint.line
drawEditLine(line, with: t, di, in: ctx)
if let t = t {
ctx.setLineWidth(1.5)
ctx.setStrokeColor(SceneDefaults.contolLineOutColor)
ctx.move(to: line.points[editPoint.controlLineIndex].applying(t))
ctx.addLine(to: line.points[editPoint.controlLineIndex + 1].applying(t))
ctx.strokePath()
ctx.setLineWidth(1)
ctx.setStrokeColor(SceneDefaults.contolLineInColor)
ctx.addLines(between: line.points.map { $0.applying(t) })
line.allEditPoints { point, index, stop in
ctx.move(to: point.applying(t))
ctx.addLine(to: line.points[index].applying(t))
}
ctx.strokePath()
} else {
ctx.setLineWidth(1.5)
ctx.setStrokeColor(SceneDefaults.contolLineOutColor)
ctx.move(to: line.points[editPoint.controlLineIndex])
ctx.addLine(to: line.points[editPoint.controlLineIndex + 1])
ctx.strokePath()
ctx.setLineWidth(1)
ctx.setStrokeColor(SceneDefaults.contolLineInColor)
ctx.addLines(between: line.points)
line.allEditPoints { point, index, stop in
ctx.move(to: point)
ctx.addLine(to: line.points[index])
}
ctx.strokePath()
}
func drawControlPoints(from lines: [Line], in ctx: CGContext) {
for line in lines {
if line === editPoint.line {
for (i, p) in line.points.enumerated() {
let cp = t != nil ? p.applying(t!) : p
drawControlPoint(cp, radius: i == editPoint.pointIndex ? lineEditPointRadius : editPointRadius,
inColor: SceneDefaults.editControlPointInColor, outColor: SceneDefaults.editControlPointOutColor, in: ctx)
}
}
line.allEditPoints { point, index, stop in
let cp = t != nil ? point.applying(t!) : point
let r = line === editPoint.line ? (index == editPoint.pointIndex ? pointEditPointRadius : lineEditPointRadius) : editPointRadius
drawControlPoint(cp, radius: r, in: ctx)
}
}
}
for cell in indicationCells {
if !cell.isLocked {
drawControlPoints(from: cell.lines, in: ctx)
}
}
drawControlPoints(from: drawingIndicationLines, in: ctx)
} else {
func drawControlPoints(from lines: [Line], in ctx: CGContext) {
for line in lines {
line.allEditPoints { point, index, stop in
drawControlPoint(t != nil ? point.applying(t!) : point, radius: editPointRadius, in: ctx)
}
}
}
for cell in indicationCells {
if !cell.isLocked {
drawControlPoints(from: cell.lines, in: ctx)
}
}
drawControlPoints(from: drawingIndicationLines, in: ctx)
}
}
func drawEditLine(_ editLine: EditLine?, withIndicationCells indicationCells: [Cell], drawingIndicationLines: [Line], viewAffineTransform t: CGAffineTransform?, _ di: DrawInfo, in ctx: CGContext) {
if let editLine = editLine {
drawEditLine(editLine.line, with: t, di, in: ctx)
if let line = editLine.otherLine {
drawEditLine(line, with: t, di, in: ctx)
}
func drawVertices(from lines: [Line], in ctx: CGContext) {
if var oldLine = lines.last {
for line in lines {
let lp: CGPoint, fp: CGPoint
if let t = t {
lp = oldLine.lastPoint.applying(t)
fp = line.firstPoint.applying(t)
} else {
lp = oldLine.lastPoint
fp = line.firstPoint
}
if lp != fp {
drawControlPoint(lp, radius: editLine.line === oldLine && !editLine.isFirst ? pointEditPointRadius : lineEditPointRadius, in: ctx)
}
drawControlPoint(fp, radius: editLine.line === line && editLine.isFirst ? pointEditPointRadius : lineEditPointRadius, in: ctx)
oldLine = line
}
}
}
for cell in indicationCells {
if !cell.isLocked {
drawVertices(from: cell.lines, in: ctx)
}
}
drawVertices(from: drawingIndicationLines, in: ctx)
} else {
func drawVertices(from lines: [Line], in ctx: CGContext) {
if var oldLine = lines.last {
for line in lines {
let lp: CGPoint, fp: CGPoint
if let t = t {
lp = oldLine.lastPoint.applying(t)
fp = line.firstPoint.applying(t)
} else {
lp = oldLine.lastPoint
fp = line.firstPoint
}
if lp != fp {
drawControlPoint(lp, radius: lineEditPointRadius, in: ctx)
}
drawControlPoint(fp, radius: lineEditPointRadius, in: ctx)
oldLine = line
}
}
}
for cell in indicationCells {
if !cell.isLocked {
drawVertices(from: cell.lines, in: ctx)
}
}
drawVertices(from: drawingIndicationLines, in: ctx)
}
}
private func drawEditLine(_ line: Line, with viewAffineTransform: CGAffineTransform?, _ di: DrawInfo, in ctx: CGContext) {
let lw = di.invertScale
if let t = viewAffineTransform {
ctx.saveGState()
ctx.concatenate(t)
}
ctx.setFillColor(SceneDefaults.editLineColor)
line.draw(size: lw, firstPressure: 1, lastPressure: 1, in: ctx)
if viewAffineTransform != nil {
ctx.restoreGState()
}
}
private func drawControlPoint(_ p: CGPoint, radius r: CGFloat, lineWidth: CGFloat = 1,
inColor: CGColor = SceneDefaults.controlPointInColor, outColor: CGColor = SceneDefaults.controlPointOutColor, in ctx: CGContext) {
let rect = CGRect(x: p.x - r, y: p.y - r, width: r*2, height: r*2)
ctx.setFillColor(outColor)
ctx.fillEllipse(in: rect.insetBy(dx: -lineWidth, dy: -lineWidth))
ctx.setFillColor(inColor)
ctx.fillEllipse(in: rect)
}
enum TransformType {
case scaleXY, scaleX, scaleY, rotate, skewX, skewY
}
private let transformXYTextLine = TextLine(string: "XY", isHorizontalCenter: true, isVerticalCenter: true, isCenterWithImageBounds: true)
private let transformXTextLine = TextLine(string: "X", isHorizontalCenter: true, isVerticalCenter: true, isCenterWithImageBounds: true)
private let transformYTextLine = TextLine(string: "Y", isHorizontalCenter: true, isVerticalCenter: true, isCenterWithImageBounds: true)
private let transformRotateTextLine = TextLine(string: "θ", isHorizontalCenter: true, isVerticalCenter: true, isCenterWithImageBounds: true)
private let transformSkewXTextLine = TextLine(string: "Skew ".localized + "X", isHorizontalCenter: true, isVerticalCenter: true, isCenterWithImageBounds: true)
private let transformSkewYTextLine = TextLine(string: "Skew ".localized + "Y", isHorizontalCenter: true, isVerticalCenter: true, isCenterWithImageBounds: true)
private let transformOpacity = 0.5.cf
func transformTypeWith(y: CGFloat, height: CGFloat) -> TransformType {
if y > -height*0.5 {
return .scaleXY
} else if y > -height*1.5 {
return .scaleX
} else if y > -height*2.5 {
return .scaleY
} else if y > -height*3.5 {
return .rotate
} else if y > -height*4.5 {
return .skewX
} else {
return .skewY
}
}
func drawTransform(type: TransformType, startPosition: CGPoint, editPosition: CGPoint, firstWidth: CGFloat, valueWidth: CGFloat, height: CGFloat, in ctx: CGContext) {
drawControlPoint(startPosition, radius: 2, in: ctx)
ctx.saveGState()
ctx.setAlpha(transformOpacity)
ctx.beginTransparencyLayer(auxiliaryInfo: nil)
let x = startPosition.x - firstWidth/2, firstFrame: CGRect
switch type {
case .scaleXY:
firstFrame = CGRect(x: x, y: startPosition.y - height*0.5, width: firstWidth, height: height)
case .scaleX:
firstFrame = CGRect(x: x, y: startPosition.y - height*1.5, width: firstWidth, height: height)
case .scaleY:
firstFrame = CGRect(x: x, y: startPosition.y - height*2.5, width: firstWidth, height: height)
case .rotate:
firstFrame = CGRect(x: x, y: startPosition.y - height*3.5, width: firstWidth, height: height)
case .skewX:
firstFrame = CGRect(x: x, y: startPosition.y - height*4.5, width: firstWidth, height: height)
case .skewY:
firstFrame = CGRect(x: x, y: startPosition.y - height*5.5, width: firstWidth, height: height)
}
let opacity = 0.25.cf
ctx.setFillColor(Defaults.subBackgroundColor.cgColor)
ctx.fill(CGRect(x: x, y: startPosition.y - height*5.5, width: firstWidth, height: height*6.5))
let scaleXYFrame = CGRect(x: x, y: startPosition.y - height*0.5 + height*0.5, width: firstWidth, height: height)
drawTransformLabelWith(textLine: transformXYTextLine, frame: scaleXYFrame, opacity: type == .scaleXY ? 1.0 : opacity, in: ctx)
let scaleXFrame = CGRect(x: x, y: startPosition.y - height*1.5 + height*0.5, width: firstWidth, height: height)
drawTransformLabelWith(textLine: transformXTextLine, frame: scaleXFrame, opacity: type == .scaleX ? 1.0 : opacity, in: ctx)
let scaleYFrame = CGRect(x: x, y: startPosition.y - height*2.5 + height*0.5, width: firstWidth, height: height)
drawTransformLabelWith(textLine: transformYTextLine, frame: scaleYFrame, opacity: type == .scaleY ? 1.0 : opacity,in: ctx)
let rotateFrame = CGRect(x: x, y: startPosition.y - height*3.5 + height*0.5, width: firstWidth, height: height)
drawTransformLabelWith(textLine: transformRotateTextLine, frame: rotateFrame, opacity: type == .rotate ? 1.0 : opacity, in: ctx)
let skewXFrame = CGRect(x: x, y: startPosition.y - height*4.5 + height*0.5, width: firstWidth, height: height)
drawTransformLabelWith(textLine: transformSkewXTextLine, frame: skewXFrame, opacity: type == .skewX ? 1.0 : opacity, in: ctx)
let skewYFrame = CGRect(x: x, y: startPosition.y - height*5.5 + height*0.5, width: firstWidth, height: height)
drawTransformLabelWith(textLine: transformSkewYTextLine, frame: skewYFrame, opacity: type == .skewY ? 1.0 : opacity, in: ctx)
drawTranformSlider(firstFrame: firstFrame, editPosition: editPosition, valueWidth: valueWidth, in: ctx)
ctx.endTransparencyLayer()
ctx.restoreGState()
}
private func drawTransformLabelWith(textLine: TextLine, frame: CGRect, opacity: CGFloat, in ctx: CGContext) {
if opacity != 1.0 {
ctx.saveGState()
ctx.setAlpha(opacity)
textLine.draw(in: frame, in: ctx)
ctx.restoreGState()
} else {
textLine.draw(in: frame, in: ctx)
}
}
private func drawTranformSlider(firstFrame: CGRect, editPosition: CGPoint, valueWidth: CGFloat, in ctx: CGContext) {
let b = ctx.boundingBoxOfClipPath
ctx.setFillColor(Defaults.subBackgroundColor.cgColor)
ctx.fill(CGRect(x: firstFrame.maxX, y: firstFrame.minY, width: max(b.width - firstFrame.maxX, 0), height: firstFrame.height))
ctx.fill(CGRect(x: b.minX, y: firstFrame.minY, width: max(firstFrame.minX - b.minX, 0), height: firstFrame.height))
ctx.setFillColor(Defaults.contentEditColor.cgColor)
ctx.fill(CGRect(x: b.minX, y: firstFrame.midY - 1, width: b.width, height: 2))
var x = firstFrame.midX
ctx.fill(CGRect(x: x - 1, y: firstFrame.minY + 6, width: 1, height: firstFrame.height - 12))
while x < b.maxX {
x += valueWidth
ctx.fill(CGRect(x: x - 1, y: firstFrame.minY + 4, width: 1, height: firstFrame.height - 8))
}
x = firstFrame.midX
while x > b.minX {
x -= valueWidth
ctx.fill(CGRect(x: x - 1, y: firstFrame.minY + 4, width: 1, height: firstFrame.height - 8))
}
drawControlPoint(CGPoint(x: editPosition.x, y : firstFrame.midY), radius: 4, in: ctx)
}
}
final class Group: NSObject, NSCoding, Copying {
private(set) var keyframes: [Keyframe] {
didSet {
self.loopedKeyframeIndexes = Group.loopedKeyframeIndexesWith(keyframes, timeLength: timeLength)
}
}
var editKeyframeIndex: Int, selectionKeyframeIndexes: [Int]
var timeLength: Int {
didSet {
self.loopedKeyframeIndexes = Group.loopedKeyframeIndexesWith(keyframes, timeLength: timeLength)
}
}
var isHidden: Bool {
didSet {
for cellItem in cellItems {
cellItem.cell.isHidden = isHidden
}
}
}
var editCellItem: CellItem?, selectionCellItems: [CellItem]
var drawingItem: DrawingItem, cellItems: [CellItem], transformItem: TransformItem?, textItem: TextItem?
private(set) var loopedKeyframeIndexes: [(index: Int, time: Int, loopCount: Int, loopingCount: Int)]
private static func loopedKeyframeIndexesWith(_ keyframes: [Keyframe], timeLength: Int) -> [(index: Int, time: Int, loopCount: Int, loopingCount: Int)] {
var keyframeIndexes = [(index: Int, time: Int, loopCount: Int, loopingCount: Int)](), previousIndexes = [Int]()
for (i, keyframe) in keyframes.enumerated() {
if keyframe.loop.isEnd, let preIndex = previousIndexes.last {
let loopCount = previousIndexes.count
previousIndexes.removeLast()
let time = keyframe.time, nextTime = i + 1 >= keyframes.count ? timeLength : keyframes[i + 1].time
var t = time, isEndT = false
while t <= nextTime {
for j in preIndex ..< i {
let nk = keyframeIndexes[j]
keyframeIndexes.append((nk.index, t, loopCount, loopCount))
t += keyframeIndexes[j + 1].time - nk.time
if t > nextTime {
if i == keyframes.count - 1 {
keyframeIndexes.append((keyframeIndexes[j + 1].index, t, loopCount, loopCount))
}
isEndT = true
break
}
}
if isEndT {
break
}
}
} else {
let loopCount = keyframe.loop.isStart ? previousIndexes.count + 1 : previousIndexes.count
keyframeIndexes.append((i, keyframe.time, loopCount, max(0, loopCount - 1)))
}
if keyframe.loop.isStart {
previousIndexes.append(keyframeIndexes.count - 1)
}
}
return keyframeIndexes
}
func update(withTime time: Int) {
let timeResult = loopedKeyframeIndex(withTime: time)
let i1 = timeResult.loopedIndex, interTime = max(0, timeResult.interValue)
let kis1 = loopedKeyframeIndexes[i1]
editKeyframeIndex = kis1.index
let k1 = keyframes[kis1.index]
if interTime == 0 || timeResult.sectionValue == 0 || i1 + 1 >= loopedKeyframeIndexes.count || k1.interpolation == .none {
step(kis1.index)
return
}
let kis2 = loopedKeyframeIndexes[i1 + 1]
if k1.interpolation == .linear || keyframes.count <= 2 {
linear(kis1.index, kis2.index, t: k1.easing.convertT(interTime.cf/timeResult.sectionValue.cf))
} else {
let t = k1.easing.isDefault ? time.cf : k1.easing.convertT(interTime.cf/timeResult.sectionValue.cf)*timeResult.sectionValue.cf + kis1.time.cf
let isUseFirstIndex = i1 - 1 >= 0 && k1.interpolation != .bound, isUseEndIndex = i1 + 2 < loopedKeyframeIndexes.count && keyframes[kis2.index].interpolation != .bound
if isUseFirstIndex {
if isUseEndIndex {
let kis0 = loopedKeyframeIndexes[i1 - 1], kis3 = loopedKeyframeIndexes[i1 + 2]
let msx = MonosplineX(x0: kis0.time.cf, x1: kis1.time.cf, x2: kis2.time.cf, x3: kis3.time.cf, x: t)
monospline(kis0.index, kis1.index, kis2.index, kis3.index, with: msx)
} else {
let kis0 = loopedKeyframeIndexes[i1 - 1]
let msx = MonosplineX(x0: kis0.time.cf, x1: kis1.time.cf, x2: kis2.time.cf, x: t)
endMonospline(kis0.index, kis1.index, kis2.index, with: msx)
}
} else if isUseEndIndex {
let kis3 = loopedKeyframeIndexes[i1 + 2]
let msx = MonosplineX(x1: kis1.time.cf, x2: kis2.time.cf, x3: kis3.time.cf, x: t)
firstMonospline(kis1.index, kis2.index, kis3.index, with: msx)
} else {
linear(kis1.index, kis2.index, t: k1.easing.convertT(interTime.cf/timeResult.sectionValue.cf))
}
}
}
func step(_ f0: Int) {
drawingItem.update(with: f0)
for cellItem in cellItems {
cellItem.step(f0)
}
transformItem?.step(f0)
textItem?.update(with: f0)
}
func linear(_ f0: Int, _ f1: Int, t: CGFloat) {
drawingItem.update(with: f0)
for cellItem in cellItems {
cellItem.linear(f0, f1, t: t)
}
transformItem?.linear(f0, f1, t: t)
textItem?.update(with: f0)
}
func firstMonospline(_ f1: Int, _ f2: Int, _ f3: Int, with msx: MonosplineX) {
drawingItem.update(with: f1)
for cellItem in cellItems {
cellItem.firstMonospline(f1, f2, f3, with: msx)
}
transformItem?.firstMonospline(f1, f2, f3, with: msx)
textItem?.update(with: f1)
}
func monospline(_ f0: Int, _ f1: Int, _ f2: Int, _ f3: Int, with msx: MonosplineX) {
drawingItem.update(with: f1)
for cellItem in cellItems {
cellItem.monospline(f0, f1, f2, f3, with: msx)
}
transformItem?.monospline(f0, f1, f2, f3, with: msx)
textItem?.update(with: f1)
}
func endMonospline(_ f0: Int, _ f1: Int, _ f2: Int, with msx: MonosplineX) {
drawingItem.update(with: f1)
for cellItem in cellItems {
cellItem.endMonospline(f0, f1, f2, with: msx)
}
transformItem?.endMonospline(f0, f1, f2, with: msx)
textItem?.update(with: f1)
}
func replaceKeyframe(_ keyframe: Keyframe, at index: Int) {
keyframes[index] = keyframe
}
func replaceKeyframes(_ keyframes: [Keyframe]) {
if keyframes.count != self.keyframes.count {
fatalError()
}
self.keyframes = keyframes
}
func insertKeyframe(_ keyframe: Keyframe, drawing: Drawing, geometries: [Geometry], materials: [Material?], transform: Transform?, text: Text?, at index: Int) {
keyframes.insert(keyframe, at: index)
drawingItem.keyDrawings.insert(drawing, at: index)
if geometries.count > cellItems.count {
fatalError()
}
for (i, cellItem) in cellItems.enumerated() {
cellItem.keyGeometries.insert(geometries[i], at: index)
}
if !materials.isEmpty {
if materials.count > cellItems.count {
fatalError()
}
for (i, cellItem) in cellItems.enumerated() {
if let material = materials[i] {
cellItem.keyMaterials.insert(material, at: index)
}
}
}
if let transform = transform {
transformItem?.keyTransforms.insert(transform, at: index)
}
if let text = text {
textItem?.keyTexts.insert(text, at: index)
}
}
func removeKeyframe(at index: Int) {
keyframes.remove(at: index)
drawingItem.keyDrawings.remove(at: index)
for cellItem in cellItems {
cellItem.keyGeometries.remove(at: index)
if !cellItem.keyMaterials.isEmpty {
cellItem.keyMaterials.remove(at: index)
}
}
transformItem?.keyTransforms.remove(at: index)
textItem?.keyTexts.remove(at: index)
}
func setKeyGeometries(_ keyGeometries: [Geometry], in cellItem: CellItem, isSetGeometryInCell: Bool = true) {
if keyGeometries.count != keyframes.count {
fatalError()
}
if isSetGeometryInCell, let i = cellItem.keyGeometries.index(of: cellItem.cell.geometry) {
cellItem.cell.geometry = keyGeometries[i]
}
cellItem.keyGeometries = keyGeometries
}
func setKeyTransforms(_ keyTransforms: [Transform], isSetTransformInItem: Bool = true) {
if let transformItem = transformItem {
if keyTransforms.count != keyframes.count {
fatalError()
}
if isSetTransformInItem, let i = transformItem.keyTransforms.index(of: transformItem.transform) {
transformItem.transform = keyTransforms[i]
}
transformItem.keyTransforms = keyTransforms
}
}
var currentItemValues: (drawing: Drawing, geometries: [Geometry], materials: [Material?], transform: Transform?, text: Text?) {
let geometries = cellItems.map { $0.cell.geometry }
let materials: [Material?] = cellItems.map { $0.keyMaterials.isEmpty ? nil : $0.cell.material }
return (drawingItem.drawing, geometries, materials, transformItem?.transform, textItem?.text)
}
func keyframeItemValues(at index: Int) -> (drawing: Drawing, geometries: [Geometry], materials: [Material?], transform: Transform?, text: Text?) {
let geometries = cellItems.map { $0.keyGeometries[index] }
let materials: [Material?] = cellItems.map {
index >= $0.keyMaterials.count ? nil : $0.keyMaterials[index]
}
return (drawingItem.keyDrawings[index], geometries, materials, transformItem?.keyTransforms[index], textItem?.keyTexts[index])
}
init(keyframes: [Keyframe] = [Keyframe()], editKeyframeIndex: Int = 0, selectionKeyframeIndexes: [Int] = [], timeLength: Int = 0,
isHidden: Bool = false, editCellItem: CellItem? = nil, selectionCellItems: [CellItem] = [],
drawingItem: DrawingItem = DrawingItem(), cellItems: [CellItem] = [], transformItem: TransformItem? = nil, textItem: TextItem? = nil) {
self.keyframes = keyframes
self.editKeyframeIndex = editKeyframeIndex
self.selectionKeyframeIndexes = selectionKeyframeIndexes
self.timeLength = timeLength
self.isHidden = isHidden
self.editCellItem = editCellItem
self.selectionCellItems = selectionCellItems
self.drawingItem = drawingItem
self.cellItems = cellItems
self.transformItem = transformItem
self.textItem = textItem
self.loopedKeyframeIndexes = Group.loopedKeyframeIndexesWith(keyframes, timeLength: timeLength)
super.init()
}
private init(keyframes: [Keyframe], editKeyframeIndex: Int, selectionKeyframeIndexes: [Int], timeLength: Int,
isHidden: Bool, editCellItem: CellItem?, selectionCellItems: [CellItem],
drawingItem: DrawingItem, cellItems: [CellItem], transformItem: TransformItem?, textItem: TextItem?,
keyframeIndexes: [(index: Int, time: Int, loopCount: Int, loopingCount: Int)]) {
self.keyframes = keyframes
self.editKeyframeIndex = editKeyframeIndex
self.selectionKeyframeIndexes = selectionKeyframeIndexes
self.timeLength = timeLength
self.isHidden = isHidden
self.editCellItem = editCellItem
self.selectionCellItems = selectionCellItems
self.drawingItem = drawingItem
self.cellItems = cellItems
self.transformItem = transformItem
self.textItem = textItem
self.loopedKeyframeIndexes = keyframeIndexes
super.init()
}
static let dataType = "C0.Group.1", keyframesKey = "0", editKeyframeIndexKey = "1", selectionKeyframeIndexesKey = "2", timeLengthKey = "3", isHiddenKey = "4"
static let editCellItemKey = "5", selectionCellItemsKey = "6", drawingItemKey = "7", cellItemsKey = "8", transformItemKey = "9", textItemKey = "10"
init?(coder: NSCoder) {
keyframes = coder.decodeStruct(forKey: Group.keyframesKey) ?? []
editKeyframeIndex = coder.decodeInteger(forKey: Group.editKeyframeIndexKey)
selectionKeyframeIndexes = coder.decodeObject(forKey: Group.selectionKeyframeIndexesKey) as? [Int] ?? []
timeLength = coder.decodeInteger(forKey: Group.timeLengthKey)
isHidden = coder.decodeBool(forKey: Group.isHiddenKey)
editCellItem = coder.decodeObject(forKey: Group.editCellItemKey) as? CellItem
selectionCellItems = coder.decodeObject(forKey: Group.selectionCellItemsKey) as? [CellItem] ?? []
drawingItem = coder.decodeObject(forKey: Group.drawingItemKey) as? DrawingItem ?? DrawingItem()
cellItems = coder.decodeObject(forKey: Group.cellItemsKey) as? [CellItem] ?? []
transformItem = coder.decodeObject(forKey: Group.transformItemKey) as? TransformItem
textItem = coder.decodeObject(forKey: Group.textItemKey) as? TextItem
loopedKeyframeIndexes = Group.loopedKeyframeIndexesWith(keyframes, timeLength: timeLength)
super.init()
}
func encode(with coder: NSCoder) {
coder.encodeStruct(keyframes, forKey: Group.keyframesKey)
coder.encode(editKeyframeIndex, forKey: Group.editKeyframeIndexKey)
coder.encode(selectionKeyframeIndexes, forKey: Group.selectionKeyframeIndexesKey)
coder.encode(timeLength, forKey: Group.timeLengthKey)
coder.encode(isHidden, forKey: Group.isHiddenKey)
coder.encode(editCellItem, forKey: Group.editCellItemKey)
coder.encode(selectionCellItems, forKey: Group.selectionCellItemsKey)
coder.encode(drawingItem, forKey: Group.drawingItemKey)
coder.encode(cellItems, forKey: Group.cellItemsKey)
coder.encode(transformItem, forKey: Group.transformItemKey)
coder.encode(textItem, forKey: Group.textItemKey)
}
var deepCopy: Group {
return Group(keyframes: keyframes, editKeyframeIndex: editKeyframeIndex, selectionKeyframeIndexes: selectionKeyframeIndexes,
timeLength: timeLength, isHidden: isHidden, editCellItem: editCellItem?.deepCopy,
selectionCellItems: selectionCellItems.map { $0.deepCopy }, drawingItem: drawingItem.deepCopy,
cellItems: cellItems.map { $0.deepCopy }, transformItem: transformItem?.deepCopy,
textItem: textItem?.deepCopy, keyframeIndexes: loopedKeyframeIndexes)
}
var editKeyframe: Keyframe {
return keyframes[min(editKeyframeIndex, keyframes.count - 1)]
}
func loopedKeyframeIndex(withTime t: Int) -> (loopedIndex: Int, index: Int, interValue: Int, sectionValue: Int) {
var oldT = timeLength
for i in (0 ..< loopedKeyframeIndexes.count).reversed() {
let ki = loopedKeyframeIndexes[i]
let kt = ki.time
if t >= kt {
return (i, ki.index, t - kt, oldT - kt)
}
oldT = kt
}
return (0, 0, t - loopedKeyframeIndexes.first!.time, oldT - loopedKeyframeIndexes.first!.time)
}
var minTimeLength: Int {
return (keyframes.last?.time ?? 0) + 1
}
var lastKeyframeTime: Int {
return keyframes.isEmpty ? 0 : keyframes[keyframes.count - 1].time
}
var lastLoopedKeyframeTime: Int {
if loopedKeyframeIndexes.isEmpty {
return 0
}
let t = loopedKeyframeIndexes[loopedKeyframeIndexes.count - 1].time
if t >= timeLength {
return loopedKeyframeIndexes.count >= 2 ? loopedKeyframeIndexes[loopedKeyframeIndexes.count - 2].time : 0
} else {
return t
}
}
func contains(_ cell: Cell) -> Bool {
for cellItem in cellItems {
if cellItem.cell == cell {
return true
}
}
return false
}
func containsSelection(_ cell: Cell) -> Bool {
for cellItem in selectionCellItems {
if cellItem.cell == cell {
return true
}
}
return false
}
func containsEditSelectionWithNotEmptyGeometry(_ cell: Cell) -> Bool {
for cellItem in editSelectionCellItemsWithNotEmptyGeometry {
if cellItem.cell == cell {
return true
}
}
return false
}
@nonobjc func contains(_ cellItem: CellItem) -> Bool {
return cellItems.contains(cellItem)
}
func cellItem(with cell: Cell) -> CellItem? {
for cellItem in cellItems {
if cellItem.cell == cell {
return cellItem
}
}
return nil
}
var cells: [Cell] {
return cellItems.map { $0.cell }
}
var selectionCells: [Cell] {
return selectionCellItems.map { $0.cell }
}
var editSelectionCellsWithNotEmptyGeometry: [Cell] {
if let editCellItem = editCellItem, !editCellItem.cell.geometry.isEmpty {
return selectionCellItems.flatMap { !$0.cell.geometry.isEmpty ? $0.cell : nil } + [editCellItem.cell]
} else {
return selectionCellItems.flatMap { !$0.cell.geometry.isEmpty ? $0.cell : nil }
}
}
var editSelectionCellItems: [CellItem] {
if let editCellItem = editCellItem {
return selectionCellItems + [editCellItem]
} else {
return selectionCellItems
}
}
var editSelectionCellItemsWithNotEmptyGeometry: [CellItem] {
if let editCellItem = editCellItem, !editCellItem.cell.geometry.isEmpty {
return selectionCellItems.filter { !$0.cell.geometry.isEmpty } + [editCellItem]
} else {
return selectionCellItems.filter { !$0.cell.geometry.isEmpty }
}
}
var emptyKeyGeometries: [Geometry] {
return keyframes.map { _ in Geometry() }
}
var isEmptyGeometryWithCells: Bool {
for cellItem in cellItems {
if cellItem.cell.geometry.isEmpty {
return false
}
}
return true
}
func wigglePhaseWith(time: Int, lastHz: CGFloat) -> CGFloat {
if let transformItem = transformItem, let firstTransform = transformItem.keyTransforms.first {
var phase = 0.0.cf, oldHz = firstTransform.wiggle.hz, oldTime = 0
for i in 1 ..< keyframes.count {
let newTime = keyframes[i].time
if time >= newTime {
let newHz = transformItem.keyTransforms[i].wiggle.hz
phase += (newHz + oldHz)*(newTime - oldTime).cf/2
oldTime = newTime
oldHz = newHz
} else {
return phase + (lastHz + oldHz)*(time - oldTime).cf/2
}
}
return phase + lastHz*(time - oldTime).cf
} else {
return 0
}
}
func snapPoint(_ p: CGPoint, snapDistance: CGFloat, otherLines: [(line: Line, isFirst: Bool)]) -> CGPoint {
let sd = snapDistance*snapDistance
var minD = CGFloat.infinity, minP = p
func snap(with lines: [Line]) {
for line in lines {
var isFirst = true, isLast = true
for ol in otherLines {
if ol.line === line {
if ol.isFirst {
isFirst = false
} else {
isLast = false
}
}
}
if isFirst {
let fp = line.firstPoint
let d = p.squaredDistance(other: fp)
if d < sd && d < minD {
minP = fp
minD = d
}
}
if isLast {
let lp = line.lastPoint
let d = p.squaredDistance(other: lp)
if d < sd && d < minD {
minP = lp
minD = d
}
}
}
}
for cellItem in cellItems {
snap(with: cellItem.cell.lines)
}
snap(with: drawingItem.drawing.lines)
return minP
}
var imageBounds: CGRect {
return cellItems.reduce(CGRect()) { $0.unionNotEmpty($1.cell.imageBounds) }.unionNotEmpty(drawingItem.imageBounds)
}
func drawPreviousNext(isShownPrevious: Bool, isShownNext: Bool, time: Int, with di: DrawInfo, in ctx: CGContext) {
drawingItem.drawPreviousNext(isShownPrevious: isShownPrevious, isShownNext: isShownNext, index:
loopedKeyframeIndex(withTime: time).index, with: di, in: ctx)
}
func drawSelectionCells(opacity: CGFloat, isDrawEdit: Bool, with di: DrawInfo, in ctx: CGContext) {
if !isHidden && !selectionCellItems.isEmpty {
ctx.setAlpha(0.6*opacity)
ctx.beginTransparencyLayer(auxiliaryInfo: nil)
var geometrys = [Geometry]()
ctx.setFillColor(SceneDefaults.subSelectionColor.copy(alpha: 1)!)
func setPaths(with cellItem: CellItem) {
let cell = cellItem.cell
if !cell.geometry.lines.isEmpty {
cell.addPath(in: ctx)
ctx.fillPath()
geometrys.append(cell.geometry)
}
}
for cellItem in selectionCellItems {
setPaths(with: cellItem)
}
if isDrawEdit, let editCellItem = editCellItem {
setPaths(with: editCellItem)
}
ctx.setFillColor(SceneDefaults.selectionColor)
for geometry in geometrys {
geometry.draw(withLineWidth: 1.5*di.invertCameraScale, in: ctx)
}
ctx.endTransparencyLayer()
ctx.setAlpha(1)
}
}
func drawSkinEditCell(with di: DrawInfo, in ctx: CGContext) {
if let editCellItem = editCellItem {
for i in (0 ..< editKeyframeIndex).reversed() {
if !editCellItem.keyGeometries[i].lines.isEmpty {
editCellItem.cell.drawSkin(lineColor: SceneDefaults.previousSkinColor, subColor: SceneDefaults.subPreviousSkinColor, opacity: i != editKeyframeIndex - 1 ? 0.1 : 0.2, geometry: editCellItem.keyGeometries[i], with: di, in: ctx)
break
}
}
for i in editKeyframeIndex + 1 ..< editCellItem.keyGeometries.count {
if !editCellItem.keyGeometries[i].lines.isEmpty {
editCellItem.cell.drawSkin(lineColor: SceneDefaults.nextSkinColor, subColor: SceneDefaults.subNextSkinColor, opacity: i != editKeyframeIndex + 1 ? 0.1 : 0.2, geometry: editCellItem.keyGeometries[i], with: di, in: ctx)
break
}
}
editCellItem.cell.drawSkin(lineColor: SceneDefaults.selectionColor, subColor: SceneDefaults.subSelectionSkinColor, opacity: 1.0, geometry: editCellItem.cell.geometry, with: di, in: ctx)
}
}
}
struct Keyframe: ByteCoding {
enum Interpolation: Int8 {
case spline, bound, linear, none
}
let time: Int, easing: Easing, interpolation: Interpolation, loop: Loop, implicitSplited: Bool
init(time: Int = 0, easing: Easing = Easing(), interpolation: Interpolation = .spline, loop: Loop = Loop(), implicitSplited: Bool = false) {
self.time = time
self.easing = easing
self.interpolation = interpolation
self.loop = loop
self.implicitSplited = implicitSplited
}
func withTime(_ time: Int) -> Keyframe {
return Keyframe(time: time, easing: easing, interpolation: interpolation, loop: loop, implicitSplited: implicitSplited)
}
func withEasing(_ easing: Easing) -> Keyframe {
return Keyframe(time: time, easing: easing, interpolation: interpolation, loop: loop, implicitSplited: implicitSplited)
}
func withInterpolation(_ interpolation: Interpolation) -> Keyframe {
return Keyframe(time: time, easing: easing, interpolation: interpolation, loop: loop, implicitSplited: implicitSplited)
}
func withLoop(_ loop: Loop) -> Keyframe {
return Keyframe(time: time, easing: easing, interpolation: interpolation, loop: loop, implicitSplited: implicitSplited)
}
static func index(time t: Int, with keyframes: [Keyframe]) -> (index: Int, interValue: Int, sectionValue: Int) {
var oldT = 0
for i in (0 ..< keyframes.count).reversed() {
let keyframe = keyframes[i]
if t >= keyframe.time {
return (i, t - keyframe.time, oldT - keyframe.time)
}
oldT = keyframe.time
}
return (0, t - keyframes.first!.time, oldT - keyframes.first!.time)
}
func equalOption(other: Keyframe) -> Bool {
return easing == other.easing && interpolation == other.interpolation && loop == other.loop
}
}
struct Loop: Equatable, ByteCoding {
let isStart: Bool, isEnd: Bool
init(isStart: Bool = false, isEnd: Bool = false) {
self.isStart = isStart
self.isEnd = isEnd
}
static func == (lhs: Loop, rhs: Loop) -> Bool {
return lhs.isStart == rhs.isStart && lhs.isEnd == rhs.isEnd
}
}
final class DrawingItem: NSObject, NSCoding, Copying {
var drawing: Drawing, color: CGColor
fileprivate(set) var keyDrawings: [Drawing]
func update(with f0: Int) {
drawing = keyDrawings[f0]
}
init(drawing: Drawing = Drawing(), keyDrawings: [Drawing] = [], color: CGColor = SceneDefaults.strokeLineColor) {
self.drawing = drawing
self.keyDrawings = keyDrawings.isEmpty ? [drawing] : keyDrawings
self.color = color
}
static let dataType = "C0.DrawingItem.1", drawingKey = "0", keyDrawingsKey = "1"
init(coder: NSCoder) {
drawing = coder.decodeObject(forKey: DrawingItem.drawingKey) as? Drawing ?? Drawing()
keyDrawings = coder.decodeObject(forKey: DrawingItem.keyDrawingsKey) as? [Drawing] ?? []
color = SceneDefaults.strokeLineColor
}
func encode(with coder: NSCoder) {
coder.encode(drawing, forKey: DrawingItem.drawingKey)
coder.encode(keyDrawings, forKey: DrawingItem.keyDrawingsKey)
}
var deepCopy: DrawingItem {
let copyDrawings = keyDrawings.map { $0.deepCopy }, copyDrawing: Drawing
if let i = keyDrawings.index(of: drawing) {
copyDrawing = copyDrawings[i]
} else {
copyDrawing = drawing.deepCopy
}
return DrawingItem(drawing: copyDrawing, keyDrawings: copyDrawings, color: color)
}
var imageBounds: CGRect {
return drawing.imageBounds(with: SceneDefaults.strokeLineWidth)
}
func draw(with di: DrawInfo, in ctx: CGContext) {
drawing.draw(lineWidth: SceneDefaults.strokeLineWidth*di.invertScale, lineColor: color, in: ctx)
}
func drawEdit(with di: DrawInfo, in ctx: CGContext) {
let lineWidth = SceneDefaults.strokeLineWidth*di.invertScale
drawing.drawRough(lineWidth: lineWidth, lineColor: SceneDefaults.roughColor, in: ctx)
drawing.draw(lineWidth: lineWidth, lineColor: color, in: ctx)
drawing.drawSelectionLines(lineWidth: lineWidth + 1.5, lineColor: SceneDefaults.selectionColor, in: ctx)
}
func drawPreviousNext(isShownPrevious: Bool, isShownNext: Bool, index: Int, with di: DrawInfo, in ctx: CGContext) {
let lineWidth = SceneDefaults.strokeLineWidth*di.invertScale
if isShownPrevious && index - 1 >= 0 {
keyDrawings[index - 1].draw(lineWidth: lineWidth, lineColor: SceneDefaults.previousColor, in: ctx)
}
if isShownNext && index + 1 <= keyDrawings.count - 1 {
keyDrawings[index + 1].draw(lineWidth: lineWidth, lineColor: SceneDefaults.nextColor, in: ctx)
}
}
}
final class CellItem: NSObject, NSCoding, Copying {
var cell: Cell
fileprivate(set) var keyGeometries: [Geometry], keyMaterials: [Material]
func replaceGeometry(_ geometry: Geometry, at i: Int) {
keyGeometries[i] = geometry
cell.geometry = geometry
}
func step(_ f0: Int) {
if !keyMaterials.isEmpty {
cell.material = keyMaterials[f0]
}
cell.geometry = keyGeometries[f0]
}
func linear(_ f0: Int, _ f1: Int, t: CGFloat) {
if !keyMaterials.isEmpty {
cell.material = Material.linear(keyMaterials[f0], keyMaterials[f1], t: t)
}
cell.geometry = Geometry.linear(keyGeometries[f0], keyGeometries[f1], t: t)
}
func firstMonospline(_ f1: Int, _ f2: Int, _ f3: Int, with msx: MonosplineX) {
if !keyMaterials.isEmpty {
cell.material = Material.firstMonospline(keyMaterials[f1], keyMaterials[f2], keyMaterials[f3], with: msx)
}
cell.geometry = Geometry.firstMonospline(keyGeometries[f1], keyGeometries[f2], keyGeometries[f3], with: msx)
}
func monospline(_ f0: Int, _ f1: Int, _ f2: Int, _ f3: Int, with msx: MonosplineX) {
if !keyMaterials.isEmpty {
cell.material = Material.monospline(keyMaterials[f0], keyMaterials[f1], keyMaterials[f2], keyMaterials[f3], with: msx)
}
cell.geometry = Geometry.monospline(keyGeometries[f0], keyGeometries[f1], keyGeometries[f2], keyGeometries[f3], with: msx)
}
func endMonospline(_ f0: Int, _ f1: Int, _ f2: Int, with msx: MonosplineX) {
if !keyMaterials.isEmpty {
cell.material = Material.endMonospline(keyMaterials[f0], keyMaterials[f1], keyMaterials[f2], with: msx)
}
cell.geometry = Geometry.endMonospline(keyGeometries[f0], keyGeometries[f1], keyGeometries[f2], with: msx)
}
init(cell: Cell, keyGeometries: [Geometry] = [], keyMaterials: [Material] = []) {
self.cell = cell
self.keyGeometries = keyGeometries
self.keyMaterials = keyMaterials
super.init()
}
static let dataType = "C0.CellItem.1", cellKey = "0", keyGeometriesKey = "1", keyMaterialsKey = "2"
init?(coder: NSCoder) {
cell = coder.decodeObject(forKey: CellItem.cellKey) as? Cell ?? Cell()
keyGeometries = coder.decodeObject(forKey: CellItem.keyGeometriesKey) as? [Geometry] ?? []
keyMaterials = coder.decodeObject(forKey: CellItem.keyMaterialsKey) as? [Material] ?? []
super.init()
}
func encode(with coder: NSCoder) {
coder.encode(cell, forKey: CellItem.cellKey)
coder.encode(keyGeometries, forKey: CellItem.keyGeometriesKey)
coder.encode(keyMaterials, forKey: CellItem.keyMaterialsKey)
}
var deepCopy: CellItem {
return CellItem(cell: cell.deepCopy, keyGeometries: keyGeometries, keyMaterials: keyMaterials)
}
var isEmptyKeyGeometries: Bool {
for keyGeometry in keyGeometries {
if !keyGeometry.lines.isEmpty {
return false
}
}
return true
}
func countRevisionLines(with lines: [Line]) -> [Line] {
return lines.enumerated().map {
var count: Int?
for keyGeometry in keyGeometries {
if $0.0 < keyGeometry.lines.count {
count = keyGeometry.lines[$0.0].count
break
}
}
if let count = count {
return countRevisionLines(newCount: count, with: $0.1, at: $0.0) ?? $0.1
} else {
return $0.1
}
}
}
private func countRevisionLines(newCount: Int, with line: Line, at index: Int) -> Line? {
if line.count != newCount {
var points = line.points
if line.count > newCount {
for _ in 0 ..< line.count - newCount {
var minIndex = 0, minDistance = CGFloat.infinity
for j in 1 ..< points.count - 1 {
let p0 = points[j - 1], p1 = points[j], p2 = points[j + 1]
let d = hypot(p1.x - p0.x, p1.y - p0.y) + hypot(p2.x - p1.x, p2.y - p1.y)
if d < minDistance {
minDistance = d
minIndex = j
}
}
points.remove(at: minIndex)
}
} else {
for _ in 0 ..< newCount - line.count {
if points.count == 2 {
points.insert(points[0].mid(points[1]), at: 1)
} else {
var maxIndex = 1, maxDistance = 0.0.cf
for j in 1 ..< points.count - 1 {
let p0 = points[j - 1], p1 = points[j], p2 = points[j + 1]
let d = hypot(p1.x - p0.x, p1.y - p0.y) + hypot(p2.x - p1.x, p2.y - p1.y)
if d > maxDistance {
maxDistance = d
maxIndex = j
}
}
let p0 = points[maxIndex - 1], p1 = points[maxIndex], p2 = points[maxIndex + 1]
points.remove(at: maxIndex)
points.insert(p0.mid(p1), at: maxIndex)
points.insert(p1.mid(p2), at: maxIndex + 1)
}
}
}
return Line(points: points, pressures: [])
}
return nil
}
}
final class TransformItem: NSObject, NSCoding, Copying {
var transform: Transform
fileprivate(set) var keyTransforms: [Transform]
func replaceTransform(_ transform: Transform, at i: Int) {
keyTransforms[i] = transform
self.transform = transform
}
func step(_ f0: Int) {
transform = keyTransforms[f0]
}
func linear(_ f0: Int, _ f1: Int, t: CGFloat) {
transform = Transform.linear(keyTransforms[f0], keyTransforms[f1], t: t)
}
func firstMonospline(_ f1: Int, _ f2: Int, _ f3: Int, with msx: MonosplineX) {
transform = Transform.firstMonospline(keyTransforms[f1], keyTransforms[f2], keyTransforms[f3], with: msx)
}
func monospline(_ f0: Int, _ f1: Int, _ f2: Int, _ f3: Int, with msx: MonosplineX) {
transform = Transform.monospline(keyTransforms[f0], keyTransforms[f1], keyTransforms[f2], keyTransforms[f3], with: msx)
}
func endMonospline(_ f0: Int, _ f1: Int, _ f2: Int, with msx: MonosplineX) {
transform = Transform.endMonospline(keyTransforms[f0], keyTransforms[f1], keyTransforms[f2], with: msx)
}
init(transform: Transform = Transform(), keyTransforms: [Transform] = [Transform()]) {
self.transform = transform
self.keyTransforms = keyTransforms
super.init()
}
static let dataType = "C0.TransformItem.1", transformKey = "0", keyTransformsKey = "1"
init(coder: NSCoder) {
transform = coder.decodeStruct(forKey: TransformItem.transformKey) ?? Transform()
keyTransforms = coder.decodeStruct(forKey: TransformItem.keyTransformsKey) ?? []
super.init()
}
func encode(with coder: NSCoder) {
coder.encodeStruct(transform, forKey: TransformItem.transformKey)
coder.encodeStruct(keyTransforms, forKey: TransformItem.keyTransformsKey)
}
static func empty(with group: Group) -> TransformItem {
let transformItem = TransformItem()
let transforms = group.keyframes.map { _ in Transform() }
transformItem.keyTransforms = transforms
transformItem.transform = transforms[group.editKeyframeIndex]
return transformItem
}
var deepCopy: TransformItem {
return TransformItem(transform: transform, keyTransforms: keyTransforms)
}
var isEmpty: Bool {
for t in keyTransforms {
if !t.isEmpty {
return false
}
}
return true
}
}
final class TextItem: NSObject, NSCoding, Copying {
var text: Text
fileprivate(set) var keyTexts: [Text]
func replaceText(_ text: Text, at i: Int) {
keyTexts[i] = text
self.text = text
}
func update(with f0: Int) {
text = keyTexts[f0]
}
init(text: Text = Text(), keyTexts: [Text] = [Text()]) {
self.text = text
self.keyTexts = keyTexts
super.init()
}
static let dataType = "C0.TextItem.1", textKey = "0", keyTextsKey = "1"
init?(coder: NSCoder) {
text = coder.decodeObject(forKey: TextItem.textKey) as? Text ?? Text()
keyTexts = coder.decodeObject(forKey: TextItem.keyTextsKey) as? [Text] ?? []
}
func encode(with coder: NSCoder) {
coder.encode(text, forKey: TextItem.textKey)
coder.encode(keyTexts, forKey: TextItem.keyTextsKey)
}
var deepCopy: TextItem {
return TextItem(text: text, keyTexts: keyTexts)
}
var isEmpty: Bool {
for t in keyTexts {
if !t.isEmpty {
return false
}
}
return true
}
}
final class SoundItem: NSObject, NSCoding, Copying {
var sound: NSSound?
var name = ""
var isHidden = false {
didSet {
sound?.volume = isHidden ? 0 : 1
}
}
init(sound: NSSound? = nil, name: String = "", isHidden: Bool = false) {
self.sound = sound
self.name = name
self.isHidden = isHidden
super.init()
}
static let dataType = "C0.SoundItem.1", soundKey = "0", nameKey = "1", isHiddenKey = "2"
init?(coder: NSCoder) {
sound = coder.decodeObject(forKey:SoundItem.soundKey) as? NSSound
name = coder.decodeObject(forKey: SoundItem.nameKey) as? String ?? ""
isHidden = coder.decodeBool(forKey: SoundItem.isHiddenKey)
}
func encode(with coder: NSCoder) {
coder.encode(sound, forKey: SoundItem.soundKey)
coder.encode(name, forKey: SoundItem.nameKey)
coder.encode(isHidden, forKey: SoundItem.isHiddenKey)
}
var deepCopy: SoundItem {
return SoundItem(sound: sound?.copy(with: nil) as? NSSound, name: name, isHidden: isHidden)
}
}
struct Transform: Equatable, ByteCoding, Interpolatable {
let position: CGPoint, scale: CGSize, zoomScale: CGSize, rotation: CGFloat, wiggle: Wiggle
init(position: CGPoint = CGPoint(), scale: CGSize = CGSize(), rotation: CGFloat = 0, wiggle: Wiggle = Wiggle()) {
self.position = position
self.scale = scale
self.rotation = rotation
self.wiggle = wiggle
self.zoomScale = CGSize(width: pow(2, scale.width), height: pow(2, scale.height))
}
static let dataType = "C0.Transform.1"
func withPosition(_ position: CGPoint) -> Transform {
return Transform(position: position, scale: scale, rotation: rotation, wiggle: wiggle)
}
func withScale(_ scale: CGFloat) -> Transform {
return Transform(position: position, scale: CGSize(width: scale, height: scale), rotation: rotation, wiggle: wiggle)
}
func withScale(_ scale: CGSize) -> Transform {
return Transform(position: position, scale: scale, rotation: rotation, wiggle: wiggle)
}
func withRotation(_ rotation: CGFloat) -> Transform {
return Transform(position: position, scale: scale, rotation: rotation, wiggle: wiggle)
}
func withWiggle(_ wiggle: Wiggle) -> Transform {
return Transform(position: position, scale: scale, rotation: rotation, wiggle: wiggle)
}
static func linear(_ f0: Transform, _ f1: Transform, t: CGFloat) -> Transform {
let newPosition = CGPoint.linear(f0.position, f1.position, t: t)
let newScaleX = CGFloat.linear(f0.scale.width, f1.scale.width, t: t)
let newScaleY = CGFloat.linear(f0.scale.height, f1.scale.height, t: t)
let newRotation = CGFloat.linear(f0.rotation, f1.rotation, t: t)
let newWiggle = Wiggle.linear(f0.wiggle, f1.wiggle, t: t)
return Transform(position: newPosition, scale: CGSize(width: newScaleX, height: newScaleY), rotation: newRotation, wiggle: newWiggle)
}
static func firstMonospline(_ f1: Transform, _ f2: Transform, _ f3: Transform, with msx: MonosplineX) -> Transform {
let newPosition = CGPoint.firstMonospline(f1.position, f2.position, f3.position, with: msx)
let newScaleX = CGFloat.firstMonospline(f1.scale.width, f2.scale.width, f3.scale.width, with: msx)
let newScaleY = CGFloat.firstMonospline(f1.scale.height, f2.scale.height, f3.scale.height, with: msx)
let newRotation = CGFloat.firstMonospline(f1.rotation, f2.rotation, f3.rotation, with: msx)
let newWiggle = Wiggle.firstMonospline(f1.wiggle, f2.wiggle, f3.wiggle, with: msx)
return Transform(position: newPosition, scale: CGSize(width: newScaleX, height: newScaleY), rotation: newRotation, wiggle: newWiggle)
}
static func monospline(_ f0: Transform, _ f1: Transform, _ f2: Transform, _ f3: Transform, with msx: MonosplineX) -> Transform {
let newPosition = CGPoint.monospline(f0.position, f1.position, f2.position, f3.position, with: msx)
let newScaleX = CGFloat.monospline(f0.scale.width, f1.scale.width, f2.scale.width, f3.scale.width, with: msx)
let newScaleY = CGFloat.monospline(f0.scale.height, f1.scale.height, f2.scale.height, f3.scale.height, with: msx)
let newRotation = CGFloat.monospline(f0.rotation, f1.rotation, f2.rotation, f3.rotation, with: msx)
let newWiggle = Wiggle.monospline(f0.wiggle, f1.wiggle, f2.wiggle, f3.wiggle, with: msx)
return Transform(position: newPosition, scale: CGSize(width: newScaleX, height: newScaleY), rotation: newRotation, wiggle: newWiggle)
}
static func endMonospline(_ f0: Transform, _ f1: Transform, _ f2: Transform, with msx: MonosplineX) -> Transform {
let newPosition = CGPoint.endMonospline(f0.position, f1.position, f2.position, with: msx)
let newScaleX = CGFloat.endMonospline(f0.scale.width, f1.scale.width, f2.scale.width, with: msx)
let newScaleY = CGFloat.endMonospline(f0.scale.height, f1.scale.height, f2.scale.height, with: msx)
let newRotation = CGFloat.endMonospline(f0.rotation, f1.rotation, f2.rotation, with: msx)
let newWiggle = Wiggle.endMonospline(f0.wiggle, f1.wiggle, f2.wiggle, with: msx)
return Transform(position: newPosition, scale: CGSize(width: newScaleX, height: newScaleY), rotation: newRotation, wiggle: newWiggle)
}
var isEmpty: Bool {
return position == CGPoint() && scale == CGSize() && rotation == 0 && !wiggle.isMove
}
func affineTransform(with bounds: CGRect) -> CGAffineTransform {
var affine = CGAffineTransform(translationX: bounds.width/2, y: bounds.height/2)
if rotation != 0 {
affine = affine.rotated(by: rotation)
}
if scale != CGSize() {
affine = affine.scaledBy(x: zoomScale.width, y: zoomScale.height)
}
return affine.translatedBy(x: position.x - bounds.width/2, y: position.y - bounds.height/2)
}
static func == (lhs: Transform, rhs: Transform) -> Bool {
return lhs.position == rhs.position && lhs.scale == rhs.scale && lhs.rotation == rhs.rotation && lhs.wiggle == rhs.wiggle
}
}
struct Wiggle: Equatable, Interpolatable {
let maxSize: CGSize, hz: CGFloat
init(maxSize: CGSize = CGSize(), hz: CGFloat = 8) {
self.maxSize = maxSize
self.hz = hz
}
func withMaxSize(_ maxSize: CGSize) -> Wiggle {
return Wiggle(maxSize: maxSize, hz: hz)
}
func withHz(_ hz: CGFloat) -> Wiggle {
return Wiggle(maxSize: maxSize, hz: hz)
}
static func linear(_ f0: Wiggle, _ f1: Wiggle, t: CGFloat) -> Wiggle {
let newMaxWidth = CGFloat.linear(f0.maxSize.width, f1.maxSize.width, t: t)
let newMaxHeight = CGFloat.linear(f0.maxSize.height, f1.maxSize.height, t: t)
let newHz = CGFloat.linear(f0.hz, f1.hz, t: t)
return Wiggle(maxSize: CGSize(width: newMaxWidth, height: newMaxHeight), hz: newHz)
}
static func firstMonospline(_ f1: Wiggle, _ f2: Wiggle, _ f3: Wiggle, with msx: MonosplineX) -> Wiggle {
let newMaxWidth = CGFloat.firstMonospline(f1.maxSize.width, f2.maxSize.width, f3.maxSize.width, with: msx)
let newMaxHeight = CGFloat.firstMonospline(f1.maxSize.height, f2.maxSize.height, f3.maxSize.height, with: msx)
let newHz = CGFloat.firstMonospline(f1.hz, f2.hz, f3.hz, with: msx)
return Wiggle(maxSize: CGSize(width: newMaxWidth, height: newMaxHeight), hz: newHz)
}
static func monospline(_ f0: Wiggle, _ f1: Wiggle, _ f2: Wiggle, _ f3: Wiggle, with msx: MonosplineX) -> Wiggle {
let newMaxWidth = CGFloat.monospline(f0.maxSize.width, f1.maxSize.width, f2.maxSize.width, f3.maxSize.width, with: msx)
let newMaxHeight = CGFloat.monospline(f0.maxSize.height, f1.maxSize.height, f2.maxSize.height, f3.maxSize.height, with: msx)
let newHz = CGFloat.monospline(f0.hz, f1.hz, f2.hz, f3.hz, with: msx)
return Wiggle(maxSize: CGSize(width: newMaxWidth, height: newMaxHeight), hz: newHz)
}
static func endMonospline(_ f0: Wiggle, _ f1: Wiggle, _ f2: Wiggle, with msx: MonosplineX) -> Wiggle {
let newMaxWidth = CGFloat.endMonospline(f0.maxSize.width, f1.maxSize.width, f2.maxSize.width, with: msx)
let newMaxHeight = CGFloat.endMonospline(f0.maxSize.height, f1.maxSize.height, f2.maxSize.height, with: msx)
let newHz = CGFloat.endMonospline(f0.hz, f1.hz, f2.hz, with: msx)
return Wiggle(maxSize: CGSize(width: newMaxWidth, height: newMaxHeight), hz: newHz)
}
var isMove: Bool {
return maxSize != CGSize()
}
func newPosition(_ position: CGPoint, phase: CGFloat) -> CGPoint {
let x = sin(2*(.pi)*phase)
return CGPoint(x: position.x + maxSize.width*x, y: position.y + maxSize.height*x)
}
static func == (lhs: Wiggle, rhs: Wiggle) -> Bool {
return lhs.maxSize == rhs.maxSize && lhs.hz == rhs.hz
}
}
final class Text: NSObject, NSCoding {
let string: String
init(string: String = "") {
self.string = string
super.init()
}
static let dataType = "C0.Text.1", stringKey = "0"
init?(coder: NSCoder) {
string = coder.decodeObject(forKey: Text.stringKey) as? String ?? ""
super.init()
}
func encode(with coder: NSCoder) {
coder.encode(string, forKey: Text.stringKey)
}
var isEmpty: Bool {
return string.isEmpty
}
let borderColor = SceneDefaults.speechBorderColor, fillColor = SceneDefaults.speechFillColor
func draw(bounds: CGRect, in ctx: CGContext) {
let attString = NSAttributedString(string: string, attributes: [
String(kCTFontAttributeName): SceneDefaults.speechFont,
String(kCTForegroundColorFromContextAttributeName): true
])
let framesetter = CTFramesetterCreateWithAttributedString(attString)
let range = CFRange(location: 0, length: attString.length), ratio = bounds.size.width/640
let lineBounds = CGRect(origin: CGPoint(), size: CTFramesetterSuggestFrameSizeWithConstraints(framesetter, range, nil, CGSize(width: CGFloat.infinity, height: CGFloat.infinity), nil))
let ctFrame = CTFramesetterCreateFrame(framesetter, range, CGPath(rect: lineBounds, transform: nil), nil)
ctx.saveGState()
ctx.translateBy(x: round(bounds.midX - lineBounds.midX), y: round(bounds.minY + 20*ratio))
ctx.setTextDrawingMode(.stroke)
ctx.setLineWidth(ceil(3*ratio))
ctx.setStrokeColor(borderColor)
CTFrameDraw(ctFrame, ctx)
ctx.setTextDrawingMode(.fill)
ctx.setFillColor(fillColor)
CTFrameDraw(ctFrame, ctx)
ctx.restoreGState()
}
}
|
gpl-3.0
|
c8ae54e3a26defd48e62b719d5c09244
| 44.763703 | 288 | 0.592685 | 4.133336 | false | false | false | false |
athiercelin/Simplistic
|
iOS/Simplistic WatchKit Extension/InterfaceController+ApplicationContext.swift
|
1
|
2385
|
//
// InterfaceController+ApplicationContext.swift
// Simplistic
//
// Created by Arnaud Thiercelin on 11/21/15.
// Copyright © 2015 Arnaud Thiercelin. All rights reserved.
//
import Foundation
import WatchKit
import WatchConnectivity
extension InterfaceController {
func setApplicationContext() {
NSLog("Setting the Application Context")
var itemId = 0
var newArray = [[String:AnyObject]]()
while let rowController = self.mainTable.rowController(at: itemId) {
let itemRowController = rowController as! ItemsRowController
let newDictionary:[String:AnyObject] = ["label" : itemRowController.labelString,
"done" : itemRowController.doneStatus]
newArray.append(newDictionary)
itemId
}
do {
try self.session!.updateApplicationContext(["result":newArray])
} catch {
NSLog("Error setting the application context")
}
}
func useApplicationContext(applicationContext: [String : AnyObject]) {
let arrayResults = applicationContext["result"]
guard arrayResults != nil else {
return
}
NSLog("data received: %@", arrayResults as! NSArray)
dispatchMain() { () -> Void in
let numberOfItems = arrayResults!.count
self.mainTable.setNumberOfRows(numberOfItems!, withRowType: "ItemsRow")
for index in 0 ..< self.mainTable.numberOfRows {
let dictionary = arrayResults?.objectAtIndex(index)
let rowController = self.mainTable.rowControllerAtIndex(index) as! ItemsRowController
let done = dictionary?.objectForKey("done") as! Bool
let label = dictionary?.objectForKey("label") as? String
let doneChanged = done != rowController.doneStatus
let labelChanged = label! != rowController.labelString
if doneChanged || labelChanged {
rowController.doneStatus = done
rowController.labelString = label!
let attributedText = NSMutableAttributedString(string: label!)
if done == false {
rowController.label.setAttributedText(attributedText)
rowController.label.setTextColor(self.cellUnDoneTextColor)
} else {
attributedText.addAttribute(NSStrikethroughStyleAttributeName, value: 2, range: NSMakeRange(0, label!.characters.count))
rowController.label.setAttributedText(attributedText)
rowController.label.setTextColor(self.cellDoneTextcolor)
}
rowController.label.setHidden(false)
}
}
}
}
}
|
mit
|
45dee2b69a72e5da0fb9cf4e603b09ad
| 29.177215 | 126 | 0.721477 | 4.382353 | false | false | false | false |
vishakhajadhav/HTTPRequest
|
HTTPRequest/ResultFormat.swift
|
1
|
1679
|
//
// ResultFormat.swift
//
// Create by Piyush on 7/6/2016
// Copyright © 2016 Kahuna Systems. All rights reserved.
//
import Foundation
class ResultFormat : NSObject{
var cause : String!
var code : Int!
var message : String!
/**
* Instantiate the instance using the passed dictionary values to set the properties values
*/
init(fromDictionary dictionary: NSDictionary){
cause = dictionary["cause"] as? String
code = dictionary["code"] as? Int
message = dictionary["message"] as? String
}
/**
* Returns all the available property values in the form of NSDictionary object where the key is the approperiate json key and the value is the value of the corresponding property
*/
func toDictionary() -> NSDictionary
{
let dictionary = NSMutableDictionary()
if cause != nil{
dictionary["cause"] = cause
}
if code != nil{
dictionary["code"] = code
}
if message != nil{
dictionary["message"] = message
}
return dictionary
}
/**
* NSCoding required initializer.
* Fills the data from the passed decoder
*/
@objc required init(coder aDecoder: NSCoder)
{
cause = aDecoder.decodeObject(forKey: "cause") as? String
code = aDecoder.decodeObject(forKey: "code") as? Int
message = aDecoder.decodeObject(forKey: "message") as? String
}
/**
* NSCoding required method.
* Encodes mode properties into the decoder
*/
@objc func encodeWithCoder(aCoder: NSCoder)
{
if cause != nil{
aCoder.encode(cause, forKey: "cause")
}
if code != nil{
aCoder.encode(code, forKey: "code")
}
if message != nil{
aCoder.encode(message, forKey: "message")
}
}
}
|
mit
|
2bc0619a6072f01622c2e1e119c082a2
| 21.675676 | 180 | 0.663886 | 3.78781 | false | false | false | false |
EaglesoftZJ/actor-platform
|
actor-sdk/sdk-core-ios/ActorSDK/Sources/Controllers/Settings/AASettingsViewController.swift
|
1
|
20495
|
//
// Copyright (c) 2014-2016 Actor LLC. <https://actor.im>
//
import UIKit
import MobileCoreServices
open class AASettingsViewController: AAContentTableController {
fileprivate var phonesCells: AAManagedArrayRows<ACUserPhone, AATitledCell>!
fileprivate var emailCells: AAManagedArrayRows<ACUserEmail, AATitledCell>!
fileprivate var headerCell: AAAvatarRow!
fileprivate var nicknameCell: AATitledRow!
fileprivate var aboutCell: AATitledRow!
public init() {
super.init(style: AAContentTableStyle.settingsPlain)
uid = Int(Actor.myUid())
content = ACAllEvents_Main.settings()
tabBarItem = UITabBarItem(title: "TabSettings", img: "TabIconSettings", selImage: "TabIconSettingsHighlighted")
navigationItem.title = AALocalized("TabSettings")
}
public required init(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
open override func tableDidLoad() {
// Profile
_ = section { [unowned self] (s) -> () in
// Profile: Photo and name
self.headerCell = s.avatar() { [unowned self] (r) -> () in
r.bindAction = { [unowned self] (r) -> () in
let upload = Actor.getOwnAvatarVM()!.uploadState.get() as? ACAvatarUploadState
let avatar = self.user.getAvatarModel().get()
let presence = self.user.getPresenceModel().get()
let presenceText = Actor.getFormatter().formatPresence(presence, with: self.user.getSex())
let name = self.user.getNameModel().get()
r.id = self.uid
r.title = name
if (upload != nil && upload!.isUploading) {
r.avatar = nil
r.avatarPath = upload!.descriptor
r.avatarLoading = true
} else {
r.avatar = avatar
r.avatarPath = nil
r.avatarLoading = false
}
if presenceText != nil {
r.subtitle = presenceText
if presence!.state.ordinal() == ACUserPresence_State.online().ordinal() {
r.subtitleColor = ActorSDK.sharedActor().style.userOnlineColor
} else {
r.subtitleColor = ActorSDK.sharedActor().style.userOfflineColor
}
} else {
r.subtitle = ""
}
}
r.avatarDidTap = { [unowned self] (view: UIView) -> () in
let avatar = self.user.getAvatarModel().get()
if avatar != nil && avatar?.fullImage != nil {
let full = avatar?.fullImage.fileReference
let small = avatar?.smallImage.fileReference
let size = CGSize(width: Int((avatar?.fullImage.width)!), height: Int((avatar?.fullImage.height)!))
self.present(AAPhotoPreviewController(file: full!, previewFile: small, size: size, fromView: view), animated: true, completion: nil)
}
}
}
// Profile: Set Photo
_ = s.action("SettingsSetPhoto") { [unowned self] (r) -> () in
r.selectAction = { [unowned self] () -> Bool in
let hasCamera = UIImagePickerController.isSourceTypeAvailable(UIImagePickerControllerSourceType.camera)
let view = self.tableView.cellForRow(at: IndexPath(row: 1, section: 0))!.contentView
self.showActionSheet(hasCamera ? ["PhotoCamera", "PhotoLibrary"] : ["PhotoLibrary"],
cancelButton: "AlertCancel",
destructButton: self.user.getAvatarModel().get() != nil ? "PhotoRemove" : nil,
sourceView: view,
sourceRect: view.bounds,
tapClosure: { [unowned self] (index) -> () in
if index == -2 {
self.confirmAlertUser("PhotoRemoveGroupMessage",
action: "PhotoRemove",
tapYes: { () -> () in
Actor.removeMyAvatar()
}, tapNo: nil)
} else if index >= 0 {
let takePhoto: Bool = (index == 0) && hasCamera
self.pickAvatar(takePhoto, closure: { (image) -> () in
Actor.changeOwnAvatar(image)
})
}
})
return true
}
}
// Profile: Set Name
// s.action("SettingsChangeName") { [unowned self] (r) -> () in
// r.selectAction = { [unowned self] () -> Bool in
//
// self.startEditField { (c) -> () in
// c.title = "SettingsEditHeader"
// c.hint = "SettingsEditHint"
//
// c.initialText = self.user.getNameModel().get()
//
// c.fieldAutocapitalizationType = .words
// c.fieldHint = "SettingsEditFieldHint"
//
// c.didDoneTap = { (t, c) -> () in
//
// if t.length == 0 {
// return
// }
//
// c.executeSafeOnlySuccess(Actor.editMyNameCommand(withName: t)!) { (val) -> Void in
// c.dismissController()
// }
// }
// }
//
// return true
// }
// }
ActorSDK.sharedActor().delegate.actorSettingsHeaderDidCreated(self, section: s)
}
// Settings
_ = section { (s) -> () in
ActorSDK.sharedActor().delegate.actorSettingsConfigurationWillCreated(self, section: s)
// Settings: Notifications
_ = s.navigate("SettingsNotifications", controller: AASettingsNotificationsViewController.self)
// Settings: Media Settings
_ = s.navigate("SettingsMedia", controller: AASettingsMediaViewController.self)
// Settings: Security
_ = s.navigate("SettingsSecurity", controller: AASettingsPrivacyViewController.self)
// Settings: Wallpapper
_ = s.custom({ [unowned self] (r: AACustomRow<AAWallpapperSettingsCell>) -> () in
r.height = 230
r.closure = { [unowned self] (cell) -> () in
cell.wallpapperDidTap = { [unowned self] (name) -> () in
self.present(AAWallpapperPreviewController(imageName: name), animated: true, completion: nil)
}
cell.bind()
}
r.selectAction = { () -> Bool in
self.navigateNext(AASettingsWallpapersController(), removeCurrent: false)
return false
}
})
ActorSDK.sharedActor().delegate.actorSettingsConfigurationDidCreated(self, section: s)
}
// Contacts
_ = section { [unowned self] (s) -> () in
// Contacts: Nicknames
self.nicknameCell = s.titled("ProfileUsername") { [unowned self] (r) -> () in
r.accessoryType = .disclosureIndicator
r.bindAction = { [unowned self] (r) -> () in
if let nick = self.user.getNickModel().get() {
r.subtitle = "@\(nick)"
r.isAction = false
} else {
r.subtitle = AALocalized("SettingsUsernameNotSet")
r.isAction = true
}
}
r.selectAction = { [unowned self] () -> Bool in
self.startEditField { (c) -> () in
c.title = "SettingsUsernameTitle"
c.actionTitle = "AlertSave"
if let nick = self.user.getNickModel().get() {
c.initialText = nick
}
c.fieldHint = "SettingsUsernameHintField"
c.fieldAutocorrectionType = .no
c.fieldAutocapitalizationType = .none
c.hint = "SettingsUsernameHint"
c.didDoneTap = { (t, c) -> () in
var nNick: String? = t.trim()
if nNick?.length == 0 {
nNick = nil
}
c.executeSafeOnlySuccess(Actor.editMyNickCommand(withNick: nNick)!, successBlock: { (val) -> Void in
c.dismissController()
})
}
}
return AADevice.isiPad
}
}
// Contacts: About
self.aboutCell = s.titled("ProfileAbout") { [unowned self] (r) -> () in
r.accessoryType = .disclosureIndicator
r.bindAction = { [unowned self] (r) -> () in
if let about = self.user.getAboutModel().get() {
r.subtitle = about
r.isAction = false
} else {
r.subtitle = AALocalized("SettingsAboutNotSet")
r.isAction = true
}
}
r.selectAction = { [unowned self] () -> Bool in
self.startEditText { (config) -> () in
config.title = "SettingsChangeAboutTitle"
config.hint = "SettingsChangeAboutHint"
config.actionTitle = "NavigationSave"
config.initialText = self.user.getAboutModel().get()
config.didCompleteTap = { (text, controller) -> () in
var updatedText: String? = text.trim()
if updatedText?.length == 0 {
updatedText = nil
}
controller.executeSafeOnlySuccess(Actor.editMyAboutCommand(withNick: updatedText)!, successBlock: { (val) -> Void in
controller.dismissController()
})
}
}
return AADevice.isiPad
}
}
// Profile: Phones
self.phonesCells = s.arrays() { (r: AAManagedArrayRows<ACUserPhone, AATitledCell>) -> () in
r.height = 55
r.data = self.user.getPhonesModel().get().toSwiftArray()
r.bindData = { (c: AATitledCell, d: ACUserPhone) -> () in
c.setContent(AALocalized("SettingsMobilePhone"), content: "+\(d.phone)", isAction: false)
c.accessoryType = .none
}
r.bindCopy = { (d: ACUserPhone) -> String? in
return "+\(d.phone)"
}
r.selectAction = { [unowned self] (d: ACUserPhone) -> Bool in
let hasPhone = UIApplication.shared.canOpenURL(URL(string: "telprompt://")!)
if (!hasPhone) {
UIPasteboard.general.string = "+\(d.phone)"
self.alertUser("NumberCopied")
}
return true
}
}
self.emailCells = s.arrays() { (r: AAManagedArrayRows<ACUserEmail, AATitledCell>) -> () in
r.height = 55
r.data = self.user.getEmailsModel().get().toSwiftArray()
r.bindData = { (c: AATitledCell, d: ACUserEmail) -> () in
c.setContent(d.title, content: d.email, isAction: false)
c.accessoryType = .none
}
r.bindCopy = { (d: ACUserEmail) -> String? in
return d.email
}
r.selectAction = { (d: ACUserEmail) -> Bool in
ActorSDK.sharedActor().openUrl("mailto:\(d.email)")
return true
}
}
}
// Support
_ = section { (s) -> () in
ActorSDK.sharedActor().delegate.actorSettingsSupportWillCreated(self, section: s)
// Support: Ask Question
if let account = ActorSDK.sharedActor().supportAccount {
_ = s.navigate("SettingsAskQuestion", closure: { (r) -> () in
r.selectAction = { () -> Bool in
self.executeSafe(Actor.findUsersCommand(withQuery: account)) { (val) -> Void in
var user:ACUserVM!
if let users = val as? IOSObjectArray {
if Int(users.length()) > 0 {
if let tempUser = users.object(at: 0) as? ACUserVM {
user = tempUser
}
}
}
if let customController = ActorSDK.sharedActor().delegate.actorControllerForConversation(ACPeer.user(with: user.getId())) {
self.navigateDetail(customController)
} else {
self.navigateDetail(ConversationViewController(peer: ACPeer.user(with: user.getId())))
}
}
return true
}
})
}
// Support: Twitter
// if let twitter = ActorSDK.sharedActor().supportTwitter {
// s.url("SettingsTwitter", url: "https://twitter.com/\(twitter)")
// }
// Support: Home page
if let homePage = ActorSDK.sharedActor().supportHomepage {
_ = s.url("SettingsAbout", url: homePage)
}
// Support: App version
let version = Bundle.main.infoDictionary!["CFBundleShortVersionString"] as! String
_ = s.hint(AALocalized("SettingsVersion").replace("{version}", dest: version))
ActorSDK.sharedActor().delegate.actorSettingsSupportDidCreated(self, section: s)
}
//退出登录
_ = section { (s) -> () in
_ = s.action("退出登录") { [unowned self] (r) -> () in
r.selectAction = { [unowned self] () -> Bool in
let alertController = UIAlertController(title: "退出登录", message: "确认退出?",preferredStyle: .actionSheet)
let cancelAction = UIAlertAction(title: "取消", style: .cancel, handler: nil)
let deleteAction = UIAlertAction(title: "确认", style: .destructive, handler: {
(action: UIAlertAction) -> Void in
self.confirmAlertUser("APP会自动退出,然后请自行打开。", action: "确定", tapYes: {
self.exitApp()
})
})
alertController.addAction(cancelAction)
alertController.addAction(deleteAction)
self.present(alertController, animated: true, completion: nil)
return true
}
}
ActorSDK.sharedActor().delegate.actorSettingsConfigurationDidCreated(self, section: s)
}
}
open func exitApp() {
let dbPath:String = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0].asNS.appendingPathComponent("actor.db")
let db = FMDatabase(path: dbPath)
db?.open()
let rs:FMResultSet = (db?.executeQuery("select 'drop table ' || name || ';' as yj from sqlite_master where type = 'table';"))!
var dropTable:String = ""
while rs.next() {
let drop:String = rs.string(forColumn: "yj")
dropTable = dropTable + drop
}
// print("这是"+dropTable+"======")
db?.executeStatements(dropTable)
db?.close()
UDPreferencesStorage().clear()
let window:UIWindow = ((UIApplication.shared.delegate?.window)!)!
UIView.animate(withDuration: 1.0, animations: {
window.alpha = 0
window.frame = CGRect(x: 0, y: window.bounds.size.width, width: 0, height: 0)
}) { (finished) in
exit(0)
}
// let window:UIWindow = ((UIApplication.shared.delegate?.window)!)!
// window.rootViewController = LoginViewController()
}
func clearCache(cachePath :String) {
// 取出cache文件夹目录 缓存文件都在这个目录下
// 取出文件夹下所有文件数组
let fileArr = FileManager.default.subpaths(atPath: cachePath)
// 遍历删除
for file in fileArr! {
let path = cachePath + "/\(file)"
if FileManager.default.fileExists(atPath: path) {
do {
try FileManager.default.removeItem(atPath: path)
} catch {
}
}
}
}
open override func tableWillBind(_ binder: AABinder) {
// Header
binder.bind(user.getNameModel()) { [unowned self] (value: String?) -> () in
self.headerCell.reload()
}
binder.bind(user.getAvatarModel()) { [unowned self] (value: ACAvatar?) -> () in
self.headerCell.reload()
}
binder.bind(Actor.getOwnAvatarVM()!.uploadState) { [unowned self] (value: ACAvatarUploadState?) -> () in
self.headerCell.reload()
}
binder.bind(user.getPresenceModel()) { [unowned self] (presence: ACUserPresence?) -> () in
self.headerCell.reload()
}
// Bind nick
binder.bind(user.getNickModel()) { [unowned self] (value: String?) -> () in
self.nicknameCell.reload()
}
// Bind about
binder.bind(user.getAboutModel()) { [unowned self] (value: String?) -> () in
self.aboutCell.reload()
}
// Bind Phone
binder.bind(user.getPhonesModel(), closure: { [unowned self] (phones: ACArrayListUserPhone?) -> () in
self.phonesCells.data = (phones?.toSwiftArray())!
self.phonesCells.reload()
})
// Bind Email
binder.bind(user.getEmailsModel(), closure: { [unowned self] (emails: ACArrayListUserEmail?) -> () in
self.emailCells.data = (emails?.toSwiftArray())!
self.emailCells.reload()
})
}
}
|
agpl-3.0
|
33fc18b3567cc118812b9b42983e7e18
| 41.051653 | 156 | 0.447109 | 5.458032 | false | false | false | false |
TheInfiniteKind/duckduckgo-iOS
|
Core/DateFilter.swift
|
1
|
553
|
//
// DateFilter.swift
// DuckDuckGo
//
// Created by Mia Alexiou on 29/03/2017.
// Copyright © 2017 DuckDuckGo. All rights reserved.
//
import Foundation
public enum DateFilter: String {
case any = ""
case day = "d"
case week = "w"
case month = "m"
public static func all() -> [DateFilter] {
return [any, day, week, month]
}
public static func forKey(_ key: String?) -> DateFilter {
guard let key = key else { return .any }
return DateFilter.init(rawValue: key) ?? .any
}
}
|
apache-2.0
|
875318927e584bddf07517aedb6b8f72
| 20.230769 | 61 | 0.583333 | 3.72973 | false | false | false | false |
ralcr/Localizabler
|
LocalizablerXcodePlugin/LocalizablerXcodePlugin.swift
|
1
|
1239
|
//
// LocalizablerXcodePlugin.swift
//
// Created by Cristian Baluta on 25/11/15.
// Copyright © 2015 Cristian Baluta. All rights reserved.
//
import AppKit
var sharedPlugin: LocalizablerXcodePlugin?
class LocalizablerXcodePlugin: NSObject {
var bundle: NSBundle
lazy var center = NSNotificationCenter.defaultCenter()
init(bundle: NSBundle) {
self.bundle = bundle
super.init()
center.addObserver(self, selector: Selector("createMenuItems"), name: NSApplicationDidFinishLaunchingNotification, object: nil)
}
deinit {
removeObserver()
}
func removeObserver() {
center.removeObserver(self)
}
func createMenuItems() {
removeObserver()
var item = NSApp.mainMenu!!.itemWithTitle("Edit")
if item != nil {
var actionMenuItem = NSMenuItem(title:"Do Action", action:"doMenuAction", keyEquivalent:"")
actionMenuItem.target = self
item!.submenu!.addItem(NSMenuItem.separatorItem())
item!.submenu!.addItem(actionMenuItem)
}
}
func doMenuAction() {
let error = NSError(domain: "Hello World!", code:42, userInfo:nil)
NSAlert(error: error).runModal()
}
}
|
mit
|
2eff8daa471ce42f8af92b171b18ce5d
| 24.265306 | 135 | 0.647011 | 4.568266 | false | false | false | false |
skylib/SnapImagePicker
|
SnapImagePicker_Unit_Tests/TestDoubles/ImagePicker/SnapImagePickerViewControllerSpy.swift
|
1
|
1047
|
@testable import SnapImagePicker
class SnapImagePickerViewControllerSpy {
var _albumTitle: String = ""
var albumTitleGetCount = 0
var albumTitleSetCount = 0
var displayMainImageCount = 0
var displayMainImageImage: SnapImagePickerImage?
var reloadCellAtIndexesCount = 0
var reloadCellAtIndexesIndexes: [Int]?
var reloadAlbumCount = 0
}
extension SnapImagePickerViewControllerSpy: SnapImagePickerViewControllerProtocol {
var albumTitle: String {
get {
albumTitleGetCount += 1
return _albumTitle
}
set {
albumTitleSetCount += 1
_albumTitle = newValue
}
}
func displayMainImage(_ mainImage: SnapImagePickerImage) {
displayMainImageCount += 1
displayMainImageImage = mainImage
}
func reloadCellAtIndexes(_ index: [Int]) {
reloadCellAtIndexesCount += 1
reloadCellAtIndexesIndexes = index
}
func reloadAlbum() {
reloadAlbumCount += 1
}
}
|
bsd-3-clause
|
8e23849520780affe57a37495b11c668
| 23.928571 | 83 | 0.642789 | 5.314721 | false | false | false | false |
ngageoint/mage-ios
|
Mage/ObservationSyncStatus.swift
|
1
|
5833
|
//
// ObservationSyncStatus.swift
// MAGE
//
// Created by Daniel Barela on 12/22/20.
// Copyright © 2020 National Geospatial Intelligence Agency. All rights reserved.
//
import Foundation
import MaterialComponents.MDCBannerView
import MaterialComponents.MDCPalettes
class ObservationSyncStatus: UIView {
private var didSetupConstraints = false;
private weak var observation: Observation?;
private var manualSync: Bool = false;
private var scheme: MDCContainerScheming?;
private lazy var syncStatusView: MDCBannerView = {
let syncStatusView = MDCBannerView(forAutoLayout: ());
syncStatusView.bannerViewLayoutStyle = .singleRow;
syncStatusView.trailingButton.isHidden = true;
syncStatusView.imageView.isHidden = false;
syncStatusView.imageView.contentMode = .center;
return syncStatusView;
}();
func applyTheme(withScheme scheme: MDCContainerScheming?) {
guard let scheme = scheme else {
return
}
self.scheme = scheme;
self.backgroundColor = scheme.colorScheme.surfaceColor;
syncStatusView.applyTheme(withScheme: scheme);
if (observation?.hasValidationError ?? false) {
syncStatusView.textView.textColor = scheme.colorScheme.errorColor;
syncStatusView.imageView.tintColor = scheme.colorScheme.errorColor;
} else if (!(observation?.isDirty ?? false) && observation?.error == nil) {
syncStatusView.textView.textColor = MDCPalette.green.accent700;
syncStatusView.imageView.tintColor = MDCPalette.green.accent700;
} else if (manualSync) {
syncStatusView.textView.textColor = scheme.colorScheme.onSurfaceColor.withAlphaComponent(0.6);
syncStatusView.imageView.tintColor = scheme.colorScheme.onSurfaceColor.withAlphaComponent(0.6);
} else {
syncStatusView.textView.textColor = scheme.colorScheme.secondaryColor;
syncStatusView.imageView.tintColor = scheme.colorScheme.secondaryColor;
}
}
public convenience init(observation: Observation?) {
self.init(frame: .zero);
configureForAutoLayout();
addSubview(syncStatusView);
self.observation = observation;
setupSyncStatusView();
}
@objc func syncObservation() {
manualSync = true;
ObservationPushService.singleton.pushObservations(observations: [observation!]);
setupSyncStatusView();
}
func updateObservationStatus(observation: Observation? = nil) {
if (observation != nil) {
self.observation = observation;
}
setupSyncStatusView();
}
override func updateConstraints() {
if (!didSetupConstraints) {
syncStatusView.autoSetDimension(.height, toSize: 36);
syncStatusView.autoPinEdgesToSuperviewEdges();
didSetupConstraints = true;
}
super.updateConstraints();
}
func setupSyncStatusView() {
self.isHidden = false;
// if the observation has an error
if (observation?.hasValidationError ?? false) {
syncStatusView.textView.text = "Error Pushing Changes\n\(observation?.errorMessage ?? "")";
syncStatusView.accessibilityLabel = "Error Pushing Changes\n\(observation?.errorMessage ?? "")";
syncStatusView.imageView.image = UIImage(systemName: "exclamationmark.circle");
syncStatusView.leadingButton.isHidden = true;
if let scheme = scheme {
applyTheme(withScheme: scheme);
}
syncStatusView.sizeToFit();
return;
}
// if the observation is not dirty and has no error, show the push date
if (!(observation?.isDirty ?? false) && observation?.error == nil) {
if let pushedDate: NSDate = observation?.lastModified as NSDate? {
syncStatusView.textView.text = "Pushed on \(pushedDate.formattedDisplay())";
syncStatusView.accessibilityLabel = "Pushed on \(pushedDate.formattedDisplay())";
}
syncStatusView.textView.textColor = MDCPalette.green.accent700;
syncStatusView.imageView.image = UIImage(systemName: "checkmark");
syncStatusView.imageView.tintColor = MDCPalette.green.accent700;
syncStatusView.leadingButton.isHidden = true;
if let scheme = scheme {
applyTheme(withScheme: scheme);
}
syncStatusView.sizeToFit();
return;
}
// if the user has attempted to manually sync
if (manualSync) {
syncStatusView.textView.text = "Force Pushing Changes...";
syncStatusView.accessibilityLabel = "Force Pushing Changes..."
syncStatusView.imageView.image = UIImage(systemName: "arrow.triangle.2.circlepath");
syncStatusView.leadingButton.isHidden = true;
if let scheme = scheme {
applyTheme(withScheme: scheme);
}
syncStatusView.sizeToFit();
return;
}
// if the observation is dirty and needs synced
syncStatusView.textView.text = "Changes Queued";
syncStatusView.accessibilityLabel = "Changes Queued";
syncStatusView.imageView.image = UIImage(systemName: "arrow.triangle.2.circlepath");
syncStatusView.leadingButton.setTitle("Sync Now", for: .normal);
syncStatusView.leadingButton.accessibilityLabel = "Sync Now";
syncStatusView.leadingButton.addTarget(self, action: #selector(self.syncObservation), for: .touchUpInside)
if let scheme = scheme {
applyTheme(withScheme: scheme);
}
syncStatusView.sizeToFit();
}
}
|
apache-2.0
|
da165e712ce15868f05b99a991291418
| 40.657143 | 114 | 0.645919 | 5.273056 | false | false | false | false |
LinDing/Positano
|
Positano/ViewControllers/Register/RegisterPickNameViewController.swift
|
1
|
4637
|
//
// RegisterPickNameViewController.swift
// Positano
//
// Created by dinglin on 2016/12/4.
// Copyright © 2016年 dinglin. All rights reserved.
//
import UIKit
import Ruler
import RxSwift
import RxCocoa
import PositanoKit
class RegisterPickNameViewController: BaseViewController {
fileprivate lazy var disposeBag = DisposeBag()
@IBOutlet fileprivate weak var pickNamePromptLabel: UILabel!
@IBOutlet fileprivate weak var pickNamePromptLabelTopConstraint: NSLayoutConstraint!
@IBOutlet fileprivate weak var promptTermsLabel: UILabel!
@IBOutlet fileprivate weak var nameTextField: BorderTextField!
@IBOutlet fileprivate weak var nameTextFieldTopConstraint: NSLayoutConstraint!
fileprivate lazy var nextButton: UIBarButtonItem = {
let button = UIBarButtonItem()
button.title = String.trans_buttonNextStep
button.rx.tap
.subscribe(onNext: {[weak self] in self?.showRegisterPickMobile() })
.addDisposableTo(self.disposeBag)
return button
}()
fileprivate var isDirty = false {
willSet {
nextButton.isEnabled = newValue
promptTermsLabel.alpha = newValue ? 1.0 : 0.5
}
}
deinit {
println("deinit RegisterPickName")
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
view.backgroundColor = UIColor.yepViewBackgroundColor()
navigationItem.titleView = NavigationTitleLabel(title: NSLocalizedString("Sign Up", comment: ""))
navigationItem.rightBarButtonItem = nextButton
pickNamePromptLabel.text = NSLocalizedString("What's your name?", comment: "")
let text = String.trans_promptTapNextAgreeTerms
let textAttributes: [String: Any] = [
NSFontAttributeName: UIFont.systemFont(ofSize: 14),
NSForegroundColorAttributeName: UIColor.gray,
]
let attributedText = NSMutableAttributedString(string: text, attributes: textAttributes)
let termsAttributes: [String: Any] = [
NSForegroundColorAttributeName: UIColor.yepTintColor(),
NSUnderlineStyleAttributeName: NSUnderlineStyle.styleSingle.rawValue,
]
let tapRange = (text as NSString).range(of: NSLocalizedString("terms", comment: ""))
attributedText.addAttributes(termsAttributes, range: tapRange)
promptTermsLabel.attributedText = attributedText
promptTermsLabel.textAlignment = .center
promptTermsLabel.alpha = 0.5
promptTermsLabel.isUserInteractionEnabled = true
let tap = UITapGestureRecognizer(target: self, action: #selector(RegisterPickNameViewController.tapTerms(_:)))
promptTermsLabel.addGestureRecognizer(tap)
nameTextField.backgroundColor = UIColor.white
nameTextField.textColor = UIColor.yepInputTextColor()
nameTextField.placeholder = " "
nameTextField.delegate = self
nameTextField.rx.textInput.text
.map({ $0 ?? "" })
.map({ !$0.isEmpty })
.subscribe(onNext: { [weak self] in self?.isDirty = $0 })
.addDisposableTo(disposeBag)
pickNamePromptLabelTopConstraint.constant = Ruler.iPhoneVertical(30, 50, 60, 60).value
nameTextFieldTopConstraint.constant = Ruler.iPhoneVertical(30, 40, 50, 50).value
nextButton.isEnabled = false
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
nameTextField.becomeFirstResponder()
}
// MARK: Actions
@objc fileprivate func tapTerms(_ sender: UITapGestureRecognizer) {
if let URL = URL(string: YepConfig.termsURLString) {
yep_openURL(URL)
}
}
fileprivate func showRegisterPickMobile() {
guard let text = nameTextField.text else {
return
}
let nickname = text.trimming(.whitespaceAndNewline)
PositanoUserDefaults.nickname.value = nickname
performSegue(withIdentifier: "showRegisterPickMobile", sender: nil)
}
}
extension RegisterPickNameViewController: UITextFieldDelegate {
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
guard let text = textField.text else {
return true
}
if !text.isEmpty {
showRegisterPickMobile()
}
return true
}
}
|
mit
|
dc30b14393458baffb4b6f63366167a9
| 31.633803 | 118 | 0.644368 | 5.510107 | false | false | false | false |
jeniffer9/SipHash
|
SipHashTests/SipHashTests.swift
|
5
|
5756
|
//
// SipHashTests.swift
// SipHash
//
// Created by Károly Lőrentey on 2016-03-08.
// Copyright © 2016-2017 Károly Lőrentey.
//
import XCTest
@testable import SipHash
private let vectors: [UInt8] = [ // From https://github.com/veorq/SipHash/blob/master/main.c
0x31, 0x0e, 0x0e, 0xdd, 0x47, 0xdb, 0x6f, 0x72,
0xfd, 0x67, 0xdc, 0x93, 0xc5, 0x39, 0xf8, 0x74,
0x5a, 0x4f, 0xa9, 0xd9, 0x09, 0x80, 0x6c, 0x0d,
0x2d, 0x7e, 0xfb, 0xd7, 0x96, 0x66, 0x67, 0x85,
0xb7, 0x87, 0x71, 0x27, 0xe0, 0x94, 0x27, 0xcf,
0x8d, 0xa6, 0x99, 0xcd, 0x64, 0x55, 0x76, 0x18,
0xce, 0xe3, 0xfe, 0x58, 0x6e, 0x46, 0xc9, 0xcb,
0x37, 0xd1, 0x01, 0x8b, 0xf5, 0x00, 0x02, 0xab,
0x62, 0x24, 0x93, 0x9a, 0x79, 0xf5, 0xf5, 0x93,
0xb0, 0xe4, 0xa9, 0x0b, 0xdf, 0x82, 0x00, 0x9e,
0xf3, 0xb9, 0xdd, 0x94, 0xc5, 0xbb, 0x5d, 0x7a,
0xa7, 0xad, 0x6b, 0x22, 0x46, 0x2f, 0xb3, 0xf4,
0xfb, 0xe5, 0x0e, 0x86, 0xbc, 0x8f, 0x1e, 0x75,
0x90, 0x3d, 0x84, 0xc0, 0x27, 0x56, 0xea, 0x14,
0xee, 0xf2, 0x7a, 0x8e, 0x90, 0xca, 0x23, 0xf7,
0xe5, 0x45, 0xbe, 0x49, 0x61, 0xca, 0x29, 0xa1,
0xdb, 0x9b, 0xc2, 0x57, 0x7f, 0xcc, 0x2a, 0x3f,
0x94, 0x47, 0xbe, 0x2c, 0xf5, 0xe9, 0x9a, 0x69,
0x9c, 0xd3, 0x8d, 0x96, 0xf0, 0xb3, 0xc1, 0x4b,
0xbd, 0x61, 0x79, 0xa7, 0x1d, 0xc9, 0x6d, 0xbb,
0x98, 0xee, 0xa2, 0x1a, 0xf2, 0x5c, 0xd6, 0xbe,
0xc7, 0x67, 0x3b, 0x2e, 0xb0, 0xcb, 0xf2, 0xd0,
0x88, 0x3e, 0xa3, 0xe3, 0x95, 0x67, 0x53, 0x93,
0xc8, 0xce, 0x5c, 0xcd, 0x8c, 0x03, 0x0c, 0xa8,
0x94, 0xaf, 0x49, 0xf6, 0xc6, 0x50, 0xad, 0xb8,
0xea, 0xb8, 0x85, 0x8a, 0xde, 0x92, 0xe1, 0xbc,
0xf3, 0x15, 0xbb, 0x5b, 0xb8, 0x35, 0xd8, 0x17,
0xad, 0xcf, 0x6b, 0x07, 0x63, 0x61, 0x2e, 0x2f,
0xa5, 0xc9, 0x1d, 0xa7, 0xac, 0xaa, 0x4d, 0xde,
0x71, 0x65, 0x95, 0x87, 0x66, 0x50, 0xa2, 0xa6,
0x28, 0xef, 0x49, 0x5c, 0x53, 0xa3, 0x87, 0xad,
0x42, 0xc3, 0x41, 0xd8, 0xfa, 0x92, 0xd8, 0x32,
0xce, 0x7c, 0xf2, 0x72, 0x2f, 0x51, 0x27, 0x71,
0xe3, 0x78, 0x59, 0xf9, 0x46, 0x23, 0xf3, 0xa7,
0x38, 0x12, 0x05, 0xbb, 0x1a, 0xb0, 0xe0, 0x12,
0xae, 0x97, 0xa1, 0x0f, 0xd4, 0x34, 0xe0, 0x15,
0xb4, 0xa3, 0x15, 0x08, 0xbe, 0xff, 0x4d, 0x31,
0x81, 0x39, 0x62, 0x29, 0xf0, 0x90, 0x79, 0x02,
0x4d, 0x0c, 0xf4, 0x9e, 0xe5, 0xd4, 0xdc, 0xca,
0x5c, 0x73, 0x33, 0x6a, 0x76, 0xd8, 0xbf, 0x9a,
0xd0, 0xa7, 0x04, 0x53, 0x6b, 0xa9, 0x3e, 0x0e,
0x92, 0x59, 0x58, 0xfc, 0xd6, 0x42, 0x0c, 0xad,
0xa9, 0x15, 0xc2, 0x9b, 0xc8, 0x06, 0x73, 0x18,
0x95, 0x2b, 0x79, 0xf3, 0xbc, 0x0a, 0xa6, 0xd4,
0xf2, 0x1d, 0xf2, 0xe4, 0x1d, 0x45, 0x35, 0xf9,
0x87, 0x57, 0x75, 0x19, 0x04, 0x8f, 0x53, 0xa9,
0x10, 0xa5, 0x6c, 0xf5, 0xdf, 0xcd, 0x9a, 0xdb,
0xeb, 0x75, 0x09, 0x5c, 0xcd, 0x98, 0x6c, 0xd0,
0x51, 0xa9, 0xcb, 0x9e, 0xcb, 0xa3, 0x12, 0xe6,
0x96, 0xaf, 0xad, 0xfc, 0x2c, 0xe6, 0x66, 0xc7,
0x72, 0xfe, 0x52, 0x97, 0x5a, 0x43, 0x64, 0xee,
0x5a, 0x16, 0x45, 0xb2, 0x76, 0xd5, 0x92, 0xa1,
0xb2, 0x74, 0xcb, 0x8e, 0xbf, 0x87, 0x87, 0x0a,
0x6f, 0x9b, 0xb4, 0x20, 0x3d, 0xe7, 0xb3, 0x81,
0xea, 0xec, 0xb2, 0xa3, 0x0b, 0x22, 0xa8, 0x7f,
0x99, 0x24, 0xa4, 0x3c, 0xc1, 0x31, 0x57, 0x24,
0xbd, 0x83, 0x8d, 0x3a, 0xaf, 0xbf, 0x8d, 0xb7,
0x0b, 0x1a, 0x2a, 0x32, 0x65, 0xd5, 0x1a, 0xea,
0x13, 0x50, 0x79, 0xa3, 0x23, 0x1c, 0xe6, 0x60,
0x93, 0x2b, 0x28, 0x46, 0xe4, 0xd7, 0x06, 0x66,
0xe1, 0x91, 0x5f, 0x5c, 0xb1, 0xec, 0xa4, 0x6c,
0xf3, 0x25, 0x96, 0x5c, 0xa1, 0x6d, 0x62, 0x9f,
0x57, 0x5f, 0xf2, 0x8e, 0x60, 0x38, 0x1b, 0xe5,
0x72, 0x45, 0x06, 0xeb, 0x4c, 0x32, 0x8a, 0x95,
]
private func vector(_ i: Int) -> Int {
let v: UInt64 = vectors.withUnsafeBufferPointer { buffer in
let b = UnsafeRawBufferPointer(buffer)
return b.load(fromByteOffset: 8 * i, as: UInt64.self)
}
return Int(truncatingIfNeeded: v)
}
private let (k0, k1): (UInt64, UInt64) = Array(UInt8(0) ..< UInt8(16)).withUnsafeBufferPointer { buffer in
let b = UnsafeRawBufferPointer(buffer)
return (b.load(fromByteOffset: 0, as: UInt64.self), b.load(fromByteOffset: 8, as: UInt64.self))
}
private let input: [UInt8] = Array(0 ..< 63)
class SipHashTests: XCTestCase {
func testVectors() {
input.withUnsafeBufferPointer { buffer in
for i in 0 ..< 64 {
let b = UnsafeRawBufferPointer(buffer)[0 ..< i]
let expected = vector(i)
var hash = SipHasher(k0: k0, k1: k1)
hash.append(b)
let actual = hash.finalize()
XCTAssertEqual(actual, expected, "Test vector failed for \(i) bytes")
}
}
}
func testSplits() {
for i in 0 ..< 64 {
input.withUnsafeBufferPointer { buffer in
let b = UnsafeRawBufferPointer(buffer)
let expected = vector(63)
var hash = SipHasher(k0: k0, k1: k1)
hash.append(b[0 ..< i])
hash.append(b[i ..< 63])
let actual = hash.finalize()
XCTAssertEqual(actual, expected, "Test vector #63 failed for split at \(i) bytes")
}
}
}
func testDefaultKey() {
// Well, we can't really test that the key is random.
// But we can check that it doesn't change.
input.withUnsafeBufferPointer { buffer in
for i in 0 ..< 64 {
let b = UnsafeRawBufferPointer(buffer)[0 ..< i]
var hash1 = SipHasher()
hash1.append(b)
let h1 = hash1.finalize()
var hash2 = SipHasher()
hash2.append(b)
let h2 = hash2.finalize()
XCTAssertEqual(h1, h2)
}
}
}
}
|
mit
|
36ce9519ebbf949305595242ea590216
| 39.216783 | 106 | 0.588072 | 2.100438 | false | true | false | false |
IAskWind/IAWExtensionTool
|
Pods/Easy/Easy/Classes/Core/EasyNavigationController.swift
|
1
|
12310
|
//
// EasyNavigationController.swift
// Easy
//
// Created by OctMon on 2018/10/12.
//
import UIKit
#if canImport(RTRootNavigationController)
import RTRootNavigationController
public extension Easy {
typealias NavigationController = EasyNavigationController
}
public class EasyNavigationController: RTRootNavigationController {
deinit { EasyLog.debug(toDeinit) }
public override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: Bundle?) {
super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil)
}
public override init(rootViewController: UIViewController) {
super.init(rootViewController: rootViewController)
useSystemBackBarButtonItem = true
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
useSystemBackBarButtonItem = true
}
}
#endif
/// 拦截返回按钮
private protocol EasyNavigationShouldPopOnBackButton {
func navigationShouldPopOnBackButton() -> Bool
func navigationPopOnBackHandler() -> Void
}
extension UIViewController: EasyNavigationShouldPopOnBackButton {
/// 拦截返回按钮, 返回false无法返回
@objc open func navigationShouldPopOnBackButton() -> Bool {
return true
}
/// 拦截返回事件, 可自定义点击 返回按钮后的事件
@objc open func navigationPopOnBackHandler() {
self.navigationController?.popViewController(animated: true)
}
}
extension UINavigationController: UINavigationBarDelegate {
open func navigationBar(_ navigationBar: UINavigationBar, shouldPop item: UINavigationItem) -> Bool {
if let items = navigationBar.items, viewControllers.count < items.count { return true }
var shouldPop = true
let vc = topViewController
if let topVC = vc, topVC.responds(to: #selector(navigationShouldPopOnBackButton)) {
shouldPop = topVC.navigationShouldPopOnBackButton()
}
if shouldPop {
if let topVC = vc, topVC.responds(to: #selector(navigationPopOnBackHandler)) {
EasyApp.runInMain {
topVC.navigationPopOnBackHandler()
}
} else {
EasyApp.runInMain {
self.popViewController(animated: true)
}
}
} else {
for subview in navigationBar.subviews {
if subview.alpha > 0.0 && subview.alpha < 1.0 {
UIView.animate(withDuration: 0.25, animations: {
subview.alpha = 1.0
})
}
}
}
return false
}
}
class EasyFullScreenPopGesture: NSObject {
static func open() -> Void {
UIViewController.vcFullScreenInit()
UINavigationController.navFullScreenInit()
}
}
private class _FullScreenPopGestureDelegate: NSObject, UIGestureRecognizerDelegate {
weak var navigationController: UINavigationController?
func gestureRecognizerShouldBegin(_ gestureRecognizer: UIGestureRecognizer) -> Bool {
guard let navController = self.navigationController else { return false }
// 忽略没有控制器可以 push 的时候
guard navController.viewControllers.count > 1 else {
return false
}
// 控制器不允许交互弹出时忽略
guard let topViewController = navController.viewControllers.last, !topViewController.interactivePopDisabled else {
return false
}
if let isTransitioning = navController.value(forKey: "_isTransitioning") as? Bool, isTransitioning {
return false
}
guard let panGesture = gestureRecognizer as? UIPanGestureRecognizer else {
return false
}
// 始位置超出最大允许初始距离时忽略
let beginningLocation = panGesture.location(in: gestureRecognizer.view)
let maxAllowedInitialDistance = topViewController.interactivePopMaxAllowedInitialDistanceToLeftEdge
if maxAllowedInitialDistance > 0, beginningLocation.x > maxAllowedInitialDistance { return false }
let translation = panGesture.translation(in: gestureRecognizer.view)
let isLeftToRight = UIApplication.shared.userInterfaceLayoutDirection == UIUserInterfaceLayoutDirection.leftToRight
let multiplier: CGFloat = isLeftToRight ? 1 : -1
if (translation.x * multiplier) <= 0 {
return false
}
return true
}
}
extension UIViewController {
fileprivate static func vcFullScreenInit() {
let appear_originalMethod = class_getInstanceMethod(self, #selector(viewWillAppear(_:)))
let appear_swizzledMethod = class_getInstanceMethod(self, #selector(_viewWillAppear))
method_exchangeImplementations(appear_originalMethod!, appear_swizzledMethod!)
let disappear_originalMethod = class_getInstanceMethod(self, #selector(viewWillDisappear(_:)))
let disappear_swizzledMethod = class_getInstanceMethod(self, #selector(_viewWillDisappear))
method_exchangeImplementations(disappear_originalMethod!, disappear_swizzledMethod!)
}
private struct Key {
static var interactivePopDisabled: Void?
static var maxAllowedInitialDistance: Void?
static var prefersNavigationBarHidden: Void?
static var willAppearInjectHandler: Void?
}
fileprivate var interactivePopDisabled: Bool {
get { return (objc_getAssociatedObject(self, &Key.interactivePopDisabled) as? Bool) ?? false }
set { objc_setAssociatedObject(self, &Key.interactivePopDisabled, newValue, .OBJC_ASSOCIATION_ASSIGN) }
}
fileprivate var interactivePopMaxAllowedInitialDistanceToLeftEdge: CGFloat {
get { return (objc_getAssociatedObject(self, &Key.maxAllowedInitialDistance) as? CGFloat) ?? 0.00 }
set { objc_setAssociatedObject(self, &Key.maxAllowedInitialDistance, max(0, newValue), .OBJC_ASSOCIATION_COPY) }
}
fileprivate var prefersNavigationBarHidden: Bool {
get {
guard let bools = objc_getAssociatedObject(self, &Key.prefersNavigationBarHidden) as? Bool else { return false }
return bools
}
set {
objc_setAssociatedObject(self, &Key.prefersNavigationBarHidden, newValue, objc_AssociationPolicy.OBJC_ASSOCIATION_ASSIGN)
}
}
fileprivate var willAppearInjectHandler: ViewControllerWillAppearInjectHandler? {
get { return objc_getAssociatedObject(self, &Key.willAppearInjectHandler) as? ViewControllerWillAppearInjectHandler }
set { objc_setAssociatedObject(self, &Key.willAppearInjectHandler, newValue, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN_NONATOMIC) }
}
@objc fileprivate func _viewWillAppear(_ animated: Bool) {
self._viewWillAppear(animated)
self.willAppearInjectHandler?(self, animated)
}
@objc fileprivate func _viewWillDisappear(animated: Bool) {
self._viewWillDisappear(animated: animated)
let vc = self.navigationController?.viewControllers.last
if vc != nil, vc!.prefersNavigationBarHidden, !self.prefersNavigationBarHidden {
self.navigationController?.setNavigationBarHidden(false, animated: false)
}
}
}
private typealias ViewControllerWillAppearInjectHandler = (_ viewController: UIViewController, _ animated: Bool) -> Void
extension UINavigationController {
fileprivate static func navFullScreenInit() {
let originalSelector = #selector(pushViewController(_:animated:))
let swizzledSelector = #selector(_pushViewController)
guard let originalMethod = class_getInstanceMethod(self, originalSelector) else { return }
guard let swizzledMethod = class_getInstanceMethod(self, swizzledSelector) else { return }
let success = class_addMethod(self.classForCoder(), originalSelector, method_getImplementation(swizzledMethod), method_getTypeEncoding(swizzledMethod))
if success {
class_replaceMethod(self.classForCoder(), swizzledSelector, method_getImplementation(originalMethod), method_getTypeEncoding(originalMethod))
} else {
method_exchangeImplementations(originalMethod, swizzledMethod)
}
}
private struct Key {
static var cmd: Void?
static var popGestureRecognizerDelegate: Void?
static var fullscreenPopGestureRecognizer: Void?
static var viewControllerBasedNavigationBarAppearanceEnabled: Void?
}
@objc private func _pushViewController(_ viewController: UIViewController, animated: Bool) {
if self.interactivePopGestureRecognizer?.view?.gestureRecognizers?.contains(self.fullscreenPopGestureRecognizer) == false {
self.interactivePopGestureRecognizer?.view?.addGestureRecognizer(self.fullscreenPopGestureRecognizer)
guard let internalTargets = self.interactivePopGestureRecognizer?.value(forKey: "targets") as? [NSObject] else { return }
guard let internalTarget = internalTargets.first!.value(forKey: "target") else { return } // internalTargets?.first?.value(forKey: "target") else { return }
let internalAction = NSSelectorFromString("handleNavigationTransition:")
self.fullscreenPopGestureRecognizer.delegate = self.popGestureRecognizerDelegate
self.fullscreenPopGestureRecognizer.addTarget(internalTarget, action: internalAction)
self.interactivePopGestureRecognizer?.isEnabled = false
}
self.setupViewControllerBasedNavigationBarAppearanceIfNeeded(viewController)
if !self.viewControllers.contains(viewController) {
self._pushViewController(viewController, animated: animated)
}
}
private func setupViewControllerBasedNavigationBarAppearanceIfNeeded(_ appearingViewController: UIViewController) -> Void {
guard self.viewControllerBasedNavigationBarAppearanceEnabled else {
return
}
let Handler: ViewControllerWillAppearInjectHandler = { [weak self] (vc, animated) in
self.unwrapped({ $0.setNavigationBarHidden(vc.prefersNavigationBarHidden, animated: animated) })
}
appearingViewController.willAppearInjectHandler = Handler
if let disappearingViewController = self.viewControllers.last, disappearingViewController.willAppearInjectHandler.isNone {
disappearingViewController.willAppearInjectHandler = Handler
}
}
private var fullscreenPopGestureRecognizer: UIPanGestureRecognizer {
guard let pan = objc_getAssociatedObject(self, &Key.fullscreenPopGestureRecognizer) as? UIPanGestureRecognizer else {
let gesture = UIPanGestureRecognizer()
gesture.maximumNumberOfTouches = 1
objc_setAssociatedObject(self, &Key.fullscreenPopGestureRecognizer, gesture, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
return gesture
}
return pan
}
private var popGestureRecognizerDelegate: _FullScreenPopGestureDelegate {
guard let delegate = objc_getAssociatedObject(self, &Key.popGestureRecognizerDelegate) as? _FullScreenPopGestureDelegate else {
let delegate = _FullScreenPopGestureDelegate()
delegate.navigationController = self
objc_setAssociatedObject(self, &Key.popGestureRecognizerDelegate, delegate, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
return delegate
}
return delegate
}
private var viewControllerBasedNavigationBarAppearanceEnabled: Bool {
get {
guard let enabel = objc_getAssociatedObject(self, &Key.viewControllerBasedNavigationBarAppearanceEnabled) as? Bool else {
self.viewControllerBasedNavigationBarAppearanceEnabled = true
return true
}
return enabel
}
set {
objc_setAssociatedObject(self, &Key.viewControllerBasedNavigationBarAppearanceEnabled, newValue, objc_AssociationPolicy.OBJC_ASSOCIATION_ASSIGN)
}
}
}
|
mit
|
2f67347eb7ca98ecbf520241e9729e87
| 40.75945 | 168 | 0.689269 | 5.607753 | false | false | false | false |
seongkyu-sim/BaseVCKit
|
Example/BaseVCKit/ModalViewController.swift
|
1
|
2762
|
//
// ModalViewController.swift
// BaseVCKit
//
// Created by frank on 2017. 4. 24..
// Copyright © 2017년 CocoaPods. All rights reserved.
//
import UIKit
import BaseVCKit
class ModalViewController: BaseViewController {
private lazy var txtField: UITextField = {
let v = UITextField()
v.backgroundColor = UIColor.lightGray
self.view.addSubview(v)
return v
}()
fileprivate lazy var modalBtn: UIButton = { [unowned self] in
let v = UIButton()
v.setTitle("Modal", for: .normal)
v.backgroundColor = .lightGray
v.setTitle("clicked", for: .highlighted)
v.addTarget(self, action: #selector(self.modal), for: .touchUpInside)
self.view.addSubview(v)
return v
}()
fileprivate lazy var doneBtn: UIButton = { [unowned self] in
let v = UIButton()
v.setTitle("Done", for: .normal)
v.backgroundColor = .lightGray
v.addTarget(self, action: #selector(self.done), for: .touchUpInside)
self.view.addSubview(v)
return v
}()
override func viewDidLoad() {
super.viewDidLoad()
title = "Modal"
layoutSubViews()
}
// MARK: - Layout
private func layoutSubViews() {
let padding = UIEdgeInsets(
top: 100,
left: 20,
bottom: keyboardFollowDisAppearOffsetB,
right: 20
)
txtField.snp.makeConstraints {
$0.top.left.right.equalToSuperview().inset(padding)
$0.height.equalTo(40)
}
modalBtn.snp.makeConstraints {
$0.left.right.equalToSuperview().inset(padding)
$0.height.equalTo(70)
$0.centerY.equalToSuperview()
}
doneBtn.snp.makeConstraints {
$0.left.right.equalToSuperview().inset(padding)
// $0.bottom.equalToSuperview().offset(-keyboardFollowOffsetB)
$0.bottom.equalToSuperview().inset(padding)
}
}
// MARK: - Actions
@objc private func done(sender:UIButton!) {
view.endEditing(true)
}
@objc private func modal(sender:UIButton!) {
modal(ModalViewController())
}
// KeyboardObserable
private let keyboardFollowAppearOffsetB = CGFloat(16)
private var keyboardFollowDisAppearOffsetB: CGFloat {
// return bottomLayoutGuide.length
return 34
}
override var keyboardFollowView: UIView? {
return doneBtn
}
override var keyboardFollowOffsetForAppeared: CGFloat {
return keyboardFollowAppearOffsetB
}
override var keyboardFollowOffsetForDisappeared: CGFloat {
// return keyboardFollowOffsetB
return keyboardFollowDisAppearOffsetB
}
}
|
mit
|
2e40cd33c70b5db09565797f10573e9d
| 24.785047 | 77 | 0.612903 | 4.50817 | false | false | false | false |
blockchain/My-Wallet-V3-iOS
|
Modules/WalletPayload/Sources/WalletPayloadKit/Models/WalletRepoState.swift
|
1
|
2901
|
// Copyright © Blockchain Luxembourg S.A. All rights reserved.
import Foundation
/// Holds the storage for wallet related access
public struct WalletRepoState: Equatable, Codable {
/// Stores credential related properties
public var credentials: WalletCredentials
/// Stores informational related properties
public var properties: WalletProperties
/// Returns the wallet payload
public var walletPayload: WalletPayload
/// Provides an empty state
public static let empty = WalletRepoState(
credentials: .empty,
properties: .empty,
walletPayload: .empty
)
}
/// Holds credential information regarding the wallet
public struct WalletCredentials: Equatable, Codable {
/// Returns the stored wallet identifier
public var guid: String
/// Returns the stored wallet shared key
public var sharedKey: String
/// Returns the stored session token
public var sessionToken: String
/// Returns the in-memory stored password
/// - NOTE: for security reasons this is not stored in the keychain
public var password: String
static let empty = WalletCredentials(
guid: "",
sharedKey: "",
sessionToken: "",
password: ""
)
enum CodingKeys: String, CodingKey {
case guid
case sharedKey
case sessionToken
}
public init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
guid = try container.decode(String.self, forKey: .guid)
sharedKey = try container.decode(String.self, forKey: .sharedKey)
sessionToken = try container.decode(String.self, forKey: .sessionToken)
password = "" // we can't decode this since we don't encode it
}
public func encode(to encoder: Encoder) throws {
var container = encoder.container(keyedBy: CodingKeys.self)
try container.encode(guid, forKey: .guid)
try container.encode(sharedKey, forKey: .sharedKey)
try container.encode(sessionToken, forKey: .sessionToken)
}
public init(
guid: String,
sharedKey: String,
sessionToken: String,
password: String
) {
self.guid = guid
self.sharedKey = sharedKey
self.sessionToken = sessionToken
self.password = password
}
}
/// Holds informational properties regarding the wallet
public struct WalletProperties: Equatable, Codable {
/// Returns `true` if the pub keys should be synchronised
public var syncPubKeys: Bool
// Returns the language as specified by the wallet
public var language: String
/// Returns the authenticator type, of the wallet
public var authenticatorType: WalletAuthenticatorType
static let empty = WalletProperties(
syncPubKeys: false,
language: "",
authenticatorType: .standard
)
}
|
lgpl-3.0
|
71f51a6b34f1fb46b286fbf25f5c325f
| 28.896907 | 79 | 0.674828 | 5.061082 | false | false | false | false |
RoomFinder/MobileApp-iOS
|
FindMeARoom/RestService.swift
|
1
|
3470
|
import Foundation
private func getUrl(var relativeUrl: String) -> NSURL {
if relativeUrl.characters.first != "/" {
relativeUrl = "/" + relativeUrl
}
return NSURL(string: "http://192.168.3.1:18799/api\(relativeUrl)")!
}
class RestService {
func login(username: String, password: String, email: String, site: String, serviceUrl: String?, callback: RestResults<String> -> Void) {
let request = NSMutableURLRequest(URL: getUrl("login"))
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
request.HTTPMethod = "POST"
var tmp: [NSObject: AnyObject] = [
"username" : username,
"password" : password,
"email" : email,
"site" : site
]
if let serviceUrl = serviceUrl {
tmp["serviceUrl"] = serviceUrl
}
let obj = NSDictionary(dictionary: tmp)
guard let data = try? NSJSONSerialization.dataWithJSONObject(obj, options: NSJSONWritingOptions(rawValue: 0)) else {
callback(.NetworkError)
return
}
request.HTTPBody = data
REST.doRequest(request, callback: callback, errorHandlers: nil) {
let obj = (try? NSJSONSerialization.JSONObjectWithData($0, options: .AllowFragments)) as? NSString
guard let ticket = obj else {
print("Response is not a string")
callback(.NetworkError)
return
}
print("Login successful!")
callback(.Success(data: ticket as String))
}
}
func getRooms(lat lat: Double?, lon: Double?, ticket: String, callback: RestResults<[Room]> -> Void) {
var url = "rooms?ticket=\(ticket)"
if let lat = lat, let lon = lon {
url += "&lat=\(lat)&lon=\(lon)"
}
let request = NSURLRequest(URL: getUrl(url))
REST.doRequest(request, callback: callback, errorHandlers: nil) {
let obj = (try? NSJSONSerialization.JSONObjectWithData($0, options: .AllowFragments)) as? NSArray
guard let array = obj else {
print("Response is not an array")
callback(.NetworkError)
return
}
let r = try? array.map(Converter.readRoom)
guard let result = r else {
print("Unable to parse contents of the array")
callback(.NetworkError)
return
}
callback(.Success(data: result))
}
}
func reserveRoom(id id: String, duration: Int, ticket: String, callback: RestResults<Bool> -> Void) {
let request = NSMutableURLRequest(URL: getUrl("rooms/\(id)?ticket=\(ticket)"))
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
request.HTTPMethod = "POST"
let tmp: [NSObject: AnyObject] = [
"duration" : duration
]
let obj = NSDictionary(dictionary: tmp)
guard let data = try? NSJSONSerialization.dataWithJSONObject(obj, options: NSJSONWritingOptions(rawValue: 0)) else {
callback(.NetworkError)
return
}
request.HTTPBody = data
let errorMap: [Int : NSData -> Void] = [
409: { _ in callback(.Success(data: false)) }
]
REST.doRequest(request, callback: callback, errorHandlers: errorMap) { _ in
callback(.Success(data: true))
}
}
}
|
mit
|
df1454c3cbdbd225fed5b7e3bf417dfe
| 38.443182 | 141 | 0.577522 | 4.695535 | false | false | false | false |
rporzuc/FindFriends
|
FindFriends/FindFriends/MessagesViews/Conversation View/ContentsOfConversationTableViewController.swift
|
1
|
5966
|
//
// ContentsOfConversationTableViewController.swift
// FindFriends
//
// Created by MacOSXRAFAL on 10/12/17.
// Copyright © 2017 MacOSXRAFAL. All rights reserved.
//
import UIKit
class ContentsOfConversationTableViewController: UITableViewController, ObserverMessagesProtocol {
var imgOfTheUser : UIImage = DataManagement.shared.getImageUserFromeCoreData().0
var imgOfTheSender : UIImage = UIImage(named: "ImagePersonRounded")!
var idConversation : Int? = nil
var idConverser : Int? = nil
public struct message{
var contentsMessage: String?
var datetimeMessage: NSDate?
var idConversation: Int32
var numberMessage: Int32
var recipientMessage: Int32
var senderMessage: Int32
var wasReadMessage: Bool
}
var arrayMessages : [message] = [message]()
override func viewDidLoad() {
super.viewDidLoad()
if idConversation != nil{
self.refreshArrayWithDataMessages(withScroll: true)
}
tableView.estimatedRowHeight = tableView.rowHeight
tableView.rowHeight = UITableViewAutomaticDimension
}
override func viewDidAppear(_ animated: Bool) {
DataManagement.shared.attachObserverMessages(observer: self)
scrollDown()
}
override func viewDidDisappear(_ animated: Bool) {
DataManagement.shared.removeObserverMessages(observer: self)
}
func scrollDown(){
if arrayMessages.count != 0{
tableView.scrollToRow(at: IndexPath(item: arrayMessages.count - 1, section: 0), at: .bottom, animated: false)
}
}
func refreshArrayWithDataMessages(withScroll : Bool)
{
if idConversation != nil
{
arrayMessages.removeAll()
DispatchQueue.global(qos: .background).async {
let connectionToServer = ConnectionToServer.shared
connectionToServer.markMessagesAsDisplayed(id_conversation: self.idConversation!, completion:
{ (bool) in
if bool{
DataManagement.shared.getMessages(id_conversation: self.idConversation!, completion: { array in
for a in array {
self.arrayMessages.append(message(contentsMessage: a.contentsMessage, datetimeMessage: a.datetimeMessage, idConversation: a.idConversation, numberMessage: a.numberMessage, recipientMessage: a.recipientMessage, senderMessage: a.senderMessage, wasReadMessage: a.wasReadMessage))
}
DispatchQueue.main.async {
if mainViewController != nil{
mainViewController.checkIfMessagesHaveBeenAdded()
}
self.tableView.reloadData()
if withScroll{
self.scrollDown()
}
self.refreshControl?.endRefreshing()
}
})
}else{
let alertView = UIAlertController(title: "Error", message: "There was an error! Please try again later.", preferredStyle: UIAlertControllerStyle.alert)
alertView.addAction(UIAlertAction(title: "OK", style: UIAlertActionStyle.cancel, handler: nil))
self.present(alertView, animated: true, completion: nil)
}
})
}
}
}
// MARK: - Table view data source
override func numberOfSections(in tableView: UITableView) -> Int {
// #warning Incomplete implementation, return the number of sections
return 1
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// #warning Incomplete implementation, return the number of rows
return arrayMessages.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let id_sender = Int(arrayMessages[indexPath.row].senderMessage)
if (id_sender == self.idConverser)
{
// incoming message
let cell = tableView.dequeueReusableCell(withIdentifier: "customIncomingMessageCell", for: indexPath) as! CustomIncomingMessageTableViewCell
cell.contentsOfMessageTextView.text = arrayMessages[indexPath.row].contentsMessage
cell.imagePersonWithConversation.image = imgOfTheSender
let formatter = DateFormatter()
formatter.dateFormat = "yyyy-MM-dd HH:mm"
cell.timeLabel.text = (formatter.string(from: arrayMessages[indexPath.row].datetimeMessage as! Date))
return cell
}else
{
//outgoing message
let cell = tableView.dequeueReusableCell(withIdentifier: "customOutgoingMessageCell", for: indexPath) as! CustomOutgoingMessageTableViewCell
cell.contentsOfMessageTextView.text = arrayMessages[indexPath.row].contentsMessage
cell.userImageView.image = imgOfTheUser
let formatter = DateFormatter()
formatter.dateFormat = "yyyy-MM-dd HH:mm"
cell.timeLabel.text = (formatter.string(from: arrayMessages[indexPath.row].datetimeMessage as! Date))
return cell
}
}
override func scrollViewShouldScrollToTop(_ scrollView: UIScrollView) -> Bool {
return false
}
//MARK: - observer message update func
func updateObserverMessages() {
self.refreshArrayWithDataMessages(withScroll: true)
}
}
|
gpl-3.0
|
3b6628b0219821ee3652336340082f6a
| 36.28125 | 304 | 0.595474 | 5.64333 | false | false | false | false |
core-plot/core-plot
|
examples/CPTTestApp-iPhone/Classes/PieChartController.swift
|
1
|
2812
|
import UIKit
class PieChartController : UIViewController, CPTPieChartDataSource, CPTPieChartDelegate {
private var pieGraph : CPTXYGraph? = nil
let dataForChart = [20.0, 30.0, 60.0]
// MARK: - Initialization
override func viewDidAppear(_ animated : Bool)
{
super.viewDidAppear(animated)
// Create graph from theme
let newGraph = CPTXYGraph(frame: .zero)
newGraph.apply(CPTTheme(named: .darkGradientTheme))
let hostingView = self.view as! CPTGraphHostingView
hostingView.hostedGraph = newGraph
// Paddings
newGraph.paddingLeft = 20.0
newGraph.paddingRight = 20.0
newGraph.paddingTop = 20.0
newGraph.paddingBottom = 20.0
newGraph.axisSet = nil
let whiteText = CPTMutableTextStyle()
whiteText.color = .white()
newGraph.titleTextStyle = whiteText
newGraph.title = "Graph Title"
// Add pie chart
let piePlot = CPTPieChart(frame: .zero)
piePlot.dataSource = self
piePlot.pieRadius = 131.0
piePlot.identifier = "Pie Chart 1" as NSString
piePlot.startAngle = CGFloat(.pi / 4.0)
piePlot.sliceDirection = .counterClockwise
piePlot.centerAnchor = CGPoint(x: 0.5, y: 0.38)
piePlot.borderLineStyle = CPTLineStyle()
piePlot.delegate = self
newGraph.add(piePlot)
self.pieGraph = newGraph
}
// MARK: - Plot Data Source Methods
func numberOfRecords(for plot: CPTPlot) -> UInt
{
return UInt(self.dataForChart.count)
}
func number(for plot: CPTPlot, field: UInt, record: UInt) -> Any?
{
if Int(record) > self.dataForChart.count {
return nil
}
else {
switch CPTPieChartField(rawValue: Int(field))! {
case .sliceWidth:
return (self.dataForChart)[Int(record)] as NSNumber
default:
return record as NSNumber
}
}
}
func dataLabel(for plot: CPTPlot, record: UInt) -> CPTLayer?
{
let label = CPTTextLayer(text:"\(record)")
if let textStyle = label.textStyle?.mutableCopy() as? CPTMutableTextStyle {
textStyle.color = .lightGray()
label.textStyle = textStyle
}
return label
}
func radialOffset(for piePlot: CPTPieChart, record recordIndex: UInt) -> CGFloat
{
var offset: CGFloat = 0.0
if ( recordIndex == 0 ) {
offset = piePlot.pieRadius / 8.0
}
return offset
}
// MARK: - Delegate Methods
func pieChart(_ plot: CPTPieChart, sliceWasSelectedAtRecord idx: UInt) {
self.pieGraph?.title = "Selected index: \(idx)"
}
}
|
bsd-3-clause
|
fd72c6c878f7db7edb914049d6cf8873
| 26.568627 | 89 | 0.590327 | 4.11713 | false | false | false | false |
liuweicode/LinkimFoundation
|
LinkimFoundation/Classes/System/Timer/TimerAgent.swift
|
1
|
794
|
//
// TimerAgent.swift
// Pods
//
// Created by 刘伟 on 16/6/30.
//
//
import UIKit
public class TimerAgent: NSObject
{
var timers: [NSTimer]!
override init()
{
timers = [NSTimer]()
}
/**
根据timer名称查找timer
- parameter name: timer名称
- returns: NSTimer
*/
public func timerForName(name:String?) -> NSTimer?
{
for timer in timers {
if timer.timeName == name || (timer.timeName == nil && name == nil){
return timer
}
}
return nil
}
deinit
{
for timer in timers {
if timer.valid {
timer.invalidate()
}
}
timers.removeAll()
timers = nil;
}
}
|
mit
|
a48e68b0c698deb98dcefcec6b683b4e
| 15.125 | 80 | 0.462532 | 4.229508 | false | false | false | false |
DianQK/rx-sample-code
|
RxDataSourcesExample/Collection/HUD.swift
|
1
|
712
|
//
// HUD.swift
// RxDataSourcesExample
//
// Created by DianQK on 03/11/2016.
// Copyright © 2016 T. All rights reserved.
//
import Foundation
import MBProgressHUD
class HUD {
private init() { }
/**
显示一个提示消息
- parameter message: 显示内容
*/
static func showMessage(_ message: String) {
let hud = MBProgressHUD.showAdded(to: UIApplication.shared.keyWindow!, animated: true)
hud.mode = MBProgressHUDMode.text
hud.label.text = message
hud.margin = 10
hud.offset.y = 150
hud.removeFromSuperViewOnHide = true
hud.isUserInteractionEnabled = false
hud.hide(animated: true, afterDelay: 1)
}
}
|
mit
|
2a284a5cd0d827e983c0569fcc5d353c
| 20.46875 | 94 | 0.633188 | 4.163636 | false | false | false | false |
Fig-leaves/curation
|
RSSReader/NewsViewController.swift
|
1
|
6375
|
//
// TwitterViewController.swift
// RSSReader
//
// Created by 伊藤総一郎 on 3/9/15.
// Copyright (c) 2015 susieyy. All rights reserved.
//
import UIKit
class NewsViewController: UIViewController, UITableViewDataSource, UITableViewDelegate, AdstirMraidViewDelegate {
var items = NSMutableArray()
var articles = NSMutableArray()
var refresh: UIRefreshControl!
var loading = false
@IBOutlet weak var table: UITableView!
var adView: AdstirMraidView? = nil
deinit {
// デリゲートを解放します。解放を忘れるとクラッシュする可能性があります。
self.adView?.delegate = nil
// 広告ビューを解放します。
self.adView = nil
}
override func viewDidLoad() {
super.viewDidLoad()
// 広告表示位置: タブバーの下でセンタリング、広告サイズ: 320,50 の場合
let originY = self.view.frame.height
let originX = (self.view.frame.size.width - kAdstirAdSize320x50.size.width) / 2
let adView = AdstirMraidView(adSize: kAdstirAdSize320x50, origin: CGPointMake(originX, originY - 100), media: Constants.ad.id, spot:Constants.ad.spot)
// リフレッシュ秒数を設定します。
adView.intervalTime = 5
// デリゲートを設定します。
adView.delegate = self
// 広告ビューを親ビューに追加します。
self.view.addSubview(adView)
self.adView = adView
self.navigationController?.navigationBar.barTintColor = UIColor.blackColor()
self.navigationController?.navigationBar.titleTextAttributes = [NSForegroundColorAttributeName: UIColor.whiteColor()]
self.navigationController?.navigationBar.tintColor = UIColor.whiteColor()
let nibName = UINib(nibName: "NewsTableViewCell", bundle:nil)
table.registerNib(nibName, forCellReuseIdentifier: "Cell")
items = NSMutableArray()
articles = NSMutableArray()
table.delegate = self
table.dataSource = self
self.refresh = UIRefreshControl()
self.refresh.attributedTitle = NSAttributedString(string: Constants.message.UPDATING)
// // NADViewクラスを生成
// nadView = NADView(frame: CGRect(x: Constants.frame.X,
// y: Constants.frame.Y,
// width: Constants.frame.WIDTH,
// height: Constants.frame.HEIGHT))
// // 広告枠のapikey/spotidを設定(必須)
// nadView.setNendID(Constants.nend_id.API_ID, spotID: Constants.nend_id.SPOT_ID)
// // nendSDKログ出力の設定(任意)
// nadView.isOutputLog = true
// // delegateを受けるオブジェクトを指定(必須)
// nadView.delegate = self
// 読み込み開始(必須)
// nadView.load()
// view.addSubview(nadView)
self.title = Constants.title.NEWS
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
let appDelegate:AppDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
if(appDelegate.newsView == false ) {
SVProgressHUD.showWithStatus(Constants.message.LOADING)
items = NSMutableArray()
articles = NSMutableArray()
dispatch_async(dispatch_get_main_queue(), { () -> Void in
self.get_article()
self.table.reloadData()
self.refresh?.endRefreshing()
SVProgressHUD.dismiss()
})
appDelegate.newsView = true
appDelegate.newsItem = items
} else {
items = appDelegate.newsItem
self.table.reloadData()
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func reload() {
items = NSMutableArray()
articles = NSMutableArray()
dispatch_async(dispatch_get_main_queue(), { () -> Void in
self.get_article()
self.table.reloadData()
self.refresh?.endRefreshing()
})
}
func get_article() {
self.request(Constants.article_url.NEWS_SITE1)
if(Constants.article_url.NEWS_SITE2 != "") {
self.request(Constants.article_url.NEWS_SITE2)
} else if(Constants.article_url.NEWS_SITE3 != "") {
self.request(Constants.article_url.NEWS_SITE3)
}
for item in self.items {
self.articles.addObject(item)
}
}
func request(url: NSString) {
self.articles = Request.fetchFromNews(url as String, items: articles)
self.loading = false
let sort_descriptor1:NSSortDescriptor = NSSortDescriptor(key:"pudDate", ascending:false)
let sorts = sort_descriptor1
Snippet.sortDate(self.articles, count: self.articles.count)
}
func tableView(table: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
return 70
}
func tableView(table: UITableView, numberOfRowsInSection section: Int) -> Int {
return self.articles.count
}
func tableView(table: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = self.table.dequeueReusableCellWithIdentifier("Cell") as! NewsTableViewCell
let item = self.articles[indexPath.row] as! NSDictionary
return CellPreference.setValueToNewsViewCell(cell, item: item)
}
func tableView(table: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
let item = self.articles[indexPath.row] as! NSDictionary
self.navigationController?.pushViewController( Snippet.setTapAction(item, mode: "blog"), animated: true)
}
func scrollViewDidScroll(scrollView: UIScrollView) {
if(self.table.contentOffset.y >= (self.table.contentSize.height - self.table.bounds.size.height) && self.loading == false) {
SVProgressHUD.showWithStatus(Constants.message.LOADING)
self.loading = true
dispatch_async(dispatch_get_main_queue(), { () -> Void in
sleep(1)
SVProgressHUD.dismiss()
})
}
}
}
|
mit
|
faeb602807218d3c7224594b28cc6cd2
| 35.343373 | 158 | 0.627548 | 4.45898 | false | false | false | false |
safx/TypetalkApp
|
TypetalkApp/OSX/ViewControllers/EditTopicViewController.swift
|
1
|
6178
|
//
// EditTopicViewController.swift
// TypetalkApp
//
// Created by Safx Developer on 2015/02/22.
// Copyright (c) 2015年 Safx Developers. All rights reserved.
//
import Cocoa
import TypetalkKit
import RxSwift
class EditTopicViewController: NSViewController, NSTableViewDataSource, NSTableViewDelegate {
let viewModel = EditTopicViewModel()
@IBOutlet weak var topicNameLabel: NSTextField!
@IBOutlet weak var teamListBox: NSComboBox!
@IBOutlet weak var idLabel: NSTextField!
@IBOutlet weak var createdLabel: NSTextField!
@IBOutlet weak var updatedLabel: NSTextField!
@IBOutlet weak var lastPostedLabel: NSTextField!
@IBOutlet weak var acceptButton: NSButton!
@IBOutlet weak var membersTableView: NSTableView!
@IBOutlet weak var invitesTableView: NSTableView!
private let disposeBag = DisposeBag()
var topic: Topic? = nil {
didSet {
self.viewModel.fetch(topic!)
}
}
override func viewDidLoad() {
super.viewDidLoad()
membersTableView.setDelegate(self)
membersTableView.setDataSource(self)
invitesTableView.setDelegate(self)
invitesTableView.setDataSource(self)
teamListBox.editable = false
acceptButton.enabled = false
precondition(topic != nil)
self.topicNameLabel.stringValue = topic!.name
self.idLabel.stringValue = "\(topic!.id)"
self.createdLabel.stringValue = topic!.createdAt.humanReadableTimeInterval
self.updatedLabel.stringValue = topic!.updatedAt.humanReadableTimeInterval
if let posted = topic!.lastPostedAt {
self.lastPostedLabel.stringValue = posted.humanReadableTimeInterval
}
Observable.combineLatest(viewModel.teamListIndex.asObservable(), viewModel.teamList.asObservable()) { ($0, $1) }
.filter { !$0.1.isEmpty }
.subscribeOn(MainScheduler.instance)
.subscribeNext { (index, teams) -> () in
self.teamListBox.removeAllItems()
self.teamListBox.addItemsWithObjectValues(teams.map { $0.description } )
self.teamListBox.selectItemAtIndex(index)
self.acceptButton.enabled = true
}
.addDisposableTo(disposeBag)
Observable.combineLatest(viewModel.teamList.asObservable(), teamListBox.rx_selectionSignal()) { ($0, $1) }
.filter { teams, idx in teams.count > 0 && (0..<teams.count).contains(idx) }
.map { teams, idx in TeamID(teams[idx].id) }
.bindTo(viewModel.teamId)
.addDisposableTo(disposeBag)
topicNameLabel
.rx_text
.throttle(0.05, scheduler: MainScheduler.instance)
.bindTo(viewModel.topicName)
.addDisposableTo(disposeBag)
viewModel.accounts
.asObservable()
.subscribeOn(MainScheduler.instance)
.subscribeNext { [weak self] _ in
self?.membersTableView.reloadData()
()
}
.addDisposableTo(disposeBag)
viewModel.invites
.asObservable()
.subscribeOn(MainScheduler.instance)
.subscribeNext { [weak self] _ in
self?.invitesTableView.reloadData()
()
}
.addDisposableTo(disposeBag)
}
@IBAction func deleteTopic(sender: AnyObject) {
let alert = NSAlert()
alert.addButtonWithTitle("Delete")
alert.addButtonWithTitle("Cancel")
let bs = alert.buttons as [NSButton]
bs[0].keyEquivalent = "\033"
bs[1].keyEquivalent = "\r"
alert.messageText = "Remove “\(topic!.name)”"
alert.informativeText = "WARNING: All messages in this topic will be removed permanently."
alert.alertStyle = .WarningAlertStyle
if let key = NSApp.keyWindow {
alert.beginSheetModalForWindow(key) { [weak self] res in
if res == NSAlertFirstButtonReturn {
if let s = self {
s.viewModel.deleteTopic()
s.presentingViewController?.dismissViewController(s)
}
}
}
}
}
@IBAction func exit(sender: NSButton) {
presentingViewController?.dismissViewController(self)
}
@IBAction func accept(sender: AnyObject) {
viewModel.updateTopic()
presentingViewController?.dismissViewController(self)
}
// MARK: - NSTableViewDataSource
func numberOfRowsInTableView(tableView: NSTableView) -> Int {
if tableView == membersTableView {
return viewModel.accounts.value.count
} else if tableView == invitesTableView {
return viewModel.invites.value.count
}
return 0
}
func tableView(tableView: NSTableView, objectValueForTableColumn tableColumn: NSTableColumn?, row: Int) -> AnyObject? {
if let i = tableColumn?.identifier {
if tableView == membersTableView && 0 <= row && row < viewModel.accounts.value.count {
let account = viewModel.accounts.value[row]
if i == "image" { return NSImage(contentsOfURL: account.imageUrl) }
if i == "name" { return account.name }
if i == "date" { return account.createdAt.humanReadableTimeInterval }
}
else if tableView == invitesTableView && 0 <= row && row < viewModel.invites.value.count {
let invite = viewModel.invites.value[row]
if i == "image" {
if let a = invite.account {
return NSImage(contentsOfURL: a.imageUrl)
}
}
if i == "name" { return invite.account?.name ?? "" }
if i == "status" { return invite.status }
if i == "date" { return invite.createdAt?.humanReadableTimeInterval ?? "" }
}
}
return nil
}
// MARK: - NSTableViewDelegate
func tableView(tableView: NSTableView, heightOfRow row: Int) -> CGFloat {
return 20
}
}
|
mit
|
7f06457ebbb07cfe779d21fcf276c793
| 35.52071 | 123 | 0.604018 | 5.071487 | false | false | false | false |
GitHubStuff/SwiftIntervals
|
SwiftEventsTests/EventTests.swift
|
1
|
4230
|
//
// EventTests.swift
// SwiftEvents
//
// Created by Steven Smith on 1/9/17.
// Copyright © 2017 LTMM. All rights reserved.
//
import XCTest
import Gloss
class EventTests: XCTestCase {
fileprivate let birthday : String = "1960-12-19T20:56:00Z"
fileprivate let future : String = "2017-01-01T20:56:00Z"
fileprivate let nextXMas : String = "2017-12-25T00:00:00Z"
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 testEventInit() {
}
func testInitEvent() {
let now = Date()
let event = Event()
guard let nowString = DateEnum.stringFrom(date: now) else {
XCTAssertTrue(false)
return
}
XCTAssertEqual(nowString, event.start)
}
func testToString() {
let event = Event()
let asString = event.toJSON()
XCTAssertNotNil(asString)
}
func testInitJSON() {
let now = Date()
let event = Event()
guard let nowString = DateEnum.stringFrom(date: now) else {
XCTAssertTrue(false)
return
}
XCTAssertEqual(nowString, event.start)
let json : JSON = event.toJSON()!
print("json:\(json)")
XCTAssertNotNil(json)
guard let event2 = Event(json: json) else {
XCTAssertTrue(false)
return
}
XCTAssertEqual(event.name, event2.name)
XCTAssertEqual(event.start, event2.start)
XCTAssertEqual(event.finish, event2.finish)
}
func testInitWithStart() {
guard let event = Event(name: "My Event", startTime: birthday) else {
XCTAssertTrue(false)
return
}
XCTAssertEqual(event.start, birthday)
XCTAssertEqual(event.finish, DateEnum.dateWildCard)
}
func testCaptioning() {
guard let event = Event(name: "My Event", startTime: birthday) else {
XCTAssertTrue(false)
return
}
XCTAssertEqual(event.start, birthday)
XCTAssertEqual(event.finish, DateEnum.dateWildCard)
let caption = event.publishCaption()
XCTAssertEqual(caption, "Since " + Date.fromUTC(string: birthday)!)
}
func testFutureCaption() {
guard let event = Event(name: "Next Christmas", startTime: nextXMas) else {
XCTAssertTrue(false)
return
}
XCTAssertEqual(event.start, nextXMas)
XCTAssertEqual(event.finish, DateEnum.dateWildCard)
let caption = event.publishCaption()
XCTAssertEqual(caption, "Until " + Date.fromUTC(string: nextXMas)!)
}
func testDateExtension() {
if let myBirthday = Date.fromUTC(string: birthday) {
XCTAssertEqual(myBirthday, "19-Dec-1960 3:56:00 PM")
} else {
XCTAssertTrue(false)
}
}
func testPublishInterval() {
guard let event = Event(name: "Next Christmas", startTime: future, endTime: nextXMas) else {
XCTAssertTrue(false)
return
}
XCTAssertEqual(event.start, future)
XCTAssertEqual(event.finish, nextXMas)
let caption = event.publishCaption()
let results = "Between \(Date.fromUTC(string: future)!) and \(Date.fromUTC(string: nextXMas)!)"
XCTAssertEqual(results, caption)
let interval = event.publishInterval()
XCTAssertNotEqual(interval, "Hello")
}
func testEventToJSONandBack() {
let event = Event()
let json = event.toString()
XCTAssertNotNil(json)
let data = json?.data(using: .utf8)
if let parsed = try? JSONSerialization.jsonObject(with: data!) as! [String:Any] {
let e = Event(json: parsed)
print("e=\(e)")
XCTAssertNotNil(e)
} else {
XCTAssertNotNil(nil)
}
}
}
|
unlicense
|
47436416b2610e98da7b53e8d1201264
| 29.207143 | 111 | 0.583353 | 4.508529 | false | true | false | false |
ansinlee/meteorology
|
meteorology/MainViewController.swift
|
1
|
3585
|
//
// MainViewController.swift
// meteorology
//
// Created by LeeAnsin on 15/3/21.
// Copyright (c) 2015年 LeeAnsin. All rights reserved.
//
import UIKit
class MainViewController: UITabBarController {
let kScreenWidth:CGFloat = UIScreen.mainScreen().bounds.size.width
let kScreenHeight:CGFloat = UIScreen.mainScreen().bounds.size.height
let tabViewHeight:CGFloat = BottomNavBarHeight
let btnWidth:CGFloat = UIScreen.mainScreen().bounds.size.width / 3
let btnHeight:CGFloat = 36
let navBtnPicArray = ["nav_pedia_normal.png","nav_bbs_normal.png","nav_prof_normal.png",
"nav_pedia_selected.png","nav_bbs_selected.png","nav_prof_selected.png"]
var navBtnArray:NSMutableArray = NSMutableArray(capacity: 3)
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
self.tabBar.hidden = true
self.initVeiwController()
self.initTabBarView()
}
// 初始化视图控制器
func initVeiwController() {
// 初始化各个视图控制器
var vcArray = [PediaViewController(), BBSViewController(), ProfViewController()]
// 初始化导航控制器
var tabArray = NSMutableArray(capacity: vcArray.count)
for vc in vcArray {
tabArray.addObject(UINavigationController(rootViewController: vc))
}
// 将导航控制器给标签控制器
self.viewControllers = tabArray as [AnyObject]
}
// 自定义工具栏
func initTabBarView() {
// 初始化标签工具栏视图
var _tabBarView = UIView(frame: CGRect(x: 0, y: kScreenHeight-tabViewHeight, width: kScreenHeight, height: tabViewHeight))
_tabBarView.backgroundColor = UIColor.whiteColor()
self.view.addSubview(_tabBarView)
// 创建导航按钮
for i in 0..<navBtnPicArray.count/2 {
var btn: UIButton = UIButton.buttonWithType(UIButtonType.Custom) as! UIButton
btn.removeConstraints(btn.constraints());
btn.setBackgroundImage(UIImage(named: navBtnPicArray[(i==0) ? (i+navBtnPicArray.count/2) : i] as String), forState: UIControlState.Normal)
btn.frame = CGRectMake(btnWidth * CGFloat(i), (tabViewHeight - btnHeight) / 2, btnWidth, btnHeight)
btn.tag = 100 + i
btn.addTarget(self, action: "navSelectBtnAction:" , forControlEvents: UIControlEvents.TouchUpInside)
_tabBarView.addSubview(btn)
navBtnArray.addObject(btn)
}
}
// 导航按钮点击事件
func navSelectBtnAction(btn:UIButton) {
self.selectedIndex = btn.tag - 100
for i in 0..<navBtnArray.count {
var index = (navBtnArray[i] as! UIButton).tag - 100
navBtnArray[i].setBackgroundImage(UIImage(named: navBtnPicArray[(self.selectedIndex == index) ? (index+navBtnArray.count) : index] as String), forState: UIControlState.Normal)
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
|
apache-2.0
|
d972f18770bb55be33d782628003f6d3
| 36.064516 | 187 | 0.651581 | 4.482445 | false | false | false | false |
PureSwift/Swallow
|
Sources/Swallow/Texture.swift
|
1
|
3360
|
//
// Texture.swift
// Swallow
//
// Created by Alsey Coleman Miller on 1/23/16.
// Copyright © 2016 PureSwift. All rights reserved.
//
#if os(iOS) || os(tvOS)
import OpenGLES
#endif
/// Represents a texture, an in-memory representation of an image in a compatible format the
/// graphics processor can process.
///
/// Allows to create OpenGL textures from image files, text (font rendering) and raw data.
///
/// - Note: Be aware that the content of the generated texture will be upside-down! This is an OpenGL oddity.
public struct Texture {
public let name: GLuint
public let pixelFormat: PixelFormat
/// Size in pixels.
public let dataSize: (width: UInt, height: UInt)
/// Content size of the texture in pixels.
public let pixelContentSize: Size
public let premultipliedAlpha: Bool
/// Content size of the texture in points.
public var contentSize: Size {
var size = Size()
size.width = pixelContentSize.width / contentScale
size.height = pixelContentSize.height / contentScale
return size
}
public var contentScale: Float
// MARK: - Initialization
public init(data: [UInt8], pixelFormat: PixelFormat = PixelFormat(), dataSize: (width: UInt, height: UInt), pixelContentSize: Size, contentScale: Float) {
// FIXME: 32 bits or POT textures uses UNPACK of 4 (is this correct ??? )
if pixelFormat == .RGBA8888 || pixelFormat == .BGRA8888 || (dataSize.width.nextPowerOfTwo == dataSize.width && dataSize.height.nextPowerOfTwo == dataSize.height) {
glPixelStorei(GLenum(GL_UNPACK_ALIGNMENT), 4)
} else {
glPixelStorei(GLenum(GL_UNPACK_ALIGNMENT), 1)
}
var name: GLuint = 0
glGenTextures(1, &name)
glBindTexture(GLenum(GL_TEXTURE_2D), name)
assert(name != 0, "Could not create OpenGL texture")
glTexParameteri(GLenum(GL_TEXTURE_2D), GLenum(GL_TEXTURE_MIN_FILTER), GLint(GL_LINEAR))
glTexParameteri(GLenum(GL_TEXTURE_2D), GLenum(GL_TEXTURE_MAG_FILTER), GLint(GL_LINEAR))
glTexParameteri(GLenum(GL_TEXTURE_2D), GLenum(GL_TEXTURE_WRAP_S), GLint(GL_CLAMP_TO_EDGE))
glTexParameteri(GLenum(GL_TEXTURE_2D), GLenum(GL_TEXTURE_WRAP_T), GLint(GL_CLAMP_TO_EDGE))
// Specify OpenGL texture image
let glPixelFormat = pixelFormat.glTexImage2D
glTexImage2D(GLenum(GL_TEXTURE_2D), 0, glPixelFormat.internalFormat, GLsizei(dataSize.width), GLsizei(dataSize.height), 0, glPixelFormat.format, glPixelFormat.type, data)
// Set values
self.name = name
self.pixelContentSize = pixelContentSize
self.pixelFormat = pixelFormat
self.dataSize = dataSize
self.contentScale = contentScale
self.premultipliedAlpha = false
}
/// Creates an empty Texture
private init() {
self.name = 0
self.pixelFormat = .RGBA8888
self.pixelSize = (0,0) // width, height
self.pixelContentSize = Size() // sizeInPixels
self.contentScale = 1.0
}
public static let none = Texture()
// MARK: - Methods
}
|
mit
|
b12b3ba544c3e49f977e46b009b7f364
| 30.688679 | 178 | 0.618934 | 4.284439 | false | false | false | false |
brentdax/swift
|
test/Generics/conditional_conformances_literals.swift
|
8
|
4963
|
// RUN: %target-typecheck-verify-swift -typecheck -verify
// rdar://problem/38461036 , https://bugs.swift.org/browse/SR-7192 and highlights the real problem in https://bugs.swift.org/browse/SR-6941
protocol SameType {}
protocol Conforms {}
struct Works: Hashable, Conforms {}
struct Fails: Hashable {}
extension Array: SameType where Element == Works {}
extension Dictionary: SameType where Value == Works {}
extension Array: Conforms where Element: Conforms {}
extension Dictionary: Conforms where Value: Conforms {}
let works = Works()
let fails = Fails()
func arraySameType() {
let arrayWorks = [works]
let arrayFails = [fails]
let _: SameType = [works]
let _: SameType = [fails]
// expected-error@-1 {{value of type '[Fails]' does not conform to specified type 'SameType'}}
let _: SameType = arrayWorks
let _: SameType = arrayFails
// expected-error@-1 {{value of type '[Fails]' does not conform to specified type 'SameType'}}
let _: SameType = [works] as [Works]
let _: SameType = [fails] as [Fails]
// expected-error@-1 {{value of type '[Fails]' does not conform to specified type 'SameType'}}
let _: SameType = [works] as SameType
let _: SameType = [fails] as SameType
// expected-error@-1 {{'[Fails]' is not convertible to 'SameType'}}
let _: SameType = arrayWorks as SameType
let _: SameType = arrayFails as SameType
// expected-error@-1 {{'[Fails]' is not convertible to 'SameType'}}
}
func dictionarySameType() {
let dictWorks: [Int : Works] = [0 : works]
let dictFails: [Int : Fails] = [0 : fails]
let _: SameType = [0 : works]
let _: SameType = [0 : fails]
// expected-error@-1 {{contextual type 'SameType' cannot be used with dictionary literal}}
let _: SameType = dictWorks
let _: SameType = dictFails
// expected-error@-1 {{value of type '[Int : Fails]' does not conform to specified type 'SameType'}}
let _: SameType = [0 : works] as [Int : Works]
let _: SameType = [0 : fails] as [Int : Fails]
// expected-error@-1 {{value of type '[Int : Fails]' does not conform to specified type 'SameType'}}
let _: SameType = [0 : works] as SameType
let _: SameType = [0 : fails] as SameType
// expected-error@-1 {{'[Int : Fails]' is not convertible to 'SameType'}}
let _: SameType = dictWorks as SameType
let _: SameType = dictFails as SameType
// expected-error@-1 {{'[Int : Fails]' is not convertible to 'SameType'}}
}
func arrayConforms() {
let arrayWorks = [works]
let arrayFails = [fails]
let _: Conforms = [works]
let _: Conforms = [fails]
// expected-error@-1 {{value of type '[Fails]' does not conform to specified type 'Conforms'}}
let _: Conforms = arrayWorks
let _: Conforms = arrayFails
// expected-error@-1 {{value of type '[Fails]' does not conform to specified type 'Conforms'}}
let _: Conforms = [works] as [Works]
let _: Conforms = [fails] as [Fails]
// expected-error@-1 {{value of type '[Fails]' does not conform to specified type 'Conforms'}}
let _: Conforms = [works] as Conforms
let _: Conforms = [fails] as Conforms
// expected-error@-1 {{'[Fails]' is not convertible to 'Conforms'}}
let _: Conforms = arrayWorks as Conforms
let _: Conforms = arrayFails as Conforms
// expected-error@-1 {{'[Fails]' is not convertible to 'Conforms'}}
}
func dictionaryConforms() {
let dictWorks: [Int : Works] = [0 : works]
let dictFails: [Int : Fails] = [0 : fails]
let _: Conforms = [0 : works]
let _: Conforms = [0 : fails]
// expected-error@-1 {{contextual type 'Conforms' cannot be used with dictionary literal}}
let _: Conforms = dictWorks
let _: Conforms = dictFails
// expected-error@-1 {{value of type '[Int : Fails]' does not conform to specified type 'Conforms'}}
let _: Conforms = [0 : works] as [Int : Works]
let _: Conforms = [0 : fails] as [Int : Fails]
// expected-error@-1 {{value of type '[Int : Fails]' does not conform to specified type 'Conforms'}}
let _: Conforms = [0 : works] as Conforms
let _: Conforms = [0 : fails] as Conforms
// expected-error@-1 {{'[Int : Fails]' is not convertible to 'Conforms'}}
let _: Conforms = dictWorks as Conforms
let _: Conforms = dictFails as Conforms
// expected-error@-1 {{'[Int : Fails]' is not convertible to 'Conforms'}}
}
func combined() {
let _: Conforms = [[0: [1 : [works]]]]
let _: Conforms = [[0: [1 : [fails]]]]
// expected-error@-1 {{value of type '[[Int : [Int : [Fails]]]]' does not conform to specified type 'Conforms'}}
// Needs self conforming protocols:
let _: Conforms = [[0: [1 : [works]] as Conforms]]
// expected-error@-1 {{value of type '[[Int : Conforms]]' does not conform to specified type 'Conforms'}}
let _: Conforms = [[0: [1 : [fails]] as Conforms]]
// expected-error@-1 {{'[Int : [Fails]]' is not convertible to 'Conforms'}}
}
|
apache-2.0
|
e801f25031481b18810b80d058762c2a
| 37.176923 | 139 | 0.633891 | 3.889498 | false | false | false | false |
fengzhihao123/FZHProjectInitializer
|
Demo/Class/ExampleTabBarViewController.swift
|
1
|
1158
|
//
// ExampleTabBarViewController.swift
// Demo
//
// Created by 冯志浩 on 2017/3/9.
// Copyright © 2017年 FZH. All rights reserved.
//
import UIKit
import FZHProjectInitializer
class ExampleTabBarViewController: FZHTabBarController {
override func viewDidLoad() {
super.viewDidLoad()
initChildVC()
}
func initChildVC() {
let homeVC = HomeViewController()
let findVC = FindViewController()
let messageVC = MessageViewController()
let meVC = MeViewController()
self.selectColor = UIColor.red
self.normalColor = UIColor.brown
self.tabBarHideStyle = TabbarHideStyle.animation
self.setupChildVC(childVC: homeVC, title: "home", imageName: "home_normal", selectImageName: "home_select")
self.setupChildVC(childVC: findVC, title: "find", imageName: "find_normal", selectImageName: "find_select")
self.setupChildVC(childVC: messageVC, title: "message", imageName: "message_normal", selectImageName: "message_select")
self.setupChildVC(childVC: meVC, title: "me", imageName: "me_normal", selectImageName: "me_select")
}
}
|
mit
|
486ab8314bb5086ffd530c78c977c872
| 34.90625 | 127 | 0.679721 | 4.163043 | false | false | false | false |
box/box-ios-sdk
|
Sources/Core/Errors/BoxSDKError.swift
|
1
|
8031
|
//
// BoxSDKError.swift
// BoxSDK-iOS
//
// Created by Sujay Garlanka on 10/14/19.
// Copyright © 2019 box. All rights reserved.
//
import Foundation
/// Box SDK Error
public enum BoxSDKErrorEnum: BoxEnum {
// swiftlint:disable cyclomatic_complexity
/// Box client was destroyed
case clientDestroyed
/// URL is invalid
case invalidURL(urlString: String)
/// The requested resource was not found
case notFound(String)
/// Object needed in closure was deallocated
case instanceDeallocated(String)
/// Could not decode or encode keychain data
case keychainDataConversionError
/// Value not found in Keychain
case keychainNoValue
/// Unhandled keychain error
case keychainUnhandledError(String)
/// Request has hit the maximum number of retries
case rateLimitMaxRetries
/// Value for key is of an unexpected type
case typeMismatch(key: String)
/// Value for key is not one of the accepted values
case valueMismatch(key: String, value: String, acceptedValues: [String])
/// Value for key is of a valid type, but was not able to convert value to expected type
case invalidValueFormat(key: String)
/// Key was not present
case notPresent(key: String)
/// The file representation couldn't be made
case representationCreationFailed
/// Error with TokenStore operation (write, read or clear)
case tokenStoreFailure
/// Unsuccessful token retrieval. Token not found
case tokenRetrieval
/// OAuth web session authorization failed due to invalid redirect configuration
case invalidOAuthRedirectConfiguration
/// Couldn't obtain authorization code from OAuth web session result
case invalidOAuthState
/// Unauthorized request to API
case unauthorizedAccess
/// Unsuccessful refresh token retrieval. Token not found in the retrieved TokenInfo object
case refreshTokenNotFound
/// Access token has expired
case expiredToken
/// Authorization with JWT token failed
case jwtAuthError
/// Authorization with CCG token failed
case ccgAuthError
/// Couldn't create paging iterable for non-paged response
case nonIterableResponse
/// The end of the list was reached
case endOfList
/// Custom error message
case customValue(String)
public init(_ value: String) {
switch value {
case "clientDestroyed":
self = .clientDestroyed
case "keychainDataConversionError":
self = .keychainDataConversionError
case "keychainNoValue":
self = .keychainNoValue
case "rateLimitMaxRetries":
self = .rateLimitMaxRetries
case "representationCreationFailed":
self = .representationCreationFailed
case "tokenStoreFailure":
self = .tokenStoreFailure
case "tokenRetrieval":
self = .tokenRetrieval
case "invalidOAuthRedirectConfiguration":
self = .invalidOAuthRedirectConfiguration
case "invalidOAuthState":
self = .invalidOAuthState
case "unauthorizedAccess":
self = .unauthorizedAccess
case "refreshTokenNotFound":
self = .refreshTokenNotFound
case "expiredToken":
self = .expiredToken
case "jwtAuthError":
self = .jwtAuthError
case "nonIterableResponse":
self = .nonIterableResponse
case "endOfList":
self = .endOfList
default:
self = .customValue(value)
}
}
public var description: String {
switch self {
case .clientDestroyed:
return "Tried to use a BoxClient instance that was already destroyed"
case let .invalidURL(urlString):
return "Invalid URL: \(urlString)"
case let .notFound(message):
return "Not found: \(message)"
case let .instanceDeallocated(message):
return "Object needed in closure was deallocated: \(message)"
case .keychainDataConversionError:
return "Could not decode or encode data for or from keychain"
case .keychainNoValue:
return "Value not found in Keychain"
case let .keychainUnhandledError(message):
return "Unhandled keychain error: \(message)"
case .rateLimitMaxRetries:
return "Request has hit the maximum number of retries"
case let .typeMismatch(key):
return "Value for key \(key) was of an unexpected type"
case let .valueMismatch(key, value, acceptedValues):
return "Value for key \(key) is \(value), which is not one of the accepted values [\(acceptedValues.map { "\(String(describing: $0))" }.joined(separator: ", "))]"
case let .invalidValueFormat(key):
return "Value for key \(key) is of a valid type, but was not able to convert value to expected type"
case let .notPresent(key):
return "Key \(key) was not present"
case .representationCreationFailed:
return "The file representation could not be made"
case .tokenStoreFailure:
return "Could not finish the operation (write, read or clear) on TokenStore object"
case .tokenRetrieval:
return "Unsuccessful token retrieval. Token was not found"
case .invalidOAuthRedirectConfiguration:
return "Failed OAuth web session authorization"
case .invalidOAuthState:
return "Couldn't obtain authorization code from OAuth web session success result"
case .unauthorizedAccess:
return "Unauthorized request to API"
case .refreshTokenNotFound:
return "Unsuccessful refresh token retrieval. Token was not found in the retrieved TokenInfo object"
case .expiredToken:
return "Access token has expired"
case .jwtAuthError:
return "Authorization with JWT token failed"
case .ccgAuthError:
return "Client Credentials Grant authorization failed"
case .nonIterableResponse:
return "Could not create paging iterable for non-paged response"
case .endOfList:
return "The end of the list has been reached"
case let .customValue(userValue):
return userValue
}
}
// swiftlint:enable cyclomatic_complexity
}
extension BoxSDKErrorEnum: ExpressibleByStringLiteral {
public init(stringLiteral value: String) {
self = BoxSDKErrorEnum(value)
}
}
/// Describes general SDK errors
public class BoxSDKError: Error {
/// Type of error
public var errorType: String
/// Error message
public var message: BoxSDKErrorEnum
/// Stack trace
public var stackTrace: [String]
/// Error
public var error: Error?
init(message: BoxSDKErrorEnum = "Internal SDK Error", error: Error? = nil) {
errorType = "BoxSDKError"
self.message = message
stackTrace = Thread.callStackSymbols
self.error = error
}
/// Get a dictionary representing BoxSDKError
public func getDictionary() -> [String: Any] {
var dict = [String: Any]()
dict["errorType"] = errorType
dict["message"] = message.description
dict["stackTrace"] = stackTrace
dict["error"] = error?.localizedDescription
return dict
}
}
extension BoxSDKError: CustomStringConvertible {
/// Provides error JSON string if found.
public var description: String {
guard
let encodedData = try? JSONSerialization.data(withJSONObject: getDictionary(), options: [.prettyPrinted, .sortedKeys]),
let JSONString = String(data: encodedData, encoding: .utf8)
else {
return "<Unparsed Box Error>"
}
return JSONString.replacingOccurrences(of: "\\", with: "")
}
}
extension BoxSDKError: LocalizedError {
public var errorDescription: String? {
return message.description
}
}
|
apache-2.0
|
555e390811d17b99d52722c3f6a17f93
| 36.877358 | 174 | 0.656663 | 5.194049 | false | false | false | false |
atl009/WordPress-iOS
|
WordPress/Classes/Utility/WebProgressView.swift
|
1
|
1421
|
import UIKit
import WordPressShared
/// A view to show progress when loading web pages.
///
/// Since UIWebView doesn't offer any real or estimate loading progress, this
/// shows an initial indication of progress and animates to a full bar when the
/// web view finishes loading.
///
class WebProgressView: UIProgressView {
override init(frame: CGRect) {
super.init(frame: frame)
configure()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
configure()
}
func startedLoading() {
alpha = Animation.visibleAlpha
progress = Progress.initial
}
func finishedLoading() {
UIView.animate(withDuration: Animation.longDuration, animations: { [weak self] in
self?.progress = Progress.final
}, completion: { [weak self] _ in
UIView.animate(withDuration: Animation.shortDuration, animations: {
self?.alpha = Animation.hiddenAlhpa
})
})
}
private func configure() {
progressTintColor = WPStyleGuide.lightBlue()
}
private enum Progress {
static let initial = Float(0.1)
static let final = Float(1.0)
}
private enum Animation {
static let shortDuration = 0.1
static let longDuration = 0.4
static let visibleAlpha = CGFloat(1.0)
static let hiddenAlhpa = CGFloat(0.0)
}
}
|
gpl-2.0
|
8554d15fcfd245b00fa21bb70d9a146a
| 26.862745 | 89 | 0.628431 | 4.583871 | false | true | false | false |
edx/edx-app-ios
|
Source/Core/Code/NetworkManager.swift
|
1
|
19617
|
//
// CourseOutline.swift
// edX
//
// Created by Jake Lim on 5/09/15.
// Copyright (c) 2015-2016 edX. All rights reserved.
//
import Foundation
public enum HTTPMethod: String {
case GET = "GET"
case POST = "POST"
case PUT = "PUT"
case DELETE = "DELETE"
case PATCH = "PATCH"
}
public enum RequestBody {
case jsonBody(JSON)
case formEncoded([String:String])
case dataBody(data : Data, contentType: String)
case emptyBody
}
private enum DeserializationResult<Out> {
case deserializedResult(value : Result<Out>, original : Data?)
case reauthenticationRequest(AuthenticateRequestCreator, original: Data?)
}
public typealias AuthenticateRequestCreator = (_ _networkManager: NetworkManager, _ _completion: @escaping (_ _success : Bool) -> Void) -> Void
public enum AuthenticationAction {
case proceed
case authenticate(AuthenticateRequestCreator)
public var isProceed : Bool {
switch self {
case .proceed: return true
case .authenticate(_): return false
}
}
public var isAuthenticate : Bool {
switch self {
case .proceed: return false
case .authenticate(_): return true
}
}
}
public enum ResponseDeserializer<Out> {
case jsonResponse((HTTPURLResponse, JSON) -> Result<Out>)
case dataResponse((HTTPURLResponse, NSData) -> Result<Out>)
case noContent((HTTPURLResponse) -> Result<Out>)
func map<A>(_ f: @escaping (Out) -> A) -> ResponseDeserializer<A> {
switch self {
case let .jsonResponse(d): return .jsonResponse({(request, json) in d(request, json).map(f)})
case let .dataResponse(d): return .dataResponse({(request, data) in d(request, data).map(f)})
case let .noContent(d): return .noContent({args in d(args).map(f)})
}
}
}
public protocol ResponseInterceptor {
func handleResponse<Out>(_ result: NetworkResult<Out>) -> Result<Out>
}
public struct NetworkRequest<Out> {
public let method : HTTPMethod
public let path : String // Absolute URL or URL relative to the API base
public let requiresAuth : Bool
public let body : RequestBody
public let query: [String:JSON]
public let deserializer : ResponseDeserializer<Out>
public let additionalHeaders: [String: String]?
public init(method : HTTPMethod,
path : String,
requiresAuth : Bool = false,
body : RequestBody = .emptyBody,
query : [String:JSON] = [:],
headers: [String: String]? = nil,
deserializer : ResponseDeserializer<Out>) {
self.method = method
self.path = path
self.requiresAuth = requiresAuth
self.body = body
self.query = query
self.deserializer = deserializer
self.additionalHeaders = headers
}
public func map<A>(_ f : @escaping (Out) -> A) -> NetworkRequest<A> {
return NetworkRequest<A>(method: method, path: path, requiresAuth: requiresAuth, body: body, query: query, headers: additionalHeaders, deserializer: deserializer.map(f))
}
}
extension NetworkRequest: CustomDebugStringConvertible {
public var debugDescription: String { return "\(type(of: self)) {\(method):\(path)}" }
}
public struct NetworkResult<Out> {
public let request: URLRequest?
public let response: HTTPURLResponse?
public let data: Out?
public let baseData : Data?
public let error: NSError?
public init(request : URLRequest?, response : HTTPURLResponse?, data : Out?, baseData : Data?, error : NSError?) {
self.request = request
self.response = response
self.data = data
self.error = error
self.baseData = baseData
}
}
open class NetworkTask : Removable {
let request : Request
fileprivate init(request : Request) {
self.request = request
}
open func remove() {
request.cancel()
}
}
@objc public protocol AuthorizationHeaderProvider {
var authorizationHeaders : [String:String] { get }
}
@objc public protocol URLCredentialProvider {
func URLCredentialForHost(_ host : NSString) -> URLCredential?
}
@objc public protocol NetworkManagerProvider {
var networkManager : NetworkManager { get }
}
extension NSError {
public static func oex_unknownNetworkError() -> NSError {
return NSError(domain: NetworkManager.errorDomain, code: NetworkManager.Error.unknownError.rawValue, userInfo: nil)
}
static func oex_HTTPError(_ statusCode : Int, userInfo: [AnyHashable: Any]) -> NSError {
return NSError(domain: NetworkManager.errorDomain, code: statusCode, userInfo: userInfo as? [String : Any])
}
public static func oex_outdatedVersionError() -> NSError {
return NSError(domain: NetworkManager.errorDomain, code: NetworkManager.Error.outdatedVersionError.rawValue, userInfo: nil)
}
@objc public var oex_isNoInternetConnectionError : Bool {
return self.domain == NSURLErrorDomain && (self.code == NSURLErrorNotConnectedToInternet || self.code == NSURLErrorNetworkConnectionLost)
}
public func errorIsThisType(_ error: NSError) -> Bool {
return error.domain == NetworkManager.errorDomain && error.code == self.code
}
}
open class NetworkManager : NSObject {
fileprivate static let errorDomain = "com.edx.NetworkManager"
enum Error : Int {
case unknownError = -1
case outdatedVersionError = -2
}
public static let NETWORK = "NETWORK" // Logger key
public typealias JSONInterceptor = (_ _response : HTTPURLResponse, _ _json : JSON) -> Result<JSON>
public typealias Authenticator = (_ _response: HTTPURLResponse?, _ _data: Data) -> AuthenticationAction
public let baseURL : URL
fileprivate let authorizationHeaderProvider: AuthorizationHeaderProvider?
fileprivate let credentialProvider : URLCredentialProvider?
fileprivate let cache : ResponseCache
fileprivate var jsonInterceptors : [JSONInterceptor] = []
fileprivate var responseInterceptors: [ResponseInterceptor] = []
open var authenticator : Authenticator?
@objc public init(authorizationHeaderProvider: AuthorizationHeaderProvider? = nil, credentialProvider : URLCredentialProvider? = nil, baseURL : URL, cache : ResponseCache) {
self.authorizationHeaderProvider = authorizationHeaderProvider
self.credentialProvider = credentialProvider
self.baseURL = baseURL
self.cache = cache
}
public static var unknownError : NSError { return NSError.oex_unknownNetworkError() }
/// Allows you to add a processing pass to any JSON response.
/// Typically used to check for errors that can be sent by any request
open func addJSONInterceptor(_ interceptor : @escaping (HTTPURLResponse,JSON) -> Result<JSON>) {
jsonInterceptors.append(interceptor)
}
open func addResponseInterceptors(_ interceptor: ResponseInterceptor) {
responseInterceptors.append(interceptor)
}
open func URLRequestWithRequest<Out>(base: String? = nil, _ request : NetworkRequest<Out>) -> Result<URLRequest> {
var formattedBaseURL: URL
if let baseURL = base, let url = URL(string: baseURL) {
formattedBaseURL = url
} else {
formattedBaseURL = self.baseURL
}
return URL(string: request.path, relativeTo: formattedBaseURL).toResult(NetworkManager.unknownError).flatMap { url -> Result<Foundation.URLRequest> in
let urlRequest = Foundation.URLRequest(url: url)
if request.query.count == 0 {
return .success(urlRequest)
}
var queryParams : [String:String] = [:]
for (key, value) in request.query {
if let stringValue = value.rawString(options : JSONSerialization.WritingOptions()) {
queryParams[key] = stringValue
}
}
// Alamofire has a kind of contorted API where you can encode parameters over URLs
// or through the POST body, but you can't do both at the same time.
//
// So first we encode the get parameters
let (paramRequest, error) = ParameterEncoding.url.encode(urlRequest, parameters: queryParams as [String : AnyObject]?)
if let error = error {
return .failure(error)
}
else {
return .success(paramRequest)
}
}
.flatMap { urlRequest in
let mutableURLRequest = (urlRequest as NSURLRequest).mutableCopy() as! NSMutableURLRequest
if request.requiresAuth {
for (key, value) in self.authorizationHeaderProvider?.authorizationHeaders ?? [:] {
mutableURLRequest.setValue(value, forHTTPHeaderField: key)
}
}
mutableURLRequest.httpMethod = request.method.rawValue
if let additionalHeaders = request.additionalHeaders {
for (header, value) in additionalHeaders {
mutableURLRequest.setValue(value, forHTTPHeaderField: header)
}
}
// Now we encode the body
switch request.body {
case .emptyBody:
return .success(mutableURLRequest as URLRequest)
case let .dataBody(data: data, contentType: contentType):
mutableURLRequest.httpBody = data
mutableURLRequest.setValue(contentType, forHTTPHeaderField: "Content-Type")
return .success(mutableURLRequest as URLRequest)
case let .formEncoded(dict):
let (bodyRequest, error) = ParameterEncoding.url.encode(mutableURLRequest as URLRequest, parameters: dict as [String : AnyObject]?)
if let error = error {
return .failure(error)
}
else {
return .success(bodyRequest)
}
case let .jsonBody(json):
let (bodyRequest, error) = ParameterEncoding.json.encode(mutableURLRequest as URLRequest, parameters: json.dictionaryObject ?? [:] )
if let error = error {
return .failure(error)
}
else {
let mutableURLRequest = (bodyRequest as NSURLRequest).mutableCopy() as! NSMutableURLRequest
if let additionalHeaders = request.additionalHeaders {
for (header, value) in additionalHeaders {
mutableURLRequest.setValue(value, forHTTPHeaderField: header)
}
}
return .success(mutableURLRequest as URLRequest)
}
}
}
}
fileprivate static func deserialize<Out>(_ deserializer : ResponseDeserializer<Out>, interceptors : [JSONInterceptor], response : HTTPURLResponse?, data : Data?, error: NSError) -> Result<Out> {
if let response = response {
switch deserializer {
case let .jsonResponse(f):
if let data = data,
let raw : AnyObject = try? JSONSerialization.jsonObject(with: data, options: JSONSerialization.ReadingOptions()) as AnyObject
{
let json = JSON(raw)
let result = interceptors.reduce(.success(json)) {(current : Result<JSON>, interceptor : @escaping (_ _response : HTTPURLResponse, _ _json : JSON) -> Result<JSON>) -> Result<JSON> in
return current.flatMap {interceptor(response, $0)}
}
return result.flatMap {
return f(response, $0)
}
}
else {
return .failure(error)
}
case let .dataResponse(f):
return data.toResult(error).flatMap { f(response, $0 as NSData) }
case let .noContent(f):
if response.hasErrorResponseCode() { // server error
guard let data = data,
let raw : AnyObject = try? JSONSerialization.jsonObject(with: data, options: JSONSerialization.ReadingOptions()) as AnyObject else {
return .failure(error)
}
let userInfo = JSON(raw).object as? [AnyHashable: Any]
return .failure(NSError.oex_HTTPError(response.statusCode, userInfo: userInfo ?? [:]))
}
return f(response)
}
}
else {
return .failure(error)
}
}
@discardableResult open func taskForRequest<Out>(base: String? = nil, _ networkRequest : NetworkRequest<Out>, handler: @escaping (NetworkResult<Out>) -> Void) -> Removable {
let URLRequest = URLRequestWithRequest(base: base, networkRequest)
let authenticator = self.authenticator
let interceptors = jsonInterceptors
let task = URLRequest.map {URLRequest -> NetworkTask in
Logger.logInfo(NetworkManager.NETWORK, "Request is \(URLRequest)")
let task = Manager.sharedInstance.request(URLRequest)
let serializer = { (URLRequest : Foundation.URLRequest, response : HTTPURLResponse?, data : Data?) -> (AnyObject?, NSError?) in
switch authenticator?(response, data!) ?? .proceed {
case .proceed:
let result = NetworkManager.deserialize(networkRequest.deserializer, interceptors: interceptors, response: response, data: data, error: NetworkManager.unknownError)
return (Box(DeserializationResult.deserializedResult(value : result, original : data)), result.error)
case .authenticate(let authenticateRequest):
let result = Box<DeserializationResult<Out>>(DeserializationResult.reauthenticationRequest(authenticateRequest, original: data))
return (result, nil)
}
}
task.response(serializer: serializer) { (request, response, object, error) in
let parsed = (object as? Box<DeserializationResult<Out>>)?.value
switch parsed {
case let .some(.deserializedResult(value, original)):
let result = NetworkResult<Out>(request: request, response: response, data: value.value, baseData: original, error: error)
Logger.logInfo(NetworkManager.NETWORK, "Response is \(String(describing: response))")
handler(result)
case let .some(.reauthenticationRequest(authHandler, originalData)):
authHandler(self, {success in
if success {
Logger.logInfo(NetworkManager.NETWORK, "Reauthentication, reattempting original request")
self.taskForRequest(base: base, networkRequest, handler: handler)
}
else {
Logger.logInfo(NetworkManager.NETWORK, "Reauthentication unsuccessful")
handler(NetworkResult<Out>(request: request, response: response, data: nil, baseData: originalData, error: error))
}
})
case .none:
assert(false, "Deserialization failed in an unexpected way")
handler(NetworkResult<Out>(request:request, response:response, data: nil, baseData: nil, error: error))
}
}
if let
host = URLRequest.url?.host,
let credential = self.credentialProvider?.URLCredentialForHost(host as NSString)
{
task.authenticate(usingCredential: credential)
}
task.resume()
return NetworkTask(request: task)
}
switch task {
case let .success(t): return t
case let .failure(error):
DispatchQueue.main.async {
handler(NetworkResult(request: nil, response: nil, data: nil, baseData : nil, error: error))
}
return BlockRemovable {}
}
}
fileprivate func combineWithPersistentCacheFetch<Out>(_ stream : OEXStream<Out>, request : NetworkRequest<Out>) -> OEXStream<Out> {
if let URLRequest = URLRequestWithRequest(request).value {
let cacheStream = Sink<Out>()
let interceptors = jsonInterceptors
cache.fetchCacheEntryWithRequest(URLRequest, completion: {(entry : ResponseCacheEntry?) -> Void in
if let entry = entry {
DispatchQueue.global(qos: DispatchQoS.QoSClass.default).async {
[weak cacheStream] in
let result = NetworkManager.deserialize(request.deserializer, interceptors: interceptors, response: entry.response, data: entry.data, error: NetworkManager.unknownError)
DispatchQueue.main.async {[weak cacheStream] in
cacheStream?.close()
cacheStream?.send(result)
}
}
}
else {
cacheStream.close()
if let error = stream.error, error.oex_isNoInternetConnectionError {
cacheStream.send(error)
}
}
})
return stream.cachedByStream(cacheStream)
}
else {
return stream
}
}
open func streamForRequest<Out>(_ request : NetworkRequest<Out>, persistResponse : Bool = false, autoCancel : Bool = true) -> OEXStream<Out> {
let stream = Sink<NetworkResult<Out>>()
let task = self.taskForRequest(request) {[weak stream, weak self] result in
if let response = result.response, let request = result.request, let data = result.baseData, (persistResponse && data.count > 0) {
self?.cache.setCacheResponse(response, withData: data, forRequest: request, completion: nil)
}
stream?.close()
stream?.send(result)
}
var result : OEXStream<Out> = stream.flatMap {(result : NetworkResult<Out>) -> Result<Out> in
return self.handleResponse(result)
}
if persistResponse {
result = combineWithPersistentCacheFetch(result, request: request)
}
if autoCancel {
result = result.autoCancel(task)
}
return result
}
fileprivate func handleResponse<Out>(_ networkResult: NetworkResult<Out>) -> Result<Out> {
var result:Result<Out>?
for responseInterceptor in self.responseInterceptors {
result = responseInterceptor.handleResponse(networkResult)
if case .none = result {
break
}
}
return result ?? networkResult.data.toResult(NetworkManager.unknownError)
}
}
|
apache-2.0
|
f2be089e08c6383a9977219541d5970b
| 41.645652 | 202 | 0.591834 | 5.371577 | false | false | false | false |
nguyenantinhbk77/Swift
|
MediaPlayerFrameworkVideoSample1/MediaPlayerFrameworkVideoSample1/ViewController.swift
|
33
|
1538
|
//
// ViewController.swift
// MediaPlayerFrameworkVideoSample1
//
// Created by Carlos Butron on 07/12/14.
// Copyright (c) 2014 Carlos Butron.
//
// This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public
// License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later
// version.
// This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied
// warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
// You should have received a copy of the GNU General Public License along with this program. If not, see
// http:/www.gnu.org/licenses/.
//
import UIKit
import MediaPlayer
class ViewController: UIViewController {
var theMovie:MPMoviePlayerController!
override func viewDidLoad() {
super.viewDidLoad()
var bundle = NSBundle.mainBundle()
//our video is 02.mov
var moviePath = bundle.pathForResource("02", ofType: "mov")
var url = NSURL(fileURLWithPath: moviePath!)
theMovie = MPMoviePlayerController(contentURL: url)
theMovie.view.frame = CGRectMake(25.0, 20.0, 270, 270);
self.view.addSubview(theMovie.view)
theMovie.play()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
|
gpl-3.0
|
4f76b69d7a6cda07549b94cde2521604
| 33.954545 | 121 | 0.69961 | 4.47093 | false | false | false | false |
hooman/swift
|
test/Concurrency/Runtime/custom_executors.swift
|
2
|
1355
|
// RUN: %target-run-simple-swift( -Xfrontend -disable-availability-checking %import-libdispatch -parse-as-library) | %FileCheck %s
// REQUIRES: concurrency
// REQUIRES: executable_test
// UNSUPPORTED: back_deployment_runtime
// UNSUPPORTED: use_os_stdlib
// Disabled until test hang can be looked at.
// UNSUPPORTED: OS=windows-msvc
actor Simple {
var count = 0
func report() {
print("simple.count == \(count)")
count += 1
}
}
actor Custom {
var count = 0
let simple = Simple()
@available(SwiftStdlib 5.5, *)
nonisolated var unownedExecutor: UnownedSerialExecutor {
print("custom unownedExecutor")
return simple.unownedExecutor
}
func report() async {
print("custom.count == \(count)")
count += 1
await simple.report()
}
}
@available(SwiftStdlib 5.5, *)
@main struct Main {
static func main() async {
print("begin")
let actor = Custom()
await actor.report()
await actor.report()
await actor.report()
print("end")
}
}
// CHECK: begin
// CHECK-NEXT: custom unownedExecutor
// CHECK-NEXT: custom.count == 0
// CHECK-NEXT: simple.count == 0
// CHECK-NEXT: custom unownedExecutor
// CHECK-NEXT: custom.count == 1
// CHECK-NEXT: simple.count == 1
// CHECK-NEXT: custom unownedExecutor
// CHECK-NEXT: custom.count == 2
// CHECK-NEXT: simple.count == 2
// CHECK-NEXT: end
|
apache-2.0
|
7766a56895685a65c3bc2e804de7ea2d
| 21.583333 | 130 | 0.665683 | 3.702186 | false | false | false | false |
czerenkow/LublinWeather
|
App/Camera Container/CameraContainerBuilder.swift
|
1
|
1115
|
//
// CameraContainerBuilder.swift
// LublinWeather
//
// Created by Damian Rzeszot on 05/05/2018.
// Copyright © 2018 Damian Rzeszot. All rights reserved.
//
import UIKit
protocol CameraContainerDependency: Dependency {
var localizer: Localizer { get }
}
final class CameraContainerBuilder: Builder<CameraContainerDependency> {
func build() -> CameraContainerRouter {
let vc = CameraContainerViewController()
let interactor = CameraContainerInteractor()
let router = CameraContainerRouter()
let component = CameraContainerComponent(dependency: dependency)
router.controller = vc
router.interactor = interactor
router.builders.capture = CameraCaptureBuilder(dependency: component)
router.builders.permission = CameraPermissionBuilder(dependency: component)
router.builders.preview = CameraPreviewBuilder(dependency: component)
interactor.router = router
interactor.presenter = vc
vc.handler = router
vc.modalPresentationCapturesStatusBarAppearance = true
return router
}
}
|
mit
|
bacc9a7f54f5ceb6fdb50793654db982
| 25.52381 | 83 | 0.713645 | 5.086758 | false | false | false | false |
elpassion/el-space-ios
|
ELSpaceTests/TestCases/ViewControllers/LoginViewControllerSpec.swift
|
1
|
5557
|
import Quick
import Nimble
import GoogleSignIn
import RxTest
@testable import ELSpace
class LoginViewControllerSpec: QuickSpec {
override func spec() {
describe("LoginViewController") {
var sut: LoginViewController!
var navigationController: UINavigationController!
var viewControllerPresenterSpy: ViewControllerPresenterSpy!
var googleUserManagerSpy: GoogleUserManagerSpy!
afterEach {
sut = nil
navigationController = nil
viewControllerPresenterSpy = nil
googleUserManagerSpy = nil
}
context("when try to initialize with init coder") {
it("should throw fatalError") {
expect { sut = LoginViewController(coder: NSCoder()) }.to(throwAssertion())
}
}
context("after initialize") {
beforeEach {
viewControllerPresenterSpy = ViewControllerPresenterSpy()
googleUserManagerSpy = GoogleUserManagerSpy()
sut = LoginViewController(googleUserManager: googleUserManagerSpy,
alertFactory: AlertFactoryFake(),
viewControllerPresenter: viewControllerPresenterSpy,
googleUserMapper: GoogleUSerMapperFake())
navigationController = UINavigationController(rootViewController: sut)
}
describe("view") {
it("should be kind of LoginView") {
expect(sut.view as? LoginView).toNot(beNil())
}
context("when appear") {
beforeEach {
sut.viewWillAppear(true)
}
it("should set navigation bar hidden") {
expect(navigationController.isNavigationBarHidden).to(beTrue())
}
}
}
context("when viewDidAppear") {
beforeEach {
sut.viewDidAppear(true)
}
it("should call autoSignIn") {
expect(googleUserManagerSpy.didCallAutoSignIn).to(beTrue())
}
}
context("when viewWillAppear") {
beforeEach {
sut.viewWillAppear(true)
}
it("should set navigation bar to hidden") {
expect(navigationController.isNavigationBarHidden).to(beTrue())
}
}
it("should have correct preferredStatusBarStyle") {
expect(sut.preferredStatusBarStyle == .lightContent).to(beTrue())
}
context("when tap sign in button and sign in with success") {
var resultToken: String!
beforeEach {
sut.googleTooken = { token in
resultToken = token
}
googleUserManagerSpy.resultUser = GIDGoogleUser()
sut.loginView.loginButton.sendActions(for: .touchUpInside)
}
it("should sign in on correct view controller") {
expect(googleUserManagerSpy.viewController).to(equal(sut))
}
it("should get correct token") {
expect(resultToken).to(equal("fake_token"))
}
}
context("when tap sign in button and sign in with ValidationError emialFormat") {
beforeEach {
googleUserManagerSpy.resultError = EmailValidator.EmailValidationError.emailFormat
sut.loginView.loginButton.sendActions(for: .touchUpInside)
}
it("should present error on correct view controller") {
expect(viewControllerPresenterSpy.presenter).to(equal(sut))
}
}
context("when tap sign in button and sign in with ValidationError incorrectDomain") {
beforeEach {
googleUserManagerSpy.resultError = EmailValidator.EmailValidationError.incorrectDomain
sut.loginView.loginButton.sendActions(for: .touchUpInside)
}
it("should present error on correct view controller") {
expect(viewControllerPresenterSpy.presenter).to(equal(sut))
}
}
context("when tap sign in button and sign in with unkown error") {
beforeEach {
googleUserManagerSpy.resultError = NSError(domain: "fake_domain",
code: 999,
userInfo: nil)
sut.loginView.loginButton.sendActions(for: .touchUpInside)
}
it("should NOT present error") {
expect(viewControllerPresenterSpy.presenter).to(beNil())
}
}
}
}
}
}
|
gpl-3.0
|
cfdc10090e4a6de252c1ed09b87c9d56
| 38.692857 | 110 | 0.478316 | 6.963659 | false | false | false | false |
davefoxy/SwiftBomb
|
Example/SwiftBomb/DetailViewControllers/VideoViewController.swift
|
1
|
1878
|
//
// VideoViewController.swift
// SwiftBomb
//
// Created by David Fox on 07/05/2016.
// Copyright © 2016 David Fox. All rights reserved.
//
import Foundation
import UIKit
import SwiftBomb
class VideoViewController: BaseResourceDetailViewController {
var video: VideoResource?
override func viewDidLoad() {
super.viewDidLoad()
video?.fetchExtendedInfo() { [weak self] error in
self?.tableView.reloadData()
}
}
override func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 1
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath) as UITableViewCell
cell.textLabel?.numberOfLines = 0
cell.textLabel?.lineBreakMode = .byWordWrapping
var infos = [ResourceInfoTuple(value: video?.name, "Name:"), ResourceInfoTuple(value: video?.deck, "Deck:")]
if let publishDate = video?.publish_date {
infos.append(ResourceInfoTuple(value: dateFormatter.string(from: publishDate), "Publish Date:"))
}
let minutesDuration = (video?.length_seconds)! / 60
let lengthString = "\(minutesDuration) minutes"
infos.append(ResourceInfoTuple(value: lengthString, "Duration:"))
cell.textLabel?.attributedText = createResourceInfoString(infos)
return cell
}
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
tableView.deselectRow(at: indexPath, animated: true)
}
}
|
mit
|
9f63a390a6d446ecffd761dc1b0711d9
| 29.274194 | 116 | 0.634523 | 5.257703 | false | false | false | false |
overtake/TelegramSwift
|
Telegram-Mac/ChannelAdminsViewController.swift
|
1
|
23322
|
//
// GroupAdminsViewController.swift
// Telegram
//
// Created by keepcoder on 22/02/2017.
// Copyright © 2017 Telegram. All rights reserved.
//
import Cocoa
import TGUIKit
import Postbox
import TelegramCore
import SwiftSignalKit
fileprivate final class ChannelAdminsControllerArguments {
let context: AccountContext
let addAdmin: () -> Void
let openAdmin: (RenderedChannelParticipant) -> Void
let removeAdmin: (PeerId) -> Void
let eventLogs:() -> Void
init(context: AccountContext, addAdmin:@escaping()->Void, openAdmin:@escaping(RenderedChannelParticipant) -> Void, removeAdmin:@escaping(PeerId)->Void, eventLogs: @escaping()->Void) {
self.context = context
self.addAdmin = addAdmin
self.openAdmin = openAdmin
self.removeAdmin = removeAdmin
self.eventLogs = eventLogs
}
}
fileprivate enum ChannelAdminsEntryStableId: Hashable {
case index(Int32)
case peer(PeerId)
var hashValue: Int {
switch self {
case let .index(index):
return index.hashValue
case let .peer(peerId):
return peerId.hashValue
}
}
}
fileprivate enum ChannelAdminsEntry : Identifiable, Comparable {
case eventLogs(sectionId:Int32, GeneralViewType)
case adminsHeader(sectionId:Int32, String, GeneralViewType)
case adminPeerItem(sectionId:Int32, Int32, RenderedChannelParticipant, ShortPeerDeleting?, GeneralViewType)
case addAdmin(sectionId:Int32, GeneralViewType)
case adminsInfo(sectionId:Int32, String, GeneralViewType)
case section(Int32)
case loading
var stableId: ChannelAdminsEntryStableId {
switch self {
case .adminsHeader:
return .index(2)
case .addAdmin:
return .index(3)
case .adminsInfo:
return .index(4)
case .eventLogs:
return .index(5)
case .loading:
return .index(6)
case let .section(sectionId):
return .index((sectionId + 1) * 1000 - sectionId)
case let .adminPeerItem(_, _, participant, _, _):
return .peer(participant.peer.id)
}
}
var index:Int32 {
switch self {
case .loading:
return 0
case let .eventLogs(sectionId, _):
return (sectionId * 1000) + 1
case let .adminsHeader(sectionId, _, _):
return (sectionId * 1000) + 2
case let .addAdmin(sectionId, _):
return (sectionId * 1000) + 3
case let .adminsInfo(sectionId, _, _):
return (sectionId * 1000) + 4
case let .adminPeerItem(sectionId, index, _, _, _):
return (sectionId * 1000) + index + 20
case let .section(sectionId):
return (sectionId + 1) * 1000 - sectionId
}
}
static func <(lhs: ChannelAdminsEntry, rhs: ChannelAdminsEntry) -> Bool {
return lhs.index < rhs.index
}
}
fileprivate struct ChannelAdminsControllerState: Equatable {
let editing: Bool
let removingPeerId: PeerId?
let removedPeerIds: Set<PeerId>
let temporaryAdmins: [RenderedChannelParticipant]
init() {
self.editing = false
self.removingPeerId = nil
self.removedPeerIds = Set()
self.temporaryAdmins = []
}
init(editing: Bool, removingPeerId: PeerId?, removedPeerIds: Set<PeerId>, temporaryAdmins: [RenderedChannelParticipant]) {
self.editing = editing
self.removingPeerId = removingPeerId
self.removedPeerIds = removedPeerIds
self.temporaryAdmins = temporaryAdmins
}
func withUpdatedEditing(_ editing: Bool) -> ChannelAdminsControllerState {
return ChannelAdminsControllerState(editing: editing, removingPeerId: self.removingPeerId, removedPeerIds: self.removedPeerIds, temporaryAdmins: self.temporaryAdmins)
}
func withUpdatedPeerIdWithRevealedOptions(_ peerIdWithRevealedOptions: PeerId?) -> ChannelAdminsControllerState {
return ChannelAdminsControllerState(editing: self.editing, removingPeerId: self.removingPeerId, removedPeerIds: self.removedPeerIds, temporaryAdmins: self.temporaryAdmins)
}
func withUpdatedRemovingPeerId(_ removingPeerId: PeerId?) -> ChannelAdminsControllerState {
return ChannelAdminsControllerState(editing: self.editing, removingPeerId: removingPeerId, removedPeerIds: self.removedPeerIds, temporaryAdmins: self.temporaryAdmins)
}
func withUpdatedRemovedPeerIds(_ removedPeerIds: Set<PeerId>) -> ChannelAdminsControllerState {
return ChannelAdminsControllerState(editing: self.editing, removingPeerId: self.removingPeerId, removedPeerIds: removedPeerIds, temporaryAdmins: self.temporaryAdmins)
}
func withUpdatedTemporaryAdmins(_ temporaryAdmins: [RenderedChannelParticipant]) -> ChannelAdminsControllerState {
return ChannelAdminsControllerState(editing: self.editing, removingPeerId: self.removingPeerId, removedPeerIds: self.removedPeerIds, temporaryAdmins: temporaryAdmins)
}
}
private func channelAdminsControllerEntries(accountPeerId: PeerId, view: PeerView, state: ChannelAdminsControllerState, participants: [RenderedChannelParticipant]?, isCreator: Bool) -> [ChannelAdminsEntry] {
var entries: [ChannelAdminsEntry] = []
let participants = participants ?? []
var sectionId:Int32 = 1
entries.append(.section(sectionId))
sectionId += 1
if let peer = view.peers[view.peerId] as? TelegramChannel {
var isGroup = false
if case .group = peer.info {
isGroup = true
}
entries.append(.eventLogs(sectionId: sectionId, .singleItem))
entries.append(.section(sectionId))
sectionId += 1
entries.append(.adminsHeader(sectionId: sectionId, isGroup ? strings().adminsGroupAdmins : strings().adminsChannelAdmins, .textTopItem))
if peer.hasPermission(.addAdmins) {
entries.append(.addAdmin(sectionId: sectionId, .singleItem))
entries.append(.adminsInfo(sectionId: sectionId, isGroup ? strings().adminsGroupDescription : strings().adminsChannelDescription, .textBottomItem))
entries.append(.section(sectionId))
sectionId += 1
}
var index: Int32 = 0
for (i, participant) in participants.sorted(by: <).enumerated() {
var editable = true
switch participant.participant {
case .creator:
editable = false
case let .member(id, _, adminInfo, _, _):
if id == accountPeerId {
editable = false
} else if let adminInfo = adminInfo {
if peer.flags.contains(.isCreator) || adminInfo.promotedBy == accountPeerId {
editable = true
} else {
editable = false
}
} else {
editable = false
}
}
let editing:ShortPeerDeleting?
if state.editing {
editing = ShortPeerDeleting(editable: editable)
} else {
editing = nil
}
entries.append(.adminPeerItem(sectionId: sectionId, index, participant, editing, bestGeneralViewType(participants, for: i)))
index += 1
}
if index > 0 {
entries.append(.section(sectionId))
sectionId += 1
}
} else if let peer = view.peers[view.peerId] as? TelegramGroup {
entries.append(.adminsHeader(sectionId: sectionId, strings().adminsGroupAdmins, .textTopItem))
if case .creator = peer.role {
entries.append(.addAdmin(sectionId: sectionId, .singleItem))
entries.append(.adminsInfo(sectionId: sectionId, strings().adminsGroupDescription, .textBottomItem))
entries.append(.section(sectionId))
sectionId += 1
}
var combinedParticipants: [RenderedChannelParticipant] = participants
var existingParticipantIds = Set<PeerId>()
for participant in participants {
existingParticipantIds.insert(participant.peer.id)
}
for participant in state.temporaryAdmins {
if !existingParticipantIds.contains(participant.peer.id) {
combinedParticipants.append(participant)
}
}
var index: Int32 = 0
let participants = combinedParticipants.sorted(by: <).filter {
!state.removedPeerIds.contains($0.peer.id)
}
for (i, participant) in participants.enumerated() {
var editable = true
switch participant.participant {
case .creator:
editable = false
case let .member(id, _, adminInfo, _, _):
if id == accountPeerId {
editable = false
} else if let adminInfo = adminInfo {
var creator: Bool = false
if case .creator = peer.role {
creator = true
}
if creator || adminInfo.promotedBy == accountPeerId {
editable = true
} else {
editable = false
}
} else {
editable = false
}
}
let editing:ShortPeerDeleting?
if state.editing {
editing = ShortPeerDeleting(editable: editable)
} else {
editing = nil
}
entries.append(.adminPeerItem(sectionId: sectionId, index, participant, editing, bestGeneralViewType(participants, for: i)))
index += 1
}
if index > 0 {
entries.append(.section(sectionId))
sectionId += 1
}
}
return entries.sorted(by: <)
}
fileprivate func prepareTransition(left:[AppearanceWrapperEntry<ChannelAdminsEntry>], right: [AppearanceWrapperEntry<ChannelAdminsEntry>], initialSize:NSSize, arguments:ChannelAdminsControllerArguments, isSupergroup:Bool) -> TableUpdateTransition {
let (removed, inserted, updated) = proccessEntriesWithoutReverse(left, right: right) { entry -> TableRowItem in
switch entry.entry {
case let .adminPeerItem(_, _, participant, editing, viewType):
let peerText: String
switch participant.participant {
case .creator:
peerText = strings().adminsOwner
case let .member(_, _, adminInfo, _, _):
if let adminInfo = adminInfo, let peer = participant.peers[adminInfo.promotedBy] {
peerText = strings().channelAdminsPromotedBy(peer.displayTitle)
} else {
peerText = strings().adminsAdmin
}
}
let interactionType:ShortPeerItemInteractionType
if let editing = editing {
interactionType = .deletable(onRemove: { adminId in
arguments.removeAdmin(adminId)
}, deletable: editing.editable)
} else {
interactionType = .plain
}
return ShortPeerRowItem(initialSize, peer: participant.peer, account: arguments.context.account, context: arguments.context, stableId: entry.stableId, status: peerText, inset: NSEdgeInsets(left: 30, right: 30), interactionType: interactionType, generalType: .none, viewType: viewType, action: {
if editing == nil {
arguments.openAdmin(participant)
}
})
case let .addAdmin(_, viewType):
return GeneralInteractedRowItem(initialSize, stableId: entry.stableId, name: strings().adminsAddAdmin, nameStyle: blueActionButton, type: .next, viewType: viewType, action: arguments.addAdmin)
case let .eventLogs(_, viewType):
return GeneralInteractedRowItem(initialSize, stableId: entry.stableId, name: strings().channelAdminsRecentActions, type: .next, viewType: viewType, action: {
arguments.eventLogs()
})
case .section:
return GeneralRowItem(initialSize, height: 30, stableId: entry.stableId, viewType: .separator)
case .loading:
return SearchEmptyRowItem(initialSize, stableId: entry.stableId, isLoading: true)
case let .adminsHeader(_, text, viewType):
return GeneralTextRowItem(initialSize, stableId: entry.stableId, text: text, viewType: viewType)
case let .adminsInfo(_, text, viewType):
return GeneralTextRowItem(initialSize, stableId: entry.stableId, text: text, viewType: viewType)
}
}
return TableUpdateTransition(deleted: removed, inserted: inserted, updated: updated, animated: true)
}
class ChannelAdminsViewController: EditableViewController<TableView> {
fileprivate let statePromise = ValuePromise(ChannelAdminsControllerState(), ignoreRepeated: true)
fileprivate let stateValue = Atomic(value: ChannelAdminsControllerState())
private let peerId:PeerId
private let addAdminDisposable:MetaDisposable = MetaDisposable()
private let disposable:MetaDisposable = MetaDisposable()
private let removeAdminDisposable:MetaDisposable = MetaDisposable()
private let openPeerDisposable:MetaDisposable = MetaDisposable()
init( _ context:AccountContext, peerId:PeerId) {
self.peerId = peerId
super.init(context)
}
let actionsDisposable = DisposableSet()
let updateAdministrationDisposable = MetaDisposable()
override func viewDidLoad() {
super.viewDidLoad()
genericView.getBackgroundColor = {
theme.colors.listBackground
}
let context = self.context
let peerId = self.peerId
var upgradedToSupergroupImpl: ((PeerId, @escaping () -> Void) -> Void)?
let upgradedToSupergroup: (PeerId, @escaping () -> Void) -> Void = { upgradedPeerId, f in
upgradedToSupergroupImpl?(upgradedPeerId, f)
}
let adminsPromise = ValuePromise<[RenderedChannelParticipant]?>(nil)
let updateState: ((ChannelAdminsControllerState) -> ChannelAdminsControllerState) -> Void = { [weak self] f in
if let strongSelf = self {
strongSelf.statePromise.set(strongSelf.stateValue.modify { f($0) })
}
}
let viewValue:Atomic<PeerView?> = Atomic(value: nil)
let arguments = ChannelAdminsControllerArguments(context: context, addAdmin: {
let behavior = peerId.namespace == Namespaces.Peer.CloudGroup ? SelectGroupMembersBehavior(peerId: peerId, limit: 1) : SelectChannelMembersBehavior(peerId: peerId, peerChannelMemberContextsManager: context.peerChannelMemberCategoriesContextsManager, limit: 1)
_ = (selectModalPeers(window: context.window, context: context, title: strings().adminsAddAdmin, limit: 1, behavior: behavior, confirmation: { peerIds in
if let _ = behavior.participants[peerId] {
return .single(true)
} else {
return .single(true)
}
}) |> map {$0.first}).start(next: { adminId in
if let adminId = adminId {
showModal(with: ChannelAdminController(context, peerId: peerId, adminId: adminId, initialParticipant: behavior.participants[adminId]?.participant, updated: { _ in }, upgradedToSupergroup: upgradedToSupergroup), for: context.window)
}
})
}, openAdmin: { participant in
showModal(with: ChannelAdminController(context, peerId: peerId, adminId: participant.peer.id, initialParticipant: participant.participant, updated: { _ in }, upgradedToSupergroup: upgradedToSupergroup), for: context.window)
}, removeAdmin: { [weak self] adminId in
updateState {
return $0.withUpdatedRemovingPeerId(adminId)
}
if peerId.namespace == Namespaces.Peer.CloudGroup {
self?.removeAdminDisposable.set((context.engine.peers.removeGroupAdmin(peerId: peerId, adminId: adminId)
|> deliverOnMainQueue).start(completed: {
updateState {
return $0.withUpdatedRemovingPeerId(nil)
}
}))
} else {
self?.removeAdminDisposable.set((context.peerChannelMemberCategoriesContextsManager.updateMemberAdminRights(peerId: peerId, memberId: adminId, adminRights: nil, rank: nil)
|> deliverOnMainQueue).start(completed: {
updateState {
return $0.withUpdatedRemovingPeerId(nil)
}
}))
}
}, eventLogs: { [weak self] in
self?.navigationController?.push(ChannelEventLogController(context, peerId: peerId))
})
let peerView = Promise<PeerView>()
peerView.set(context.account.viewTracker.peerView(peerId))
let membersAndLoadMoreControl: (Disposable, PeerChannelMemberCategoryControl?)
if peerId.namespace == Namespaces.Peer.CloudChannel {
membersAndLoadMoreControl = context.peerChannelMemberCategoriesContextsManager.admins(peerId: peerId, updated: { membersState in
if case .loading = membersState.loadingState, membersState.list.isEmpty {
adminsPromise.set(nil)
} else {
adminsPromise.set(membersState.list)
}
})
} else {
let membersDisposable = (peerView.get()
|> map { peerView -> [RenderedChannelParticipant]? in
guard let cachedData = peerView.cachedData as? CachedGroupData, let participants = cachedData.participants else {
return nil
}
var result: [RenderedChannelParticipant] = []
var creatorPeer: Peer?
for participant in participants.participants {
if let peer = peerView.peers[participant.peerId] {
switch participant {
case .creator:
creatorPeer = peer
default:
break
}
}
}
guard let creator = creatorPeer else {
return nil
}
for participant in participants.participants {
if let peer = peerView.peers[participant.peerId] {
switch participant {
case .creator:
result.append(RenderedChannelParticipant(participant: .creator(id: peer.id, adminInfo: nil, rank: nil), peer: peer))
case .admin:
var peers: [PeerId: Peer] = [:]
peers[creator.id] = creator
peers[peer.id] = peer
result.append(RenderedChannelParticipant(participant: .member(id: peer.id, invitedAt: 0, adminInfo: ChannelParticipantAdminInfo(rights: TelegramChatAdminRights(rights: .internal_groupSpecific), promotedBy: creator.id, canBeEditedByAccountPeer: creator.id == context.account.peerId), banInfo: nil, rank: nil), peer: peer, peers: peers))
case .member:
break
}
}
}
return result
}).start(next: { members in
adminsPromise.set(members)
})
membersAndLoadMoreControl = (membersDisposable, nil)
}
let (membersDisposable, _) = membersAndLoadMoreControl
actionsDisposable.add(membersDisposable)
let initialSize = atomicSize
let previousEntries:Atomic<[AppearanceWrapperEntry<ChannelAdminsEntry>]> = Atomic(value: [])
let signal = combineLatest(statePromise.get(), peerView.get(), adminsPromise.get(), appearanceSignal)
|> map { state, view, admins, appearance -> (TableUpdateTransition, Bool) in
var isCreator = false
var isSupergroup = false
if let channel = peerViewMainPeer(view) as? TelegramChannel {
isCreator = channel.flags.contains(.isCreator)
isSupergroup = channel.isSupergroup
}
_ = viewValue.swap(view)
let entries = channelAdminsControllerEntries(accountPeerId: context.peerId, view: view, state: state, participants: admins, isCreator: isCreator).map{AppearanceWrapperEntry(entry: $0, appearance: appearance)}
return (prepareTransition(left: previousEntries.swap(entries), right: entries, initialSize: initialSize.modify{$0}, arguments: arguments, isSupergroup: isSupergroup), isCreator)
}
disposable.set((signal |> deliverOnMainQueue).start(next: { [weak self] transition, isCreator in
self?.rightBarView.isHidden = !isCreator
self?.genericView.merge(with: transition)
self?.readyOnce()
}))
upgradedToSupergroupImpl = { [weak self] upgradedPeerId, f in
guard let `self` = self, let navigationController = self.navigationController else {
return
}
let chatController = ChatController(context: context, chatLocation: .peer(upgradedPeerId))
navigationController.removeAll()
navigationController.push(chatController, false, style: .none)
let signal = chatController.ready.get() |> filter {$0} |> take(1) |> deliverOnMainQueue |> ignoreValues
_ = signal.start(completed: { [weak navigationController] in
navigationController?.push(ChannelAdminsViewController(context, peerId: upgradedPeerId), false, style: .none)
f()
})
}
}
override func update(with state: ViewControllerState) {
super.update(with: state)
self.statePromise.set(stateValue.modify({$0.withUpdatedEditing(state == .Edit)}))
}
deinit {
addAdminDisposable.dispose()
disposable.dispose()
removeAdminDisposable.dispose()
updateAdministrationDisposable.dispose()
openPeerDisposable.dispose()
actionsDisposable.dispose()
}
}
|
gpl-2.0
|
69847d1eff4edc02e19710f6a0ed7c9e
| 41.712454 | 367 | 0.595601 | 5.290608 | false | false | false | false |
AdamZikmund/strv
|
strv/strv/Classes/Model/City.swift
|
1
|
2284
|
//
// City.swift
// strv
//
// Created by Adam Zikmund on 12.05.15.
// Copyright (c) 2015 Adam Zikmund. All rights reserved.
//
import UIKit
class City: NSObject, NSCoding, Hashable {
let stateCode : String
var stateName : String? = nil
let name : String
var weather : Weather?
var forecast : [Weather] = []
override var hashValue : Int {
return "\(self.name)\(self.stateCode)".hashValue
}
init(stateCode : String, name : String) {
self.stateCode = stateCode
self.name = name
}
init(stateCode : String, stateName : String, name : String) {
self.stateCode = stateCode
self.stateName = stateName
self.name = name
}
required init(coder aDecoder: NSCoder) {
stateCode = aDecoder.decodeObjectForKey("stateCode") as! String
stateName = aDecoder.decodeObjectForKey("stateName") as? String
name = aDecoder.decodeObjectForKey("name") as! String
}
func encodeWithCoder(aCoder: NSCoder) {
aCoder.encodeObject(stateCode, forKey: "stateCode")
aCoder.encodeObject(stateName, forKey: "stateName")
aCoder.encodeObject(name, forKey: "name")
}
override func isEqual(object: AnyObject?) -> Bool {
if let city = object as? City {
if self.hashValue == city.hashValue {
return true
}else{
return false
}
}else{
return false
}
}
func updateWeather(completionHandler : () -> Void){
ForecastHandler.getWeatherForCity(self, completionHandler: { (weather) -> Void in
self.weather = weather
dispatch_async(dispatch_get_main_queue()) {
completionHandler()
}
})
}
func updateForecast(completionHandler : () -> Void){
ForecastHandler.getForecastForCity(self, completionHandler: { (forecast) -> Void in
self.forecast = forecast
dispatch_async(dispatch_get_main_queue()) {
completionHandler()
}
})
}
}
func ==(lhs: City, rhs: City) -> Bool{
if lhs.hashValue == rhs.hashValue {
return true
}else{
return false
}
}
|
mit
|
a4b8ae4eb43cadf3eb0e4016785525be
| 26.202381 | 91 | 0.573993 | 4.558882 | false | false | false | false |
pennlabs/penn-mobile-ios
|
PennMobile/Dining/SwiftUI/DiningAnalyticsViewModel.swift
|
1
|
9950
|
//
// DiningAnalyticsViewModel.swift
// PennMobile
//
// Created by Andrew Antenberg on 3/27/22.
// Copyright © 2022 PennLabs. All rights reserved.
//
import Foundation
import XLPagerTabStrip
import SwiftUI
struct DiningAnalyticsBalance: Codable {
let date: Date
let balance: Double
}
class DiningAnalyticsViewModel: ObservableObject {
static let dollarHistoryDirectory = "diningAnalyticsDollarData"
static let swipeHistoryDirectory = "diningAnalyticsSwipeData"
@Published var dollarHistory: [DiningAnalyticsBalance] = Storage.fileExists(dollarHistoryDirectory, in: .documents) ? Storage.retrieve(dollarHistoryDirectory, from: .documents, as: [DiningAnalyticsBalance].self) : []
@Published var swipeHistory: [DiningAnalyticsBalance] = Storage.fileExists(swipeHistoryDirectory, in: .documents) ? Storage.retrieve(swipeHistoryDirectory, from: .documents, as: [DiningAnalyticsBalance].self) : []
@Published var dollarPredictedZeroDate: Date = Date.endOfSemester
@Published var predictedDollarSemesterEndBalance: Double = 0
@Published var swipesPredictedZeroDate: Date = Date.endOfSemester
@Published var predictedSwipesSemesterEndBalance: Double = 0
@Published var swipeAxisLabel: ([String], [String]) = ([], [])
@Published var dollarAxisLabel: ([String], [String]) = ([], [])
@Published var dollarSlope: Double = 0.0
@Published var swipeSlope: Double = 0.0
var yIntercept = 0.0
var slope = 0.0
let formatter = DateFormatter()
init() {
formatter.dateFormat = "yyyy-MM-dd"
clearStorageIfNewSemester()
}
func clearStorageIfNewSemester() {
if Storage.fileExists(DiningAnalyticsViewModel.dollarHistoryDirectory, in: .documents), let nextAnalyticsStartDate = Storage.retrieve(DiningAnalyticsViewModel.dollarHistoryDirectory, from: .documents, as: [DiningAnalyticsBalance].self).last?.date,
nextAnalyticsStartDate < Date.startOfSemester {
self.dollarHistory = []
self.swipeHistory = []
Storage.remove(DiningAnalyticsViewModel.dollarHistoryDirectory, from: .documents)
Storage.remove(DiningAnalyticsViewModel.swipeHistoryDirectory, from: .documents)
}
}
func refresh() async {
guard let diningToken = KeychainAccessible.instance.getDiningToken() else {
return
}
var startDate = dollarHistory.last?.date ?? Date.startOfSemester
if startDate != Date.startOfSemester {
startDate = Calendar.current.date(byAdding: .day, value: 1, to: startDate)!
}
let startDateStr = formatter.string(from: startDate)
let balances = await DiningAPI.instance.getPastDiningBalances(diningToken: diningToken, startDate: startDateStr)
switch balances {
case .failure:
return
case .success(let balanceList):
let planStartDateResult = await DiningAPI.instance.getDiningPlanStartDate(diningToken: diningToken)
if startDateStr != self.formatter.string(from: Date()) {
let newDollarHistory = balanceList.map({DiningAnalyticsBalance(date: self.formatter.date(from: $0.date)!, balance: Double($0.diningDollars) ?? 0.0)})
let newSwipeHistory = balanceList.map({DiningAnalyticsBalance(date: self.formatter.date(from: $0.date)!, balance: Double($0.regularVisits))})
self.swipeHistory.append(contentsOf: newSwipeHistory)
self.dollarHistory.append(contentsOf: newDollarHistory)
Storage.store(self.swipeHistory, to: .documents, as: DiningAnalyticsViewModel.swipeHistoryDirectory)
Storage.store(self.dollarHistory, to: .documents, as: DiningAnalyticsViewModel.dollarHistoryDirectory)
}
guard let lastDollarBalance = self.dollarHistory.last,
let lastSwipeBalance = self.swipeHistory.last else {
return
}
guard let maxDollarBalance = (self.dollarHistory.max { $0.balance < $1.balance }),
let maxSwipeBalance = (self.swipeHistory.max { $0.balance < $1.balance }) else {
return
}
// If no dining plan found, refresh will return, these are just placeholders
var startDollarBalance = maxDollarBalance
var startSwipeBalance = maxSwipeBalance
switch planStartDateResult {
case .failure:
return
case .success(let planStartDate):
// If dining plan found, start prediction from the date dining plan started
startDollarBalance = (self.dollarHistory.first { $0.date == planStartDate }) ?? startDollarBalance
startSwipeBalance = (self.swipeHistory.first { $0.date == planStartDate }) ?? startSwipeBalance
// However, it's possible that people recharged dining dollars (swipes maybe?), and if so, predict from this date (most recent increase)
for (i, day) in self.dollarHistory.enumerated() {
if i != 0 && day.date > planStartDate && day.balance > self.dollarHistory[i - 1].balance {
startDollarBalance = day
}
}
for (i, day) in self.swipeHistory.enumerated() {
if i != 0 && day.date > planStartDate && day.balance > self.swipeHistory[i - 1].balance {
startSwipeBalance = day
}
}
}
let dollarPredictions = self.getPredictions(firstBalance: startDollarBalance, lastBalance: lastDollarBalance, maxBalance: maxDollarBalance)
self.dollarSlope = dollarPredictions.slope
self.dollarPredictedZeroDate = dollarPredictions.predictedZeroDate
self.predictedDollarSemesterEndBalance = dollarPredictions.predictedEndBalance
self.dollarAxisLabel = self.getAxisLabelsYX(from: self.dollarHistory)
let swipePredictions = self.getPredictions(firstBalance: startSwipeBalance, lastBalance: lastSwipeBalance, maxBalance: maxSwipeBalance)
self.swipeSlope = swipePredictions.slope
self.swipesPredictedZeroDate = swipePredictions.predictedZeroDate
self.predictedSwipesSemesterEndBalance = swipePredictions.predictedEndBalance
self.swipeAxisLabel = self.getAxisLabelsYX(from: self.swipeHistory)
}
}
func getPredictions(firstBalance: DiningAnalyticsBalance, lastBalance: DiningAnalyticsBalance, maxBalance: DiningAnalyticsBalance) -> (slope: Double, predictedZeroDate: Date, predictedEndBalance: Double) {
if firstBalance.date == lastBalance.date || firstBalance.balance == lastBalance.balance {
let zeroDate = Calendar.current.date(byAdding: .day, value: 1, to: Date.endOfSemester)!
return (Double(0.0), zeroDate, lastBalance.balance)
} else {
// This is the slope needed to calculate zeroDate and endBalance
var slope = self.getSlope(firstBalance: firstBalance, lastBalance: lastBalance)
let zeroDate = self.predictZeroDate(firstBalance: firstBalance, lastBalance: lastBalance, slope: slope)
let endBalance = self.predictSemesterEndBalance(firstBalance: firstBalance, lastBalance: lastBalance, slope: slope)
let fullSemester = Date.startOfSemester.distance(to: Date.endOfSemester)
let fullZeroDistance = firstBalance.date.distance(to: zeroDate)
let deltaX = fullZeroDistance / fullSemester
let deltaY = firstBalance.balance / maxBalance.balance
slope = -deltaY / deltaX // Resetting slope to different value for graph format
return (slope, zeroDate, endBalance)
}
}
func getSlope(firstBalance: DiningAnalyticsBalance, lastBalance: DiningAnalyticsBalance) -> Double {
let balanceDiff = lastBalance.balance - firstBalance.balance
let timeDiff = Double(Calendar.current.dateComponents([.day], from: firstBalance.date, to: lastBalance.date).day!)
return balanceDiff / timeDiff
}
func predictZeroDate(firstBalance: DiningAnalyticsBalance, lastBalance: DiningAnalyticsBalance, slope: Double) -> Date {
let offset = -firstBalance.balance / slope
let zeroDate = Calendar.current.date(byAdding: .day, value: Int(offset), to: firstBalance.date)!
return zeroDate
}
func predictSemesterEndBalance(firstBalance: DiningAnalyticsBalance, lastBalance: DiningAnalyticsBalance, slope: Double) -> Double {
let diffInDays = Calendar.current.dateComponents([.day], from: firstBalance.date, to: Date.endOfSemester).day!
let endBalance = (slope * Double(diffInDays)) + firstBalance.balance
return endBalance
}
// Compute axis labels
func getAxisLabelsYX(from trans: [DiningAnalyticsBalance]) -> ([String], [String]) {
let xAxisLabelCount = 4
let yAxisLabelCount = 5
var xLabels: [String] = []
var yLabels: [String] = []
// Generate Y Axis Labels
let maxDollarValue = trans.max(by: { $0.balance < $1.balance })?.balance ?? 1.0
let dollarStep = (maxDollarValue / Double(yAxisLabelCount - 1))
for i in 0 ..< yAxisLabelCount {
let yAxisLabel = "\(Int(dollarStep * Double(yAxisLabelCount - i - 1)))"
yLabels.append(yAxisLabel)
}
// Generate X Axis Labels
let semester = Date.startOfSemester.distance(to: Date.endOfSemester)
let semesterStep = semester / Double(xAxisLabelCount - 1)
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "M/d"
for i in 0 ..< xAxisLabelCount {
let dateForLabel = Date.startOfSemester.advanced(by: semesterStep * Double(i))
xLabels.append(dateFormatter.string(from: dateForLabel))
}
return (yLabels, xLabels)
}
}
|
mit
|
fe1889211b9f816d49502f60c16178b4
| 56.178161 | 255 | 0.674741 | 4.576357 | false | false | false | false |
alexandreblin/ios-car-dashboard
|
CarDash/DashboardViewController.swift
|
1
|
10502
|
//
// DashboardViewController.swift
// CarDash
//
// Created by Alexandre Blin on 12/06/2016.
// Copyright © 2016 Alexandre Blin. All rights reserved.
//
import UIKit
/// Main view controller displayed on the external screen.
///
/// Contains a view controller on the left which depends on
/// what audio source is currently selected (FM, Bluetooth or Aux)
///
/// Also contains trip info view controller on the right displaying
/// trip computer data and a live fuel usage graph.
///
/// Displays the current time and outside temperature at the top.
class DashboardViewController: CarObservingViewController {
/// Main container view. Has a fixed size of 1280x720 and is then scaled
/// to the external screen resolution.
@IBOutlet private weak var dashboardView: UIView!
/// Current audio source label
@IBOutlet private weak var modeLabel: UILabel!
@IBOutlet private weak var hoursLabel: UILabel!
@IBOutlet private weak var minutesLabel: UILabel!
@IBOutlet private weak var timeColonLabel: UILabel!
@IBOutlet private weak var temperatureLabel: UILabel!
private var popupView: PopupView! = nil
private var audioSettingsView: AudioSettingsView! = nil
private var subViewControllers: [CarInfo.CarRadioSource: UIViewController] = [:]
private weak var displayedViewController: UIViewController? = nil
@IBOutlet private weak var mainContainerView: UIView!
private var volumePopupTimer: Timer? = nil
// TODO: move this in a subclass
@IBOutlet private weak var volumeContainerView: UIView!
@IBOutlet private weak var volumePopup: UIView!
@IBOutlet private weak var volumeLabel: UILabel!
@IBOutlet private weak var volumeBarWidthConstraint: NSLayoutConstraint!
@IBOutlet private weak var volumePopupYConstraint: NSLayoutConstraint!
override func viewDidLoad() {
super.viewDidLoad()
// Setup child view controllers
if let viewController = storyboard?.instantiateViewController(withIdentifier: "radioViewController") {
subViewControllers[.fmTuner] = viewController
}
if let viewController = storyboard?.instantiateViewController(withIdentifier: "bluetoothViewController") {
subViewControllers[.phone] = viewController
}
if let viewController = storyboard?.instantiateViewController(withIdentifier: "jackViewController") {
subViewControllers[.aux] = viewController
}
for viewController in subViewControllers.values {
viewController.view.backgroundColor = UIColor.clear
}
switchToSource(.fmTuner)
// Prepare popup view to display messages and audio settings view (hidden by default)
popupView = Bundle.main.loadNibNamed("PopupView", owner: nil, options: nil)?.first as? PopupView
popupView.isHidden = true
popupView.addToView(dashboardView)
audioSettingsView = Bundle.main.loadNibNamed("AudioSettingsView", owner: nil, options: nil)?.first as? AudioSettingsView
audioSettingsView.isHidden = true
audioSettingsView.addToView(dashboardView)
// Setup time and temperature labels
updateTime()
Timer.scheduledTimer(timeInterval: 1.0, target: self, selector: #selector(DashboardViewController.updateTime), userInfo: nil, repeats: true)
updateTemperature()
Timer.scheduledTimer(timeInterval: 5.0, target: self, selector: #selector(DashboardViewController.updateTemperature), userInfo: nil, repeats: true)
volumePopupYConstraint.constant = -400
}
override func viewWillLayoutSubviews() {
super.viewWillLayoutSubviews()
// Scale the view to the external screen's bounds. This makes sure the view is always
// displayed the same way on any screen resolution. This could be removed since the
// external screen I'm now using has a fixed resolution and is unlikely to change.
dashboardView.transform = CGAffineTransform(scaleX: view.bounds.width / dashboardView.bounds.width, y: view.bounds.height / dashboardView.bounds.height)
}
private func switchToSource(_ source: CarInfo.CarRadioSource) {
guard let newViewController = subViewControllers[source] else {
return
}
// Fade the new subViewController into view
addChildViewController(newViewController)
mainContainerView.addSubview(newViewController.view)
newViewController.view.frame = mainContainerView.bounds
displayedViewController?.willMove(toParentViewController: nil)
newViewController.view.alpha = 0
UIView.animate(withDuration: 0.2, animations: {
newViewController.view.alpha = 1
self.displayedViewController?.view.alpha = 0
switch source {
case .fmTuner:
self.modeLabel.text = "Radio FM"
case .phone:
self.modeLabel.text = "Auxiliaire 1"
case .aux:
self.modeLabel.text = "Auxiliaire 2"
}
}, completion: { _ in
self.displayedViewController?.view.removeFromSuperview()
self.displayedViewController?.removeFromParentViewController()
newViewController.didMove(toParentViewController: self)
self.displayedViewController = newViewController
})
}
override func carInfoPropertyChanged(_ carInfo: CarInfo, property: CarInfo.Property) {
// Update view when data changes on the CAN bus
if property == .radioSource {
switchToSource(carInfo.radioSource)
} else if property == .infoMessage {
if let message = carInfo.infoMessage {
// Show message
popupView.textLabel.text = message
popupView.setImage(nil)
if popupView.isHidden {
popupView.alpha = 0
popupView.isHidden = false
UIView.animate(withDuration: 0.2, animations: {
self.popupView.alpha = 1
})
}
} else {
// Hide message
UIView.animate(withDuration: 0.2, animations: {
self.popupView.alpha = 0
}, completion: { _ in
self.popupView.isHidden = true
})
}
} else if property == .carDoors {
if carInfo.carDoors != .None {
// Display car doors status if at least one door is open
popupView.textLabel.text = carInfo.carDoors.stringRepresentation()
popupView.setImage(carInfo.carDoors.imageRepresentation())
if popupView.isHidden {
popupView.alpha = 0
popupView.isHidden = false
UIView.animate(withDuration: 0.2, animations: {
self.popupView.alpha = 1
})
}
} else {
// Hide car doors status
UIView.animate(withDuration: 0.2, animations: {
self.popupView.alpha = 0
}, completion: { _ in
self.popupView.isHidden = true
})
}
} else if property == .audioSettings {
if carInfo.audioSettings.activeMode != .none {
// Display audio settings
audioSettingsView.audioSettings = carInfo.audioSettings
if audioSettingsView.isHidden {
audioSettingsView.alpha = 0
audioSettingsView.isHidden = false
UIView.animate(withDuration: 0.2, animations: {
self.audioSettingsView.alpha = 1
})
}
} else {
// Hide audio settings
if !audioSettingsView.isHidden {
UIView.animate(withDuration: 0.2, animations: {
self.audioSettingsView.alpha = 0
}, completion: { _ in
self.audioSettingsView.isHidden = true
})
}
}
} else if property == .volume {
// Animate volume bar into view
displayVolumeBar()
UIView.animate(withDuration: 0.2, animations: {
self.volumeBarWidthConstraint.constant = CGFloat(self.carInfo.volume) * (self.volumeContainerView.bounds.width / 30.0)
self.volumePopup.layoutIfNeeded()
})
volumeLabel.text = "\(carInfo.volume)"
}
}
/// Displays the volume bar and hides it after 500ms of inactivity
private func displayVolumeBar() {
volumePopupTimer?.invalidate()
volumePopupTimer = Timer.scheduledTimer(timeInterval: 3, target: self, selector: #selector(DashboardViewController.hideVolumeBar), userInfo: nil, repeats: false)
if !volumePopup.isHidden {
return
}
volumePopup.isHidden = false
UIView.animate(withDuration: 0.5, delay: 0, usingSpringWithDamping: 0.7, initialSpringVelocity: 0.5, options: .beginFromCurrentState, animations: {
self.volumePopupYConstraint.constant = -275
self.volumePopup.layoutIfNeeded()
}) { _ in }
}
func hideVolumeBar() {
if volumePopup.isHidden {
return
}
UIView.animate(withDuration: 0.5, delay: 0, usingSpringWithDamping: 0.7, initialSpringVelocity: 0.5, options: .beginFromCurrentState, animations: {
self.volumePopupYConstraint.constant = -400
self.volumePopup.layoutIfNeeded()
}) { _ in
self.volumePopup.isHidden = true
}
}
func updateTime() {
UIView.animate(withDuration: 0.2, animations: {
self.timeColonLabel.alpha = self.timeColonLabel.alpha > 0 ? 0 : 1
})
let dateComponents = (Calendar.current as NSCalendar).components([.hour, .minute], from: Date())
guard let hour = dateComponents.hour, let minute = dateComponents.minute else {
return
}
hoursLabel.text = "\(hour)"
minutesLabel.text = String(format: "%02ld", minute)
}
func updateTemperature() {
temperatureLabel.text = "\(carInfo.temperature)º"
}
override var prefersStatusBarHidden: Bool {
return true
}
}
|
mit
|
a68d70a9dfbeb3fd78f3955754e1fb98
| 37.602941 | 169 | 0.620667 | 5.236908 | false | false | false | false |
Gatada/Bits
|
Sources/JBits/Foundation/Utility/Log.swift
|
1
|
7888
|
//
// Log.swift
// JBits
//
// Created by Johan Basberg on 16/12/2019.
// Copyright © 2019 Johan Basberg. All rights reserved.
//
import Foundation
import os.log
/// Logging related helpers, details and types used by `xc_log()`.
public enum Log {
// MARK: - Properties
/// By default the output is associated with this subsystem.
private static var subsystem = Bundle.main.bundleIdentifier!
/// The logging category to be used for the log message.
///
/// The category will determine if the message is printed only
/// in the Xcode console or also output in the Terminal for the
/// given process.
public enum Category: String {
/// Used for general and usually temporary output.
///
/// Logs of this kind are usually added to track execution flow or show state information
/// that is not useful once the feature is fully developed or refactored. Logs in this category
/// are usually removed before the code is committed.
case `default`
/// Used to log state information.
///
/// Info logs will usually be left in the application even
/// after the feature is fully implemented.
case info
/// Used for debug related state expectations during development.
///
/// An error marks the result of a bug. Errors are hard to catch,
/// which is why debug logs are some times used.
///
/// When the wrong variable is used or the design is incorrectly
/// implemented by the developer the result is an error. If a variable
/// is received with unexpected or invalid values an error occurs.
///
/// Ideally messages using this log category should be self-contained and
/// their validity verifiable. In other words, include your expectation and the
/// actual value:
///
/// ```
/// Expecting 5 == 4
/// ```
///
/// Debug output should usually be removed after the feature has been
/// fully implemented.
case debug
/// Used for to log unintended behaviour caused by bugs.
///
/// When an application executes code that were not suppose to be
/// reached, you experience a fault. A fault could be a non-critical anomaly
/// that emerges from refactoring.
///
/// Fault logs are useful for the inevitable refactoring and should
/// therefore not be removed.
case fault
/// Used to log a failure to fulfill performance requirements.
///
/// Tests can be used to prevent failure. Assertions can also be
/// used to catch or inform the developer about failures even
/// before testing begins.
case failure
/// A suitable emoji that marks the beginning of a log message.
var emoji: Character {
switch self {
case .default:
return "📎"
case .info:
return "ℹ️"
case .debug:
return "🧑🏼💻"
case .fault:
return "⁉️"
case .failure:
return "❌"
}
}
/// Mapping a Category to a suitable OSLog type.
var osLogEquivalent: OSLog {
return OSLog(subsystem: subsystem, category: self.rawValue)
}
/// Maps the Category to a suitable OSLogType.
///
/// Only some of the existing OSLogTypes seem to appear in
/// the Console, which is handled by this mapping.
var osLogTypeEquivalent: OSLogType {
switch self {
case .default, .info, .debug:
return OSLogType.default
case .fault:
return OSLogType.fault
case .failure:
return OSLogType.error
}
}
}
/// The default subsystem used when logging.
public static let mainBundle = Bundle.main.bundleIdentifier!
// MARK: - API
/// Use to temporary log events in the Xcode debug area.
///
/// These calls will be completely removed for release or any non-debugging build.
///
/// - Parameters:
/// - messages: A variadic parameter of strings to print in the debug area.
/// - log: Use this to group logs into a suitable `Category`.
/// - subsystem: A string describing a subsystem. Default value is the main bundle identifier.
/// - terminator: The string appended to the end of the messages. By default this is `\n`.
public static func da(_ messages: String..., log: Log.Category, prefix customEmoji: Character? = nil, subsystem: String = Log.mainBundle, terminator: String = "\n") {
assert(Log.debugAreaPrint(messages, terminator: terminator, log: log, customEmoji: customEmoji, subsystem: subsystem))
}
/// Send one or more messages to both the Xcode debug area and the OS logging system.
///
/// The messages received by the logging system are retained in a ring buffer managed
/// by the operating system. All received log messages can be exported on the device,
/// however the file is usually quite large (probably too large to send by email).
///
/// To review the log messages in real time please launch the Console app on your Mac.
/// Make sure you have selected the correct device when browsing the messages.
///
/// - Important:
/// Nothing will be seen in the debug area or the OS logging system if `OS_ACTIVITY_MODE` is disabled
/// in the the build scheme for the target.
///
/// - Parameters:
/// - messages: A variadic parameter of strings to print in the debug area.
/// - log: Use this to group logs into a suitable `Category`.
/// - subsystem: A string describing a subsystem. Default value is the main bundle identifier.
/// - terminator: The string appended to the end of the messages. By default this is `\n`.
public static func os(_ messages: String..., log: Log.Category, prefix customEmoji: Character? = nil, subsystem: String = Log.mainBundle, terminator: String = "\n") {
let resultingMessage = messages.reduce("") { $0 + " " + $1 }
os_log("%{private}@", log: log.osLogEquivalent, type: log.osLogTypeEquivalent, "\(customEmoji ?? log.emoji) \(subsystem) -\(resultingMessage)\(terminator)")
}
// MARK: - Private Helpers
/// Prints the messages received in the Xcode debug area.
///
/// All the messages are printed on a single line, separated with a space character,
/// and at the end of the message the terminator is appended.
///
/// - Parameters:
/// - messages: An array of strings, each resulting in a message sent to the OS logging system.
/// - terminator: The string appended to the message. By default this is `\n`.
/// - log: Use this to group logs into a suitable `Category`.
/// - subsystem: A string describing a subsystem. Default value is the main bundle identifier.
private static func debugAreaPrint(_ messages: [String], terminator: String, log: Log.Category, customEmoji: Character? = nil, subsystem: String) -> Bool {
print("\(customEmoji ?? log.emoji) \(timestamp()) \(subsystem) –", terminator: "")
let resultingMessage = messages.reduce("") { $0 + " " + $1 }
print(resultingMessage, terminator: terminator)
return true
}
/// Creates a timestamp used as part of the temporary logging in the debug area.
static func timestamp() -> String {
let date = Date()
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "HH:mm:ss.SSS"
return dateFormatter.string(from: date)
}
}
|
gpl-3.0
|
1549b05352ce94435528faa484541d2c
| 41.263441 | 170 | 0.614934 | 4.867492 | false | false | false | false |
czpc/ZpKit
|
ZpKit/UIKit/UIView+ZpKit.swift
|
1
|
1405
|
//
// UIView+ZpKit.swift
// ZpKit
//
// Created by 陈中培 on 16/4/12.
// Copyright © 2016年 陈中培. All rights reserved.
//
import UIKit
public extension UIView {
//TODO :
/**
加载Xib文件
:returns:
*/
class func zp_instanceFromXib() -> UIView {
var nib:[AnyObject]!
let identifier : String = NSStringFromClass(self)
let identifiers : [String] = identifier.componentsSeparatedByString(".")
nib = NSBundle.mainBundle().loadNibNamed(identifiers.last!, owner: nil, options: nil)
let result : UIView = nib.last! as! UIView
return result
}
/**
找到view的第一个响应VC
:returns:
*/
func zp_nextResponderViewController() -> UIViewController? {
var nextResponder: UIResponder! = self.nextResponder()
repeat{
nextResponder = nextResponder.nextResponder()!
if (nextResponder is UIViewController) {
return nextResponder as? UIViewController
}
} while (nextResponder != nil)
return nil
}
/**
取得当前view下的所有子视图
:returns:
*/
func zp_descViews() -> [AnyObject] {
let subViews:[AnyObject] = self.subviews
for subview in self.subviews {
subViews.zp_mergeArrays(subview.zp_descViews())
}
return subViews
}
}
|
mit
|
a6d56689cb8d798859460aa1fc234ac9
| 22.189655 | 93 | 0.587798 | 4.321543 | false | false | false | false |
mlatham/AFToolkit
|
Sources/AFToolkit/Sqlite/Sqlite+Column.swift
|
1
|
1423
|
import Foundation
extension Sqlite {
// Struct so that columns passed into views / tables are passed by value, not reference.
// This prevents one parent table overriding another.
public class Column<ColumnType>: CustomStringConvertible, SqliteColumnProtocol {
public let name: String
public let affinity: TypeAffinity
public let options: [Keyword]
public let type: ColumnType.Type
// Table that owns this column.
public var table: SqliteTableProtocol?
public var description: String {
return fullName
}
public init(name: String, affinity: TypeAffinity, type: ColumnType.Type, options: [Keyword] = []) {
self.name = name
self.type = type
self.affinity = affinity
self.options = options
}
public convenience init(_ column: Column<ColumnType>) {
self.init(name: column.name, affinity: column.affinity, type: column.type, options: column.options)
}
public convenience init(name: String, type: ColumnType.Type, options: [Keyword] = []) {
let affinity: TypeAffinity
switch type {
case is String.Type:
affinity = .text
case is Int.Type, is Bool.Type:
affinity = .integer
case is Double.Type:
affinity = .real
case is Data.Type:
affinity = .blob
// Shouldn't happen.
default: fatalError("Invalid column type")
}
self.init(name: name, affinity: affinity, type: type, options: options)
}
}
}
|
mit
|
e60b2cbff66a2f9d084b40bb5e4c346a
| 25.849057 | 102 | 0.687983 | 3.686528 | false | false | false | false |
flockoffiles/FFDataWrapper
|
FFDataWrapper/FFDataWrapper+InitializationWithInfo.swift
|
1
|
8761
|
//
// FFDataWrapper+InitializationWithInfo.swift
// FFDataWrapper
//
// Created by Sergey Novitsky on 19/02/2019.
// Copyright © 2019 Flock of Files. All rights reserved.
//
import Foundation
extension FFDataWrapper.CodersEnum {
init(infoCoders: FFDataWrapper.InfoCoders?) {
if let infoCoders = infoCoders {
self = .infoCoders(encoder: infoCoders.encoder, decoder: infoCoders.decoder)
} else {
let coders = FFDataWrapperEncoders.xorWithRandomVectorOfLength(0).infoCoders
self = .infoCoders(encoder: coders.encoder, decoder: coders.decoder)
}
}
}
extension Optional where Wrapped == FFDataWrapper.InfoCoders {
func unwrapWithDefault(length: Int) -> FFDataWrapper.InfoCoders {
switch self {
case .some(let encoder, let decoder):
return (encoder, decoder)
case .none:
return FFDataWrapperEncoders.xorWithRandomVectorOfLength(length).infoCoders
}
}
}
extension FFDataWrapper {
/// Create a wrapper of the given length and the given initializer closure.
/// The initializer closure is used to set the initial data contents.
/// - Parameters:
/// - length: The desired length.
/// - infoCoders: Pair of coders to use to convert to/from the internal representation. If nil, the default coders will be used.
/// - info: Additional info to pass to the coders.
/// - encode: If true (default), the initial data constructed with the initializer closure will be encoded; if false, it won't be encoded
/// and will be assumed to be already encoded.
/// - initializer: Initializer closure to set initial contents.
public init(length: Int,
infoCoders: FFDataWrapper.InfoCoders? = nil,
info: Any? = nil,
encode: Bool = true,
initializer: (UnsafeMutableBufferPointer<UInt8>) throws -> Void) rethrows {
guard length > 0 else {
self.storedCoders = CodersEnum(infoCoders: infoCoders.unwrapWithDefault(length: 0))
self.dataRef = FFDataRef(length: 0)
return
}
let unwrappedCoders = infoCoders.unwrapWithDefault(length: length)
self.storedCoders = CodersEnum(infoCoders: unwrappedCoders)
self.dataRef = FFDataRef(length: length)
let tempBufferPtr = UnsafeMutablePointer<UInt8>.allocate(capacity: length)
defer {
tempBufferPtr.initialize(repeating: 0, count: length)
tempBufferPtr.deallocate()
}
try initializer(UnsafeMutableBufferPointer(start: tempBufferPtr, count: length))
let initialEncoder = encode ? unwrappedCoders.encoder : FFDataWrapperEncoders.identity.infoCoders.encoder
initialEncoder(UnsafeBufferPointer(start: tempBufferPtr, count: length),
UnsafeMutableBufferPointer(start: self.dataRef.dataBuffer.baseAddress!, count: length), info)
}
/// Create a wrapper of the given length and the given initializer closure.
/// The initializer closure is used to set the initial data contents.
/// - Parameters:
/// - length: The desired length.
/// - coder: Coder to convert to and from the internal representation.
/// - info: Additional info to pass to the coders.
/// - encode: If true (default), the initial data constructed with the initializer closure will be encoded; if false, it won't be encoded
/// and will be assumed to be already encoded.
/// - initializer: Initializer closure to set initial contents.
public init(length: Int,
infoCoder: @escaping FFDataWrapper.InfoCoder,
info: Any? = nil,
encode: Bool = true,
initializer: (UnsafeMutableBufferPointer<UInt8>) throws -> Void) throws {
let coders: FFDataWrapper.InfoCoders? = FFDataWrapper.InfoCoders(infoCoder, infoCoder)
try self.init(length: length, infoCoders: coders, info: info, encode: encode, initializer: initializer)
}
/// Create a wrapper of the given length and the given initializer closure.
/// The initializer closure is used to set the initial data contents.
/// - Parameters:
/// - length: The desired length.
/// - coder: Coder to convert to and from the internal representation.
/// - info: Additional info to pass to the coders.
/// - encode: If true (default), the initial data constructed with the initializer closure will be encoded; if false, it won't be encoded
/// and will be assumed to be already encoded.
/// - initializer: Initializer closure to set initial contents.
public init(length: Int,
infoCoder: @escaping FFDataWrapper.InfoCoder,
info: Any? = nil,
encode: Bool = true,
initializer: (UnsafeMutableBufferPointer<UInt8>) -> Void) {
let coders: FFDataWrapper.InfoCoders? = FFDataWrapper.InfoCoders(infoCoder, infoCoder)
try! self.init(length: length, infoCoders: coders, info: info, encode: encode, initializer: initializer)
}
/// Create a wrapper with the given maximum capacity (in bytes).
///
/// - Parameters:
/// - capacity: The desired capacity (in bytes)
/// - infoCoders: Pair of coders to use to convert to/from the internal representation. If nil, the default XOR coders will be used.
/// - info: Additional info to pass to the coders.
/// - encode: If true (default), the initial data constructed with the initializer closure will be encoded; if false, it won't be encoded
/// and will be assumed to be already encoded.
/// - initializer: Initializer closure to create initial data contents. The size of created data can be smaller (but never greater)
/// than the capacity. The initializer closure must return the actual length of the data in its second parameter.
/// - Throws: Error if capacity is >= 0 or if the actual length turns out to exceed the capacity.
public init(capacity: Int,
infoCoders: FFDataWrapper.InfoCoders? = nil,
info: Any? = nil,
encode: Bool = true,
initializer: (UnsafeMutableBufferPointer<UInt8>, UnsafeMutablePointer<Int>) throws -> Void) rethrows {
guard capacity > 0 else {
self.storedCoders = CodersEnum(infoCoders: infoCoders.unwrapWithDefault(length: 0))
self.dataRef = FFDataRef(length: 0)
return
}
let tempBufferPtr = UnsafeMutablePointer<UInt8>.allocate(capacity: capacity)
defer {
// Securely wipe the temp buffer.
tempBufferPtr.initialize(repeating: 0, count: capacity)
tempBufferPtr.deallocate()
}
var actualLength = capacity
try initializer(UnsafeMutableBufferPointer(start: tempBufferPtr, count: capacity), &actualLength)
guard actualLength > 0 && actualLength <= capacity else {
self.storedCoders = CodersEnum(infoCoders: infoCoders.unwrapWithDefault(length: 0))
self.dataRef = FFDataRef(length: 0)
return
}
let unwrappedCoders = infoCoders.unwrapWithDefault(length: actualLength)
self.storedCoders = CodersEnum(infoCoders: unwrappedCoders)
self.dataRef = FFDataRef(length: actualLength)
let encoder = encode ? unwrappedCoders.encoder : FFDataWrapperEncoders.identity.infoCoders.encoder
encoder(UnsafeBufferPointer(start: tempBufferPtr, count: actualLength),
UnsafeMutableBufferPointer(start: self.dataRef.dataBuffer.baseAddress!, count: self.dataRef.dataBuffer.count), info)
}
public init(capacity: Int,
infoCoder: @escaping FFDataWrapper.InfoCoder,
info: Any? = nil,
encode: Bool = true,
initializer: (UnsafeMutableBufferPointer<UInt8>, UnsafeMutablePointer<Int>) throws -> Void) throws {
let coders = FFDataWrapper.InfoCoders(infoCoder, infoCoder)
try self.init(capacity: capacity, infoCoders: coders, encode: encode, initializer: initializer)
}
public init(capacity: Int,
infoCoder: @escaping FFDataWrapper.InfoCoder,
info: Any? = nil,
encode: Bool = true,
initializer: (UnsafeMutableBufferPointer<UInt8>, UnsafeMutablePointer<Int>) -> Void) {
let coders = FFDataWrapper.InfoCoders(infoCoder, infoCoder)
try! self.init(capacity: capacity, infoCoders: coders, encode: encode, initializer: initializer)
}
}
|
mit
|
ab0e92e4a3c37f706ea6cdf61dadb990
| 49.344828 | 143 | 0.650457 | 4.699571 | false | false | false | false |
yarshure/Surf
|
Surf/Socks.swift
|
1
|
1385
|
//
// Socks.swift
// Surf
//
// Created by yarshure on 15/12/3.
// Copyright © 2015年 yarshure. All rights reserved.
//
import Foundation
@objc(KKSocks) class Socks :NSObject,NSCoding{
public func encode(with aCoder: NSCoder) {
aCoder.encode(self.proxyName, forKey: "proxyName")
aCoder.encode(self.serverAddress, forKey: "serverAddress")
aCoder.encode(self.serverPort, forKey: "serverPort")
aCoder.encode(self.password, forKey: "password")
aCoder.encode(self.method, forKey: "method")
aCoder.encode(self.serverType, forKey: "serverType")
}
internal var proxyName:String?
internal var serverAddress:String?
internal var serverPort:String?
var password:String?
var method:String?
var serverType:String?
override init() {}
required init?(coder aDecoder: NSCoder){
super.init()
self.proxyName = aDecoder.decodeObject(forKey: "proxyName") as? String
self.serverAddress = aDecoder.decodeObject(forKey: "serverAddress") as? String
self.serverPort = aDecoder.decodeObject(forKey: "serverPort") as? String
self.password = aDecoder.decodeObject(forKey: "password") as? String
self.method = aDecoder.decodeObject(forKey: "method") as? String
self.serverType = aDecoder.decodeObject(forKey: "serverType") as? String
}
}
|
bsd-3-clause
|
ffba1553debc6db83ece4700bd7f9fbe
| 34.435897 | 87 | 0.675832 | 4.10089 | false | false | false | false |
shralpmeister/shralptide2
|
ShralpTide/Shared/Interactors/CalendarAppStateInteractor.swift
|
1
|
1724
|
//
// CalendarAppStateInteractor.swift
// SwiftTides
//
// Created by Michael Parlee on 4/4/21.
//
import ShralpTideFramework
extension AppStateInteractor {
func calculateCalendarTides(appState: AppState, settings: UserSettings, month: Int, year: Int)
-> [SingleDayTideModel]
{
let units: SDTideUnitsPref = settings.unitsPref == "US" ? .US : .METRIC
let interval = findDateRange(year: year, month: month)
let station = appState.tides[appState.locationPage].stationName
return SDTideFactory.tides(
forStationName: station, withInterval: 900,
forDays: Calendar.current.dateComponents([.day], from: interval.start, to: interval.end).day!,
withUnits: units, from: interval.start.startOfDay()
).map { SingleDayTideModel(tideDataToChart: $0, day: $0.startTime) }
}
fileprivate func findStartDate(year: Int, month: Int) -> Date {
let cal = Calendar.current
let firstDay = cal.date(from: DateComponents(year: year, month: month, day: 1))!
let offset = cal.component(.weekday, from: firstDay) - 1
return cal.date(byAdding: .day, value: -1 * offset, to: firstDay)!
}
fileprivate func findDateRange(year: Int, month: Int) -> DateInterval {
let cal = Calendar.current
let lastDay = cal.date(from: DateComponents(year: year, month: month + 1, day: 1))!
let startDate = findStartDate(year: year, month: month)
let days = cal.dateComponents([.day], from: startDate, to: lastDay).day!
let remainder = days % 7
return DateInterval(
start: startDate, end: cal.date(byAdding: .day, value: 7 - remainder, to: lastDay)!
)
}
}
|
gpl-3.0
|
30aa7eb066b4e7108df7002b5fef73be
| 41.04878 | 106 | 0.650232 | 3.918182 | false | false | false | false |
uhnmdi/CCContinuousGlucose
|
CCContinuousGlucose/Classes/RACP.swift
|
1
|
502
|
//
// RACP.swift
// Pods
//
// Created by Kevin Tallevi on 7/12/16.
//
//
import Foundation
import CCBluetooth
import CoreBluetooth
let reportStoredRecords = "01"
let deleteStoredRecords = "02"
let abortOperation = "03"
let reportNumberOfStoredRecords = "04"
let numberOfStoredRecordsResponse = "05"
let responseCode = "06"
var readNumberOfStoredRecords:String = "0401"
var readAllStoredRecords:String = "0101"
|
mit
|
0d486ac2379f724c623db785df3f73d3
| 22.904762 | 46 | 0.625498 | 3.774436 | false | false | false | false |
pvbaleeiro/movie-aholic
|
movieaholic/movieaholic/recursos/view/PageTabItem.swift
|
1
|
2614
|
//
// PageTabItem.swift
// movieaholic
//
// Created by Victor Baleeiro on 24/09/17.
// Copyright © 2017 Victor Baleeiro. All rights reserved.
//
import UIKit
//-------------------------------------------------------------------------------------------------------------
// MARK: Delegate
//-------------------------------------------------------------------------------------------------------------
protocol PageTabItemDelegate {
func didSelect(tabItem: PageTabItem, completion: (() -> Void)?)
}
class PageTabItem: BasePageTabItemView {
//-------------------------------------------------------------------------------------------------------------
// MARK: Propriedades
//-------------------------------------------------------------------------------------------------------------
var delegate: PageTabItemDelegate?
var title: String = "" {
didSet {
titleButton.setTitle(title.uppercased(), for: .normal)
}
}
var titleColor: UIColor = UIColor.white {
didSet {
titleButton.setTitleColor(titleColor, for: .normal)
}
}
var selectedTitleColor: UIColor = UIColor.white {
didSet {
if isSelected {
titleButton.setTitleColor(selectedTitleColor, for: .normal)
}
}
}
var isSelected: Bool = false {
didSet {
if isSelected {
} else {
}
}
}
lazy var titleButton: UIButton = {
let view = UIButton()
view.translatesAutoresizingMaskIntoConstraints = false
view.setTitleColor(self.titleColor, for: .normal)
view.titleLabel?.textAlignment = .center
view.titleLabel?.font = UIFont.boldSystemFont(ofSize: 12)
view.addTarget(self, action: #selector(PageTabItem.didSelect), for: .touchUpInside)
return view
}()
var titleLabelWidthAnchor: NSLayoutConstraint?
override func setupViews() {
super.setupViews()
addSubview(titleButton)
titleButton.centerXAnchor.constraint(equalTo: centerXAnchor).isActive = true
titleButton.topAnchor.constraint(equalTo: topAnchor).isActive = true
titleButton.heightAnchor.constraint(equalTo: heightAnchor).isActive = true
titleButton.widthAnchor.constraint(equalTo: widthAnchor, constant: -30).isActive = true
}
@objc func didSelect() {
if let handler = delegate {
handler.didSelect(tabItem: self, completion: nil)
}
}
}
|
mit
|
48b5cb6d65635689cd778c28195c8303
| 30.107143 | 115 | 0.49713 | 5.87191 | false | false | false | false |
anthonypuppo/GDAXSwift
|
GDAXSwift/Classes/GDAXAccount.swift
|
1
|
1530
|
//
// GDAX24HRStats.swift
// GDAXSwift
//
// Created by Anthony on 6/6/17.
// Copyright © 2017 Anthony Puppo. All rights reserved.
//
public struct GDAXAccount: JSONInitializable {
public let id: String
public let currency: String
public let balance: Double
public let available: Double
public let hold: Double
public let profileID: String
internal init(json: Any) throws {
var jsonData: Data?
if let json = json as? Data {
jsonData = json
} else {
jsonData = try JSONSerialization.data(withJSONObject: json, options: [])
}
guard let json = jsonData?.json else {
throw GDAXError.invalidResponseData
}
guard let id = json["id"] as? String else {
throw GDAXError.responseParsingFailure("id")
}
guard let currency = json["currency"] as? String else {
throw GDAXError.responseParsingFailure("currency")
}
guard let balance = Double(json["balance"] as? String ?? "") else {
throw GDAXError.responseParsingFailure("balance")
}
guard let available = Double(json["available"] as? String ?? "") else {
throw GDAXError.responseParsingFailure("available")
}
guard let hold = Double(json["hold"] as? String ?? "") else {
throw GDAXError.responseParsingFailure("hold")
}
guard let profileID = json["profile_id"] as? String else {
throw GDAXError.responseParsingFailure("profile_id")
}
self.id = id
self.currency = currency
self.balance = balance
self.available = available
self.hold = hold
self.profileID = profileID
}
}
|
mit
|
a705a3fa3f2f3d463dee410ae3646e25
| 23.269841 | 75 | 0.686723 | 3.747549 | false | false | false | false |
tush4r/DVIA-Swift
|
DVIA-Swift/DVIA-Swift/Constants.swift
|
1
|
3149
|
//
// Constants.swift
// DVIA-Swift
//
// Created by Tushar Sharma on 07/05/16.
// Copyright © 2016 Edbinx. All rights reserved.
//
import Foundation
import UIKit
////Heights and Fonts
let kRowHeight:CGFloat = 44.0
let kCellFont = UIFont(name: "Avenir-Roman", size: 14.0)
////Parse Constants
let kParseAppId = "UaaSszBfQVE6Jt1QrwZ4SPiY822TAulkoEDTHJyf"
let kParseClientKey = "R8fRtBGNuDSCwezz5poKIxEHuRxvsFZFJnDrubX0"
////GoogleAnalytics Constants
let kGATrackingID = "UA-63106875-1"
////Flurry Constants
let kFlurrySession = "ZMSFBDBYFQ8XHQBRP2VY"
////Article URL's
//#define kHomePage @"http://damnvulnerableiosapp.com"
//#define kSolutionsPage @"http://damnvulnerableiosapp.com/#solutions"
//#define kLearnIOSSecurityURL @"http://highaltitudehacks.com/categories/security"
//#define kArticleURLLocalDataStorage @"http://highaltitudehacks.com/2013/10/26/ios-application-security-part-20-local-data-storage-nsuserdefaults"
//#define kArticleURLJailbreakDetection @"http://highaltitudehacks.com/2013/12/17/ios-application-security-part-24-jailbreak-detection-and-evasion"
//#define kArticleURLRuntime1 @"http://highaltitudehacks.com/2013/06/16/ios-application-security-part-3-understanding-the-objective-c-runtime"
//#define kArticleURLRuntime2 @"http://highaltitudehacks.com/2013/07/02/ios-aios-appllication-security-part-4-runtime-analysis-using-cycript-yahoo-weather-app"
//#define kArticleURLRuntime3 @"http://highaltitudehacks.com/2013/07/02/ios-application-security-part-5-advanced-runtime-analysis-and-manipulation-using-cycript-yahoo-weather-app"
//#define kArticleURLRuntime4 @"http://highaltitudehacks.com/2013/07/25/ios-application-security-part-8-method-swizzling-using-cycript"
//#define kArticleURLRuntime5 @"http://highaltitudehacks.com/2013/09/17/ios-application-security-part-16-runtime-analysis-of-ios-applications-using-inalyzer"
//#define kArticleURLRuntime6 @"http://highaltitudehacks.com/2013/11/08/ios-application-security-part-21-arm-and-gdb-basics"
//#define kArticleURLRuntime7 @"http://highaltitudehacks.com/2013/12/17/ios-application-security-part-22-runtime-analysis-and-manipulation-using-gdb"
//#define kArticlePatchingApplication1 @"http://highaltitudehacks.com/2013/12/17/ios-application-security-part-26-patching-ios-applications-using-ida-pro-and-hex-fiend"
//#define kArticlePatchingApplication2 @"http://highaltitudehacks.com/2014/01/17/ios-application-security-part-28-patching-ios-application-with-hopper"
//#define kArticleURLTransportLayer @"http://highaltitudehacks.com/2013/08/20/ios-application-security-part-11-analyzing-network-traffic-over-http-slash-https"
//#define kArticleURLBrokenCryptography @"http://highaltitudehacks.com/2014/01/17/ios-application-security-part-29-insecure-or-broken-cryptography"
//#define kArticleURLSchemes @"http://highaltitudehacks.com/2014/03/07/ios-application-security-part-30-attacking-url-schemes"
//#define kArticleParse @"http://highaltitudehacks.com/2015/01/24/ios-application-security-part-38-attacking-apps-using-parse"
//
////Colours
//#define kNavigationTintColor [UIColor colorWithRed:223.0/255 green:186.0/255 blue:105.0/255 alpha:1.0]
//
//#endif
|
mit
|
3b580374f437d7c49e4da41a54561da9
| 63.265306 | 179 | 0.802097 | 3.098425 | false | false | false | false |
roambotics/swift
|
test/Interop/CxxToSwiftToCxx/bridge-cxx-struct-back-to-cxx.swift
|
2
|
10921
|
// rdar://101431096
// XFAIL: *
// RUN: %empty-directory(%t)
// RUN: split-file %s %t
// RUN: %target-swift-frontend -typecheck %t/use-cxx-types.swift -typecheck -module-name UseCxxTy -emit-clang-header-path %t/UseCxxTy.h -I %t -enable-experimental-cxx-interop -clang-header-expose-decls=all-public
// RUN: %FileCheck %s < %t/UseCxxTy.h
// RUN: %target-swift-frontend -typecheck %t/use-cxx-types.swift -typecheck -module-name UseCxxTy -emit-clang-header-path %t/UseCxxTyExposeOnly.h -I %t -enable-experimental-cxx-interop -clang-header-expose-decls=has-expose-attr
// RUN: %FileCheck %s < %t/UseCxxTyExposeOnly.h
// FIXME: remove once https://github.com/apple/swift/pull/60971 lands.
// RUN: echo "#include \"header.h\"" > %t/full-cxx-swift-cxx-bridging.h
// RUN: cat %t/UseCxxTy.h >> %t/full-cxx-swift-cxx-bridging.h
// RUN: %check-interop-cxx-header-in-clang(%t/full-cxx-swift-cxx-bridging.h -Wno-reserved-identifier)
// FIXME: test in C++ with modules (but libc++ modularization is preventing this)
//--- header.h
struct Trivial {
short x, y;
};
namespace ns {
struct TrivialinNS {
short x, y;
};
template<class T>
struct NonTrivialTemplate {
T x;
NonTrivialTemplate();
NonTrivialTemplate(const NonTrivialTemplate<T> &) = default;
NonTrivialTemplate(NonTrivialTemplate<T> &&) = default;
~NonTrivialTemplate() {}
};
using TypeAlias = NonTrivialTemplate<TrivialinNS>;
struct NonTrivialImplicitMove {
NonTrivialTemplate<int> member;
};
#define IMMORTAL_REF \
__attribute__((swift_attr("import_as_ref"))) \
__attribute__((swift_attr("retain:immortal"))) \
__attribute__((swift_attr("release:immortal")))
struct IMMORTAL_REF Immortal {
public:
};
inline Immortal *makeNewImmortal() {
return new Immortal;
}
template<class T>
struct IMMORTAL_REF ImmortalTemplate {
public:
};
inline ImmortalTemplate<int> *makeNewImmortalInt() {
return new ImmortalTemplate<int>;
}
using ImmortalCInt = ImmortalTemplate<int>;
}
//--- module.modulemap
module CxxTest {
header "header.h"
requires cplusplus
}
//--- use-cxx-types.swift
import CxxTest
@_expose(Cxx)
public func retImmortal() -> ns.Immortal {
return ns.makeNewImmortal()
}
@_expose(Cxx)
public func retImmortalTemplate() -> ns.ImmortalCInt {
return ns.makeNewImmortalInt()
}
@_expose(Cxx)
public func retNonTrivial() -> ns.NonTrivialTemplate<CInt> {
return ns.NonTrivialTemplate<CInt>()
}
@_expose(Cxx)
public func retNonTrivial2() -> ns.NonTrivialTemplate<ns.TrivialinNS> {
return ns.NonTrivialTemplate<ns.TrivialinNS>()
}
@_expose(Cxx)
public func retNonTrivialImplicitMove() -> ns.NonTrivialImplicitMove {
return ns.NonTrivialImplicitMove()
}
@_expose(Cxx)
public func retNonTrivialTypeAlias() -> ns.TypeAlias {
return ns.TypeAlias()
}
@_expose(Cxx)
public func retTrivial() -> Trivial {
return Trivial()
}
@_expose(Cxx)
public func takeImmortal(_ x: ns.Immortal) {
}
@_expose(Cxx)
public func takeImmortalTemplate(_ x: ns.ImmortalCInt) {
}
@_expose(Cxx)
public func takeNonTrivial2(_ x: ns.NonTrivialTemplate<ns.TrivialinNS>) {
}
@_expose(Cxx)
public func takeTrivial(_ x: Trivial) {
}
@_expose(Cxx)
public func takeTrivialInout(_ x: inout Trivial) {
}
// CHECK: #if __has_feature(objc_modules)
// CHECK: #if __has_feature(objc_modules)
// CHECK-NEXT: #if __has_warning("-Watimport-in-framework-header")
// CHECK-NEXT: #pragma clang diagnostic ignored "-Watimport-in-framework-header"
// CHECK-NEXT:#endif
// CHECK-NEXT: #pragma clang module import CxxTest;
// CHECK-NEXT: #endif
// CHECK: SWIFT_EXTERN void $s8UseCxxTy13retNonTrivialSo2nsO02__b18TemplateInstN2ns18efH4IiEEVyF(SWIFT_INDIRECT_RESULT void * _Nonnull) SWIFT_NOEXCEPT SWIFT_CALL; // retNonTrivial()
// CHECK: SWIFT_EXTERN struct swift_interop_returnStub_UseCxxTy_uint32_t_0_4 $s8UseCxxTy10retTrivialSo0E0VyF(void) SWIFT_NOEXCEPT SWIFT_CALL; // retTrivial()
// CHECK: ns::Immortal *_Nonnull retImmortal() noexcept SWIFT_WARN_UNUSED_RESULT {
// CHECK-NEXT: return _impl::$s8UseCxxTy11retImmortalSo2nsO0E0VyF();
// CHECK-NEXT: }
// CHECK: ns::ImmortalTemplate<int> *_Nonnull retImmortalTemplate() noexcept SWIFT_WARN_UNUSED_RESULT {
// CHECK-NEXT: return _impl::$s8UseCxxTy19retImmortalTemplateSo2nsO02__bf10InstN2ns16eF4IiEEVyF();
// CHECK-NEXT: }
// CHECK: } // end namespace
// CHECK-EMPTY:
// CHECK-NEXT: namespace swift {
// CHECK-NEXT: namespace _impl {
// CHECK-EMPTY:
// CHECK-NEXT: // Type metadata accessor for __CxxTemplateInstN2ns18NonTrivialTemplateIiEE
// CHECK-NEXT: SWIFT_EXTERN swift::_impl::MetadataResponseTy $sSo2nsO033__CxxTemplateInstN2ns18NonTrivialC4IiEEVMa(swift::_impl::MetadataRequestTy) SWIFT_NOEXCEPT SWIFT_CALL;
// CHECK-EMPTY:
// CHECK-EMPTY:
// CHECK-NEXT: } // namespace _impl
// CHECK-EMPTY:
// CHECK-NEXT: #pragma clang diagnostic push
// CHECK-NEXT: #pragma clang diagnostic ignored "-Wc++17-extensions"
// CHECK-NEXT: template<>
// CHECK-NEXT: static inline const constexpr bool isUsableInGenericContext<ns::NonTrivialTemplate<int>> = true;
// CHECK-NEXT: template<>
// CHECK-NEXT: struct TypeMetadataTrait<ns::NonTrivialTemplate<int>> {
// CHECK-NEXT: static inline void * _Nonnull getTypeMetadata() {
// CHECK-NEXT: return _impl::$sSo2nsO033__CxxTemplateInstN2ns18NonTrivialC4IiEEVMa(0)._0;
// CHECK-NEXT: }
// CHECK-NEXT: };
// CHECK-NEXT: namespace _impl{
// CHECK-NEXT: template<>
// CHECK-NEXT: static inline const constexpr bool isSwiftBridgedCxxRecord<ns::NonTrivialTemplate<int>> = true;
// CHECK-NEXT: } // namespace
// CHECK-NEXT: #pragma clang diagnostic pop
// CHECK-NEXT: } // namespace swift
// CHECK-EMPTY:
// CHECK-NEXT: namespace UseCxxTy {
// CHECK: inline ns::NonTrivialTemplate<int> retNonTrivial() noexcept SWIFT_WARN_UNUSED_RESULT {
// CHECK-NEXT: alignas(alignof(ns::NonTrivialTemplate<int>)) char storage[sizeof(ns::NonTrivialTemplate<int>)];
// CHECK-NEXT: auto * _Nonnull storageObjectPtr = reinterpret_cast<ns::NonTrivialTemplate<int> *>(storage);
// CHECK-NEXT: _impl::$s8UseCxxTy13retNonTrivialSo2nsO02__b18TemplateInstN2ns18efH4IiEEVyF(storage);
// CHECK-NEXT: ns::NonTrivialTemplate<int> result(static_cast<ns::NonTrivialTemplate<int> &&>(*storageObjectPtr));
// CHECK-NEXT: storageObjectPtr->~NonTrivialTemplate();
// CHECK-NEXT: return result;
// CHECK-NEXT: }
// CHECK-EMPTY:
// CHECK-NEXT: } // end namespace
// CHECK-EMPTY:
// CHECK-NEXT: namespace swift {
// CHECK-NEXT: namespace _impl {
// CHECK-EMPTY:
// CHECK-NEXT: // Type metadata accessor for __CxxTemplateInstN2ns18NonTrivialTemplateINS_11TrivialinNSEEE
// CHECK-NEXT: SWIFT_EXTERN swift::_impl::MetadataResponseTy $sSo2nsO033__CxxTemplateInstN2ns18NonTrivialC20INS_11TrivialinNSEEEVMa(swift::_impl::MetadataRequestTy) SWIFT_NOEXCEPT SWIFT_CALL;
// CHECK-EMPTY:
// CHECK-EMPTY:
// CHECK-NEXT: } // namespace _impl
// CHECK-EMPTY:
// CHECK-NEXT: #pragma clang diagnostic push
// CHECK-NEXT: #pragma clang diagnostic ignored "-Wc++17-extensions"
// CHECK-NEXT: template<>
// CHECK-NEXT: static inline const constexpr bool isUsableInGenericContext<ns::NonTrivialTemplate<ns::TrivialinNS>> = true;
// CHECK-NEXT: template<>
// CHECK-NEXT: struct TypeMetadataTrait<ns::NonTrivialTemplate<ns::TrivialinNS>> {
// CHECK-NEXT: static inline void * _Nonnull getTypeMetadata() {
// CHECK-NEXT: return _impl::$sSo2nsO033__CxxTemplateInstN2ns18NonTrivialC20INS_11TrivialinNSEEEVMa(0)._0;
// CHECK-NEXT: }
// CHECK-NEXT: };
// CHECK-NEXT: namespace _impl{
// CHECK-NEXT: template<>
// CHECK-NEXT: static inline const constexpr bool isSwiftBridgedCxxRecord<ns::NonTrivialTemplate<ns::TrivialinNS>> = true;
// CHECK-NEXT: } // namespace
// CHECK-NEXT: #pragma clang diagnostic pop
// CHECK-NEXT: } // namespace swift
// CHECK-EMPTY:
// CHECK-NEXT: namespace UseCxxTy {
// CHECK-EMPTY:
// CHECK-NEXT: inline ns::NonTrivialTemplate<ns::TrivialinNS> retNonTrivial2() noexcept SWIFT_WARN_UNUSED_RESULT {
// CHECK-NEXT: alignas(alignof(ns::NonTrivialTemplate<ns::TrivialinNS>)) char storage[sizeof(ns::NonTrivialTemplate<ns::TrivialinNS>)];
// CHECK-NEXT: auto * _Nonnull storageObjectPtr = reinterpret_cast<ns::NonTrivialTemplate<ns::TrivialinNS> *>(storage);
// CHECK-NEXT: _impl::$s8UseCxxTy14retNonTrivial2So2nsO02__b18TemplateInstN2ns18e7TrivialH20INS_11TrivialinNSEEEVyF(storage);
// CHECK-NEXT: ns::NonTrivialTemplate<ns::TrivialinNS> result(static_cast<ns::NonTrivialTemplate<ns::TrivialinNS> &&>(*storageObjectPtr));
// CHECK-NEXT: storageObjectPtr->~NonTrivialTemplate();
// CHECK-NEXT: return result;
// CHECK-NEXT: }
// CHECK: inline ns::NonTrivialImplicitMove retNonTrivialImplicitMove() noexcept SWIFT_WARN_UNUSED_RESULT {
// CHECK-NEXT: alignas(alignof(ns::NonTrivialImplicitMove)) char storage[sizeof(ns::NonTrivialImplicitMove)];
// CHECK-NEXT: auto * _Nonnull storageObjectPtr = reinterpret_cast<ns::NonTrivialImplicitMove *>(storage);
// CHECK-NEXT: _impl::$s8UseCxxTy25retNonTrivialImplicitMoveSo2nsO0efgH0VyF(storage);
// CHECK-NEXT: ns::NonTrivialImplicitMove result(static_cast<ns::NonTrivialImplicitMove &&>(*storageObjectPtr));
// CHECK-NEXT: storageObjectPtr->~NonTrivialImplicitMove();
// CHECK-NEXT: return result;
// CHECK-NEXT: }
// CHECK: ns::NonTrivialTemplate<ns::TrivialinNS> retNonTrivialTypeAlias() noexcept SWIFT_WARN_UNUSED_RESULT {
// CHECK: inline Trivial retTrivial() noexcept SWIFT_WARN_UNUSED_RESULT {
// CHECK-NEXT: alignas(alignof(Trivial)) char storage[sizeof(Trivial)];
// CHECK-NEXT: auto * _Nonnull storageObjectPtr = reinterpret_cast<Trivial *>(storage);
// CHECK-NEXT: _impl::swift_interop_returnDirect_UseCxxTy_uint32_t_0_4(storage, _impl::$s8UseCxxTy10retTrivialSo0E0VyF());
// CHECK-NEXT: return *storageObjectPtr;
// CHECK-NEXT: }
// CHECK: void takeImmortal(ns::Immortal *_Nonnull x) noexcept {
// CHECK-NEXT: return _impl::$s8UseCxxTy12takeImmortalyySo2nsO0E0VF(x);
// CHECK-NEXT: }
// CHECK: void takeImmortalTemplate(ns::ImmortalTemplate<int> *_Nonnull x) noexcept {
// CHECK-NEXT: return _impl::$s8UseCxxTy20takeImmortalTemplateyySo2nsO02__bf10InstN2ns16eF4IiEEVF(x);
// CHECK-NEXT: }
// CHECK: inline void takeNonTrivial2(const ns::NonTrivialTemplate<ns::TrivialinNS>& x) noexcept {
// CHECK-NEXT: return _impl::$s8UseCxxTy15takeNonTrivial2yySo2nsO02__b18TemplateInstN2ns18e7TrivialH20INS_11TrivialinNSEEEVF(swift::_impl::getOpaquePointer(x));
// CHECK-NEXT: }
// CHECK: inline void takeTrivial(const Trivial& x) noexcept {
// CHECK-NEXT: return _impl::$s8UseCxxTy11takeTrivialyySo0E0VF(_impl::swift_interop_passDirect_UseCxxTy_uint32_t_0_4(reinterpret_cast<const char *>(swift::_impl::getOpaquePointer(x))));
// CHECK-NEXT: }
// CHECK: inline void takeTrivialInout(Trivial& x) noexcept {
// CHECK-NEXT: return _impl::$s8UseCxxTy16takeTrivialInoutyySo0E0VzF(swift::_impl::getOpaquePointer(x));
// CHECK-NEXT: }
|
apache-2.0
|
bf1db31131c358aa5c2f0ad43ea07f84
| 39.003663 | 227 | 0.730428 | 3.321472 | false | false | false | false |
marcelmueller/MyWeight
|
MyWeight/AppCoordinator.swift
|
1
|
2981
|
//
// AppCoordinator.swift
// MyWeight
//
// Created by Diogo on 09/10/16.
// Copyright © 2016 Diogo Tridapalli. All rights reserved.
//
import UIKit
public class AppCoordinator {
let navigationController: UINavigationController
let massService: MassService = MassService()
public init(with navigationController: UINavigationController)
{
navigationController.isNavigationBarHidden = true
self.navigationController = navigationController
}
public func start()
{
let controller = ListViewController(with: massService)
controller.delegate = self
navigationController.pushViewController(controller, animated: true)
}
func startAdd(last mass: Mass?)
{
let addViewController = AddViewController(with: massService,
startMass: mass ?? Mass())
addViewController.delegate = self
self.navigationController.present(addViewController,
animated: true,
completion: nil)
}
func startAuthorizationRequest()
{
let viewController = AuthorizationRequestViewController(with: massService)
viewController.delegate = self
self.navigationController.present(viewController,
animated: true,
completion: nil)
}
func startAuthorizationDenied()
{
let viewController = AccessDeniedViewController()
viewController.delegate = self
self.navigationController.present(viewController,
animated: true,
completion: nil)
}
}
extension AppCoordinator: ListViewControllerDelegate {
public func didTapAddMeasure(last mass: Mass?)
{
switch massService.authorizationStatus {
case .authorized:
startAdd(last: mass)
case .notDetermined:
startAuthorizationRequest()
case .denied:
startAuthorizationDenied()
}
}
}
extension AppCoordinator: AddViewControllerDelegate {
public func didEnd()
{
self.navigationController.dismiss(animated: true, completion: nil)
}
}
extension AppCoordinator: AuthorizationRequestViewControllerDelegate {
public func didFinish(on controller: AuthorizationRequestViewController,
with authorized: Bool)
{
if authorized {
controller.dismiss(animated: true, completion: {
self.startAdd(last: nil)
})
} else {
controller.dismiss(animated: true, completion: nil)
}
}
}
extension AppCoordinator: AccessDeniedViewControllerDelegate {
public func didFinish(on controller: AccessDeniedViewController)
{
controller.dismiss(animated: true, completion: nil)
}
}
|
mit
|
3c99939e7935f62dbb1c94008886289c
| 26.592593 | 82 | 0.611074 | 5.854617 | false | false | false | false |
NobodyNada/SwiftChatSE
|
Sources/SwiftChatSE/Levenshtein.swift
|
1
|
1710
|
/**
* Levenshtein edit distance calculator
* From https://en.wikibooks.org/wiki/Algorithm_Implementation/Strings/Levenshtein_distance#Swift
*
* Inspired by https://gist.github.com/bgreenlee/52d93a1d8fa1b8c1f38b
* Improved with http://stackoverflow.com/questions/26990394/slow-swift-arrays-and-strings-performance
*/
public final class Levenshtein {
private class func min(_ numbers: Int...) -> Int {
return numbers.reduce(numbers[0]) {$0 < $1 ? $0 : $1}
}
private class Array2D {
var cols:Int, rows:Int
var matrix: [Int]
init(cols:Int, rows:Int) {
self.cols = cols
self.rows = rows
matrix = Array(repeating:0, count:cols*rows)
}
subscript(col:Int, row:Int) -> Int {
get {
return matrix[cols * row + col]
}
set {
matrix[cols*row+col] = newValue
}
}
func colCount() -> Int {
return self.cols
}
func rowCount() -> Int {
return self.rows
}
}
///Calclates and returns the levenshtein distance between two strings.
public class func distanceBetween(_ aStr: String, and bStr: String) -> Int {
let a = Array(aStr.utf16)
let b = Array(bStr.utf16)
if a.isEmpty {
return b.count
}
if b.isEmpty {
return a.count
}
let dist = Array2D(cols: a.count + 1, rows: b.count + 1)
for i in 1...a.count {
dist[i, 0] = i
}
for j in 1...b.count {
dist[0, j] = j
}
for i in 1...a.count {
for j in 1...b.count {
if a[i-1] == b[j-1] {
dist[i, j] = dist[i-1, j-1] // noop
} else {
dist[i, j] = min(
dist[i-1, j] + 1, // deletion
dist[i, j-1] + 1, // insertion
dist[i-1, j-1] + 1 // substitution
)
}
}
}
return dist[a.count, b.count]
}
}
|
mit
|
fe3655944bc4befd965dc3afbb2d8fa0
| 19.853659 | 101 | 0.593567 | 2.688679 | false | false | false | false |
itechline/bonodom_new
|
SlideMenuControllerSwift/MenuItemView.swift
|
1
|
2251
|
//
// MenuItemViewController.swift
// Bonodom
//
// Created by Attila Dán on 2016. 06. 06..
// Copyright © 2016. Itechline. All rights reserved.
//
import UIKit
/*struct MenuItemViewCellData {
init(imageUrl_menu: String, text_menu: String) {
self.imageUrl_menu = imageUrl_menu
self.text_menu = text_menu
}
var imageUrl_menu: String
var text_menu: String
}*/
struct MenuItemViewCellData2{
init(imagePath_menu: UIImage, text_menu: String, messages: Int, appointment: Int){
self.imagePath_menu = imagePath_menu
self.text_menu = text_menu
self.messages = messages
self.appointment = appointment
}
var imagePath_menu: UIImage
var text_menu: String
var messages: Int
var appointment: Int
}
class MenuItemView: BaseMenuItemViewController {
@IBOutlet weak var dataImage: UIImageView!
@IBOutlet weak var dataText: UILabel!
@IBOutlet weak var messages_text: UILabel!
override func awakeFromNib() {
self.dataText?.font = UIFont.boldSystemFontOfSize(16)
self.dataText?.textColor = UIColor(hex: "000000")
}
override class func height() -> CGFloat {
return 60
}
/*override func setData(data: Any?) {
if let data = data as? MenuItemViewCellData {
self.dataImage.setRandomDownloadImage(50, height: 50)
self.dataText.text = data.text_menu
}
}*/
override func setData(data: Any?){
if let data = data as? MenuItemViewCellData2{
self.dataImage.image = data.imagePath_menu
self.dataText.text = data.text_menu
if (data.messages != 0) {
self.messages_text.hidden = false
self.messages_text.text = String(data.messages)
} else {
self.messages_text.hidden = true
}
if (data.appointment != 0) {
self.messages_text.hidden = false
self.messages_text.text = String(data.appointment)
} else {
self.messages_text.hidden = true
}
if (data.messages != 0) {
self.messages_text.hidden = false
}
}
}
}
|
mit
|
30ea507d00e2515dca2e266413e7557f
| 27.833333 | 86 | 0.590929 | 4.195896 | false | false | false | false |
gnachman/iTerm2
|
BetterFontPicker/BetterFontPicker/FontListTableView.swift
|
2
|
1778
|
//
// FontListTableView.swift
// BetterFontPicker
//
// Created by George Nachman on 4/7/19.
// Copyright © 2019 George Nachman. All rights reserved.
//
import Foundation
@objc(BFPFontListTableView)
protocol FontListTableViewDelegate: NSObjectProtocol {
func fontListTableView(_ fontListTableView: FontListTableView,
didToggleFavoriteForRow row: Int)
}
@objc(BFPFontListTableView)
public class FontListTableView: NSTableView {
weak var fontListDelegate: FontListTableViewDelegate?
@objc(keyDown:)
public override func keyDown(with event: NSEvent) {
if event.keyCode == NSUpArrowFunctionKey || event.keyCode == NSDownArrowFunctionKey {
return
}
super.keyDown(with: event)
}
@objc(mouseDown:)
public override func mouseDown(with event: NSEvent) {
if !tryMouseDown(with: event) {
super.mouseDown(with: event)
}
}
private func tryMouseDown(with event: NSEvent) -> Bool {
guard event.clickCount == 1 else {
return false
}
let localPoint = convert(event.locationInWindow, from: nil)
let row = self.row(at: localPoint)
guard row >= 0 else {
return false
}
guard let view = self.view(atColumn: 2, row: row, makeIfNecessary: false) else {
return false
}
guard let starSuperview = view.superview else {
return false
}
let pointInSuperView = starSuperview.convert(localPoint, from: self)
let result = view.hitTest(pointInSuperView)
if result == nil {
return false
}
fontListDelegate?.fontListTableView(self, didToggleFavoriteForRow: row)
return true
}
}
|
gpl-2.0
|
6f86f6052ff4519e36c9083fc48432f8
| 26.765625 | 93 | 0.633089 | 4.579897 | false | false | false | false |
CoderST/DYZB
|
DYZB/DYZB/Class/Tools/Category/Extension/UIImageView+Extension.swift
|
1
|
1602
|
//
// UIImageView+Extension.swift
// DYZB
//
// Created by xiudou on 16/11/1.
// Copyright © 2016年 xiudo. All rights reserved.
//
import UIKit
import AVFoundation
extension UIImageView{
/**
开始动画
*/
func playGifAnimation(_ images : [UIImage]?){
guard let imageArray = images else { return }
animationImages = imageArray
animationDuration = 0.5
animationRepeatCount = 0
startAnimating()
}
/**
结束动画
*/
func stopGifAnimation(){
if isAnimating == true{
stopAnimating()
}
removeFromSuperview()
}
}
// MARK:- 获取网络视频截图第一帧
extension UIImageView {
func getNetWorkVidoeImage(url:String){
DispatchQueue.global().async {
//需要长时间处理的代码
let asset = AVURLAsset(url: URL(string: url)!)
let generator = AVAssetImageGenerator(asset: asset)
generator.appliesPreferredTrackTransform=true
let time = CMTimeMakeWithSeconds(0.0,600)
var actualTime : CMTime = CMTimeMake(0,0)
var image:CGImage!
do{
image = try generator.copyCGImage(at: time, actualTime: &actualTime)
}catch let error as NSError{
print(error)
}
DispatchQueue.main.async {
self.image = UIImage(cgImage: image)
}
}
}
}
|
mit
|
bc79535c8ec67b73b2bbf0fcc6b4d6b2
| 20.704225 | 84 | 0.517197 | 5.102649 | false | false | false | false |
sarvex/SwiftRecepies
|
Basics/Creating Scrollable Content with UIScrollView/Creating Scrollable Content with UIScrollView/ViewController.swift
|
1
|
2588
|
//
// ViewController.swift
// Creating Scrollable Content with UIScrollView
//
// Created by Vandad Nahavandipoor on 6/29/14.
// Copyright (c) 2014 Pixolity Ltd. All rights reserved.
//
// These example codes are written for O'Reilly's iOS 8 Swift Programming Cookbook
// If you use these solutions in your apps, you can give attribution to
// Vandad Nahavandipoor for his work. Feel free to visit my blog
// at http://vandadnp.wordpress.com for daily tips and tricks in Swift
// and Objective-C and various other programming languages.
//
// You can purchase "iOS 8 Swift Programming Cookbook" from
// the following URL:
// http://shop.oreilly.com/product/0636920034254.do
//
// If you have any questions, you can contact me directly
// at vandad.np@gmail.com
// Similarly, if you find an error in these sample codes, simply
// report them to O'Reilly at the following URL:
// http://www.oreilly.com/catalog/errata.csp?isbn=0636920034254
/* 1 */
//import UIKit
//
//class ViewController: UIViewController {
// var imageView: UIImageView!
// var scrollView: UIScrollView!
// let image = UIImage(named: "Safari")
//}
/* 2 */
//import UIKit
//
//class ViewController: UIViewController {
// var imageView: UIImageView!
// var scrollView: UIScrollView!
// let image = UIImage(named: "Safari")
//
// override func viewDidLoad() {
// super.viewDidLoad()
//
// imageView = UIImageView(image: image)
// scrollView = UIScrollView(frame: view.bounds)
//
// scrollView.addSubview(imageView)
// scrollView.contentSize = imageView.bounds.size
// view.addSubview(scrollView)
//
// }
//
//}
/* 3 */
import UIKit
class ViewController: UIViewController, UIScrollViewDelegate {
var imageView: UIImageView!
var scrollView: UIScrollView!
let image = UIImage(named: "Safari")
func scrollViewDidScroll(scrollView: UIScrollView){
/* Gets called when user scrolls or drags */
scrollView.alpha = 0.50
}
func scrollViewDidEndDecelerating(scrollView: UIScrollView){
/* Gets called only after scrolling */
scrollView.alpha = 1
}
func scrollViewDidEndDragging(scrollView: UIScrollView,
willDecelerate decelerate: Bool){
scrollView.alpha = 1
}
override func viewDidLoad() {
super.viewDidLoad()
imageView = UIImageView(image: image)
scrollView = UIScrollView(frame: view.bounds)
scrollView.addSubview(imageView)
scrollView.contentSize = imageView.bounds.size
scrollView.delegate = self
scrollView.indicatorStyle = .White
view.addSubview(scrollView)
}
}
|
isc
|
2cd2ad19fe2843ca502f8cc40aaa4ded
| 27.141304 | 83 | 0.705951 | 4.187702 | false | false | false | false |
rzrasel/iOS-Swift-2016-01
|
SwiftGoogleMapTwo/SwiftGoogleMapTwo/ViewController.swift
|
2
|
2473
|
//
// ViewController.swift
// SwiftGoogleMapTwo
//
// Created by NextDot on 2/7/16.
// Copyright © 2016 RzRasel. All rights reserved.
//
import UIKit
import GoogleMaps
class ViewController: UIViewController {
//|------------------------------------|
@IBOutlet var sysGoogleMapView: GMSMapView!
//|------------------------------------|
//|~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~|
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
customViewGoogleMapView();
}
//|~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~|
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
//|~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~|
func customViewGoogleMapView()
{
//|------------------------------------|
let camera = GMSCameraPosition.cameraWithLatitude(23.817012, longitude: 90.410389, zoom: 12)
sysGoogleMapView.camera = camera
//|------------------------------------|
dispatch_async(dispatch_get_main_queue(), { () -> Void in
self.sysGoogleMapView.myLocationEnabled = true
self.sysGoogleMapView.autoresizingMask = UIViewAutoresizing.FlexibleWidth
self.sysGoogleMapView.myLocationEnabled = true
self.sysGoogleMapView.indoorEnabled = false
self.sysGoogleMapView.settings.myLocationButton = true
self.sysGoogleMapView.indoorEnabled = false
self.sysGoogleMapView.accessibilityElementsHidden = false
self.sysGoogleMapView.settings.compassButton = true;
self.sysGoogleMapView.settings.zoomGestures = true;
self.sysGoogleMapView.mapType = kGMSTypeNormal
})
//|------------------------------------|
let marker = GMSMarker()
marker.position = CLLocationCoordinate2DMake(23.817012, 90.410389)
marker.appearAnimation = kGMSMarkerAnimationPop
marker.title = "Dhaka"
marker.snippet = "Bangladesh"
marker.map = sysGoogleMapView
//|------------------------------------|
}
//|~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~|
/*
HELP LINK:-
https://developers.google.com/maps/documentation/ios-sdk/start
https://kodesnippets.wordpress.com/2015/07/09/google-maps-with-custom-view-in-ios/
*/
//|~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~|
}
|
apache-2.0
|
0700308e894d7f4a01c290f291720325
| 38.887097 | 100 | 0.544094 | 4.924303 | false | false | false | false |
masteranca/Flow
|
Flow/Request.swift
|
1
|
649
|
//
// Created by Anders Carlsson on 14/01/16.
// Copyright (c) 2016 CoreDev. All rights reserved.
//
import Foundation
public final class Request {
private let task: NSURLSessionTask
public var isRunning: Bool {
return task.state == NSURLSessionTaskState.Running
}
public var isFinished: Bool {
return task.state == NSURLSessionTaskState.Completed
}
public var isCanceling: Bool {
return task.state == NSURLSessionTaskState.Canceling
}
init(task: NSURLSessionTask) {
self.task = task
}
public func cancel() -> Request {
task.cancel()
return self
}
}
|
mit
|
fb214385d1a16c0a331ccbb5ee853a44
| 19.3125 | 60 | 0.645609 | 4.570423 | false | false | false | false |
koba-uy/chivia-app-ios
|
src/Pods/Alamofire/Source/TaskDelegate.swift
|
111
|
15808
|
//
// TaskDelegate.swift
//
// Copyright (c) 2014-2017 Alamofire Software Foundation (http://alamofire.org/)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
import Foundation
/// The task delegate is responsible for handling all delegate callbacks for the underlying task as well as
/// executing all operations attached to the serial operation queue upon task completion.
open class TaskDelegate: NSObject {
// MARK: Properties
/// The serial operation queue used to execute all operations after the task completes.
open let queue: OperationQueue
/// The data returned by the server.
public var data: Data? { return nil }
/// The error generated throughout the lifecyle of the task.
public var error: Error?
var task: URLSessionTask? {
set {
taskLock.lock(); defer { taskLock.unlock() }
_task = newValue
}
get {
taskLock.lock(); defer { taskLock.unlock() }
return _task
}
}
var initialResponseTime: CFAbsoluteTime?
var credential: URLCredential?
var metrics: AnyObject? // URLSessionTaskMetrics
private var _task: URLSessionTask? {
didSet { reset() }
}
private let taskLock = NSLock()
// MARK: Lifecycle
init(task: URLSessionTask?) {
_task = task
self.queue = {
let operationQueue = OperationQueue()
operationQueue.maxConcurrentOperationCount = 1
operationQueue.isSuspended = true
operationQueue.qualityOfService = .utility
return operationQueue
}()
}
func reset() {
error = nil
initialResponseTime = nil
}
// MARK: URLSessionTaskDelegate
var taskWillPerformHTTPRedirection: ((URLSession, URLSessionTask, HTTPURLResponse, URLRequest) -> URLRequest?)?
var taskDidReceiveChallenge: ((URLSession, URLSessionTask, URLAuthenticationChallenge) -> (URLSession.AuthChallengeDisposition, URLCredential?))?
var taskNeedNewBodyStream: ((URLSession, URLSessionTask) -> InputStream?)?
var taskDidCompleteWithError: ((URLSession, URLSessionTask, Error?) -> Void)?
@objc(URLSession:task:willPerformHTTPRedirection:newRequest:completionHandler:)
func urlSession(
_ session: URLSession,
task: URLSessionTask,
willPerformHTTPRedirection response: HTTPURLResponse,
newRequest request: URLRequest,
completionHandler: @escaping (URLRequest?) -> Void)
{
var redirectRequest: URLRequest? = request
if let taskWillPerformHTTPRedirection = taskWillPerformHTTPRedirection {
redirectRequest = taskWillPerformHTTPRedirection(session, task, response, request)
}
completionHandler(redirectRequest)
}
@objc(URLSession:task:didReceiveChallenge:completionHandler:)
func urlSession(
_ session: URLSession,
task: URLSessionTask,
didReceive challenge: URLAuthenticationChallenge,
completionHandler: @escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Void)
{
var disposition: URLSession.AuthChallengeDisposition = .performDefaultHandling
var credential: URLCredential?
if let taskDidReceiveChallenge = taskDidReceiveChallenge {
(disposition, credential) = taskDidReceiveChallenge(session, task, challenge)
} else if challenge.protectionSpace.authenticationMethod == NSURLAuthenticationMethodServerTrust {
let host = challenge.protectionSpace.host
if
let serverTrustPolicy = session.serverTrustPolicyManager?.serverTrustPolicy(forHost: host),
let serverTrust = challenge.protectionSpace.serverTrust
{
if serverTrustPolicy.evaluate(serverTrust, forHost: host) {
disposition = .useCredential
credential = URLCredential(trust: serverTrust)
} else {
disposition = .cancelAuthenticationChallenge
}
}
} else {
if challenge.previousFailureCount > 0 {
disposition = .rejectProtectionSpace
} else {
credential = self.credential ?? session.configuration.urlCredentialStorage?.defaultCredential(for: challenge.protectionSpace)
if credential != nil {
disposition = .useCredential
}
}
}
completionHandler(disposition, credential)
}
@objc(URLSession:task:needNewBodyStream:)
func urlSession(
_ session: URLSession,
task: URLSessionTask,
needNewBodyStream completionHandler: @escaping (InputStream?) -> Void)
{
var bodyStream: InputStream?
if let taskNeedNewBodyStream = taskNeedNewBodyStream {
bodyStream = taskNeedNewBodyStream(session, task)
}
completionHandler(bodyStream)
}
@objc(URLSession:task:didCompleteWithError:)
func urlSession(_ session: URLSession, task: URLSessionTask, didCompleteWithError error: Error?) {
if let taskDidCompleteWithError = taskDidCompleteWithError {
taskDidCompleteWithError(session, task, error)
} else {
if let error = error {
if self.error == nil { self.error = error }
if
let downloadDelegate = self as? DownloadTaskDelegate,
let resumeData = (error as NSError).userInfo[NSURLSessionDownloadTaskResumeData] as? Data
{
downloadDelegate.resumeData = resumeData
}
}
queue.isSuspended = false
}
}
}
// MARK: -
class DataTaskDelegate: TaskDelegate, URLSessionDataDelegate {
// MARK: Properties
var dataTask: URLSessionDataTask { return task as! URLSessionDataTask }
override var data: Data? {
if dataStream != nil {
return nil
} else {
return mutableData
}
}
var progress: Progress
var progressHandler: (closure: Request.ProgressHandler, queue: DispatchQueue)?
var dataStream: ((_ data: Data) -> Void)?
private var totalBytesReceived: Int64 = 0
private var mutableData: Data
private var expectedContentLength: Int64?
// MARK: Lifecycle
override init(task: URLSessionTask?) {
mutableData = Data()
progress = Progress(totalUnitCount: 0)
super.init(task: task)
}
override func reset() {
super.reset()
progress = Progress(totalUnitCount: 0)
totalBytesReceived = 0
mutableData = Data()
expectedContentLength = nil
}
// MARK: URLSessionDataDelegate
var dataTaskDidReceiveResponse: ((URLSession, URLSessionDataTask, URLResponse) -> URLSession.ResponseDisposition)?
var dataTaskDidBecomeDownloadTask: ((URLSession, URLSessionDataTask, URLSessionDownloadTask) -> Void)?
var dataTaskDidReceiveData: ((URLSession, URLSessionDataTask, Data) -> Void)?
var dataTaskWillCacheResponse: ((URLSession, URLSessionDataTask, CachedURLResponse) -> CachedURLResponse?)?
func urlSession(
_ session: URLSession,
dataTask: URLSessionDataTask,
didReceive response: URLResponse,
completionHandler: @escaping (URLSession.ResponseDisposition) -> Void)
{
var disposition: URLSession.ResponseDisposition = .allow
expectedContentLength = response.expectedContentLength
if let dataTaskDidReceiveResponse = dataTaskDidReceiveResponse {
disposition = dataTaskDidReceiveResponse(session, dataTask, response)
}
completionHandler(disposition)
}
func urlSession(
_ session: URLSession,
dataTask: URLSessionDataTask,
didBecome downloadTask: URLSessionDownloadTask)
{
dataTaskDidBecomeDownloadTask?(session, dataTask, downloadTask)
}
func urlSession(_ session: URLSession, dataTask: URLSessionDataTask, didReceive data: Data) {
if initialResponseTime == nil { initialResponseTime = CFAbsoluteTimeGetCurrent() }
if let dataTaskDidReceiveData = dataTaskDidReceiveData {
dataTaskDidReceiveData(session, dataTask, data)
} else {
if let dataStream = dataStream {
dataStream(data)
} else {
mutableData.append(data)
}
let bytesReceived = Int64(data.count)
totalBytesReceived += bytesReceived
let totalBytesExpected = dataTask.response?.expectedContentLength ?? NSURLSessionTransferSizeUnknown
progress.totalUnitCount = totalBytesExpected
progress.completedUnitCount = totalBytesReceived
if let progressHandler = progressHandler {
progressHandler.queue.async { progressHandler.closure(self.progress) }
}
}
}
func urlSession(
_ session: URLSession,
dataTask: URLSessionDataTask,
willCacheResponse proposedResponse: CachedURLResponse,
completionHandler: @escaping (CachedURLResponse?) -> Void)
{
var cachedResponse: CachedURLResponse? = proposedResponse
if let dataTaskWillCacheResponse = dataTaskWillCacheResponse {
cachedResponse = dataTaskWillCacheResponse(session, dataTask, proposedResponse)
}
completionHandler(cachedResponse)
}
}
// MARK: -
class DownloadTaskDelegate: TaskDelegate, URLSessionDownloadDelegate {
// MARK: Properties
var downloadTask: URLSessionDownloadTask { return task as! URLSessionDownloadTask }
var progress: Progress
var progressHandler: (closure: Request.ProgressHandler, queue: DispatchQueue)?
var resumeData: Data?
override var data: Data? { return resumeData }
var destination: DownloadRequest.DownloadFileDestination?
var temporaryURL: URL?
var destinationURL: URL?
var fileURL: URL? { return destination != nil ? destinationURL : temporaryURL }
// MARK: Lifecycle
override init(task: URLSessionTask?) {
progress = Progress(totalUnitCount: 0)
super.init(task: task)
}
override func reset() {
super.reset()
progress = Progress(totalUnitCount: 0)
resumeData = nil
}
// MARK: URLSessionDownloadDelegate
var downloadTaskDidFinishDownloadingToURL: ((URLSession, URLSessionDownloadTask, URL) -> URL)?
var downloadTaskDidWriteData: ((URLSession, URLSessionDownloadTask, Int64, Int64, Int64) -> Void)?
var downloadTaskDidResumeAtOffset: ((URLSession, URLSessionDownloadTask, Int64, Int64) -> Void)?
func urlSession(
_ session: URLSession,
downloadTask: URLSessionDownloadTask,
didFinishDownloadingTo location: URL)
{
temporaryURL = location
guard
let destination = destination,
let response = downloadTask.response as? HTTPURLResponse
else { return }
let result = destination(location, response)
let destinationURL = result.destinationURL
let options = result.options
self.destinationURL = destinationURL
do {
if options.contains(.removePreviousFile), FileManager.default.fileExists(atPath: destinationURL.path) {
try FileManager.default.removeItem(at: destinationURL)
}
if options.contains(.createIntermediateDirectories) {
let directory = destinationURL.deletingLastPathComponent()
try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true)
}
try FileManager.default.moveItem(at: location, to: destinationURL)
} catch {
self.error = error
}
}
func urlSession(
_ session: URLSession,
downloadTask: URLSessionDownloadTask,
didWriteData bytesWritten: Int64,
totalBytesWritten: Int64,
totalBytesExpectedToWrite: Int64)
{
if initialResponseTime == nil { initialResponseTime = CFAbsoluteTimeGetCurrent() }
if let downloadTaskDidWriteData = downloadTaskDidWriteData {
downloadTaskDidWriteData(
session,
downloadTask,
bytesWritten,
totalBytesWritten,
totalBytesExpectedToWrite
)
} else {
progress.totalUnitCount = totalBytesExpectedToWrite
progress.completedUnitCount = totalBytesWritten
if let progressHandler = progressHandler {
progressHandler.queue.async { progressHandler.closure(self.progress) }
}
}
}
func urlSession(
_ session: URLSession,
downloadTask: URLSessionDownloadTask,
didResumeAtOffset fileOffset: Int64,
expectedTotalBytes: Int64)
{
if let downloadTaskDidResumeAtOffset = downloadTaskDidResumeAtOffset {
downloadTaskDidResumeAtOffset(session, downloadTask, fileOffset, expectedTotalBytes)
} else {
progress.totalUnitCount = expectedTotalBytes
progress.completedUnitCount = fileOffset
}
}
}
// MARK: -
class UploadTaskDelegate: DataTaskDelegate {
// MARK: Properties
var uploadTask: URLSessionUploadTask { return task as! URLSessionUploadTask }
var uploadProgress: Progress
var uploadProgressHandler: (closure: Request.ProgressHandler, queue: DispatchQueue)?
// MARK: Lifecycle
override init(task: URLSessionTask?) {
uploadProgress = Progress(totalUnitCount: 0)
super.init(task: task)
}
override func reset() {
super.reset()
uploadProgress = Progress(totalUnitCount: 0)
}
// MARK: URLSessionTaskDelegate
var taskDidSendBodyData: ((URLSession, URLSessionTask, Int64, Int64, Int64) -> Void)?
func URLSession(
_ session: URLSession,
task: URLSessionTask,
didSendBodyData bytesSent: Int64,
totalBytesSent: Int64,
totalBytesExpectedToSend: Int64)
{
if initialResponseTime == nil { initialResponseTime = CFAbsoluteTimeGetCurrent() }
if let taskDidSendBodyData = taskDidSendBodyData {
taskDidSendBodyData(session, task, bytesSent, totalBytesSent, totalBytesExpectedToSend)
} else {
uploadProgress.totalUnitCount = totalBytesExpectedToSend
uploadProgress.completedUnitCount = totalBytesSent
if let uploadProgressHandler = uploadProgressHandler {
uploadProgressHandler.queue.async { uploadProgressHandler.closure(self.uploadProgress) }
}
}
}
}
|
lgpl-3.0
|
20c8e651c2ef1d01ae7376eeaa51bd3a
| 32.922747 | 149 | 0.662323 | 6.124758 | false | false | false | false |
baottran/nSURE
|
nSURE/RepairMainViewController.swift
|
1
|
26413
|
//
// RepairMainViewController.swift
// nSURE
//
// Created by Bao Tran on 7/27/15.
// Copyright (c) 2015 Sprout Designs. All rights reserved.
//
import UIKit
import MBProgressHUD
protocol RepairMainViewControllerDelegate: class {
func filterActivityChosen(activity: String)
}
class RepairMainViewController: UIViewController, UICollectionViewDataSource, UICollectionViewDelegate, RepairMainViewControllerDelegate {
//==============================
// MARK: -Setup
//==============================
@IBOutlet weak var openSideBarButton: UIBarButtonItem!
@IBOutlet weak var userNameWelcomeLabel: UIButton!
@IBOutlet weak var repairCollectionView: UICollectionView!
@IBOutlet weak var workStatusButton: UIButton!
var vehicleRepairSegue = "Repair Vehicle"
var repairObjs: [PFObject]!
@IBOutlet weak var activityStatusFilter: UISegmentedControl!
var repairObjectsByActivity = ["DropOff": [PFObject](),
"Teardown":[PFObject](),
"Mechanical":[PFObject](),
"Body":[PFObject](),
"Paint": [PFObject](),
"QualityAssessment": [PFObject](),
"SignOff": [PFObject]()]
var currentActivityFilter = "All"
var currentSections = [String]()
//==============================
// MARK: - View Load/Appear
//==============================
override func viewDidLoad() {
super.viewDidLoad()
openSideBarButton.target = self.revealViewController()
openSideBarButton.action = Selector("revealToggle:")
self.view.addGestureRecognizer(self.revealViewController().panGestureRecognizer())
self.view.addSubview(repairCollectionView)
repairCollectionView.dataSource = self
repairCollectionView.delegate = self
let currentUser = PFUser.currentUser()
if let user = currentUser {
let firstName = user["firstName"] as! String
let custLastName = user["lastName"] as! String
userNameWelcomeLabel.setTitle(" Welcome \(firstName) \(custLastName)", forState: .Normal)
}
}
override func viewDidAppear(animated: Bool) {
super.viewDidAppear(true)
//find repair objects by current filters
filterActivityChosen(currentActivityFilter)
}
//==============================
// MARK: - Collection View Data Source Methods
//==============================
func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int {
return currentSections.count
}
func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
let activityForSection = currentSections[section]
if let activity = repairObjectsByActivity[activityForSection] {
return activity.count
} else {
return 0
}
}
func collectionView(collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, atIndexPath indexPath: NSIndexPath) -> UICollectionReusableView {
let headerView = collectionView.dequeueReusableSupplementaryViewOfKind(kind, withReuseIdentifier: "Section Header", forIndexPath: indexPath) as! DashHeaderCollectionReusableView
if let sectionTitle = currentSections[indexPath.section] as? String {
headerView.title.text = sectionTitle
if let currentSection = repairObjectsByActivity[sectionTitle] {
headerView.num.text = "\(currentSection.count)"
}
}
return headerView
}
//==============================
// MARK: - Find Repair Parse Objects
//==============================
func findRepairObjs(statusFilterSetting: String, activityFilterSetting: String){
let loadingModal = MBProgressHUD.showHUDAddedTo(self.view, animated: true)
loadingModal.labelText = "Finding \(statusFilterSetting) Repairs"
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), {
let currentUser = PFUser.currentUser()
// var repairObjs: [PFObject]?
if let user = currentUser {
if let company = user["company"] as? PFObject {
let query = PFQuery(className: "Repair")
query.whereKey("company", equalTo: company)
query.whereKey("estimateCompleted", equalTo: true)
query.orderByAscending("updatedAt")
// let result = query.findObjects() as! [PFObject]
let result = query.findObjects() as! [Repair]
let filteredRepairObjectsByStatus = self.filterObjResults(result, filterSetting: statusFilterSetting)
self.repairObjectsByActivity = self.sortObjsByActivity(filteredRepairObjectsByStatus)
self.determineAvailableSections(activityFilterSetting)
self.refreshActivityButtonLabel(activityFilterSetting)
dispatch_async(dispatch_get_main_queue(), { () -> Void in
// self.repairObjs = result
MBProgressHUD.hideAllHUDsForView(self.view, animated: true)
self.repairCollectionView.reloadData()
})
}
}
})
}
// func calculate
func determineAvailableSections(activityFilterSetting: String){
self.currentSections = []
switch activityFilterSetting {
case "All":
if self.repairObjectsByActivity["DropOff"]!.count > 0 {
self.currentSections.append("DropOff")
}
if self.repairObjectsByActivity["Teardown"]!.count > 0 {
self.currentSections.append("Teardown")
}
if self.repairObjectsByActivity["Mechanical"]!.count > 0 {
self.currentSections.append("Mechanical")
}
if self.repairObjectsByActivity["Body"]!.count > 0 {
self.currentSections.append("Body")
}
if self.repairObjectsByActivity["Paint"]!.count > 0 {
self.currentSections.append("Paint")
}
if self.repairObjectsByActivity["QualityAssessment"]!.count > 0 {
self.currentSections.append("QualityAssessment")
}
if self.repairObjectsByActivity["SignOff"]!.count > 0 {
self.currentSections.append("SignOff")
}
case "DropOff":
self.currentSections.append("DropOff")
case "Teardown":
self.currentSections.append("Teardown")
case "Body":
self.currentSections.append("Body")
case "Paint":
self.currentSections.append("Paint")
case "Mechanical":
self.currentSections.append("Mechanical")
case "QualityAssessment":
self.currentSections.append("QualityAssessment")
case "SignOff":
self.currentSections.append("SignOff")
default:
print("couldn't find chosen option \(activityFilterSetting)")
}
}
//==============================
// MARK: - Activity String Value Helper Methods
//==============================
func activityTypeShort(activityTypeString: String) -> String {
switch activityTypeString {
case "DropOff":
return "Drop Off"
case "Teardown":
return "Teardown"
case "Body":
return "Body"
case "Paint":
return "Paint"
case "Mechanical":
return "Mechanical"
case "QualityAssessment":
return "QA"
case "SignOff":
return "Sign Off"
default:
return ""
}
}
func valueForSectionId(sectionId: Int)-> String {
switch sectionId {
case 0:
return "DropOff"
case 1:
return "Teardown"
case 2:
return "Mechanical"
case 3:
return "Body"
case 4:
return "Paint"
case 5:
return "QualityAssessment"
case 6:
return "SignOff"
default:
return "break"
}
}
//==============================
// MARK: - Cell For Item At Index Path
//==============================
func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCellWithReuseIdentifier("Repair Item", forIndexPath: indexPath) as! DashMiniCardCell
let repairObj = repairObjectsByActivity[currentSections[indexPath.section]]![indexPath.row]
let repairItem = repairObj as! Repair
//
// if let repairStatus = repairItem.statusString
// {
// cell.currentStatusLabel.text = repairStatus
// } else {
// if let currentActivity = repairObj["currentActivity"] as? String {
// if currentActivity == "" {
// cell.currentStatusLabel.text = "IDLE2"
// repairItem.statusString = "IDLE2"
// print("couldn't find the current activity for repair object \(repairItem.objectId)")
// } else {
// getRepairStatus(repairObj, currentActivity: currentActivity, cell: cell, repair: repairItem)
// }
// } else {
// cell.currentStatusLabel.text = "IDLE3"
// repairItem.statusString = "IDLE3"
// print("current activity is nil for \(repairItem.objectId)")
// }
// }
// if let repairStatus = repairItem.statusString
// {
// cell.currentStatusLabel.text = repairStatus
// } else {
if let currentActivity = repairObj["currentActivity"] as? String {
if currentActivity == "" {
cell.currentStatusLabel.text = "IDLE"
// repairItem.statusString = "IDLE2"
print("couldn't find the current activity for repair object \(repairItem.objectId)")
} else {
getRepairStatus(repairObj, currentActivity: currentActivity, cell: cell, repair: repairItem)
}
} else {
cell.currentStatusLabel.text = "IDLE"
// repairItem.statusString = "IDLE3"
print("current activity is nil for \(repairItem.objectId)")
}
// }
cell.currentActivityLabel.text = activityTypeShort(currentSections[indexPath.section])
if let customerName = repairItem.customerName {
cell.customerNameLabel.text = customerName
} else {
if let customer = repairObj["customer"] as? PFObject {
getCustomerName(customer, cell: cell, repair: repairItem)
}
}
if let repairDashImage = repairItem.dashImage {
cell.vehicleImage.image = repairDashImage
} else {
if let frontCenterObj = repairObj["frontCenterDamage"] as? PFObject {
getImage(frontCenterObj, cell: cell, repairItem: repairItem)
}
}
if let vehicleMake = repairItem.vehicleMake, vehicleModel = repairItem.vehicleModel, vehicleYear = repairItem.vehicleYear {
cell.vehicleLine1.text = "\(vehicleYear) \(vehicleMake)"
cell.vehicleLine2.text = vehicleModel
} else {
let vehicle = repairObj["damagedVehicle"] as! PFObject
setVehicleLabels(cell, vehicle: vehicle, repair: repairItem)
}
return cell
}
//==============================
// MARK: - Helper Methods For Cell
//==============================
func setVehicleLabels(cell: DashMiniCardCell, vehicle: PFObject, repair: Repair){
let query = PFQuery(className: "Vehicle")
query.getObjectInBackgroundWithId(vehicle.objectId!, block: { vehicleObj, error in
if let vehicle = vehicleObj {
repair.vehicleMake = vehicle["make"] as! String
repair.vehicleModel = vehicle["model"] as! String
repair.vehicleYear = vehicle["year"] as! String
cell.vehicleLine1.text = "\(repair.vehicleYear!) \(repair.vehicleMake!)"
cell.vehicleLine2.text = repair.vehicleModel!
} else {
print("error extracting vehicle object", terminator: "")
print(error, terminator: "")
}
})
}
func getRepairStatus(repairObj: PFObject, currentActivity: String, cell: DashMiniCardCell, repair: Repair){
if let activityObj = repairObj[currentActivity] as? PFObject {
let query = PFQuery(className: "Activity")
query.getObjectInBackgroundWithId(activityObj.objectId!, block: { activity, error in
if let activity = activity as? Activity {
let currentStatus = activity.getActivityStatus()
cell.currentStatusLabel.text = currentStatus
repair.statusString = currentStatus
} else {
print("\n error getting activity object for status: \(error) \(currentActivity) object id: \(activityObj.objectId!) activity: \(activity)", terminator: "")
}
})
} else {
print("ERROR: Error Retrieving Activity", terminator: "")
}
}
func getCustomerName(customerObj: PFObject, cell: DashMiniCardCell, repair: Repair){
let query = PFQuery(className: "Customer")
query.getObjectInBackgroundWithId(customerObj.objectId!, block: { success, error in
if success != nil {
if let customer = success {
let customerFirstName = customer["firstName"] as! String
let customerLastName = customer["lastName"] as! String
cell.customerNameLabel.text = "\(customerFirstName) \(customerLastName)"
repair.customerName = "\(customerFirstName) \(customerLastName)"
}
} else {
print("not good", terminator: "")
}
})
}
func getImage(frontCenterObj: PFObject, cell: DashMiniCardCell, repairItem: Repair){
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_LOW, 0), {
let query = PFQuery(className: "DamagedSection")
query.getObjectInBackgroundWithId(frontCenterObj.objectId!, block: { damageObj, error in
if let damageObj = damageObj {
if let damagePhotos = damageObj["images"] as? [PFFile]{
let coverPhoto = damagePhotos.first!
coverPhoto.getDataInBackgroundWithBlock{ (imageData: NSData?, error: NSError?) -> Void in
if let imageData = imageData {
let image = UIImage(data: imageData)
cell.vehicleImage.image = image
repairItem.dashImage = image
}
}
} else {
print("error finding images\n")
}
} else {
print("ERROR: couldn't find damage object\n")
print(error)
}
})
})
}
//==============================
// MARK: - Activity Filter Methods
//==============================
func refreshActivityButtonLabel(activity: String){
var repairCount = 0
let currentActivity = currentActivityFilter
for activity in currentSections {
if let objectArray = repairObjectsByActivity[activity]{
repairCount = repairCount + objectArray.count
}
}
dispatch_async(dispatch_get_main_queue(), {
self.workStatusButton.setTitle("\(currentActivity) (\(repairCount))", forState: .Normal)
})
}
func filterActivityChosen(activity: String) {
print("activity \(activity) chosen")
var activityStatusFilterValue: String
currentActivityFilter = activity
switch activityStatusFilter.selectedSegmentIndex {
case 0:
activityStatusFilterValue = "All"
case 1:
activityStatusFilterValue = "Idle"
case 2:
activityStatusFilterValue = "Ontime"
case 3:
activityStatusFilterValue = "Overtime"
default:
activityStatusFilterValue = "All"
}
findRepairObjs(activityStatusFilterValue, activityFilterSetting: currentActivityFilter)
}
func filterObjResults(repairObjs: [PFObject], filterSetting: String) -> [PFObject]{
var filteredRepairObjs = [PFObject]()
for var index = 0; index < repairObjs.count; ++index {
switch filterSetting {
case "All":
filteredRepairObjs = repairObjs
case "Idle":
if currentRepairStatus(repairObjs[index]) == .Idle {
filteredRepairObjs.append(repairObjs[index])
}
case "Ontime":
if currentRepairStatus(repairObjs[index]) == .Ontime {
filteredRepairObjs.append(repairObjs[index])
}
case "Overtime":
if currentRepairStatus(repairObjs[index]) == .Overtime {
filteredRepairObjs.append(repairObjs[index])
}
default:
break
}
}
return filteredRepairObjs
}
func sortObjsByActivity(repairObjs: [PFObject]) -> [String: [PFObject]]{
var sortedRepairs = ["DropOff": [PFObject](),
"Teardown":[PFObject](),
"Mechanical":[PFObject](),
"Body":[PFObject](),
"Paint": [PFObject](),
"QualityAssessment": [PFObject](),
"SignOff": [PFObject]()]
for repair in repairObjs {
let currentActivity = findCurrentActivityForRepair(repair)
switch currentActivity {
case .Dropoff:
sortedRepairs["DropOff"]?.append(repair)
case .Teardown:
sortedRepairs["Teardown"]?.append(repair)
case .Mechanical:
sortedRepairs["Mechanical"]?.append(repair)
case .Body:
sortedRepairs["Body"]?.append(repair)
case .Paint:
sortedRepairs["Paint"]?.append(repair)
case .Qa:
sortedRepairs["QualityAssessment"]?.append(repair)
case .Signoff:
sortedRepairs["SignOff"]?.append(repair)
}
}
return sortedRepairs
}
enum ActivityType {
case Dropoff, Teardown, Mechanical, Body, Paint, Qa, Signoff
}
func activityStringToEnum(activity: String) -> ActivityType {
switch activity {
case "DropOff":
return .Dropoff
case "Teardown":
return .Teardown
case "Mechanical":
return .Mechanical
case "Body":
return .Body
case "Paint":
return .Paint
case "QualityAssessment":
return .Qa
case "SignOff":
return .Signoff
default:
print("ERROR: went to default for activity to enum")
return .Dropoff
}
}
func findCurrentActivityForRepair(repairObj: PFObject) -> ActivityType {
if let currentActivity = repairObj["currentActivity"] as? String {
if currentActivity == "" {
return findNextPendingActivity(repairObj)
} else {
return activityStringToEnum(currentActivity)
}
} else {
return .Dropoff
}
}
func findNextPendingActivity(repairObj: PFObject) -> ActivityType {
// assumes at least the drop off is at least complete
if let teardownObj = repairObj["Teardown"] as? PFObject {
if isActivityObjectComplete(teardownObj) == false {
return .Teardown
}
}
if let mechanicalObj = repairObj["Mechanical"] as? PFObject {
if isActivityObjectComplete(mechanicalObj) == false {
return .Mechanical
}
}
if let bodyObj = repairObj["Body"] as? PFObject {
if isActivityObjectComplete(bodyObj) == false {
return .Body
}
}
if let paintObj = repairObj["Paint"] as? PFObject {
if isActivityObjectComplete(paintObj) == false {
return .Paint
}
}
if let qaObj = repairObj["QualityAssessment"] as? PFObject {
if isActivityObjectComplete(qaObj) == false {
return .Qa
}
}
if let signOffObj = repairObj["SignOff"] as? PFObject {
if isActivityObjectComplete(signOffObj) == false {
return .Signoff
}
}
return .Teardown
}
func isActivityObjectComplete(activityObj: PFObject) -> Bool {
let query = PFQuery(className: "Activity")
let result = query.getObjectWithId(activityObj.objectId!)
if let result = result {
if let isCompleted = result["completed"] as? Bool {
return isCompleted
} else {
return false
}
} else {
return false
}
}
//
enum ActivityStatus {
case Idle, Ontime, Overtime
}
func currentRepairStatus(repairObj: PFObject) -> ActivityStatus? {
var currentStatus: ActivityStatus?
if let currentActivity = repairObj["currentActivity"] as? String {
if let activityObj = repairObj[currentActivity] as? PFObject {
let query = PFQuery(className: "Activity")
let activity = query.getObjectWithId(activityObj.objectId!)
if let activity = activity as? Activity {
// print("successfully got activity object: \(activity)", terminator: "")
var currentActivityString = activity.getActivityStatus()
switch currentActivityString {
case "Idle":
currentStatus = .Idle
case "ON-TIME":
currentStatus = .Ontime
case "OVERTIME":
currentStatus = .Overtime
default:
print("ERROR setting repair activity")
}
} else {
currentStatus = .Idle
}
} else {
currentStatus = .Idle
}
} else {
currentStatus = .Idle
}
return currentStatus
}
@IBAction func filterByRepairStatus(sender: UISegmentedControl){
let currentActivity = currentActivityFilter
switch activityStatusFilter.selectedSegmentIndex {
case 0:
print("all selected", terminator: "")
findRepairObjs("All", activityFilterSetting: currentActivity)
case 1:
print("idle selected", terminator: "")
findRepairObjs("Idle", activityFilterSetting: currentActivity)
case 2:
print("on time selected", terminator: "")
findRepairObjs("Ontime", activityFilterSetting: currentActivity)
case 3:
print("overtime selected", terminator: "")
findRepairObjs("Overtime", activityFilterSetting: currentActivity)
default:
break
}
}
//==============================
// MARK: - Select Repair and Prepare for Segue
//==============================
func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
print("selected \(indexPath.row)", terminator: "")
self.performSegueWithIdentifier(vehicleRepairSegue, sender: indexPath)
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if segue.identifier == vehicleRepairSegue {
let repairVehicleVC = segue.destinationViewController as! RepairVehicleViewController
let repairIndex = sender as! NSIndexPath
let cell = repairCollectionView.cellForItemAtIndexPath(repairIndex) as! DashMiniCardCell
repairVehicleVC.titleText = "\(cell.customerNameLabel.text!) \(cell.vehicleLine1.text!) \(cell.vehicleLine2.text!)"
repairVehicleVC.repairObj = repairObjectsByActivity[currentSections[repairIndex.section]]![repairIndex.row]
} else if segue.identifier == "Choose Activity To Filter" {
let dropDownVC = segue.destinationViewController as! RepairActivityDropDownTableViewController
dropDownVC.nestedRepairObjArray = repairObjectsByActivity
dropDownVC.delegate = self
}
}
}
|
mit
|
13beec4e28786346437fd06225b782f6
| 35.583102 | 185 | 0.541779 | 5.519958 | false | false | false | false |
benlangmuir/swift
|
stdlib/public/core/UnsafeRawPointer.swift
|
1
|
62872
|
//===--- UnsafeRawPointer.swift -------------------------------*- swift -*-===//
//
// 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
//
//===----------------------------------------------------------------------===//
/// A raw pointer for accessing
/// untyped data.
///
/// The `UnsafeRawPointer` type provides no automated memory management, no type safety,
/// and no alignment guarantees. You are responsible for handling the life
/// cycle of any memory you work with through unsafe pointers, to avoid leaks
/// or undefined behavior.
///
/// Memory that you manually manage can be either *untyped* or *bound* to a
/// specific type. You use the `UnsafeRawPointer` type to access and
/// manage raw bytes in memory, whether or not that memory has been bound to a
/// specific type.
///
/// Understanding a Pointer's Memory State
/// ======================================
///
/// The memory referenced by an `UnsafeRawPointer` instance can be in one of several
/// states. Many pointer operations must only be applied to pointers with
/// memory in a specific state---you must keep track of the state of the
/// memory you are working with and understand the changes to that state that
/// different operations perform. Memory can be untyped and uninitialized,
/// bound to a type and uninitialized, or bound to a type and initialized to a
/// value. Finally, memory that was allocated previously may have been
/// deallocated, leaving existing pointers referencing unallocated memory.
///
/// Raw, Uninitialized Memory
/// -------------------------
///
/// Raw memory that has just been allocated is in an *uninitialized, untyped*
/// state. Uninitialized memory must be initialized with values of a type
/// before it can be used with any typed operations.
///
/// To bind uninitialized memory to a type without initializing it, use the
/// `bindMemory(to:count:)` method. This method returns a typed pointer
/// for further typed access to the memory.
///
/// Typed Memory
/// ------------
///
/// Memory that has been bound to a type, whether it is initialized or
/// uninitialized, is typically accessed using typed pointers---instances of
/// `UnsafePointer` and `UnsafeMutablePointer`. Initialization, assignment,
/// and deinitialization can be performed using `UnsafeMutablePointer`
/// methods.
///
/// Memory that has been bound to a type can be rebound to a different type
/// only after it has been deinitialized or if the bound type is a *trivial
/// type*. Deinitializing typed memory does not unbind that memory's type. The
/// deinitialized memory can be reinitialized with values of the same type,
/// bound to a new type, or deallocated.
///
/// - Note: A trivial type can be copied bit for bit with no indirection or
/// reference-counting operations. Generally, native Swift types that do not
/// contain strong or weak references or other forms of indirection are
/// trivial, as are imported C structs and enumerations.
///
/// When reading from memory as raw
/// bytes when that memory is bound to a type, you must ensure that you
/// satisfy any alignment requirements.
///
/// Raw Pointer Arithmetic
/// ======================
///
/// Pointer arithmetic with raw pointers is performed at the byte level. When
/// you add to or subtract from a raw pointer, the result is a new raw pointer
/// offset by that number of bytes. The following example allocates four bytes
/// of memory and stores `0xFF` in all four bytes:
///
/// let bytesPointer = UnsafeMutableRawPointer.allocate(byteCount: 4, alignment: 4)
/// bytesPointer.storeBytes(of: 0xFFFF_FFFF, as: UInt32.self)
///
/// // Load a value from the memory referenced by 'bytesPointer'
/// let x = bytesPointer.load(as: UInt8.self) // 255
///
/// // Load a value from the last two allocated bytes
/// let offsetPointer = bytesPointer + 2
/// let y = offsetPointer.load(as: UInt16.self) // 65535
///
/// The code above stores the value `0xFFFF_FFFF` into the four newly allocated
/// bytes, and then loads the first byte as a `UInt8` instance and the third
/// and fourth bytes as a `UInt16` instance.
///
/// Always remember to deallocate any memory that you allocate yourself.
///
/// bytesPointer.deallocate()
///
/// Implicit Casting and Bridging
/// =============================
///
/// When calling a function or method with an `UnsafeRawPointer` parameter, you can pass
/// an instance of that specific pointer type, pass an instance of a
/// compatible pointer type, or use Swift's implicit bridging to pass a
/// compatible pointer.
///
/// For example, the `print(address:as:)` function in the following code sample
/// takes an `UnsafeRawPointer` instance as its first parameter:
///
/// func print<T>(address p: UnsafeRawPointer, as type: T.Type) {
/// let value = p.load(as: type)
/// print(value)
/// }
///
/// As is typical in Swift, you can call the `print(address:as:)` function with
/// an `UnsafeRawPointer` instance. This example passes `rawPointer` as the initial
/// parameter.
///
/// // 'rawPointer' points to memory initialized with `Int` values.
/// let rawPointer: UnsafeRawPointer = ...
/// print(address: rawPointer, as: Int.self)
/// // Prints "42"
///
/// Because typed pointers can be implicitly cast to raw pointers when passed
/// as a parameter, you can also call `print(address:as:)` with any mutable or
/// immutable typed pointer instance.
///
/// let intPointer: UnsafePointer<Int> = ...
/// print(address: intPointer, as: Int.self)
/// // Prints "42"
///
/// let mutableIntPointer = UnsafeMutablePointer(mutating: intPointer)
/// print(address: mutableIntPointer, as: Int.self)
/// // Prints "42"
///
/// Alternatively, you can use Swift's *implicit bridging* to pass a pointer to
/// an instance or to the elements of an array. Use inout syntax to implicitly
/// create a pointer to an instance of any type. The following example uses
/// implicit bridging to pass a pointer to `value` when calling
/// `print(address:as:)`:
///
/// var value: Int = 23
/// print(address: &value, as: Int.self)
/// // Prints "23"
///
/// An immutable pointer to the elements of an array is implicitly created when
/// you pass the array as an argument. This example uses implicit bridging to
/// pass a pointer to the elements of `numbers` when calling
/// `print(address:as:)`.
///
/// let numbers = [5, 10, 15, 20]
/// print(address: numbers, as: Int.self)
/// // Prints "5"
///
/// You can also use inout syntax to pass a mutable pointer to the elements of
/// an array. Because `print(address:as:)` requires an immutable pointer,
/// although this is syntactically valid, it isn't necessary.
///
/// var mutableNumbers = numbers
/// print(address: &mutableNumbers, as: Int.self)
///
/// - Important: The pointer created through implicit bridging of an instance
/// or of an array's elements is only valid during the execution of the
/// called function. Escaping the pointer to use after the execution of the
/// function is undefined behavior. In particular, do not use implicit
/// bridging when calling an `UnsafeRawPointer` initializer.
///
/// var number = 5
/// let numberPointer = UnsafeRawPointer(&number)
/// // Accessing 'numberPointer' is undefined behavior.
@frozen
public struct UnsafeRawPointer: _Pointer {
public typealias Pointee = UInt8
/// The underlying raw pointer.
/// Implements conformance to the public protocol `_Pointer`.
public let _rawValue: Builtin.RawPointer
/// Creates a new raw pointer from a builtin raw pointer.
@_transparent
public init(_ _rawValue: Builtin.RawPointer) {
self._rawValue = _rawValue
}
/// Creates a new raw pointer from the given typed pointer.
///
/// Use this initializer to explicitly convert `other` to an `UnsafeRawPointer`
/// instance. This initializer creates a new pointer to the same address as
/// `other` and performs no allocation or copying.
///
/// - Parameter other: The typed pointer to convert.
@_transparent
public init<T>(@_nonEphemeral _ other: UnsafePointer<T>) {
_rawValue = other._rawValue
}
/// Creates a new raw pointer from the given typed pointer.
///
/// Use this initializer to explicitly convert `other` to an `UnsafeRawPointer`
/// instance. This initializer creates a new pointer to the same address as
/// `other` and performs no allocation or copying.
///
/// - Parameter other: The typed pointer to convert. If `other` is `nil`, the
/// result is `nil`.
@_transparent
public init?<T>(@_nonEphemeral _ other: UnsafePointer<T>?) {
guard let unwrapped = other else { return nil }
_rawValue = unwrapped._rawValue
}
/// Creates a new raw pointer from the given mutable raw pointer.
///
/// Use this initializer to explicitly convert `other` to an `UnsafeRawPointer`
/// instance. This initializer creates a new pointer to the same address as
/// `other` and performs no allocation or copying.
///
/// - Parameter other: The mutable raw pointer to convert.
@_transparent
public init(@_nonEphemeral _ other: UnsafeMutableRawPointer) {
_rawValue = other._rawValue
}
/// Creates a new raw pointer from the given mutable raw pointer.
///
/// Use this initializer to explicitly convert `other` to an `UnsafeRawPointer`
/// instance. This initializer creates a new pointer to the same address as
/// `other` and performs no allocation or copying.
///
/// - Parameter other: The mutable raw pointer to convert. If `other` is
/// `nil`, the result is `nil`.
@_transparent
public init?(@_nonEphemeral _ other: UnsafeMutableRawPointer?) {
guard let unwrapped = other else { return nil }
_rawValue = unwrapped._rawValue
}
/// Creates a new raw pointer from the given typed pointer.
///
/// Use this initializer to explicitly convert `other` to an `UnsafeRawPointer`
/// instance. This initializer creates a new pointer to the same address as
/// `other` and performs no allocation or copying.
///
/// - Parameter other: The typed pointer to convert.
@_transparent
public init<T>(@_nonEphemeral _ other: UnsafeMutablePointer<T>) {
_rawValue = other._rawValue
}
/// Creates a new raw pointer from the given typed pointer.
///
/// Use this initializer to explicitly convert `other` to an `UnsafeRawPointer`
/// instance. This initializer creates a new pointer to the same address as
/// `other` and performs no allocation or copying.
///
/// - Parameter other: The typed pointer to convert. If `other` is `nil`, the
/// result is `nil`.
@_transparent
public init?<T>(@_nonEphemeral _ other: UnsafeMutablePointer<T>?) {
guard let unwrapped = other else { return nil }
_rawValue = unwrapped._rawValue
}
/// Deallocates the previously allocated memory block referenced by this pointer.
///
/// The memory to be deallocated must be uninitialized or initialized to a
/// trivial type.
@inlinable
public func deallocate() {
// Passing zero alignment to the runtime forces "aligned
// deallocation". Since allocation via `UnsafeMutable[Raw][Buffer]Pointer`
// always uses the "aligned allocation" path, this ensures that the
// runtime's allocation and deallocation paths are compatible.
Builtin.deallocRaw(_rawValue, (-1)._builtinWordValue, (0)._builtinWordValue)
}
/// Binds the memory to the specified type and returns a typed pointer to the
/// bound memory.
///
/// Use the `bindMemory(to:capacity:)` method to bind the memory referenced
/// by this pointer to the type `T`. The memory must be uninitialized or
/// initialized to a type that is layout compatible with `T`. If the memory
/// is uninitialized, it is still uninitialized after being bound to `T`.
///
/// In this example, 100 bytes of raw memory are allocated for the pointer
/// `bytesPointer`, and then the first four bytes are bound to the `Int8`
/// type.
///
/// let count = 4
/// let bytesPointer = UnsafeMutableRawPointer.allocate(
/// byteCount: 100,
/// alignment: MemoryLayout<Int8>.alignment)
/// let int8Pointer = bytesPointer.bindMemory(to: Int8.self, capacity: count)
///
/// After calling `bindMemory(to:capacity:)`, the first four bytes of the
/// memory referenced by `bytesPointer` are bound to the `Int8` type, though
/// they remain uninitialized. The remainder of the allocated region is
/// unbound raw memory. All 100 bytes of memory must eventually be
/// deallocated.
///
/// - Warning: A memory location may only be bound to one type at a time. The
/// behavior of accessing memory as a type unrelated to its bound type is
/// undefined.
///
/// - Parameters:
/// - type: The type `T` to bind the memory to.
/// - count: The amount of memory to bind to type `T`, counted as instances
/// of `T`.
/// - Returns: A typed pointer to the newly bound memory. The memory in this
/// region is bound to `T`, but has not been modified in any other way.
/// The number of bytes in this region is
/// `count * MemoryLayout<T>.stride`.
@_transparent
@discardableResult
public func bindMemory<T>(
to type: T.Type, capacity count: Int
) -> UnsafePointer<T> {
Builtin.bindMemory(_rawValue, count._builtinWordValue, type)
return UnsafePointer<T>(_rawValue)
}
/// Executes the given closure while temporarily binding memory to
/// the specified number of instances of type `T`.
///
/// Use this method when you have a pointer to raw memory and you need
/// to access that memory as instances of a given type `T`. Accessing
/// memory as a type `T` requires that the memory be bound to that type. A
/// memory location may only be bound to one type at a time, so accessing
/// the same memory as an unrelated type without first rebinding the memory
/// is undefined.
///
/// Any instance of `T` within the re-bound region may be initialized or
/// uninitialized. The memory underlying any individual instance of `T`
/// must have the same initialization state (i.e. initialized or
/// uninitialized.) Accessing a `T` whose underlying memory
/// is in a mixed initialization state shall be undefined behaviour.
///
/// The following example temporarily rebinds a raw memory pointer
/// to `Int64`, then accesses a property on the signed integer.
///
/// let pointer: UnsafeRawPointer = fetchValue()
/// let isNegative = pointer.withMemoryRebound(
/// to: Int64.self, capacity: 1
/// ) {
/// return $0.pointee < 0
/// }
///
/// After executing `body`, this method rebinds memory back to its original
/// binding state. This can be unbound memory, or bound to a different type.
///
/// - Note: The region of memory starting at this pointer must match the
/// alignment of `T` (as reported by `MemoryLayout<T>.alignment`).
/// That is, `Int(bitPattern: self) % MemoryLayout<T>.alignment`
/// must equal zero.
///
/// - Note: The region of memory starting at this pointer may have been
/// bound to a type. If that is the case, then `T` must be
/// layout compatible with the type to which the memory has been bound.
/// This requirement does not apply if the region of memory
/// has not been bound to any type.
///
/// - Parameters:
/// - type: The type to temporarily bind the memory referenced by this
/// pointer. This pointer must be a multiple of this type's alignment.
/// - count: The number of instances of `T` in the re-bound region.
/// - body: A closure that takes a typed pointer to the
/// same memory as this pointer, only bound to type `T`. The closure's
/// pointer argument is valid only for the duration of the closure's
/// execution. If `body` has a return value, that value is also used as
/// the return value for the `withMemoryRebound(to:capacity:_:)` method.
/// - pointer: The pointer temporarily bound to `T`.
/// - Returns: The return value, if any, of the `body` closure parameter.
@inlinable
@_alwaysEmitIntoClient
public func withMemoryRebound<T, Result>(
to type: T.Type,
capacity count: Int,
_ body: (_ pointer: UnsafePointer<T>) throws -> Result
) rethrows -> Result {
_debugPrecondition(
Int(bitPattern: self) & (MemoryLayout<T>.alignment-1) == 0,
"self must be a properly aligned pointer for type T"
)
let binding = Builtin.bindMemory(_rawValue, count._builtinWordValue, T.self)
defer { Builtin.rebindMemory(_rawValue, binding) }
return try body(.init(_rawValue))
}
/// Returns a typed pointer to the memory referenced by this pointer,
/// assuming that the memory is already bound to the specified type.
///
/// Use this method when you have a raw pointer to memory that has *already*
/// been bound to the specified type. The memory starting at this pointer
/// must be bound to the type `T`. Accessing memory through the returned
/// pointer is undefined if the memory has not been bound to `T`. To bind
/// memory to `T`, use `bindMemory(to:capacity:)` instead of this method.
///
/// - Parameter to: The type `T` that the memory has already been bound to.
/// - Returns: A typed pointer to the same memory as this raw pointer.
@_transparent
public func assumingMemoryBound<T>(to: T.Type) -> UnsafePointer<T> {
return UnsafePointer<T>(_rawValue)
}
/// Returns a new instance of the given type, constructed from the raw memory
/// at the specified offset.
///
/// The memory at this pointer plus `offset` must be properly aligned for
/// accessing `T` and initialized to `T` or another type that is layout
/// compatible with `T`.
///
/// - Parameters:
/// - offset: The offset from this pointer, in bytes. `offset` must be
/// nonnegative. The default is zero.
/// - type: The type of the instance to create.
/// - Returns: A new instance of type `T`, read from the raw bytes at
/// `offset`. The returned instance is memory-managed and unassociated
/// with the value in the memory referenced by this pointer.
@inlinable
public func load<T>(fromByteOffset offset: Int = 0, as type: T.Type) -> T {
_debugPrecondition(0 == (UInt(bitPattern: self + offset)
& (UInt(MemoryLayout<T>.alignment) - 1)),
"load from misaligned raw pointer")
let rawPointer = (self + offset)._rawValue
#if compiler(>=5.5) && $BuiltinAssumeAlignment
let alignedPointer =
Builtin.assumeAlignment(rawPointer,
MemoryLayout<T>.alignment._builtinWordValue)
return Builtin.loadRaw(alignedPointer)
#else
return Builtin.loadRaw(rawPointer)
#endif
}
/// Returns a new instance of the given type, constructed from the raw memory
/// at the specified offset.
///
/// This function only supports loading trivial types,
/// and will trap if this precondition is not met.
/// A trivial type does not contain any reference-counted property
/// within its in-memory representation.
/// The memory at this pointer plus `offset` must be laid out
/// identically to the in-memory representation of `T`.
///
/// - Note: A trivial type can be copied with just a bit-for-bit copy without
/// any indirection or reference-counting operations. Generally, native
/// Swift types that do not contain strong or weak references or other
/// forms of indirection are trivial, as are imported C structs and enums.
///
/// - Parameters:
/// - offset: The offset from this pointer, in bytes. `offset` must be
/// nonnegative. The default is zero.
/// - type: The type of the instance to create.
/// - Returns: A new instance of type `T`, read from the raw bytes at
/// `offset`. The returned instance isn't associated
/// with the value in the range of memory referenced by this pointer.
@inlinable
@_alwaysEmitIntoClient
public func loadUnaligned<T>(
fromByteOffset offset: Int = 0,
as type: T.Type
) -> T {
_debugPrecondition(_isPOD(T.self))
return withUnsafeTemporaryAllocation(of: T.self, capacity: 1) {
let temporary = $0.baseAddress._unsafelyUnwrappedUnchecked
Builtin.int_memcpy_RawPointer_RawPointer_Int64(
temporary._rawValue,
(self + offset)._rawValue,
UInt64(MemoryLayout<T>.size)._value,
/*volatile:*/ false._value
)
return temporary.pointee
}
//FIXME: reimplement with `loadRaw` when supported in SIL (rdar://96956089)
// e.g. Builtin.loadRaw((self + offset)._rawValue)
}
}
extension UnsafeRawPointer: Strideable {
// custom version for raw pointers
@_transparent
public func advanced(by n: Int) -> UnsafeRawPointer {
return UnsafeRawPointer(Builtin.gepRaw_Word(_rawValue, n._builtinWordValue))
}
}
extension UnsafeRawPointer {
/// Obtain the next pointer properly aligned to store a value of type `T`.
///
/// If `self` is properly aligned for accessing `T`,
/// this function returns `self`.
///
/// - Parameters:
/// - type: the type to be stored at the returned address.
/// - Returns: a pointer properly aligned to store a value of type `T`.
@inlinable
@_alwaysEmitIntoClient
public func alignedUp<T>(for type: T.Type) -> Self {
let mask = UInt(Builtin.alignof(T.self)) &- 1
let bits = (UInt(Builtin.ptrtoint_Word(_rawValue)) &+ mask) & ~mask
_debugPrecondition(bits != 0, "Overflow in pointer arithmetic")
return .init(Builtin.inttoptr_Word(bits._builtinWordValue))
}
/// Obtain the preceding pointer properly aligned to store a value of type `T`.
///
/// If `self` is properly aligned for accessing `T`,
/// this function returns `self`.
///
/// - Parameters:
/// - type: the type to be stored at the returned address.
/// - Returns: a pointer properly aligned to store a value of type `T`.
@inlinable
@_alwaysEmitIntoClient
public func alignedDown<T>(for type: T.Type) -> Self {
let mask = UInt(Builtin.alignof(T.self)) &- 1
let bits = UInt(Builtin.ptrtoint_Word(_rawValue)) & ~mask
_debugPrecondition(bits != 0, "Overflow in pointer arithmetic")
return .init(Builtin.inttoptr_Word(bits._builtinWordValue))
}
/// Obtain the next pointer whose bit pattern is a multiple of `alignment`.
///
/// If the bit pattern of `self` is a multiple of `alignment`,
/// this function returns `self`.
///
/// - Parameters:
/// - alignment: the alignment of the returned pointer, in bytes.
/// `alignment` must be a whole power of 2.
/// - Returns: a pointer aligned to `alignment`.
@inlinable
@_alwaysEmitIntoClient
public func alignedUp(toMultipleOf alignment: Int) -> Self {
let mask = UInt(alignment._builtinWordValue) &- 1
_debugPrecondition(
alignment > 0 && UInt(alignment._builtinWordValue) & mask == 0,
"alignment must be a whole power of 2."
)
let bits = (UInt(Builtin.ptrtoint_Word(_rawValue)) &+ mask) & ~mask
_debugPrecondition(bits != 0, "Overflow in pointer arithmetic")
return .init(Builtin.inttoptr_Word(bits._builtinWordValue))
}
/// Obtain the preceding pointer whose bit pattern is a multiple of `alignment`.
///
/// If the bit pattern of `self` is a multiple of `alignment`,
/// this function returns `self`.
///
/// - Parameters:
/// - alignment: the alignment of the returned pointer, in bytes.
/// `alignment` must be a whole power of 2.
/// - Returns: a pointer aligned to `alignment`.
@inlinable
@_alwaysEmitIntoClient
public func alignedDown(toMultipleOf alignment: Int) -> Self {
let mask = UInt(alignment._builtinWordValue) &- 1
_debugPrecondition(
alignment > 0 && UInt(alignment._builtinWordValue) & mask == 0,
"alignment must be a whole power of 2."
)
let bits = UInt(Builtin.ptrtoint_Word(_rawValue)) & ~mask
_debugPrecondition(bits != 0, "Overflow in pointer arithmetic")
return .init(Builtin.inttoptr_Word(bits._builtinWordValue))
}
}
/// A raw pointer for accessing and manipulating
/// untyped data.
///
/// The `UnsafeMutableRawPointer` type provides no automated memory management, no type safety,
/// and no alignment guarantees. You are responsible for handling the life
/// cycle of any memory you work with through unsafe pointers, to avoid leaks
/// or undefined behavior.
///
/// Memory that you manually manage can be either *untyped* or *bound* to a
/// specific type. You use the `UnsafeMutableRawPointer` type to access and
/// manage raw bytes in memory, whether or not that memory has been bound to a
/// specific type.
///
/// Understanding a Pointer's Memory State
/// ======================================
///
/// The memory referenced by an `UnsafeMutableRawPointer` instance can be in one of several
/// states. Many pointer operations must only be applied to pointers with
/// memory in a specific state---you must keep track of the state of the
/// memory you are working with and understand the changes to that state that
/// different operations perform. Memory can be untyped and uninitialized,
/// bound to a type and uninitialized, or bound to a type and initialized to a
/// value. Finally, memory that was allocated previously may have been
/// deallocated, leaving existing pointers referencing unallocated memory.
///
/// Raw, Uninitialized Memory
/// -------------------------
///
/// Raw memory that has just been allocated is in an *uninitialized, untyped*
/// state. Uninitialized memory must be initialized with values of a type
/// before it can be used with any typed operations.
///
/// You can use methods like `initializeMemory(as:from:)` and
/// `moveInitializeMemory(as:from:count:)` to bind raw memory to a type and
/// initialize it with a value or series of values. To bind uninitialized
/// memory to a type without initializing it, use the `bindMemory(to:count:)`
/// method. These methods all return typed pointers for further typed access
/// to the memory.
///
/// Typed Memory
/// ------------
///
/// Memory that has been bound to a type, whether it is initialized or
/// uninitialized, is typically accessed using typed pointers---instances of
/// `UnsafePointer` and `UnsafeMutablePointer`. Initialization, assignment,
/// and deinitialization can be performed using `UnsafeMutablePointer`
/// methods.
///
/// Memory that has been bound to a type can be rebound to a different type
/// only after it has been deinitialized or if the bound type is a *trivial
/// type*. Deinitializing typed memory does not unbind that memory's type. The
/// deinitialized memory can be reinitialized with values of the same type,
/// bound to a new type, or deallocated.
///
/// - Note: A trivial type can be copied bit for bit with no indirection or
/// reference-counting operations. Generally, native Swift types that do not
/// contain strong or weak references or other forms of indirection are
/// trivial, as are imported C structs and enumerations.
///
/// When reading from or writing to memory as raw
/// bytes when that memory is bound to a type, you must ensure that you
/// satisfy any alignment requirements.
/// Writing to typed memory as raw bytes must only be performed when the bound
/// type is a trivial type.
///
/// Raw Pointer Arithmetic
/// ======================
///
/// Pointer arithmetic with raw pointers is performed at the byte level. When
/// you add to or subtract from a raw pointer, the result is a new raw pointer
/// offset by that number of bytes. The following example allocates four bytes
/// of memory and stores `0xFF` in all four bytes:
///
/// let bytesPointer = UnsafeMutableRawPointer.allocate(byteCount: 4, alignment: 1)
/// bytesPointer.storeBytes(of: 0xFFFF_FFFF, as: UInt32.self)
///
/// // Load a value from the memory referenced by 'bytesPointer'
/// let x = bytesPointer.load(as: UInt8.self) // 255
///
/// // Load a value from the last two allocated bytes
/// let offsetPointer = bytesPointer + 2
/// let y = offsetPointer.load(as: UInt16.self) // 65535
///
/// The code above stores the value `0xFFFF_FFFF` into the four newly allocated
/// bytes, and then loads the first byte as a `UInt8` instance and the third
/// and fourth bytes as a `UInt16` instance.
///
/// Always remember to deallocate any memory that you allocate yourself.
///
/// bytesPointer.deallocate()
///
/// Implicit Casting and Bridging
/// =============================
///
/// When calling a function or method with an `UnsafeMutableRawPointer` parameter, you can pass
/// an instance of that specific pointer type, pass an instance of a
/// compatible pointer type, or use Swift's implicit bridging to pass a
/// compatible pointer.
///
/// For example, the `print(address:as:)` function in the following code sample
/// takes an `UnsafeMutableRawPointer` instance as its first parameter:
///
/// func print<T>(address p: UnsafeMutableRawPointer, as type: T.Type) {
/// let value = p.load(as: type)
/// print(value)
/// }
///
/// As is typical in Swift, you can call the `print(address:as:)` function with
/// an `UnsafeMutableRawPointer` instance. This example passes `rawPointer` as the initial
/// parameter.
///
/// // 'rawPointer' points to memory initialized with `Int` values.
/// let rawPointer: UnsafeMutableRawPointer = ...
/// print(address: rawPointer, as: Int.self)
/// // Prints "42"
///
/// Because typed pointers can be implicitly cast to raw pointers when passed
/// as a parameter, you can also call `print(address:as:)` with any mutable
/// typed pointer instance.
///
/// let intPointer: UnsafeMutablePointer<Int> = ...
/// print(address: intPointer, as: Int.self)
/// // Prints "42"
///
/// Alternatively, you can use Swift's *implicit bridging* to pass a pointer to
/// an instance or to the elements of an array. Use inout syntax to implicitly
/// create a pointer to an instance of any type. The following example uses
/// implicit bridging to pass a pointer to `value` when calling
/// `print(address:as:)`:
///
/// var value: Int = 23
/// print(address: &value, as: Int.self)
/// // Prints "23"
///
/// A mutable pointer to the elements of an array is implicitly created when
/// you pass the array using inout syntax. This example uses implicit bridging
/// to pass a pointer to the elements of `numbers` when calling
/// `print(address:as:)`.
///
/// var numbers = [5, 10, 15, 20]
/// print(address: &numbers, as: Int.self)
/// // Prints "5"
///
/// - Important: The pointer created through implicit bridging of an instance
/// or of an array's elements is only valid during the execution of the
/// called function. Escaping the pointer to use after the execution of the
/// function is undefined behavior. In particular, do not use implicit
/// bridging when calling an `UnsafeMutableRawPointer` initializer.
///
/// var number = 5
/// let numberPointer = UnsafeMutableRawPointer(&number)
/// // Accessing 'numberPointer' is undefined behavior.
@frozen
public struct UnsafeMutableRawPointer: _Pointer {
public typealias Pointee = UInt8
/// The underlying raw pointer.
/// Implements conformance to the public protocol `_Pointer`.
public let _rawValue: Builtin.RawPointer
/// Creates a new raw pointer from a builtin raw pointer.
@_transparent
public init(_ _rawValue: Builtin.RawPointer) {
self._rawValue = _rawValue
}
/// Creates a new raw pointer from the given typed pointer.
///
/// Use this initializer to explicitly convert `other` to an `UnsafeMutableRawPointer`
/// instance. This initializer creates a new pointer to the same address as
/// `other` and performs no allocation or copying.
///
/// - Parameter other: The typed pointer to convert.
@_transparent
public init<T>(@_nonEphemeral _ other: UnsafeMutablePointer<T>) {
_rawValue = other._rawValue
}
/// Creates a new raw pointer from the given typed pointer.
///
/// Use this initializer to explicitly convert `other` to an `UnsafeMutableRawPointer`
/// instance. This initializer creates a new pointer to the same address as
/// `other` and performs no allocation or copying.
///
/// - Parameter other: The typed pointer to convert. If `other` is `nil`, the
/// result is `nil`.
@_transparent
public init?<T>(@_nonEphemeral _ other: UnsafeMutablePointer<T>?) {
guard let unwrapped = other else { return nil }
_rawValue = unwrapped._rawValue
}
/// Creates a new mutable raw pointer from the given immutable raw pointer.
///
/// Use this initializer to explicitly convert `other` to an `UnsafeMutableRawPointer`
/// instance. This initializer creates a new pointer to the same address as
/// `other` and performs no allocation or copying.
///
/// - Parameter other: The immutable raw pointer to convert.
@_transparent
public init(@_nonEphemeral mutating other: UnsafeRawPointer) {
_rawValue = other._rawValue
}
/// Creates a new mutable raw pointer from the given immutable raw pointer.
///
/// Use this initializer to explicitly convert `other` to an `UnsafeMutableRawPointer`
/// instance. This initializer creates a new pointer to the same address as
/// `other` and performs no allocation or copying.
///
/// - Parameter other: The immutable raw pointer to convert. If `other` is
/// `nil`, the result is `nil`.
@_transparent
public init?(@_nonEphemeral mutating other: UnsafeRawPointer?) {
guard let unwrapped = other else { return nil }
_rawValue = unwrapped._rawValue
}
/// Allocates uninitialized memory with the specified size and alignment.
///
/// You are in charge of managing the allocated memory. Be sure to deallocate
/// any memory that you manually allocate.
///
/// The allocated memory is not bound to any specific type and must be bound
/// before performing any typed operations. If you are using the memory for
/// a specific type, allocate memory using the
/// `UnsafeMutablePointer.allocate(capacity:)` static method instead.
///
/// - Parameters:
/// - byteCount: The number of bytes to allocate. `byteCount` must not be negative.
/// - alignment: The alignment of the new region of allocated memory, in
/// bytes. `alignment` must be a whole power of 2.
/// - Returns: A pointer to a newly allocated region of memory. The memory is
/// allocated, but not initialized.
@inlinable
public static func allocate(
byteCount: Int, alignment: Int
) -> UnsafeMutableRawPointer {
// For any alignment <= _minAllocationAlignment, force alignment = 0.
// This forces the runtime's "aligned" allocation path so that
// deallocation does not require the original alignment.
//
// The runtime guarantees:
//
// align == 0 || align > _minAllocationAlignment:
// Runtime uses "aligned allocation".
//
// 0 < align <= _minAllocationAlignment:
// Runtime may use either malloc or "aligned allocation".
var alignment = alignment
if alignment <= _minAllocationAlignment() {
alignment = 0
}
return UnsafeMutableRawPointer(Builtin.allocRaw(
byteCount._builtinWordValue, alignment._builtinWordValue))
}
/// Deallocates the previously allocated memory block referenced by this pointer.
///
/// The memory to be deallocated must be uninitialized or initialized to a
/// trivial type.
@inlinable
public func deallocate() {
// Passing zero alignment to the runtime forces "aligned
// deallocation". Since allocation via `UnsafeMutable[Raw][Buffer]Pointer`
// always uses the "aligned allocation" path, this ensures that the
// runtime's allocation and deallocation paths are compatible.
Builtin.deallocRaw(_rawValue, (-1)._builtinWordValue, (0)._builtinWordValue)
}
/// Binds the memory to the specified type and returns a typed pointer to the
/// bound memory.
///
/// Use the `bindMemory(to:capacity:)` method to bind the memory referenced
/// by this pointer to the type `T`. The memory must be uninitialized or
/// initialized to a type that is layout compatible with `T`. If the memory
/// is uninitialized, it is still uninitialized after being bound to `T`.
///
/// In this example, 100 bytes of raw memory are allocated for the pointer
/// `bytesPointer`, and then the first four bytes are bound to the `Int8`
/// type.
///
/// let count = 4
/// let bytesPointer = UnsafeMutableRawPointer.allocate(
/// byteCount: 100,
/// alignment: MemoryLayout<Int8>.alignment)
/// let int8Pointer = bytesPointer.bindMemory(to: Int8.self, capacity: count)
///
/// After calling `bindMemory(to:capacity:)`, the first four bytes of the
/// memory referenced by `bytesPointer` are bound to the `Int8` type, though
/// they remain uninitialized. The remainder of the allocated region is
/// unbound raw memory. All 100 bytes of memory must eventually be
/// deallocated.
///
/// - Warning: A memory location may only be bound to one type at a time. The
/// behavior of accessing memory as a type unrelated to its bound type is
/// undefined.
///
/// - Parameters:
/// - type: The type `T` to bind the memory to.
/// - count: The amount of memory to bind to type `T`, counted as instances
/// of `T`.
/// - Returns: A typed pointer to the newly bound memory. The memory in this
/// region is bound to `T`, but has not been modified in any other way.
/// The number of bytes in this region is
/// `count * MemoryLayout<T>.stride`.
@_transparent
@discardableResult
public func bindMemory<T>(
to type: T.Type, capacity count: Int
) -> UnsafeMutablePointer<T> {
Builtin.bindMemory(_rawValue, count._builtinWordValue, type)
return UnsafeMutablePointer<T>(_rawValue)
}
/// Executes the given closure while temporarily binding memory to
/// the specified number of instances of type `T`.
///
/// Use this method when you have a pointer to raw memory and you need
/// to access that memory as instances of a given type `T`. Accessing
/// memory as a type `T` requires that the memory be bound to that type. A
/// memory location may only be bound to one type at a time, so accessing
/// the same memory as an unrelated type without first rebinding the memory
/// is undefined.
///
/// Any instance of `T` within the re-bound region may be initialized or
/// uninitialized. The memory underlying any individual instance of `T`
/// must have the same initialization state (i.e. initialized or
/// uninitialized.) Accessing a `T` whose underlying memory
/// is in a mixed initialization state shall be undefined behaviour.
///
/// The following example temporarily rebinds a raw memory pointer
/// to `Int64`, then modifies the signed integer.
///
/// let pointer: UnsafeMutableRawPointer = fetchValue()
/// pointer.withMemoryRebound(to: Int64.self, capacity: 1) {
/// $0.pointee.negate()
/// }
///
/// After executing `body`, this method rebinds memory back to its original
/// binding state. This can be unbound memory, or bound to a different type.
///
/// - Note: The region of memory starting at this pointer must match the
/// alignment of `T` (as reported by `MemoryLayout<T>.alignment`).
/// That is, `Int(bitPattern: self) % MemoryLayout<T>.alignment`
/// must equal zero.
///
/// - Note: The region of memory starting at this pointer may have been
/// bound to a type. If that is the case, then `T` must be
/// layout compatible with the type to which the memory has been bound.
/// This requirement does not apply if the region of memory
/// has not been bound to any type.
///
/// - Parameters:
/// - type: The type to temporarily bind the memory referenced by this
/// pointer. This pointer must be a multiple of this type's alignment.
/// - count: The number of instances of `T` in the re-bound region.
/// - body: A closure that takes a typed pointer to the
/// same memory as this pointer, only bound to type `T`. The closure's
/// pointer argument is valid only for the duration of the closure's
/// execution. If `body` has a return value, that value is also used as
/// the return value for the `withMemoryRebound(to:capacity:_:)` method.
/// - pointer: The pointer temporarily bound to `T`.
/// - Returns: The return value, if any, of the `body` closure parameter.
@inlinable
@_alwaysEmitIntoClient
public func withMemoryRebound<T, Result>(
to type: T.Type,
capacity count: Int,
_ body: (_ pointer: UnsafeMutablePointer<T>) throws -> Result
) rethrows -> Result {
_debugPrecondition(
Int(bitPattern: self) & (MemoryLayout<T>.alignment-1) == 0,
"self must be a properly aligned pointer for type T"
)
let binding = Builtin.bindMemory(_rawValue, count._builtinWordValue, T.self)
defer { Builtin.rebindMemory(_rawValue, binding) }
return try body(.init(_rawValue))
}
/// Returns a typed pointer to the memory referenced by this pointer,
/// assuming that the memory is already bound to the specified type.
///
/// Use this method when you have a raw pointer to memory that has *already*
/// been bound to the specified type. The memory starting at this pointer
/// must be bound to the type `T`. Accessing memory through the returned
/// pointer is undefined if the memory has not been bound to `T`. To bind
/// memory to `T`, use `bindMemory(to:capacity:)` instead of this method.
///
/// - Parameter to: The type `T` that the memory has already been bound to.
/// - Returns: A typed pointer to the same memory as this raw pointer.
@_transparent
public func assumingMemoryBound<T>(to: T.Type) -> UnsafeMutablePointer<T> {
return UnsafeMutablePointer<T>(_rawValue)
}
/// Initializes the memory referenced by this pointer with the given value,
/// binds the memory to the value's type, and returns a typed pointer to the
/// initialized memory.
///
/// The memory referenced by this pointer must be uninitialized or
/// initialized to a trivial type, and must be properly aligned for
/// accessing `T`.
///
/// The following example allocates enough raw memory to hold four instances
/// of `Int8`, and then uses the `initializeMemory(as:repeating:count:)` method
/// to initialize the allocated memory.
///
/// let count = 4
/// let bytesPointer = UnsafeMutableRawPointer.allocate(
/// byteCount: count * MemoryLayout<Int8>.stride,
/// alignment: MemoryLayout<Int8>.alignment)
/// let int8Pointer = bytesPointer.initializeMemory(
/// as: Int8.self, repeating: 0, count: count)
///
/// // After using 'int8Pointer':
/// int8Pointer.deallocate()
///
/// After calling this method on a raw pointer `p`, the region starting at
/// `self` and continuing up to `p + count * MemoryLayout<T>.stride` is bound
/// to type `T` and initialized. If `T` is a nontrivial type, you must
/// eventually deinitialize or move from the values in this region to avoid leaks.
///
/// - Parameters:
/// - type: The type to bind this memory to.
/// - repeatedValue: The instance to copy into memory.
/// - count: The number of copies of `value` to copy into memory. `count`
/// must not be negative.
/// - Returns: A typed pointer to the memory referenced by this raw pointer.
@inlinable
@discardableResult
public func initializeMemory<T>(
as type: T.Type, repeating repeatedValue: T, count: Int
) -> UnsafeMutablePointer<T> {
_debugPrecondition(count >= 0,
"UnsafeMutableRawPointer.initializeMemory: negative count")
Builtin.bindMemory(_rawValue, count._builtinWordValue, type)
var nextPtr = self
for _ in 0..<count {
Builtin.initialize(repeatedValue, nextPtr._rawValue)
nextPtr += MemoryLayout<T>.stride
}
return UnsafeMutablePointer(_rawValue)
}
/// Initializes the memory referenced by this pointer with the values
/// starting at the given pointer, binds the memory to the values' type, and
/// returns a typed pointer to the initialized memory.
///
/// The memory referenced by this pointer must be uninitialized or
/// initialized to a trivial type, and must be properly aligned for
/// accessing `T`.
///
/// The following example allocates enough raw memory to hold four instances
/// of `Int8`, and then uses the `initializeMemory(as:from:count:)` method
/// to initialize the allocated memory.
///
/// let count = 4
/// let bytesPointer = UnsafeMutableRawPointer.allocate(
/// byteCount: count * MemoryLayout<Int8>.stride,
/// alignment: MemoryLayout<Int8>.alignment)
/// let values: [Int8] = [1, 2, 3, 4]
/// let int8Pointer = values.withUnsafeBufferPointer { buffer in
/// return bytesPointer.initializeMemory(as: Int8.self,
/// from: buffer.baseAddress!,
/// count: buffer.count)
/// }
/// // int8Pointer.pointee == 1
/// // (int8Pointer + 3).pointee == 4
///
/// // After using 'int8Pointer':
/// int8Pointer.deallocate()
///
/// After calling this method on a raw pointer `p`, the region starting at
/// `p` and continuing up to `p + count * MemoryLayout<T>.stride` is bound
/// to type `T` and initialized. If `T` is a nontrivial type, you must
/// eventually deinitialize or move from the values in this region to avoid
/// leaks. The instances in the region `source..<(source + count)` are
/// unaffected.
///
/// - Parameters:
/// - type: The type to bind this memory to.
/// - source: A pointer to the values to copy. The memory in the region
/// `source..<(source + count)` must be initialized to type `T` and must
/// not overlap the destination region.
/// - count: The number of copies of `value` to copy into memory. `count`
/// must not be negative.
/// - Returns: A typed pointer to the memory referenced by this raw pointer.
@inlinable
@discardableResult
public func initializeMemory<T>(
as type: T.Type, from source: UnsafePointer<T>, count: Int
) -> UnsafeMutablePointer<T> {
_debugPrecondition(
count >= 0,
"UnsafeMutableRawPointer.initializeMemory with negative count")
_debugPrecondition(
(UnsafeRawPointer(self + count * MemoryLayout<T>.stride)
<= UnsafeRawPointer(source))
|| UnsafeRawPointer(source + count) <= UnsafeRawPointer(self),
"UnsafeMutableRawPointer.initializeMemory overlapping range")
Builtin.bindMemory(_rawValue, count._builtinWordValue, type)
Builtin.copyArray(
T.self, self._rawValue, source._rawValue, count._builtinWordValue)
// This builtin is equivalent to:
// for i in 0..<count {
// (self.assumingMemoryBound(to: T.self) + i).initialize(to: source[i])
// }
return UnsafeMutablePointer(_rawValue)
}
/// Initializes the memory referenced by this pointer with the values
/// starting at the given pointer, binds the memory to the values' type,
/// deinitializes the source memory, and returns a typed pointer to the
/// newly initialized memory.
///
/// The memory referenced by this pointer must be uninitialized or
/// initialized to a trivial type, and must be properly aligned for
/// accessing `T`.
///
/// The memory in the region `source..<(source + count)` may overlap with the
/// destination region. The `moveInitializeMemory(as:from:count:)` method
/// automatically performs a forward or backward copy of all instances from
/// the source region to their destination.
///
/// After calling this method on a raw pointer `p`, the region starting at
/// `p` and continuing up to `p + count * MemoryLayout<T>.stride` is bound
/// to type `T` and initialized. If `T` is a nontrivial type, you must
/// eventually deinitialize or move from the values in this region to avoid
/// leaks. Any memory in the region `source..<(source + count)` that does
/// not overlap with the destination region is returned to an uninitialized
/// state.
///
/// - Parameters:
/// - type: The type to bind this memory to.
/// - source: A pointer to the values to copy. The memory in the region
/// `source..<(source + count)` must be initialized to type `T`.
/// - count: The number of copies of `value` to copy into memory. `count`
/// must not be negative.
/// - Returns: A typed pointer to the memory referenced by this raw pointer.
@inlinable
@discardableResult
public func moveInitializeMemory<T>(
as type: T.Type, from source: UnsafeMutablePointer<T>, count: Int
) -> UnsafeMutablePointer<T> {
_debugPrecondition(
count >= 0,
"UnsafeMutableRawPointer.moveInitializeMemory with negative count")
Builtin.bindMemory(_rawValue, count._builtinWordValue, type)
if self < UnsafeMutableRawPointer(source)
|| self >= UnsafeMutableRawPointer(source + count) {
// initialize forward from a disjoint or following overlapping range.
Builtin.takeArrayFrontToBack(
T.self, self._rawValue, source._rawValue, count._builtinWordValue)
// This builtin is equivalent to:
// for i in 0..<count {
// (self.assumingMemoryBound(to: T.self) + i)
// .initialize(to: (source + i).move())
// }
}
else {
// initialize backward from a non-following overlapping range.
Builtin.takeArrayBackToFront(
T.self, self._rawValue, source._rawValue, count._builtinWordValue)
// This builtin is equivalent to:
// var src = source + count
// var dst = self.assumingMemoryBound(to: T.self) + count
// while dst != self {
// (--dst).initialize(to: (--src).move())
// }
}
return UnsafeMutablePointer(_rawValue)
}
/// Returns a new instance of the given type, constructed from the raw memory
/// at the specified offset.
///
/// The memory at this pointer plus `offset` must be properly aligned for
/// accessing `T` and initialized to `T` or another type that is layout
/// compatible with `T`.
///
/// - Parameters:
/// - offset: The offset from this pointer, in bytes. `offset` must be
/// nonnegative. The default is zero.
/// - type: The type of the instance to create.
/// - Returns: A new instance of type `T`, read from the raw bytes at
/// `offset`. The returned instance is memory-managed and unassociated
/// with the value in the memory referenced by this pointer.
@inlinable
public func load<T>(fromByteOffset offset: Int = 0, as type: T.Type) -> T {
_debugPrecondition(0 == (UInt(bitPattern: self + offset)
& (UInt(MemoryLayout<T>.alignment) - 1)),
"load from misaligned raw pointer")
let rawPointer = (self + offset)._rawValue
#if compiler(>=5.5) && $BuiltinAssumeAlignment
let alignedPointer =
Builtin.assumeAlignment(rawPointer,
MemoryLayout<T>.alignment._builtinWordValue)
return Builtin.loadRaw(alignedPointer)
#else
return Builtin.loadRaw(rawPointer)
#endif
}
/// Returns a new instance of the given type, constructed from the raw memory
/// at the specified offset.
///
/// This function only supports loading trivial types,
/// and will trap if this precondition is not met.
/// A trivial type does not contain any reference-counted property
/// within its in-memory representation.
/// The memory at this pointer plus `offset` must be laid out
/// identically to the in-memory representation of `T`.
///
/// - Note: A trivial type can be copied with just a bit-for-bit copy without
/// any indirection or reference-counting operations. Generally, native
/// Swift types that do not contain strong or weak references or other
/// forms of indirection are trivial, as are imported C structs and enums.
///
/// - Parameters:
/// - offset: The offset from this pointer, in bytes. `offset` must be
/// nonnegative. The default is zero.
/// - type: The type of the instance to create.
/// - Returns: A new instance of type `T`, read from the raw bytes at
/// `offset`. The returned instance isn't associated
/// with the value in the range of memory referenced by this pointer.
@inlinable
@_alwaysEmitIntoClient
public func loadUnaligned<T>(
fromByteOffset offset: Int = 0,
as type: T.Type
) -> T {
_debugPrecondition(_isPOD(T.self))
return withUnsafeTemporaryAllocation(of: T.self, capacity: 1) {
let temporary = $0.baseAddress._unsafelyUnwrappedUnchecked
Builtin.int_memcpy_RawPointer_RawPointer_Int64(
temporary._rawValue,
(self + offset)._rawValue,
UInt64(MemoryLayout<T>.size)._value,
/*volatile:*/ false._value
)
return temporary.pointee
}
//FIXME: reimplement with `loadRaw` when supported in SIL (rdar://96956089)
// e.g. Builtin.loadRaw((self + offset)._rawValue)
}
/// Stores the given value's bytes into raw memory at the specified offset.
///
/// The type `T` to be stored must be a trivial type. The memory
/// must also be uninitialized, initialized to `T`, or initialized to
/// another trivial type that is layout compatible with `T`.
///
/// After calling `storeBytes(of:toByteOffset:as:)`, the memory is
/// initialized to the raw bytes of `value`. If the memory is bound to a
/// type `U` that is layout compatible with `T`, then it contains a value of
/// type `U`. Calling `storeBytes(of:toByteOffset:as:)` does not change the
/// bound type of the memory.
///
/// - Note: A trivial type can be copied with just a bit-for-bit copy without
/// any indirection or reference-counting operations. Generally, native
/// Swift types that do not contain strong or weak references or other
/// forms of indirection are trivial, as are imported C structs and enums.
///
/// If you need to store into memory a copy of a value of a type that isn't
/// trivial, you cannot use the `storeBytes(of:toByteOffset:as:)` method.
/// Instead, you must know either initialize the memory or,
/// if you know the memory was already bound to `type`, assign to the memory.
/// For example, to replace a value stored in a raw pointer `p`,
/// where `U` is the current type and `T` is the new type, use a typed
/// pointer to access and deinitialize the current value before initializing
/// the memory with a new value:
///
/// let typedPointer = p.bindMemory(to: U.self, capacity: 1)
/// typedPointer.deinitialize(count: 1)
/// p.initializeMemory(as: T.self, repeating: newValue, count: 1)
///
/// - Parameters:
/// - value: The value to store as raw bytes.
/// - offset: The offset from this pointer, in bytes. `offset` must be
/// nonnegative. The default is zero.
/// - type: The type of `value`.
@inlinable
@_alwaysEmitIntoClient
// This custom silgen name is chosen to not interfere with the old ABI
@_silgen_name("_swift_se0349_UnsafeMutableRawPointer_storeBytes")
public func storeBytes<T>(
of value: T, toByteOffset offset: Int = 0, as type: T.Type
) {
_debugPrecondition(_isPOD(T.self))
withUnsafePointer(to: value) { source in
// FIXME: to be replaced by _memcpy when conversions are implemented.
Builtin.int_memcpy_RawPointer_RawPointer_Int64(
(self + offset)._rawValue,
source._rawValue,
UInt64(MemoryLayout<T>.size)._value,
/*volatile:*/ false._value
)
}
}
// This unavailable implementation uses the expected mangled name
// of `storeBytes<T>(of:toByteOffset:as:)`, and provides an entry point for
// any binary compiled against the stdlib binary for Swift 5.6 and older.
@available(*, unavailable)
@_silgen_name("$sSv10storeBytes2of12toByteOffset2asyx_SixmtlF")
@usableFromInline func _legacy_se0349_storeBytes<T>(
of value: T, toByteOffset offset: Int = 0, as type: T.Type
) {
_legacy_se0349_storeBytes_internal(
of: value, toByteOffset: offset, as: T.self
)
}
// This is the implementation of `storeBytes` from SwiftStdlib 5.6
@_alwaysEmitIntoClient
internal func _legacy_se0349_storeBytes_internal<T>(
of value: T, toByteOffset offset: Int = 0, as type: T.Type
) {
_debugPrecondition(0 == (UInt(bitPattern: self + offset)
& (UInt(MemoryLayout<T>.alignment) - 1)),
"storeBytes to misaligned raw pointer")
var temp = value
withUnsafeMutablePointer(to: &temp) { source in
let rawSrc = UnsafeMutableRawPointer(source)._rawValue
// FIXME: to be replaced by _memcpy when conversions are implemented.
Builtin.int_memcpy_RawPointer_RawPointer_Int64(
(self + offset)._rawValue, rawSrc, UInt64(MemoryLayout<T>.size)._value,
/*volatile:*/ false._value)
}
}
/// Copies the specified number of bytes from the given raw pointer's memory
/// into this pointer's memory.
///
/// If the `byteCount` bytes of memory referenced by this pointer are bound to
/// a type `T`, then `T` must be a trivial type, this pointer and `source`
/// must be properly aligned for accessing `T`, and `byteCount` must be a
/// multiple of `MemoryLayout<T>.stride`.
///
/// The memory in the region `source..<(source + byteCount)` may overlap with
/// the memory referenced by this pointer.
///
/// After calling `copyMemory(from:byteCount:)`, the `byteCount` bytes of
/// memory referenced by this pointer are initialized to raw bytes. If the
/// memory is bound to type `T`, then it contains values of type `T`.
///
/// - Parameters:
/// - source: A pointer to the memory to copy bytes from. The memory in the
/// region `source..<(source + byteCount)` must be initialized to a
/// trivial type.
/// - byteCount: The number of bytes to copy. `byteCount` must not be negative.
@inlinable
public func copyMemory(from source: UnsafeRawPointer, byteCount: Int) {
_debugPrecondition(
byteCount >= 0, "UnsafeMutableRawPointer.copyMemory with negative count")
_memmove(dest: self, src: source, size: UInt(byteCount))
}
}
extension UnsafeMutableRawPointer: Strideable {
// custom version for raw pointers
@_transparent
public func advanced(by n: Int) -> UnsafeMutableRawPointer {
return UnsafeMutableRawPointer(Builtin.gepRaw_Word(_rawValue, n._builtinWordValue))
}
}
extension UnsafeMutableRawPointer {
/// Obtain the next pointer properly aligned to store a value of type `T`.
///
/// If `self` is properly aligned for accessing `T`,
/// this function returns `self`.
///
/// - Parameters:
/// - type: the type to be stored at the returned address.
/// - Returns: a pointer properly aligned to store a value of type `T`.
@inlinable
@_alwaysEmitIntoClient
public func alignedUp<T>(for type: T.Type) -> Self {
let mask = UInt(Builtin.alignof(T.self)) &- 1
let bits = (UInt(Builtin.ptrtoint_Word(_rawValue)) &+ mask) & ~mask
_debugPrecondition(bits != 0, "Overflow in pointer arithmetic")
return .init(Builtin.inttoptr_Word(bits._builtinWordValue))
}
/// Obtain the preceding pointer properly aligned to store a value of type `T`.
///
/// If `self` is properly aligned for accessing `T`,
/// this function returns `self`.
///
/// - Parameters:
/// - type: the type to be stored at the returned address.
/// - Returns: a pointer properly aligned to store a value of type `T`.
@inlinable
@_alwaysEmitIntoClient
public func alignedDown<T>(for type: T.Type) -> Self {
let mask = UInt(Builtin.alignof(T.self)) &- 1
let bits = UInt(Builtin.ptrtoint_Word(_rawValue)) & ~mask
_debugPrecondition(bits != 0, "Overflow in pointer arithmetic")
return .init(Builtin.inttoptr_Word(bits._builtinWordValue))
}
/// Obtain the next pointer whose bit pattern is a multiple of `alignment`.
///
/// If the bit pattern of `self` is a multiple of `alignment`,
/// this function returns `self`.
///
/// - Parameters:
/// - alignment: the alignment of the returned pointer, in bytes.
/// `alignment` must be a whole power of 2.
/// - Returns: a pointer aligned to `alignment`.
@inlinable
@_alwaysEmitIntoClient
public func alignedUp(toMultipleOf alignment: Int) -> Self {
let mask = UInt(alignment._builtinWordValue) &- 1
_debugPrecondition(
alignment > 0 && UInt(alignment._builtinWordValue) & mask == 0,
"alignment must be a whole power of 2."
)
let bits = (UInt(Builtin.ptrtoint_Word(_rawValue)) &+ mask) & ~mask
_debugPrecondition(bits != 0, "Overflow in pointer arithmetic")
return .init(Builtin.inttoptr_Word(bits._builtinWordValue))
}
/// Obtain the preceding pointer whose bit pattern is a multiple of `alignment`.
///
/// If the bit pattern of `self` is a multiple of `alignment`,
/// this function returns `self`.
///
/// - Parameters:
/// - alignment: the alignment of the returned pointer, in bytes.
/// `alignment` must be a whole power of 2.
/// - Returns: a pointer aligned to `alignment`.
@inlinable
@_alwaysEmitIntoClient
public func alignedDown(toMultipleOf alignment: Int) -> Self {
let mask = UInt(alignment._builtinWordValue) &- 1
_debugPrecondition(
alignment > 0 && UInt(alignment._builtinWordValue) & mask == 0,
"alignment must be a whole power of 2."
)
let bits = UInt(Builtin.ptrtoint_Word(_rawValue)) & ~mask
_debugPrecondition(bits != 0, "Overflow in pointer arithmetic")
return .init(Builtin.inttoptr_Word(bits._builtinWordValue))
}
}
extension OpaquePointer {
@_transparent
public init(@_nonEphemeral _ from: UnsafeMutableRawPointer) {
self._rawValue = from._rawValue
}
@_transparent
public init?(@_nonEphemeral _ from: UnsafeMutableRawPointer?) {
guard let unwrapped = from else { return nil }
self._rawValue = unwrapped._rawValue
}
@_transparent
public init(@_nonEphemeral _ from: UnsafeRawPointer) {
self._rawValue = from._rawValue
}
@_transparent
public init?(@_nonEphemeral _ from: UnsafeRawPointer?) {
guard let unwrapped = from else { return nil }
self._rawValue = unwrapped._rawValue
}
}
|
apache-2.0
|
21fad89cd41095a182f9d0bf1e4f8884
| 42.41989 | 95 | 0.678601 | 4.359451 | false | false | false | false |
realm-demos/realm-loginkit
|
RealmLoginKit Apple/RealmLoginKit/Views/LoginView.swift
|
1
|
16800
|
////////////////////////////////////////////////////////////////////////////
//
// Copyright 2017 Realm Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
////////////////////////////////////////////////////////////////////////////
import UIKit
import TORoundedTableView
class LoginView: UIView, UITableViewDelegate, UIViewControllerTransitioningDelegate {
/* Controls whether the 'Register' button is visible or not. */
public var canRegisterNewAccounts = true {
didSet {
footerView.isRegisterButtonHidden = !canRegisterNewAccounts
tableView.reloadData()
}
}
/* Controls whether to show the 'close' button or not. */
public var isCancelButtonHidden = true {
didSet {
setUpCloseButton()
}
}
/* Closure called when the user taps the 'Close' button */
public var didTapCloseHandler: (() ->())?
/* Closure called when the footer register button is tapped */
public var didTapRegisterHandler: (() -> ())? {
set { footerView.registerButtonTappedHandler = newValue }
get { return footerView.registerButtonTappedHandler }
}
/* Closure called the the 'submit' button is tapped */
public var didTapLogInHandler: (() -> ())? {
set { footerView.loginButtonTappedHandler = newValue }
get { return footerView.loginButtonTappedHandler }
}
/* Whether the view is in a state of registration or not */
private var _registering = false
public var isRegistering: Bool {
set { self.setRegistering(newValue, animated: false) }
get { return _registering }
}
/* Removes the Realm copyright text at the bottom. */
public var isCopyrightLabelHidden = false {
didSet {
if isCopyrightLabelHidden {
copyrightView?.removeFromSuperview()
copyrightView = nil
}
else {
setUpCopyrightLabel()
applyTheme()
}
self.setNeedsLayout()
}
}
/* The copyright text displayed at the bottom of
the view when there is sufficient space */
public var copyrightLabelText = "With ❤️ from the Realm team, 2017." {
didSet {
setUpCopyrightLabel()
copyrightView?.text = copyrightLabelText
copyrightView?.sizeToFit()
self.setNeedsLayout()
}
}
/* Subviews */
public let containerView = UIView()
public let navigationBar = StatusBarUnderlayView()
public let tableView = TORoundedTableView()
public let headerView = LoginHeaderView()
public let footerView = LoginFooterView()
public var copyrightView: UILabel?
public var closeButton: UIButton?
public var effectView: UIVisualEffectView?
public var backgroundView: UIView?
public let isDarkStyle: Bool
public let isTranslucentStyle: Bool
/* Layout Constraints */
public var keyboardHeight: CGFloat = 0.0
public var copyrightViewMargin: CGFloat = 45
public var closeButtonInset = UIEdgeInsets(top: 15, left: 18, bottom: 0, right: 0)
// MARK: - Class Creation -
override init(frame: CGRect) {
self.isDarkStyle = false
self.isTranslucentStyle = true
super.init(frame: frame)
setUpViews()
}
init(darkStyle: Bool, translucentStyle: Bool) {
self.isDarkStyle = darkStyle
self.isTranslucentStyle = translucentStyle
super.init(frame: CGRect.zero)
setUpViews()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
// MARK: - View Setup -
private func setUpViews() {
backgroundColor = .clear
setUpTranslucentViews()
setUpCommonViews()
setUpTableView()
setUpCloseButton()
applyTheme()
}
private func setUpTranslucentViews() {
guard isTranslucentStyle == true else { return }
effectView = UIVisualEffectView()
effectView?.effect = UIBlurEffect(style: isDarkStyle ? .dark : .light)
effectView?.frame = bounds
effectView?.autoresizingMask = [.flexibleWidth, .flexibleHeight]
addSubview(effectView!)
}
private func setUpTableView() {
tableView.frame = bounds
tableView.autoresizingMask = [.flexibleWidth, .flexibleHeight]
tableView.backgroundColor = .clear
tableView.maximumWidth = 500
tableView.tableHeaderView = headerView
tableView.tableFooterView = footerView
tableView.delaysContentTouches = false
tableView.delegate = self
#if swift(>=3.2)
if #available(iOS 11.0, *) {
tableView.contentInsetAdjustmentBehavior = .never
}
#endif
containerView.addSubview(tableView)
let infoDictionary = Bundle.main.infoDictionary!
if let displayName = infoDictionary["CFBundleDisplayName"] {
headerView.appName = displayName as? String
}
else if let displayName = infoDictionary[kCFBundleNameKey as String] {
headerView.appName = displayName as? String
}
}
private func setUpCloseButton() {
//Check if we're already set up
if isCancelButtonHidden && closeButton == nil { return }
if !isCancelButtonHidden && closeButton != nil { return }
if isCancelButtonHidden {
closeButton?.removeFromSuperview()
closeButton = nil
return
}
let closeIcon = UIImage.closeIcon()
closeButton = UIButton(type: .system)
closeButton?.setImage(closeIcon, for: .normal)
closeButton?.frame = CGRect(origin: .zero, size: closeIcon.size)
closeButton?.addTarget(self, action: #selector(didTapCloseButton), for: .touchUpInside)
self.addSubview(closeButton!)
applyTheme()
}
private func setUpCopyrightLabel()
{
guard isCopyrightLabelHidden == false, copyrightView == nil else { return }
copyrightView = UILabel()
guard let copyrightView = copyrightView else { return }
copyrightView.text = copyrightLabelText
copyrightView.textAlignment = .center
copyrightView.font = UIFont.systemFont(ofSize: 15)
copyrightView.sizeToFit()
copyrightView.autoresizingMask = [.flexibleLeftMargin, .flexibleRightMargin, .flexibleTopMargin]
copyrightView.frame.origin.y = self.bounds.height - copyrightViewMargin
copyrightView.frame.origin.x = (self.bounds.width - copyrightView.frame.width) * 0.5
containerView.addSubview(copyrightView)
}
private func setUpCommonViews() {
backgroundView = UIView()
backgroundView?.frame = bounds
backgroundView?.autoresizingMask = [.flexibleWidth, .flexibleHeight]
self.addSubview(backgroundView!)
containerView.frame = bounds
containerView.autoresizingMask = [.flexibleWidth, .flexibleHeight]
self.addSubview(containerView)
navigationBar.frame = CGRect(x: 0, y: 0, width: bounds.size.width, height: 20)
navigationBar.autoresizingMask = [.flexibleWidth]
navigationBar.alpha = 0.0
self.addSubview(navigationBar)
setUpTableView()
setUpCloseButton()
setUpCopyrightLabel()
applyTheme()
}
private func applyTheme() {
// view accessory views
navigationBar.style = isDarkStyle ? StatusBarUnderlayStyle.dark : StatusBarUnderlayStyle.light
copyrightView?.textColor = isDarkStyle ? UIColor(white: 0.3, alpha: 1.0) : UIColor(white: 0.6, alpha: 1.0)
// view background
if isTranslucentStyle {
backgroundView?.backgroundColor = UIColor(white: isDarkStyle ? 0.1 : 0.9, alpha: 0.3)
}
else {
backgroundView?.backgroundColor = UIColor(white: isDarkStyle ? 0.15 : 0.95, alpha: 1.0)
}
if effectView != nil {
effectView?.effect = UIBlurEffect(style: isDarkStyle ? .dark : .light)
}
if closeButton != nil {
let greyShade = isDarkStyle ? 1.0 : 0.2
closeButton?.tintColor = UIColor(white: CGFloat(greyShade), alpha: 1.0)
}
// table accessory views
headerView.style = isDarkStyle ? .dark : .light
footerView.style = isDarkStyle ? .dark : .light
// table view and cells
tableView.separatorColor = isDarkStyle ? UIColor(white: 0.4, alpha: 1.0) : nil
tableView.cellBackgroundColor = UIColor(white: isDarkStyle ? 0.2 : 1.0, alpha: 1.0)
}
// MARK: - Table View Layout -
public func scrollViewDidScroll(_ scrollView: UIScrollView) {
layoutNavigationBar()
layoutCopyrightView()
updateCloseButtonVisibility()
}
// MARK: - View Layout -
public override func layoutSubviews() {
super.layoutSubviews()
// Recalculate the state for the on-screen views
layoutTableContentInset()
layoutNavigationBar()
layoutCopyrightView()
layoutCloseButton()
// Hide the copyright view if there's not enough space on screen
updateCopyrightViewVisibility()
}
public func animateContentInsetTransition() {
UIView.animate(withDuration: 0.6, delay: 0, usingSpringWithDamping: 1.0, initialSpringVelocity: 0.9, options: [], animations: {
self.layoutTableContentInset()
self.layoutNavigationBar()
}, completion: nil)
// When animating the table view edge insets when its rounded, the header view
// snaps because their width override is caught in the animation block.
tableView.tableHeaderView?.layer.removeAllAnimations()
}
public func layoutTableContentInset() {
// Vertically align the table view so the table cells are in the middle
let boundsHeight = bounds.size.height - keyboardHeight // Adjusted for keyboard visibility
let contentHeight = tableView.contentSize.height
let sectionHeight = tableView.rect(forSection: 0).size.height
let contentMidPoint: CGFloat //
// If keyboard is not visible, align the table cells to the middle of the screen,
// else just align the whole content region
if keyboardHeight > 0 {
contentMidPoint = contentHeight * 0.5
}
else {
contentMidPoint = headerView.frame.height + (sectionHeight * 0.5)
}
var topPadding = max(0, (boundsHeight * 0.5) - contentMidPoint)
topPadding += (UIApplication.shared.statusBarFrame.height + 10)
var bottomPadding:CGFloat = 0.0
if keyboardHeight > 0 {
bottomPadding = keyboardHeight + 15
}
var edgeInsets = tableView.contentInset
edgeInsets.top = topPadding
edgeInsets.bottom = bottomPadding
tableView.contentInset = edgeInsets
// Align the scroll view offset so it's centered vertically
if boundsHeight < contentHeight {
var verticalOffset = tableView.tableHeaderView!.frame.size.height - topPadding
verticalOffset = min(verticalOffset, -(bounds.size.height - (contentHeight + bottomPadding)))
tableView.contentOffset = CGPoint(x: 0.0, y: verticalOffset)
}
}
public func layoutNavigationBar() {
if UIApplication.shared.isStatusBarHidden {
navigationBar.alpha = 0.0
return
}
let statusBarFrameHeight = UIApplication.shared.statusBarFrame.height
navigationBar.frame.size.height = statusBarFrameHeight
// Show the navigation bar when content starts passing under the status bar
let verticalOffset = self.tableView.contentOffset.y
if verticalOffset >= -statusBarFrameHeight {
navigationBar.alpha = 1.0
}
else if verticalOffset <= -(statusBarFrameHeight + 5) {
navigationBar.alpha = 0.0
}
else {
navigationBar.alpha = 1.0 - ((abs(verticalOffset) - statusBarFrameHeight) / 5.0)
}
}
public func updateCopyrightViewVisibility() {
guard let copyrightView = copyrightView else { return }
// Hide the copyright if there's not enough vertical space on the screen for it to not
// interfere with the rest of the content
let isHidden = (tableView.contentInset.top + tableView.contentSize.height) > copyrightView.frame.minY
copyrightView.alpha = isHidden ? 0.0 : 1.0
}
public func updateCloseButtonVisibility() {
guard let closeButton = self.closeButton else {
return
}
guard self.traitCollection.horizontalSizeClass == .compact else {
closeButton.alpha = 1.0
return
}
// Don't override the alpha if we're currently in an alpha animation
guard closeButton.layer.animation(forKey: "opacity") == nil else { return }
let titleLabel = self.headerView.titleLabel
let yOffset = titleLabel.frame.origin.y - tableView.contentOffset.y
let thresholdY = closeButton.frame.maxY
let normalizedOffset = yOffset - thresholdY
var alpha = normalizedOffset / 30.0
alpha = min(1.0, alpha); alpha = max(0.0, alpha)
closeButton.alpha = alpha
}
public func layoutCopyrightView() {
guard let copyrightView = copyrightView, copyrightView.isHidden == false else {
return
}
// Offset the copyright label
let verticalOffset = tableView.contentOffset.y
let normalizedOffset = verticalOffset + tableView.contentInset.top
copyrightView.frame.origin.y = (bounds.height - copyrightViewMargin) - normalizedOffset
copyrightView.frame.origin.x = floor((bounds.size.width - copyrightView.frame.size.width) * 0.5)
}
public func layoutCloseButton() {
guard let closeButton = self.closeButton else {
return
}
let statusBarFrame = UIApplication.shared.statusBarFrame
var rect = closeButton.frame
rect.origin.x = closeButtonInset.left
rect.origin.y = statusBarFrame.size.height + closeButtonInset.top
closeButton.frame = rect
}
//MARK: - State Management -
public func setRegistering(_ isRegistering: Bool, animated: Bool) {
guard isRegistering != _registering else { return }
_registering = isRegistering
// Animate the content size adjustments
animateContentInsetTransition()
// Update the accessory views
headerView.setRegistering(isRegistering, animated: animated)
footerView.setRegistering(isRegistering, animated: animated)
// Hide the copyright view if needed
UIView.animate(withDuration: animated ? 0.25 : 0.0) {
self.updateCopyrightViewVisibility()
}
}
//MARK: - Interactions -
@objc private func didTapCloseButton(sender: AnyObject?) {
didTapCloseHandler?()
}
//MARK: - View Presentation Transitioning
public func animationController(forPresented presented: UIViewController, presenting: UIViewController, source: UIViewController) -> UIViewControllerAnimatedTransitioning? {
let animationController = LoginViewControllerTransitioning()
animationController.statusBarView = navigationBar
animationController.backgroundView = backgroundView
animationController.contentView = containerView
animationController.effectsView = effectView
animationController.controlView = closeButton
animationController.isDismissing = false
return animationController
}
public func animationController(forDismissed dismissed: UIViewController) -> UIViewControllerAnimatedTransitioning? {
let animationController = LoginViewControllerTransitioning()
animationController.statusBarView = navigationBar
animationController.backgroundView = backgroundView
animationController.contentView = containerView
animationController.effectsView = effectView
animationController.controlView = closeButton
animationController.isDismissing = true
return animationController
}
}
|
apache-2.0
|
d82e8980a52b266e28d3a1719c055628
| 35.198276 | 177 | 0.650631 | 5.281761 | false | false | false | false |
thomasvl/swift-protobuf
|
Sources/SwiftProtobufTestHelpers/Descriptor+TestHelpers.swift
|
2
|
1337
|
// Sources/protoc-gen-swift/Descriptor+TestHelpers.swift - Additions to Descriptors
//
// Copyright (c) 2014 - 2017 Apple Inc. and the project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See LICENSE.txt for license information:
// https://github.com/apple/swift-protobuf/blob/main/LICENSE.txt
//
// -----------------------------------------------------------------------------
import SwiftProtobuf
public extension Google_Protobuf_FileDescriptorProto {
init(name: String, dependencies: [String] = [], publicDependencies: [Int32] = []) {
for idx in publicDependencies { precondition(Int(idx) <= dependencies.count) }
self.init()
self.name = name
dependency = dependencies
publicDependency = publicDependencies
}
init(textFormatStrings: [String]) throws {
let s = textFormatStrings.joined(separator: "\n") + "\n"
try self.init(textFormatString: s)
}
}
public extension Google_Protobuf_FileDescriptorSet {
init(files: [Google_Protobuf_FileDescriptorProto]) {
self.init()
file = files
}
init(file: Google_Protobuf_FileDescriptorProto) {
self.init()
self.file = [file]
}
}
public extension Google_Protobuf_EnumValueDescriptorProto {
init(name: String, number: Int32) {
self.init()
self.name = name
self.number = number
}
}
|
apache-2.0
|
57ad5b16ca00c78d37ff4caafa7b1ef8
| 29.386364 | 85 | 0.667913 | 4.165109 | false | false | false | false |
devpunk/cartesian
|
cartesian/View/DrawProject/Main/VDrawProjectRules.swift
|
1
|
2513
|
import UIKit
class VDrawProjectRules:UIView
{
private weak var controller:CDrawProject!
private var offsetX:Int
private var offsetY:Int
private let attributes:[String:AnyObject]
private let kLineWidth:Int = 1
private let kLineHeightFifties:Int = 20
private let kLineHeightTens:Int = 10
private let kLineHeightFives:Int = 7
private let kStringTop:Int = 22
private let kStringWidth:Int = 150
private let kStringHeight:Int = 14
init(controller:CDrawProject)
{
offsetX = 0
offsetY = 0
attributes = [
NSFontAttributeName:UIFont.numeric(size:10),
NSForegroundColorAttributeName:UIColor.black]
super.init(frame:CGRect.zero)
clipsToBounds = true
backgroundColor = UIColor.clear
isUserInteractionEnabled = false
translatesAutoresizingMaskIntoConstraints = false
self.controller = controller
}
required init?(coder:NSCoder)
{
return nil
}
override func layoutSubviews()
{
setNeedsDisplay()
super.layoutSubviews()
}
override func draw(_ rect:CGRect)
{
guard
let context:CGContext = UIGraphicsGetCurrentContext()
else
{
return
}
context.setStrokeColor(UIColor.black.cgColor)
let width:Int = Int(rect.maxX)
let height:Int = Int(rect.maxY)
let zoomModel:MDrawProjectMenuZoomItem = controller.modelZoom.currentZoomModel()
for positionX:Int in 0 ..< width
{
let sumPositionX:Int = positionX + offsetX
zoomModel.draw(
context:context,
position:positionX,
compositePosition:sumPositionX,
ruleType:MDrawProjectMenuZoom.RuleType.horizontal)
}
for positionY:Int in 0 ..< height
{
let sumPositionY:Int = positionY + offsetY
zoomModel.draw(
context:context,
position:positionY,
compositePosition:sumPositionY,
ruleType:MDrawProjectMenuZoom.RuleType.vertical)
}
context.drawPath(using:CGPathDrawingMode.fill)
}
//MARK: public
func scrollDidScroll(offset:CGPoint)
{
offsetX = Int(round(offset.x))
offsetY = Int(round(offset.y))
setNeedsDisplay()
}
}
|
mit
|
f2173287bbb88fba93758f868c47b44e
| 26.021505 | 88 | 0.587346 | 5.268344 | false | false | false | false |
HuiDongSHI/Swift_DouYuTV
|
DouYuTV/DouYuTV/Classes/Main/View/PageTitleView.swift
|
1
|
6102
|
//
// PageTitleView.swift
// DouYuTV
//
// Created by HuiDong Shi on 2017/4/14.
// Copyright © 2017年 HuiDongShi. All rights reserved.
//
import UIKit
//MARK: - 定义协议
// 后面的class表示这个协议 只能被类遵守
protocol PageTitleViewDelegate:class {
func pageTitleView(titleView:PageTitleView, selectIndex index:Int)
}
//MARK: - 定义常量
private let kScrollLineH:CGFloat = 2
private let kNormalColor:(CGFloat, CGFloat, CGFloat) = (85, 85, 85) // 元祖
private let kSelectColor:(CGFloat, CGFloat, CGFloat) = (255, 128, 0)
class PageTitleView: UIView {
//MARK: - 定义属性
fileprivate var titles:[String]
fileprivate var currentIndex = 0
weak var delegate:PageTitleViewDelegate?
//MARK: - 懒加载属性
fileprivate lazy var scrollView:UIScrollView = {
let scrollView = UIScrollView()
scrollView.showsHorizontalScrollIndicator = false
scrollView.scrollsToTop = false
scrollView.bounces = false
return scrollView
}()
fileprivate lazy var scrollLine:UIView = {
let scrollLine = UIView()
scrollLine.backgroundColor = UIColor.orange
return scrollLine
}()
fileprivate lazy var titleLabels:[UILabel] = [UILabel]()
//MARK: - 自定义构造函数
init(frame: CGRect, titles:[String]) {
self.titles = titles
super.init(frame: frame)
// 1. 设置UI界面
setupUI()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
//MARK: - 设置UI界面
extension PageTitleView{
fileprivate func setupUI(){
// 1. 添加UIScrollView
addSubview(scrollView)
scrollView.frame = bounds
// 2. 添加titles对应的label
setupTitleLables()
// 3. 设置滚动huakuai
setupBottomLineAndScrollLine()
}
private func setupTitleLables(){
let labelW:CGFloat = frame.size.width / CGFloat(titles.count)
let labelH:CGFloat = frame.size.height - kScrollLineH
let labelY:CGFloat = 0
for (index, title) in titles.enumerated(){
// 1. 创建Label
let label:UILabel = UILabel()
// 2. 设置label的属性
label.text = title
label.tag = index
label.font = UIFont.systemFont(ofSize: 16)
label.textColor = UIColor(r: kNormalColor.0, g: kNormalColor.1, b: kNormalColor.2)
label.textAlignment = .center
// 3. 设置label的frame
let labelX:CGFloat = labelW * CGFloat(index)
label.frame = CGRect(x: labelX, y: labelY, width: labelW, height: labelH)
// 4. 将label添加到scrollView中
scrollView.addSubview(label)
// 5. 将label添加到label数组中
titleLabels.append(label)
// 6. 给label添加手势
label.isUserInteractionEnabled = true
let tapGes = UITapGestureRecognizer(target: self, action: #selector(titleLabelClick(tapGes:)))
label.addGestureRecognizer(tapGes)
}
}
private func setupBottomLineAndScrollLine(){
// 1. 添加底线
let bottomLine:UIView = UIView()
let lineH:CGFloat = 0.5
bottomLine.backgroundColor = UIColor.lightGray
bottomLine.frame = CGRect(x: 0, y: frame.height - lineH, width: frame.width, height: lineH)
addSubview(bottomLine)
// 2. 添加滑块
scrollView.addSubview(scrollLine)
// 2.1 获取第一个label
guard let firstLabel = titleLabels.first else {return}
firstLabel.textColor = UIColor.orange
scrollLine.frame = CGRect(x: firstLabel.frame.origin.x, y: frame.height - kScrollLineH, width: firstLabel.frame.width, height: kScrollLineH)
}
}
//MARK: - 监听label点击
extension PageTitleView{
@objc fileprivate func titleLabelClick(tapGes:UITapGestureRecognizer){
// 1. 获取当前labal的下标值
guard let currentLabel = tapGes.view as? UILabel else {return}
// 2. 获取之前的label
let oldLabel = titleLabels[currentIndex]
// 3. 保存 新的label的下标值
currentIndex = currentLabel.tag
// 4. 切换文字颜色
currentLabel.textColor = UIColor(r: kSelectColor.0, g: kSelectColor.1, b: kSelectColor.2)
oldLabel.textColor = UIColor(r: kNormalColor.0, g: kNormalColor.1, b: kNormalColor.2)
// 5. 滚动条位置改变
let scrollLineX = currentLabel.frame.origin.x
UIView.animate(withDuration: 0.15) {
self.scrollLine.frame.origin.x = scrollLineX
}
// 6. 通知代理做事情
delegate?.pageTitleView(titleView: self, selectIndex: currentIndex)
}
}
//MARK: - 暴露给外部的方法
extension PageTitleView{
func setTitleWithProgress(progress:CGFloat, sourceIndex:Int, targetIndex:Int){
// 1. 取出sourceLabel/targetLabel
let sourceLabel = titleLabels[sourceIndex]
let targetLabel = titleLabels[targetIndex]
// 2. 处理滑块逻辑
let totalX = targetLabel.frame.origin.x - sourceLabel.frame.origin.x
let movx = totalX * progress
scrollLine.frame.origin.x = sourceLabel.frame.origin.x + movx
// 3. 颜色渐变
// 3.1 取出颜色变化范围
let colorDelta = (kSelectColor.0 - kNormalColor.0, kSelectColor.1-kNormalColor.1, kSelectColor.2-kNormalColor.2);
// 3.2 变化sourceLabe
sourceLabel.textColor = UIColor(r: kSelectColor.0 - colorDelta.0*progress, g: kSelectColor.1-colorDelta.1*progress, b: kSelectColor.2-colorDelta.2*progress)
// 3.3 变化tartgetLabel
targetLabel.textColor = UIColor(r: kNormalColor.0 + colorDelta.0*progress, g: kNormalColor.1 + colorDelta.1*progress, b: kNormalColor.2 + colorDelta.2*progress)
// 4. 更改当前index
currentIndex = targetIndex
}
}
|
mit
|
69b6bc225dde6254a88e31cdccfc27f8
| 34.41358 | 168 | 0.630295 | 4.471551 | false | false | false | false |
janniklorenz/MyPlan
|
MyPlan/MPSubjectViewController.swift
|
1
|
15902
|
//
// MPSubjectViewController.swift
// MyPlan
//
// Show the details of one subject and edit them
//
// Created by Jannik Lorenz on 07.04.15.
// Copyright (c) 2015 Jannik Lorenz. All rights reserved.
//
import UIKit
import CoreData
class MPSubjectViewController: UITableViewController, NSFetchedResultsControllerDelegate, MPColorPickerViewControllerDelegate {
let kSectionTitle = 0
let kSectionColor = 1
let kSectionIO = 2
let kSectionAttributes = 3
let kSectionDelete = 4
var subject: Subject? {
didSet {
self.title = self.subject?.fullTitle
self.tableView.reloadData()
}
}
var _fetchedResultsController: NSFetchedResultsController?
var fetchedResultsController: NSFetchedResultsController {
if self._fetchedResultsController != nil {
return self._fetchedResultsController!
}
let managedObjectContext = NSManagedObjectContext.MR_defaultContext()
let req = NSFetchRequest()
req.entity = InfoSubject.MR_entityDescription()
req.sortDescriptors = [NSSortDescriptor(key: "timestamp", ascending: true)]
req.predicate = NSPredicate(format: "(subject == %@)", self.subject!)
let aFetchedResultsController = NSFetchedResultsController(fetchRequest: req, managedObjectContext: managedObjectContext, sectionNameKeyPath: nil, cacheName: nil)
aFetchedResultsController.delegate = self
self._fetchedResultsController = aFetchedResultsController
var e: NSError?
if !self._fetchedResultsController!.performFetch(&e) {
println("fetch error: \(e!.localizedDescription)")
abort();
}
return self._fetchedResultsController!
}
// MARK: - Init
required init() {
super.init(style: UITableViewStyle.Grouped)
self.tableView.registerClass(UITableViewCell.self, forCellReuseIdentifier: "CellButton")
self.tableView.registerClass(UITableViewCell.self, forCellReuseIdentifier: "CellColor")
self.tableView.registerClass(UITableViewCell.self, forCellReuseIdentifier: "Cell")
self.tableView.registerClass(MPTableViewCellTextInput.self, forCellReuseIdentifier: "TextInput")
self.tableView.registerClass(MPTableViewCellSwitch.self, forCellReuseIdentifier: "Switch")
self.tableView.registerClass(MPTableViewCellTextInputDual.self, forCellReuseIdentifier: "TextInputDual")
}
required init(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
private override init(nibName nibNameOrNil: String!, bundle nibBundleOrNil: NSBundle!) {
super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil)
}
// MARK: - View Livestyle
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
// Add Info
self.navigationItem.rightBarButtonItem = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.Add, target: self, action: "addInfo" )
}
override func viewWillDisappear(animated: Bool) {
super.viewWillDisappear(animated)
if let saveSubject = self.subject {
if saveSubject.deleted == false {
MagicalRecord.saveWithBlock { (localContext: NSManagedObjectContext!) -> Void in
var s = saveSubject.MR_inContext(localContext) as! Subject
s.notify = saveSubject.notify
s.usingMarks = saveSubject.usingMarks
s.title = saveSubject.title
s.titleShort = saveSubject.titleShort
s.color = saveSubject.color
localContext.MR_saveToPersistentStoreAndWait()
}
}
}
}
// MARK: - Table view data source
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 5
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
switch (section) {
case kSectionTitle:
return 2
case kSectionColor:
return 1
case kSectionIO:
return 2
case kSectionAttributes:
let info = self.fetchedResultsController.sections![0] as! NSFetchedResultsSectionInfo
return info.numberOfObjects
case kSectionDelete:
return 1
default:
return 0
}
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
var reuseIdentifier: String
switch (indexPath.section, indexPath.row) {
case (kSectionTitle, 0...1):
reuseIdentifier = "TextInput"
case (kSectionColor, 0):
reuseIdentifier = "CellColor"
case (kSectionIO, 0...1):
reuseIdentifier = "Switch"
case (kSectionAttributes, 0...self.tableView(self.tableView, numberOfRowsInSection: kSectionAttributes)):
reuseIdentifier = "TextInputDual"
case (kSectionDelete, 0):
reuseIdentifier = "CellButton"
default:
reuseIdentifier = "Cell"
}
let cell = tableView.dequeueReusableCellWithIdentifier(reuseIdentifier, forIndexPath: indexPath) as! UITableViewCell
cell.selectionStyle = .None
switch (indexPath.section, indexPath.row) {
case (kSectionTitle, 0):
var cell = cell as! MPTableViewCellTextInput
cell.textLabel?.text = NSLocalizedString("Title", comment: "")
cell.textField.text = subject?.title
cell.didChange = { text in
self.subject?.title = text
self.title = self.subject?.fullTitle
}
case (kSectionTitle, 1):
var cell = cell as! MPTableViewCellTextInput
cell.textLabel?.text = NSLocalizedString("Short", comment: "")
cell.textField.text = subject?.titleShort
cell.didChange = { text in
self.subject?.titleShort = text
self.title = self.subject?.fullTitle
}
case (kSectionColor, 0):
cell.textLabel?.text = NSLocalizedString("Color", comment: "")
cell.accessoryType = UITableViewCellAccessoryType.DisclosureIndicator
cell.backgroundColor = subject?.color
cell.textLabel?.textColor = subject?.color.getReadableTextColor()
case (kSectionIO, 0):
var cell = cell as! MPTableViewCellSwitch
cell.textLabel?.text = NSLocalizedString("Notifications", comment: "")
if let on = subject?.notify.boolValue {
cell.switchItem.on = on
}
cell.didChange = { value in
subject?.notify = NSNumber(bool: value)
}
case (kSectionIO, 1):
var cell = cell as! MPTableViewCellSwitch
cell.textLabel?.text = NSLocalizedString("Using marks", comment: "")
if let on = subject?.usingMarks.boolValue {
cell.switchItem.on = on
}
cell.didChange = { value in
subject?.usingMarks = NSNumber(bool: value)
}
case (kSectionAttributes, 0...self.tableView(self.tableView, numberOfRowsInSection: kSectionAttributes)):
var cell = cell as! MPTableViewCellTextInputDual
let info = self.fetchedResultsController.objectAtIndexPath(NSIndexPath(forRow: indexPath.row, inSection: 0)) as! InfoSubject
cell.textField.text = info.key
cell.detailTextField.text = info.value
cell.didChange = {key, value in
MagicalRecord.saveWithBlock({ (localContext: NSManagedObjectContext!) -> Void in
var info = info.MR_inContext(localContext) as! InfoSubject
info.key = key
info.value = value
localContext.MR_saveToPersistentStoreAndWait()
})
}
case (kSectionDelete, 0):
cell.textLabel?.text = NSLocalizedString("Delete Subject", comment: "")
cell.textLabel?.textAlignment = .Center
cell.textLabel?.textColor = UIColor.redColor()
default:
break
}
return cell
}
override func tableView(tableView: UITableView, titleForFooterInSection section: Int) -> String? {
switch (section) {
case kSectionTitle:
return NSLocalizedString("__Foother_Subject_Title", comment: "")
case kSectionColor:
return NSLocalizedString("__Foother_Subject_Color", comment: "")
case kSectionAttributes:
if self.tableView(self.tableView, numberOfRowsInSection: 3) != 0 {
return NSLocalizedString("__Foother_Subject_Attribute", comment: "")
}
case kSectionDelete:
return NSLocalizedString("__Delete_Subject_Ask", comment: "")
default:
break
}
return "";
}
override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
switch (indexPath.section, indexPath.row) {
case (kSectionColor, 0):
if let subject = self.subject {
var colorPickerVC = MPColorPickerViewController(delegate: self)
self.navigationController?.pushViewController(colorPickerVC, animated: true)
colorPickerVC.color = subject.color
}
case (4, 0):
let alert = UIAlertController(
title: NSLocalizedString("Delete Subject", comment: ""),
message: NSLocalizedString("__Delete_Subject_Ask", comment: ""),
preferredStyle: .Alert
)
alert.addAction(UIAlertAction(title: NSLocalizedString("Delete", comment: ""), style: UIAlertActionStyle.Destructive, handler: { (action: UIAlertAction!) -> Void in
if let subject = self.subject {
MagicalRecord.saveWithBlock({ (localContext: NSManagedObjectContext!) -> Void in
var subject = subject.MR_inContext(localContext) as! Subject
subject.MR_deleteInContext(localContext)
localContext.MR_saveToPersistentStoreWithCompletion({ (bool: Bool, error: NSError!) -> Void in
self.navigationController?.popViewControllerAnimated(true)
})
})
}
}))
alert.addAction(UIAlertAction(title: NSLocalizedString("Cancel", comment: ""), style: UIAlertActionStyle.Cancel, handler: { (action: UIAlertAction!) -> Void in
}))
self.presentViewController(alert, animated: true, completion: nil)
default:
break
}
}
override func tableView(tableView: UITableView, didDeselectRowAtIndexPath indexPath: NSIndexPath) {
if let selectedIndexPath = self.tableView.indexPathForSelectedRow() {
var cell = self.tableView(tableView, cellForRowAtIndexPath: selectedIndexPath)
cell.setSelected(false, animated: true)
}
}
override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool {
switch indexPath.section {
case 3:
return true
default:
break
}
return false
}
override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
if editingStyle == .Delete {
if let subject = self.subject {
MagicalRecord.saveWithBlock { (localContext: NSManagedObjectContext!) -> Void in
let info = self.fetchedResultsController.objectAtIndexPath(NSIndexPath(forRow: indexPath.row, inSection: 0)).MR_inContext(localContext) as! InfoSubject
info.MR_deleteInContext(localContext)
localContext.MR_saveToPersistentStoreAndWait()
}
}
}
else if editingStyle == .Insert {
// Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
}
}
/*
// Override to support rearranging the table view.
override func tableView(tableView: UITableView, moveRowAtIndexPath fromIndexPath: NSIndexPath, toIndexPath: NSIndexPath) {
}
*/
/*
// Override to support conditional rearranging of the table view.
override func tableView(tableView: UITableView, canMoveRowAtIndexPath indexPath: NSIndexPath) -> Bool {
// Return NO if you do not want the item to be re-orderable.
return true
}
*/
// MARK: - UI Interaction
func addInfo() {
if let subject = self.subject {
MagicalRecord.saveWithBlock { (localContext: NSManagedObjectContext!) -> Void in
var info = InfoSubject.MR_createInContext(localContext) as! InfoSubject
info.subject = subject.MR_inContext(localContext) as! Subject
info.timestamp = NSDate()
info.key = "key"
info.value = "value"
localContext.MR_saveToPersistentStoreAndWait()
}
}
}
// MAKR: - MPColorPickerViewControllerDelegate
func didPickColor(color: UIColor) {
self.subject?.color = color
self.tableView.reloadData()
}
// MARK: - NSFetchedResultsControllerDelegate
func controllerWillChangeContent(controller: NSFetchedResultsController) {
self.tableView.beginUpdates()
}
func controller(controller: NSFetchedResultsController, didChangeObject object: AnyObject, atIndexPath indexPath: NSIndexPath?, forChangeType type: NSFetchedResultsChangeType, newIndexPath: NSIndexPath?) {
switch type {
case .Insert:
self.tableView.insertRowsAtIndexPaths([NSIndexPath(forRow: newIndexPath!.row, inSection: kSectionAttributes)], withRowAnimation: .Fade)
// case .Update:
// let cell = self.tableView.cellForRowAtIndexPath(NSIndexPath(forRow: indexPath!.row, inSection: kSectionAttributes))
// self.tableView.reloadRowsAtIndexPaths([NSIndexPath(forRow: indexPath!.row, inSection: 3)], withRowAnimation: .Fade)
case .Move:
self.tableView.deleteRowsAtIndexPaths([NSIndexPath(forRow: indexPath!.row, inSection: kSectionAttributes)], withRowAnimation: .Fade)
self.tableView.insertRowsAtIndexPaths([NSIndexPath(forRow: newIndexPath!.row, inSection: kSectionAttributes)], withRowAnimation: .Fade)
case .Delete:
self.tableView.deleteRowsAtIndexPaths([NSIndexPath(forRow: indexPath!.row, inSection: kSectionAttributes)], withRowAnimation: .Fade)
default:
return
}
}
func controllerDidChangeContent(controller: NSFetchedResultsController) {
self.tableView.endUpdates()
}
}
|
gpl-2.0
|
7a27f481f2492f521e5b8c5e5f16c3cf
| 36.861905 | 209 | 0.601937 | 5.848474 | false | false | false | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.