repo_name
stringlengths 6
91
| path
stringlengths 8
968
| copies
stringclasses 210
values | size
stringlengths 2
7
| content
stringlengths 61
1.01M
| license
stringclasses 15
values | hash
stringlengths 32
32
| line_mean
float64 6
99.8
| line_max
int64 12
1k
| alpha_frac
float64 0.3
0.91
| ratio
float64 2
9.89
| autogenerated
bool 1
class | config_or_test
bool 2
classes | has_no_keywords
bool 2
classes | has_few_assignments
bool 1
class |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
creatubbles/ctb-api-swift
|
CreatubblesAPIClient/Sources/CreationUploadSession/CreationUploadService.swift
|
1
|
10911
|
//
// CreationUploadService.swift
// CreatubblesAPIClient
//
// Copyright (c) 2017 Creatubbles Pte. Ltd.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import UIKit
protocol CreationUploadServiceDelegate: class {
func creationUploadService(_ sender: CreationUploadService, newSessionAdded session: CreationUploadSession)
func creationUploadService(_ sender: CreationUploadService, uploadFinished session: CreationUploadSession)
func creationUploadService(_ sender: CreationUploadService, uploadFailed session: CreationUploadSession, withError error: Error)
func creationUploadService(_ sender: CreationUploadService, progressChanged session: CreationUploadSession, completedUnitCount: Int64, totalUnitcount: Int64, fractionCompleted: Double)
}
class CreationUploadService: CreationUploadSessionDelegate {
weak var delegate: CreationUploadServiceDelegate?
fileprivate let databaseDAO: DatabaseDAO
fileprivate let requestSender: RequestSender
fileprivate var uploadSessions: Array<CreationUploadSession>
fileprivate let operationQueue: OperationQueue
fileprivate let preparationQueue: OperationQueue
init(requestSender: RequestSender) {
self.requestSender = requestSender
self.databaseDAO = DatabaseDAO()
self.uploadSessions = Array<CreationUploadSession>()
self.operationQueue = OperationQueue()
self.operationQueue.maxConcurrentOperationCount = 1
// To make sure that upload sessions can be retried we have to define a preparation stage. Basically, it's responsible for saving all required data locally and shouldn't be related to API calls.
self.preparationQueue = OperationQueue()
self.preparationQueue.maxConcurrentOperationCount = 1
setupSessions()
}
fileprivate func setupSessions() {
uploadSessions = databaseDAO.fetchAllCreationUploadSessions(requestSender)
uploadSessions.forEach({ $0.delegate = self })
}
func getAllActiveUploadSessionsPublicData() -> Array<CreationUploadSessionPublicData> {
return uploadSessions.filter({ $0.isActive == true && $0.state != .cancelled }).map({ CreationUploadSessionPublicData(creationUploadSession: $0) })
}
func getAllNotFinishedUploadSessionsPublicData() -> Array<CreationUploadSessionPublicData> {
return uploadSessions.filter({ $0.state.rawValue < CreationUploadSessionState.serverNotified.rawValue })
.map({ CreationUploadSessionPublicData(creationUploadSession: $0) })
}
func getAllFinishedUploadSessionPublicData() -> Array<CreationUploadSessionPublicData> {
return uploadSessions.filter({ $0.state == .serverNotified }).map({ CreationUploadSessionPublicData(creationUploadSession: $0) })
}
func startAllNotFinishedUploadSessions(_ completion: CreationClosure?) {
// Before we start all unfinished sessions we have make sure that upload sessions has a correct state
removeInvalidUploadSessions()
var newUploadSessions: [CreationUploadSession] = []
databaseDAO.fetchAllCreationUploadSessions(requestSender).forEach { (uploadSession) in
if uploadSessions.filter({ $0.localIdentifier == uploadSession.localIdentifier }).isEmpty {
uploadSession.delegate = self
newUploadSessions.append(uploadSession)
}
}
uploadSessions.append(contentsOf: newUploadSessions)
uploadSessions.filter({ !$0.isActive }).forEach { (uploadSession) in
let operation = CreationUploadSessionOperation(session: uploadSession, completion: completion)
operationQueue.addOperation(operation)
}
}
func startUploadSession(sessionIdentifier sessionId: String) {
guard let session = uploadSessions.filter({ $0.localIdentifier == sessionId }).first
else {
Logger.log(.warning, "Cannot find session with identifier \(sessionId) to start")
return
}
session.delegate = self
session.start(nil)
}
func removeUploadSession(sessionIdentifier sessionId: String) {
guard let session = uploadSessions.filter({ $0.localIdentifier == sessionId }).first,
let index = uploadSessions.index(of: session)
else {
Logger.log(.warning, "Cannot find session with identifier \(sessionId) to remove")
return
}
session.delegate = nil
session.cancel()
uploadSessions.remove(at: index)
databaseDAO.removeUploadSession(withIdentifier: sessionId)
delegate?.creationUploadService(self, uploadFailed: session, withError: APIClientError.genericUploadCancelledError as Error)
}
func removeAllUploadSessions() {
uploadSessions.forEach {
$0.delegate = nil
$0.cancel()
}
databaseDAO.removeAllUploadSessions()
uploadSessions = databaseDAO.fetchAllCreationUploadSessions(requestSender)
}
func uploadCreation(data: NewCreationData, localDataPreparationCompletion: ((_ error: Error?) -> Void)?, completion: CreationClosure?) -> CreationUploadSessionPublicData? {
let session = CreationUploadSession(data: data, requestSender: requestSender)
if let _ = uploadSessions.filter({ $0.localIdentifier == data.localIdentifier }).first {
let error = APIClientError.duplicatedUploadLocalIdentifierError
localDataPreparationCompletion?(error)
completion?(nil, error)
delegate?.creationUploadService(self, uploadFailed: session, withError: error)
return nil
}
// Before adding a new upload session we have to make sure that it has been prepared correctly. This step is required to have a possibility to retry the upload sessions at the later stage (i.e. reopening the app)
let operation = BlockOperation()
operation.addExecutionBlock { [unowned operation, weak self] in
guard !operation.isCancelled else {
let error = APIClientError.genericUploadCancelledError
localDataPreparationCompletion?(error)
completion?(nil, error)
return
}
session.prepare() { [weak self] (error) in
guard let strongSelf = self, error == nil else {
localDataPreparationCompletion?(error)
completion?(nil, APIClientError.genericUploadCancelledError)
return
}
DispatchQueue.main.async {
strongSelf.uploadSessions.append(session)
strongSelf.databaseDAO.saveCreationUploadSessionToDatabase(session)
session.delegate = strongSelf
strongSelf.delegate?.creationUploadService(strongSelf, newSessionAdded: session)
let operation = CreationUploadSessionOperation(session: session, completion: completion)
strongSelf.operationQueue.addOperation(operation)
localDataPreparationCompletion?(nil)
}
}
}
preparationQueue.addOperation(operation)
return CreationUploadSessionPublicData(creationUploadSession: session)
}
open func refreshCreationStatusInUploadSession(sessionId: String) {
let sessions = uploadSessions.filter({ $0.localIdentifier == sessionId })
sessions.forEach({ $0.refreshCreation(completion: nil) })
}
open func refreshCreationStatusInUploadSession(creationId: String) {
let sessions = uploadSessions.filter({ $0.creation?.identifier == creationId })
sessions.forEach({ $0.refreshCreation(completion: nil) })
}
open func notifyCreationProcessingFailed(creationId: String) {
let sessions = uploadSessions.filter({ $0.creation?.identifier == creationId })
sessions.forEach({ $0.setCreationProcessingFailed() })
}
// MARK: - CreationUploadSessionDelegate
func creationUploadSessionChangedState(_ creationUploadSession: CreationUploadSession) {
databaseDAO.saveCreationUploadSessionToDatabase(creationUploadSession)
if(creationUploadSession.isAlreadyFinished) {
delegate?.creationUploadService(self, uploadFinished: creationUploadSession)
}
}
func creationUploadSessionChangedProgress(_ creationUploadSession: CreationUploadSession, completedUnitCount: Int64, totalUnitcount totalUnitCount: Int64, fractionCompleted: Double) {
delegate?.creationUploadService(self, progressChanged: creationUploadSession, completedUnitCount: completedUnitCount, totalUnitcount: totalUnitCount, fractionCompleted: fractionCompleted)
}
func creationUploadSessionUploadFailed(_ creationUploadSession: CreationUploadSession, error: Error) {
delegate?.creationUploadService(self, uploadFailed: creationUploadSession, withError: error)
}
// MARK: - Validation
private func removeInvalidUploadSessions() {
var invalidUploadSessions: [CreationUploadSession] = []
databaseDAO.fetchAllCreationUploadSessions(requestSender).forEach { (uploadSession) in
if !uploadSession.isValid() {
invalidUploadSessions.append(uploadSession)
}
}
invalidUploadSessions.forEach { (session) in
if let existingUploadSession = uploadSessions.filter({ $0.localIdentifier == session.localIdentifier }).first, let index = uploadSessions.index(of: existingUploadSession) {
uploadSessions.remove(at: index)
databaseDAO.removeUploadSession(withIdentifier: existingUploadSession.localIdentifier)
}
}
}
}
|
mit
|
4cefff0d168f7231d46a460eb661cd25
| 47.278761 | 220 | 0.700211 | 5.401485 | false | false | false | false |
ben-ng/swift
|
validation-test/stdlib/UnicodeUTFEncoders.swift
|
14
|
4027
|
// RUN: rm -rf %t
// RUN: mkdir -p %t
// RUN: %target-build-swift %s -o %t/a.out -O
// RUN: %target-run %t/a.out
// REQUIRES: executable_test
// REQUIRES: objc_interop
import SwiftPrivate
import StdlibUnittest
import Foundation
protocol TestableUnicodeCodec : UnicodeCodec {
associatedtype CodeUnit : Integer
static func encodingId() -> String.Encoding
static func name() -> NSString
}
extension UTF8 : TestableUnicodeCodec {
static func encodingId() -> String.Encoding {
return .utf8
}
static func name() -> NSString {
return "UTF8"
}
}
extension UTF16 : TestableUnicodeCodec {
static func encodingId() -> String.Encoding {
return .utf16LittleEndian
}
static func name() -> NSString {
return "UTF16"
}
}
extension UTF32 : TestableUnicodeCodec {
static func encodingId() -> String.Encoding {
return .utf32LittleEndian
}
static func name() -> NSString {
return "UTF32"
}
}
// The valid ranges of Unicode scalar values
var unicodeScalarRanges: [CountableClosedRange<UInt32>] = [UInt32(0)...0xd7ff, 0xe000...0x10ffff]
var unicodeScalarCount: Int {
var count = 0
for r in unicodeScalarRanges {
count += Int(r.upperBound - r.lowerBound)
}
return count
}
func nthUnicodeScalar(_ n: UInt32) -> UnicodeScalar {
var count: UInt32 = 0
for r in unicodeScalarRanges {
count += r.upperBound - r.lowerBound
if count > n {
return UnicodeScalar(r.upperBound - (count - n))!
}
}
_preconditionFailure("Index out of range")
}
// `buffer` should have a length >= 4
func nsEncode<CodeUnit>(
_ c: UInt32,
_ encoding: String.Encoding,
_ buffer: inout [CodeUnit],
_ used: inout Int
) {
var c = c
_precondition(buffer.count >= 4, "buffer is not large enough")
let s = NSString(
bytes: &c,
length: 4,
encoding: String.Encoding.utf32LittleEndian.rawValue)!
s.getBytes(
&buffer,
maxLength: buffer.count,
usedLength: &used,
encoding: encoding.rawValue,
options: [],
range: NSRange(location: 0, length: s.length),
remaining: nil)
}
final class CodecTest<Codec : TestableUnicodeCodec> {
var used = 0
typealias CodeUnit = Codec.CodeUnit
var nsEncodeBuffer: [CodeUnit] = Array(repeating: 0, count: 4)
var encodeBuffer: [CodeUnit] = Array(repeating: 0, count: 4)
final func testOne(_ scalar: UnicodeScalar) {
/* Progress reporter
if (scalar.value % 0x1000) == 0 {
print("\(asHex(scalar.value))")
}
*/
// Use Cocoa to encode the scalar
nsEncode(scalar.value, Codec.encodingId(), &nsEncodeBuffer, &used)
let nsEncoded = nsEncodeBuffer[0..<(used/MemoryLayout<CodeUnit>.size)]
var encodeIndex = encodeBuffer.startIndex
let encodeOutput: (CodeUnit) -> Void = {
self.encodeBuffer[encodeIndex] = $0
encodeIndex += 1
}
var iter = nsEncoded.makeIterator()
var decoded: UnicodeScalar
var decoder = Codec()
switch decoder.decode(&iter) {
case .scalarValue(let us):
decoded = us
default:
fatalError("decoding failed")
}
expectEqualTest(
scalar, decoded,
"Decoding failed: \(asHex(scalar.value)) => " +
"\(asHex(nsEncoded)) => \(asHex(decoded.value))"
) { $0 == $1 }
encodeIndex = encodeBuffer.startIndex
Codec.encode(scalar, into: encodeOutput)
expectEqualTest(
nsEncoded, encodeBuffer[0..<encodeIndex],
"Decoding failed: \(asHex(nsEncoded)) => " +
"\(asHex(scalar.value)) => \(asHex(self.encodeBuffer[0]))"
) { $0 == $1 }
}
final func run(_ minScalarOrd: Int, _ maxScalarOrd: Int) {
print("testing \(Codec.name())")
for i in minScalarOrd..<maxScalarOrd {
testOne(nthUnicodeScalar(UInt32(i)))
}
}
}
var UTFEncoders = TestSuite("UTFEncoders")
UTFEncoders.test("encode") {
let minScalarOrd = 0
let maxScalarOrd = unicodeScalarCount
CodecTest<UTF8>().run(minScalarOrd, maxScalarOrd)
CodecTest<UTF16>().run(minScalarOrd, maxScalarOrd)
CodecTest<UTF32>().run(minScalarOrd, maxScalarOrd)
}
runAllTests()
|
apache-2.0
|
dac80e618a7d46b5e747ba705c5e153d
| 24.327044 | 97 | 0.66228 | 3.684355 | false | true | false | false |
alickbass/ViewComponents
|
ViewComponents/TableViewCellStyle.swift
|
1
|
2972
|
//
// UITableViewCellStyle.swift
// ViewComponents
//
// Created by Oleksii on 12/05/2017.
// Copyright © 2017 WeAreReasonablePeople. All rights reserved.
//
import UIKit
private enum TableViewCellStyleKey: Int, StyleKey {
case accessoryType = 400, editingAccessoryType, isSelected
case selectionStyle, isHighlighted, isEditing
case showsReorderControl, indentationLevel, indentationWidth
case shouldIndentWhileEditing, separatorInset, focusStyle
}
public extension AnyStyle where T: UITableViewCell {
private typealias ViewStyle<Item> = Style<T, Item, TableViewCellStyleKey>
public static func accessoryType(_ value: UITableViewCellAccessoryType) -> AnyStyle<T> {
return ViewStyle(value, key: .accessoryType, sideEffect: { $0.accessoryType = $1 }).toAnyStyle
}
public static func editingAccessoryType(_ value: UITableViewCellAccessoryType) -> AnyStyle<T> {
return ViewStyle(value, key: .editingAccessoryType, sideEffect: { $0.editingAccessoryType = $1 }).toAnyStyle
}
public static func isSelected(_ value: Bool) -> AnyStyle<T> {
return ViewStyle(value, key: .isSelected, sideEffect: { $0.isSelected = $1 }).toAnyStyle
}
public static func selectionStyle(_ value: UITableViewCellSelectionStyle) -> AnyStyle<T> {
return ViewStyle(value, key: .selectionStyle, sideEffect: { $0.selectionStyle = $1 }).toAnyStyle
}
public static func isHighlighted(_ value: Bool) -> AnyStyle<T> {
return ViewStyle(value, key: .isHighlighted, sideEffect: { $0.isHighlighted = $1 }).toAnyStyle
}
public static func isEditing(_ value: Bool) -> AnyStyle<T> {
return ViewStyle(value, key: .isEditing, sideEffect: { $0.isEditing = $1 }).toAnyStyle
}
public static func showsReorderControl(_ value: Bool) -> AnyStyle<T> {
return ViewStyle(value, key: .showsReorderControl, sideEffect: { $0.showsReorderControl = $1 }).toAnyStyle
}
public static func indentationLevel(_ value: Int) -> AnyStyle<T> {
return ViewStyle(value, key: .indentationLevel, sideEffect: { $0.indentationLevel = $1 }).toAnyStyle
}
public static func indentationWidth(_ value: CGFloat) -> AnyStyle<T> {
return ViewStyle(value, key: .indentationWidth, sideEffect: { $0.indentationWidth = $1 }).toAnyStyle
}
public static func shouldIndentWhileEditing(_ value: Bool) -> AnyStyle<T> {
return ViewStyle(value, key: .shouldIndentWhileEditing, sideEffect: { $0.shouldIndentWhileEditing = $1 }).toAnyStyle
}
public static func separatorInset(_ value: UIEdgeInsets) -> AnyStyle<T> {
return ViewStyle(value, key: .separatorInset, sideEffect: { $0.separatorInset = $1 }).toAnyStyle
}
public static func focusStyle(_ value: UITableViewCellFocusStyle) -> AnyStyle<T> {
return ViewStyle(value, key: .focusStyle, sideEffect: { $0.focusStyle = $1 }).toAnyStyle
}
}
|
mit
|
eb8f6651ae26d7b365ea321d4b3d1e30
| 42.691176 | 124 | 0.692359 | 4.577812 | false | false | false | false |
zalando/zmon-ios
|
zmon/client/ZmonAlertsService.swift
|
1
|
6038
|
//
// ZmonAlertsService.swift
// zmon
//
// Created by Andrej Kincel on 16/12/15.
// Copyright © 2015 Zalando Tech. All rights reserved.
//
import Alamofire
class ZmonAlertsService: NSObject {
func list(success success: ([ZmonAlertStatus]) -> ()) {
ZmonService.sharedInstance.getObjectList(path: "/active-alerts", parameters: [:], headers: CredentialsStore.sharedInstance.accessTokenHeader(), success: success)
}
func listByTeam(teamName teamName: String, success: ([ZmonAlertStatus]) -> ()) {
log.debug("Listing alerts for teams with query ?team=\(teamName)")
ZmonService.sharedInstance.getObjectList(path: "/active-alerts", parameters: ["team": teamName], headers: CredentialsStore.sharedInstance.accessTokenHeader(), success: success)
}
func listRemoteObservableAlertsWithCompletion(completion: (alerts: [ZmonServiceResponse.Alert]?) -> ()) {
let path = "https://notification-service.zmon.zalan.do/api/v1/mobile/alert"
let headers = CredentialsStore.sharedInstance.accessTokenHeader()
Alamofire.request(.GET, path, parameters: [:], encoding: .URL, headers: headers).responseJSON { response in
guard let rootJsonObject = response.result.value else {
log.error("Failed to fetch remote observable alerts with error: \(response.result.error)")
completion(alerts: nil)
return
}
guard let jsonArray = rootJsonObject as? NSArray else {
log.error("Error while parsing remote alerts data: invalid JSON object found where NSArray was expected")
completion(alerts: nil)
return
}
let parsedAlerts = ZmonServiceResponse.parseAlertCollectionWithJSONArray(jsonArray)
completion(alerts: parsedAlerts)
}
}
func listUserObservedAlertsWithCompletion(completion: (alertIDs: [Int]?) -> ()) {
let path = "https://notification-service.zmon.zalan.do/api/v1/user/subscriptions"
let headers = CredentialsStore.sharedInstance.accessTokenHeader()
Alamofire.request(.GET, path, parameters: [:], encoding: .URL, headers: headers).responseString { response in
if let responseString = response.result.value {
// The response is in format of "[123,456,789,...]"
let skipChars = NSMutableCharacterSet(charactersInString: "[],")
skipChars.formUnionWithCharacterSet(NSCharacterSet.whitespaceAndNewlineCharacterSet())
let scanner = NSScanner(string: responseString)
scanner.charactersToBeSkipped = skipChars
var result: [Int] = []
var scannedID:Int = 0
while scanner.scanInteger(&scannedID) {
result.append(scannedID)
}
completion(alertIDs: result)
} else {
log.error("Failed to list user observed alerts with error: \(response.result.error?.localizedDescription)")
completion(alertIDs: nil)
}
}
}
func registerDevice(deviceSubscription deviceSubscription: DeviceSubscription, success: () -> (), failure: (NSError) -> ()) {
let parameters: [String:String] = deviceSubscription.toDictionary() as! [String:String]
ZmonService.sharedInstance.postJson(path: "/device", parameters: parameters, headers: CredentialsStore.sharedInstance.accessTokenHeader(), success: success, failure: failure)
}
func registerDeviceWithToken(token: String, success: () -> (), failure: (NSError) -> ()) {
// TODO: We cannot use the ZmonSerivce class as it uses /mobile endpoint for all calls. This is why the path is explicit. Better solution needed...
let path = "https://notification-service.zmon.zalan.do/api/v1/device"
Alamofire
.request(.POST, path, parameters: ["registration_token":token], encoding: .JSON, headers: CredentialsStore.sharedInstance.accessTokenHeader())
.validate()
.response { (request, response, data, error) -> Void in
if error == nil {
success()
}
else {
log.error(response.debugDescription)
failure(error!)
}
}
}
func subscribeToAlertWithID(alertID: String, success: ()->(), failure: (NSError)->()) {
let path = "https://notification-service.zmon.zalan.do/api/v1/subscription"
let parameters = ["alert_id":alertID]
let headers = CredentialsStore.sharedInstance.accessTokenHeader()
Alamofire
.request(.POST, path, parameters: parameters, encoding: .JSON, headers: headers)
.validate()
.response { (request, response, data, error) -> Void in
if error == nil {
success()
}
else {
log.error(response.debugDescription)
failure(error!)
}
}
}
func unsubscribeFromAlertWithID(alertID: String, success: () -> (), failure: (NSError) -> ()) {
let path = "https://notification-service.zmon.zalan.do/api/v1/subscription/\(alertID)"
let headers = CredentialsStore.sharedInstance.accessTokenHeader()
Alamofire
.request(.DELETE, path, parameters: [:], encoding: .URL, headers: headers)
.validate()
.response { (request, response, data, error) -> Void in
if error == nil {
success()
}
else {
log.error(response.debugDescription)
failure(error!)
}
}
}
}
|
mit
|
1f44ddf05f92d92057fbfb5af843ad0a
| 41.216783 | 184 | 0.580752 | 5.085931 | false | false | false | false |
Keenan144/IOSSpaceGame
|
IOS SpaceGame/SpaceGame/GameOverScene.swift
|
1
|
1186
|
import UIKit
import SpriteKit
class GameOverScene: SKScene {
init(size: CGSize, won:Bool){
super.init(size: size)
var label:SKLabelNode = SKLabelNode(fontNamed: "Optima-ExtraBlack")
self.backgroundColor = SKColor.blackColor()
var message:NSString = NSString()
if (won){
label.fontColor = SKColor.greenColor()
message = "Nice"
}else{
label.fontColor = SKColor.redColor()
message = "Game Over"
}
label.text = message
label.position = CGPointMake(self.size.width/2, self.size.height/2)
self.addChild(label)
self.runAction(SKAction.sequence([SKAction.waitForDuration(3.0),
SKAction.runBlock({
var transition:SKTransition = SKTransition.flipHorizontalWithDuration(0.5)
var scene:SKScene = GameScene(size: self.size)
self.view?.presentScene(scene, transition: transition)
})
]))
}
required init(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
}
|
mit
|
391e56929806ab63a086e131116acbd4
| 26.581395 | 90 | 0.553963 | 4.941667 | false | false | false | false |
tavultesoft/keymanweb
|
ios/engine/KMEI/KeymanEngine/Classes/Constants.swift
|
1
|
6059
|
//
// Constants.swift
// KeymanEngine
//
// Created by Gabriel Wong on 2017-10-20.
// Copyright © 2017 SIL International. All rights reserved.
//
import Foundation
public enum Key {
public static let keyboardInfo = "keyboardInfo"
public static let lexicalModelInfo = "lexicalModelInfo"
/// Array of user keyboards info list in UserDefaults
static let userKeyboardsList = "UserKeyboardsList"
/// Array of user lexical models info list in UserDefaults
static let userLexicalModelsList = "UserLexicalModelsList"
/// Dictionary of cached query results for a user's installed packages
static let userPackageQueryCacheDict = "UserQueryDistributionStateCache"
/// Currently/last selected keyboard info in UserDefaults
static let userCurrentKeyboard = "UserCurrentKeyboard"
/// Currently/last selected lexical model info in UserDefaults
static let userCurrentLexicalModel = "UserCurrentLexicalModel"
/// Dictionary of lexical model ids keyed by language id in UserDefaults
static let userPreferredLexicalModels = "UserPreferredLexicalModels"
/// Dictionary of prediction/correction toggle settings keyed by language id in UserDefaults
static let userPredictSettings = "UserPredictionEnablementSettings"
static let userCorrectSettings = "UserCorrectionEnablementSettings"
// Internal user defaults keys
static let engineVersion = "KeymanEngineVersion"
static let keyboardPickerDisplayed = "KeyboardPickerDisplayed"
static let synchronizeSWKeyboard = "KeymanSynchronizeSWKeyboard"
static let synchronizeSWLexicalModel = "KeymanSynchronizeSWLexicalModel"
static let migrationLevel = "KeymanEngineMigrationLevel"
// JSON keys for language REST calls
static let options = "options"
static let language = "language"
// TODO: Check if it matches with the key in Keyman Cloud API
static let keyboardCopyright = "copyright"
static let lexicalModelCopyright = "lexicalmodelcopyright"
static let languages = "languages"
// Other keys
static let update = "update"
// ResourceDownloadQueue keys
static let downloadTask = "downloadTask"
static let downloadBatch = "downloadBatch"
static let downloadQueueFrame = "queueFrame"
// Settings-related keys
static let optShouldReportErrors = "ShouldReportErrors"
static let optShouldShowBanner = "ShouldShowBanner"
static let optSpacebarText = "SpacebarText"
// This one SHOULD be app-only, but is needed by the currently
// in-engine Settings menus. Alas.
static let optShouldShowGetStarted = "ShouldShowGetStarted"
}
public enum Defaults {
private static let font = Font(family: "LatinWeb", source: ["DejaVuSans.ttf"], size: nil)
public static let keyboardID = FullKeyboardID(keyboardID: "sil_euro_latin", languageID: "en")
public static let lexicalModelID = FullLexicalModelID(lexicalModelID: "nrc.en.mtnt", languageID: "en")
public static var keyboardPackage: KeyboardKeymanPackage = {
let bundledKMP = Resources.bundle.url(forResource: keyboardID.keyboardID, withExtension: ".kmp")!
return try! ResourceFileManager.shared.prepareKMPInstall(from: bundledKMP) as! KeyboardKeymanPackage
}()
public static let lexicalModelPackage: LexicalModelKeymanPackage = {
let bundledKMP = Resources.bundle.url(forResource: lexicalModelID.lexicalModelID, withExtension: ".model.kmp")!
return try! ResourceFileManager.shared.prepareKMPInstall(from: bundledKMP) as! LexicalModelKeymanPackage
}()
// Must be retrieved from their packages!
public static let keyboard: InstallableKeyboard = {
return keyboardPackage.findResource(withID: keyboardID)!
}()
public static let lexicalModel: InstallableLexicalModel = {
return lexicalModelPackage.findResource(withID: lexicalModelID)!
}()
}
public enum Resources {
/// Keyman Web resources
public static let bundle: Bundle = {
// If we're executing this code, KMEI's framework should already be loaded. Just use that.
let frameworkBundle = Bundle(for: Manager.self) //Bundle(identifier: "org.sil.Keyman.ios.Engine")!
return Bundle(path: frameworkBundle.path(forResource: "Keyman", ofType: "bundle")!)!
}()
public static let oskFontFilename = "keymanweb-osk.ttf"
static let kmwFilename = "keyboard.html"
}
public enum Util {
/// Is the process of a custom keyboard extension. Avoid using this
/// in most situations as Manager.shared.isSystemKeyboard is more
/// reliable in situations where in-app and system keyboard can
/// be used in the same app, for example using the Web Browser in
/// the Keyman app. However, in initialization scenarios this test
/// makes sense.
public static let isSystemKeyboard: Bool = {
let infoDict = Bundle.main.infoDictionary
let extensionInfo = infoDict?["NSExtension"] as? [AnyHashable: Any]
let extensionID = extensionInfo?["NSExtensionPointIdentifier"] as? String
return extensionID == "com.apple.keyboard-service"
}()
/// The version of the Keyman SDK
public static let sdkVersion: String = {
let url = Resources.bundle.url(forResource: "KeymanEngine-Info", withExtension: "plist")!
let info = NSDictionary(contentsOf: url)!
return info["CFBundleShortVersionString"] as! String
}()
}
public enum FileExtensions {
public static let javaScript = "js"
public static let trueTypeFont = "ttf"
public static let openTypeFont = "otf"
public static let configurationProfile = "mobileconfig"
}
public enum KeymanError: Error, LocalizedError {
case unknown
// file that is missing, is the file critical?
case missingFile(String, Bool)
var localizedDescription: String {
switch self {
case .unknown:
return engineBundle.localizedString(forKey: "error-unknown", value: nil, table: nil)
case .missingFile(_, let isCritical):
if isCritical {
return engineBundle.localizedString(forKey: "error-missing-file-critical", value: nil, table: nil)
} else {
return engineBundle.localizedString(forKey: "error-missing-file", value: nil, table: nil)
}
}
}
}
|
apache-2.0
|
f1e243b03056ce48725bac035be2d178
| 38.083871 | 115 | 0.750743 | 4.537828 | false | false | false | false |
SwiftFMI/iOS_2017_2018
|
Upr/21.10.17/LoginApp-final-3/LoginApp-final-3/ViewController.swift
|
1
|
8003
|
//
// ViewController.swift
// SwiftFmi
//
// Created by Petko Haydushki on 21.10.17.
// Copyright © 2017 Petko Haydushki. All rights reserved.
//
import UIKit
class ViewController: UIViewController, UITextFieldDelegate {
@IBOutlet weak var usernameTextField: UITextField!
@IBOutlet weak var passwordTextField: UITextField!
@IBOutlet weak var infoLabel: UILabel!
@IBOutlet weak var loginButton: UIButton!
@IBOutlet weak var registerButton: UIButton!
/// This outlet is used to move the login button upwards when the keyboard is changing its frame.
/// Its relative to the bottom of the screen and you can move the button by changing the value
/// of the constant property of NSLayoutConstraint class instances.
@IBOutlet weak var loginButtonVerticalSpaceToSafeAreaBottom: NSLayoutConstraint!
/// This data set represents key:value pairs (username:password)
var userData : [String : String] = [:]
override func viewDidLoad() {
super.viewDidLoad()
// You can change the alpha channel of UIView class and subclasses instances
// You can use this property to show/hide views or achieve some kind of animation behaviour
self.infoLabel.alpha = 0.0;
// This is how we round UIView and set a border. Often you should use maskToBounds property
self.loginButton.layer.borderColor = UIColor.white.cgColor
self.loginButton.layer.borderWidth = 2
self.loginButton.layer.cornerRadius = 8.0;
// Here we are subscribing for the system notification (event) when the keyboard is going to change its frame.
// There are a lot of system notifications that we can subscribe for, e.g rotation changes, keyboard events, application state changes etc.
// More interesting is that you can create your own and subscribe to them somewhere else in the project
NotificationCenter.default.addObserver(self, selector: #selector(self.keyboardNotification(notification:)), name: NSNotification.Name.UIKeyboardWillChangeFrame, object: nil)
// UserDefaults can be used to persist some information,mainly user preferences or some other small size data.
// See documentation for further info
if (UserDefaults.standard.object(forKey: "userData") != nil)
{
userData = UserDefaults.standard.object(forKey: "userData") as! [String : String]
}
else
{
userData = [:]
}
}
@IBAction func loginButtonAction(_ sender: Any) {
print("LoginBtn")
// When you want to animate properties of UIView instances you should embed you animation code inside UIView.animate block
UIView.animate(withDuration: 0.3) {
self.infoLabel.alpha = 1.0;
}
if successfullLogin(usernameTextField: usernameTextField, passwordTextField: passwordTextField)
{
let user = usernameTextField.text!
print("You are now logged in as \(user)")
self.performSegue(withIdentifier: "successfullLogin", sender: self)
}
else
{
self.infoLabel.text = "Incorect username or password"
print("user not exist")
}
}
@IBAction func registerButtonAction(_ sender: Any) {
if (isValidRegex(textField: usernameTextField) && isValidRegex(textField: passwordTextField))
{
let name = usernameTextField.text!
self.infoLabel.text = "Registered \(name)"
userData[usernameTextField.text!] = passwordTextField.text
UserDefaults.standard.set(userData, forKey: "userData")
// This is how we can delay execution of some code
DispatchQueue.main.asyncAfter(deadline:.now() + 0.5, execute: {
self.performSegue(withIdentifier: "successfullLogin", sender: self)
})
print("Registered \(name)")
}
else
{
self.infoLabel.text = "Username or password validation failed"
}
UIView.animate(withDuration: 0.3) {
self.infoLabel.alpha = 1.0;
}
}
// MARK: - UITextField Delegate methods - I've set the delegate of usernameTextField and passwordTextField in the interface builder to delegate this methods to our ViewController. We can also set them programatically.
func textFieldDidBeginEditing(_ textField: UITextField) {
textField.becomeFirstResponder()
if (textField == usernameTextField)
{
print("textFieldDidBeginEditing :: username")
}
else
{
print("textFieldDidBeginEditing :: password")
}
}
func successfullLogin(usernameTextField : UITextField,passwordTextField : UITextField) -> Bool {
if (isValidRegex(textField: usernameTextField) && isValidRegex(textField: passwordTextField))
{
if userData.count > 0 && userData[usernameTextField.text!] != nil && userData[usernameTextField.text!]! == passwordTextField.text!
{
return true
}
}
return false
}
func isValidRegex(textField : UITextField) -> Bool {
if (textField == usernameTextField)
{
if (textField.text?.contains("@"))! && (textField.text?.count)! >= 8
{
return true
}
return false
}
else if (textField == passwordTextField)
{
return true;
}
return false
}
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
print("textFieldShouldReturn")
if (textField == usernameTextField)
{
passwordTextField.becomeFirstResponder()
}
textField.resignFirstResponder()
return true
}
func textFieldDidEndEditing(_ textField: UITextField) {
print("textFieldDidEndEditing");
}
// MARK: - Keyboard Notification Handlers
@objc func keyboardNotification(notification: NSNotification) {
if let userInfo = notification.userInfo {
let endFrame = (userInfo[UIKeyboardFrameEndUserInfoKey] as? NSValue)?.cgRectValue
let duration:TimeInterval = (userInfo[UIKeyboardAnimationDurationUserInfoKey] as? NSNumber)?.doubleValue ?? 0
let animationCurveRawNSN = userInfo[UIKeyboardAnimationCurveUserInfoKey] as? NSNumber
let animationCurveRaw = animationCurveRawNSN?.uintValue ?? UIViewAnimationOptions.curveEaseInOut.rawValue
let animationCurve:UIViewAnimationOptions = UIViewAnimationOptions(rawValue: animationCurveRaw)
if (endFrame?.origin.y)! >= UIScreen.main.bounds.size.height {
self.loginButtonVerticalSpaceToSafeAreaBottom?.constant = 80.0
print(NSStringFromCGRect(endFrame!))
} else {
print(NSStringFromCGRect(endFrame!))
self.loginButtonVerticalSpaceToSafeAreaBottom?.constant = ((endFrame?.size.height)! + 20)
}
UIView.animate(withDuration: duration,
delay: TimeInterval(0),
options: animationCurve,
animations: { self.view.layoutIfNeeded() },
completion: nil)
}
}
// MARK: - Segue Handlers
// Here we can decide what to do before performing our segues (transitions)
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
let succ = segue.destination as! SuccessViewController
let name = self.usernameTextField.text!
succ.labelText = "You are now logged in as \(name)"
succ.username = name
}
}
|
apache-2.0
|
8cbf81778ac2b9cf075c1f2a7c00e1ce
| 38.034146 | 221 | 0.621345 | 5.627286 | false | false | false | false |
aschwaighofer/swift
|
test/expr/postfix/dot/init_ref_delegation.swift
|
2
|
20036
|
// RUN: %target-typecheck-verify-swift
// Tests for initializer delegation via self.init(...).
// Initializer delegation: classes
class C0 {
convenience init() {
self.init(value: 5)
}
init(value: Int) { /* ... */ }
}
class C1 {
convenience init() {
self.init(value: 5)
}
init(value: Int) { /* ... */ }
init(value: Double) { /* ... */ }
}
// Initializer delegation: structs
struct S0 {
init() {
self.init(value: 5)
}
init(value: Int) { /* ... */ }
}
struct S1 {
init() {
self.init(value: 5)
}
init(value: Int) { /* ... */ }
init(value: Double) { /* ... */ }
}
// Initializer delegation: enum
enum E0 {
case A
case B
init() {
self.init(value: 5)
}
init(value: Int) { /* ... */ }
}
enum E1 {
case A
case B
init() {
self.init(value: 5)
}
init(value: Int) { /* ... */ }
init(value: Double) { /* ... */ }
}
// Ill-formed initializer delegation: no matching constructor
class Z0 {
init() { // expected-error {{designated initializer for 'Z0' cannot delegate (with 'self.init'); did you mean this to be a convenience initializer?}} {{3-3=convenience }}
// expected-note @+2 {{delegation occurs here}}
self.init(5, 5) // expected-error{{extra argument in call}}
}
init(value: Int) { /* ... */ }
init(value: Double) { /* ... */ }
}
struct Z1 {
init() {
self.init(5, 5) // expected-error{{extra argument in call}}
}
init(value: Int) { /* ... */ }
init(value: Double) { /* ... */ }
}
enum Z2 {
case A
case B
init() {
self.init(5, 5) // expected-error{{extra argument in call}}
}
init(value: Int) { /* ... */ }
init(value: Double) { /* ... */ }
}
// Ill-formed initialization: wrong context.
class Z3 {
func f() {
self.init() // expected-error{{'init' is a member of the type; use 'type(of: ...)' to initialize a new object of the same dynamic type}} {{5-5=type(of: }} {{9-9=)}}
}
init() { }
}
// 'init' is a static-ish member.
class Z4 {
init() {} // expected-note{{selected non-required initializer}}
convenience init(other: Z4) {
other.init() // expected-error{{'init' is a member of the type; use 'type(of: ...)' to initialize a new object of the same dynamic type}} {{5-5=type(of: }} {{10-10=)}}
type(of: other).init() // expected-error{{must use a 'required' initializer}}
}
}
class Z5 : Z4 {
override init() { }
convenience init(other: Z5) {
other.init() // expected-error{{'init' is a member of the type; use 'type(of: ...)' to initialize a new object of the same dynamic type}} {{5-5=type(of: }} {{10-10=)}}
}
}
// Ill-formed initialization: failure to call initializer.
class Z6 {
convenience init() {
var _ : () -> Z6 = self.init // expected-error{{partial application of 'self.init' initializer delegation is not allowed}}
}
init(other: Z6) { }
}
// Ill-formed initialization: both superclass and delegating.
class Z7Base { }
class Z7 : Z7Base {
override init() { }
init(b: Bool) {
if b { super.init() } // expected-note{{previous chaining call is here}}
else { self.init() } // expected-error{{initializer cannot both delegate ('self.init') and chain to a }}
}
}
struct RDar16603812 {
var i = 42
init() {}
func foo() {
self.init() // expected-error {{'init' is a member of the type; use 'type(of: ...)' to initialize a new object of the same dynamic type}} {{7-7=type(of: }} {{11-11=)}}
type(of: self).init() // expected-warning{{result of 'RDar16603812' initializer is unused}}
}
}
class RDar16666631 {
var i: Int
var d: Double
var s: String
init(i: Int, d: Double, s: String) { // expected-note {{'init(i:d:s:)' declared here}}
self.i = i
self.d = d
self.s = s
}
convenience init(i: Int, s: String) {
self.init(i: i, d: 0.1, s: s)
}
}
let rdar16666631 = RDar16666631(i: 5, d: 6) // expected-error {{missing argument for parameter 's' in call}} {{43-43=, s: <#String#>}}
struct S {
init() {
let _ = S.init()
self.init()
let _ = self.init // expected-error{{partial application of 'self.init' initializer delegation is not allowed}}
}
}
class C {
convenience init() { // expected-note 11 {{selected non-required initializer 'init()'}}
self.init()
let _: C = self.init() // expected-error{{cannot convert value of type '()' to specified type 'C'}}
let _: () -> C = self.init // expected-error{{partial application of 'self.init' initializer delegation is not allowed}}
}
init(x: Int) {} // expected-note 11 {{selected non-required initializer 'init(x:)'}}
required init(required: Double) {}
}
class D: C {
override init(x: Int) {
super.init(x: x)
let _: C = super.init() // expected-error{{cannot convert value of type '()' to specified type 'C'}}
let _: () -> C = super.init // expected-error{{partial application of 'super.init' initializer chain is not allowed}}
}
func foo() {
self.init(x: 0) // expected-error{{'init' is a member of the type; use 'type(of: ...)' to initialize a new object of the same dynamic type}} {{5-5=type(of: }} {{9-9=)}}
}
func bar() {
super.init(x: 0) // expected-error{{'super.init' cannot be called outside of an initializer}}
}
class func zim() -> Self {
return self.init(required: 0)
}
class func zang() -> C {
return super.init(required: 0)
}
required init(required: Double) {}
}
func init_tests() {
var s = S.self
var s1 = s.init()
var ss1 = S.init()
var c: C.Type = D.self
var c1 = c.init(required: 0)
var c2 = c.init(x: 0) // expected-error{{'required' initializer}}
var c3 = c.init() // expected-error{{'required' initializer}}
var c1a = c.init(required: 0)
var c2a = c.init(x: 0) // expected-error{{'required' initializer}}
var c3a = c.init() // expected-error{{'required' initializer}}
var cf1: (Double) -> C = c.init
var cf2: (Int) -> C = c.init // expected-error{{'required' initializer}}
var cf3: () -> C = c.init // expected-error{{'required' initializer}}
var cs1 = C.init(required: 0)
var cs2 = C.init(x: 0)
var cs3 = C.init()
var csf1: (Double) -> C = C.init
var csf2: (Int) -> C = C.init
var csf3: () -> C = C.init
var cs1a = C(required: 0)
var cs2a = C(x: 0)
var cs3a = C()
var y = x.init() // expected-error{{cannot find 'x' in scope}}
}
protocol P {
init(proto: String)
}
func foo<T: C>(_ x: T, y: T.Type) where T: P {
var c1 = type(of: x).init(required: 0)
var c2 = type(of: x).init(x: 0) // expected-error{{'required' initializer}}
var c3 = type(of: x).init() // expected-error{{'required' initializer}}
var c4 = type(of: x).init(proto: "")
var cf1: (Double) -> T = type(of: x).init
var cf2: (Int) -> T = type(of: x).init // expected-error{{'required' initializer}}
var cf3: () -> T = type(of: x).init // expected-error{{'required' initializer}}
var cf4: (String) -> T = type(of: x).init
var c1a = type(of: x).init(required: 0)
var c2a = type(of: x).init(x: 0) // expected-error{{'required' initializer}}
var c3a = type(of: x).init() // expected-error{{'required' initializer}}
var c4a = type(of: x).init(proto: "")
var ci1 = x.init(required: 0) // expected-error{{'init' is a member of the type; use 'type(of: ...)' to initialize a new object of the same dynamic type}} {{13-13=type(of: }} {{14-14=)}}
var ci2 = x.init(x: 0) // expected-error{{'init' is a member of the type; use 'type(of: ...)' to initialize a new object of the same dynamic type}} {{13-13=type(of: }} {{14-14=)}}
var ci3 = x.init() // expected-error{{'init' is a member of the type; use 'type(of: ...)' to initialize a new object of the same dynamic type}} {{13-13=type(of: }} {{14-14=)}}
var ci4 = x.init(proto: "") // expected-error{{'init' is a member of the type; use 'type(of: ...)' to initialize a new object of the same dynamic type}} {{13-13=type(of: }} {{14-14=)}}
var z = x
z.init(required: 0) // expected-error {{'init' is a member of the type; use assignment to initalize the value instead}} {{4-4= = }}
z.init(x: 0) // expected-error {{'init' is a member of the type; use assignment to initalize the value instead}} {{4-4= = }}
z.init() // expected-error {{'init' is a member of the type; use assignment to initalize the value instead}} {{4-4= = }}
z.init(proto: "") // expected-error {{'init' is a member of the type; use assignment to initalize the value instead}} {{4-4= = }}
var ci1a = z.init(required: 0) // expected-error {{'init' is a member of the type; use 'type(of: ...)' to initialize a new object of the same dynamic type}} {{14-14=type(of: }} {{15-15=)}}
var ci2a = z.init(x: 0) // expected-error {{'init' is a member of the type; use 'type(of: ...)' to initialize a new object of the same dynamic type}} {{14-14=type(of: }} {{15-15=)}}
var ci3a = z.init() // expected-error {{'init' is a member of the type; use 'type(of: ...)' to initialize a new object of the same dynamic type}} {{14-14=type(of: }} {{15-15=)}}
var ci4a = z.init(proto: "") // expected-error {{'init' is a member of the type; use 'type(of: ...)' to initialize a new object of the same dynamic type}} {{14-14=type(of: }} {{15-15=)}}
var ci1b = x(required: 0) // expected-error{{cannot call value of non-function type 'T'}}
var ci2b = x(x: 0) // expected-error{{cannot call value of non-function type 'T'}}
var ci3b = x() // expected-error{{cannot call value of non-function type 'T'}}{{15-17=}}
var ci4b = x(proto: "") // expected-error{{cannot call value of non-function type 'T'}}
var cm1 = y.init(required: 0)
var cm2 = y.init(x: 0) // expected-error{{'required' initializer}}
var cm3 = y.init() // expected-error{{'required' initializer}}
var cm4 = y.init(proto: "")
var cm1a = y.init(required: 0)
var cm2a = y.init(x: 0) // expected-error{{'required' initializer}}
var cm3a = y.init() // expected-error{{'required' initializer}}
var cm4a = y.init(proto: "")
var cs1 = T.init(required: 0)
var cs2 = T.init(x: 0) // expected-error{{'required' initializer}}
var cs3 = T.init() // expected-error{{'required' initializer}}
var cs4 = T.init(proto: "")
var cs5 = T.init(notfound: "") // expected-error{{incorrect argument label in call (have 'notfound:', expected 'proto:')}}
var csf1: (Double) -> T = T.init
var csf2: (Int) -> T = T.init // expected-error{{'required' initializer}}
var csf3: () -> T = T.init // expected-error{{'required' initializer}}
var csf4: (String) -> T = T.init
var cs1a = T(required: 0)
var cs2a = T(x: 0) // expected-error{{'required' initializer}}
var cs3a = T() // expected-error{{'required' initializer}}
var cs4a = T(proto: "")
}
class TestOverloadSets {
convenience init() {
self.init(5, 5) // expected-error{{extra argument in call}}
}
convenience init(a : Z0) { // expected-note{{candidate has partially matching parameter list (a: Z0)}}
self.init(42 as Int8) // expected-error{{no exact matches in call to initializer}}
}
init(value: Int) { /* ... */ } // expected-note{{candidate has partially matching parameter list (value: Int)}}
init(value: Double) { /* ... */ } // expected-note{{candidate has partially matching parameter list (value: Double)}}
}
class TestNestedExpr {
init() {}
init?(fail: Bool) {}
init(error: Bool) throws {}
convenience init(a: Int) {
let x: () = self.init() // expected-error {{initializer delegation ('self.init') cannot be nested in another statement}}
// expected-warning@-1 {{immutable value 'x' was never used; consider replacing with '_' or removing it}}
}
convenience init(b: Int) {
func use(_ x: ()) {}
use(self.init()) // expected-error {{initializer delegation ('self.init') cannot be nested in another expression}}
}
convenience init(c: Int) {
_ = ((), self.init()) // expected-error {{initializer delegation ('self.init') cannot be nested in another expression}}
}
convenience init(d: Int) {
let x: () = self.init(fail: true)! // expected-error {{initializer delegation ('self.init') cannot be nested in another statement}}
// expected-warning@-1 {{immutable value 'x' was never used; consider replacing with '_' or removing it}}
}
convenience init(e: Int) {
func use(_ x: ()) {}
use(self.init(fail: true)!) // expected-error {{initializer delegation ('self.init') cannot be nested in another expression}}
}
convenience init(f: Int) {
_ = ((), self.init(fail: true)!) // expected-error {{initializer delegation ('self.init') cannot be nested in another expression}}
}
convenience init(g: Int) {
let x: () = try! self.init(error: true) // expected-error {{initializer delegation ('self.init') cannot be nested in another statement}}
// expected-warning@-1 {{immutable value 'x' was never used; consider replacing with '_' or removing it}}
}
convenience init(h: Int) {
func use(_ x: ()) {}
use(try! self.init(error: true)) // expected-error {{initializer delegation ('self.init') cannot be nested in another expression}}
}
convenience init(i: Int) {
_ = ((), try! self.init(error: true)) // expected-error {{initializer delegation ('self.init') cannot be nested in another expression}}
}
convenience init(j: Int) throws {
_ = {
try self.init(error: true)
// expected-error@-1 {{initializer delegation ('self.init') cannot be nested in another expression}}
}
_ = {
do {
try self.init(error: true)
// expected-error@-1 {{initializer delegation ('self.init') cannot be nested in another expression}}
}
}
defer {
try! self.init(error: true)
// expected-error@-1 {{initializer delegation ('self.init') cannot be nested in another expression}}
}
func local() throws {
try self.init(error: true)
// expected-error@-1 {{initializer delegation ('self.init') cannot be nested in another expression}}
}
}
convenience init(k: Int) {
func use(_ x: Any...) {}
use(self.init()) // expected-error {{initializer delegation ('self.init') cannot be nested in another expression}}
}
}
class TestNestedExprSub : TestNestedExpr {
init(a: Int) {
let x: () = super.init() // expected-error {{initializer chaining ('super.init') cannot be nested in another statement}}
// expected-warning@-1 {{immutable value 'x' was never used; consider replacing with '_' or removing it}}
}
init(b: Int) {
func use(_ x: ()) {}
use(super.init()) // expected-error {{initializer chaining ('super.init') cannot be nested in another expression}}
}
init(c: Int) {
_ = ((), super.init()) // expected-error {{initializer chaining ('super.init') cannot be nested in another expression}}
}
init(d: Int) {
let x: () = super.init(fail: true)! // expected-error {{initializer chaining ('super.init') cannot be nested in another statement}}
// expected-warning@-1 {{immutable value 'x' was never used; consider replacing with '_' or removing it}}
}
init(e: Int) {
func use(_ x: ()) {}
use(super.init(fail: true)!) // expected-error {{initializer chaining ('super.init') cannot be nested in another expression}}
}
init(f: Int) {
_ = ((), super.init(fail: true)!) // expected-error {{initializer chaining ('super.init') cannot be nested in another expression}}
}
init(g: Int) {
let x: () = try! super.init(error: true) // expected-error {{initializer chaining ('super.init') cannot be nested in another statement}}
// expected-warning@-1 {{immutable value 'x' was never used; consider replacing with '_' or removing it}}
}
init(h: Int) {
func use(_ x: ()) {}
use(try! super.init(error: true)) // expected-error {{initializer chaining ('super.init') cannot be nested in another expression}}
}
init(i: Int) {
_ = ((), try! super.init(error: true)) // expected-error {{initializer chaining ('super.init') cannot be nested in another expression}}
}
init(j: Int) {
func use(_ x: Any...) {}
use(super.init()) // expected-error {{initializer chaining ('super.init') cannot be nested in another expression}}
}
}
class TestOptionalTry {
init() throws {}
convenience init(a: Int) { // expected-note {{propagate the failure with 'init?'}} {{19-19=?}}
try? self.init() // expected-error {{a non-failable initializer cannot use 'try?' to delegate to another initializer}}
// expected-note@-1 {{force potentially-failing result with 'try!'}} {{5-9=try!}}
}
init?(fail: Bool) throws {}
convenience init(failA: Int) { // expected-note {{propagate the failure with 'init?'}} {{19-19=?}}
try? self.init(fail: true)! // expected-error {{a non-failable initializer cannot use 'try?' to delegate to another initializer}}
// expected-note@-1 {{force potentially-failing result with 'try!'}} {{5-9=try!}}
}
convenience init(failB: Int) { // expected-note {{propagate the failure with 'init?'}} {{19-19=?}}
try! self.init(fail: true) // expected-error {{a non-failable initializer cannot delegate to failable initializer 'init(fail:)' written with 'init?'}}
// expected-note@-1 {{force potentially-failing result with '!'}} {{31-31=!}}
}
convenience init(failC: Int) {
try! self.init(fail: true)! // okay
}
convenience init?(failD: Int) {
try? self.init(fail: true) // okay
}
convenience init?(failE: Int) {
try! self.init(fail: true) // okay
}
convenience init?(failF: Int) {
try! self.init(fail: true)! // okay
}
convenience init?(failG: Int) {
try? self.init(fail: true) // okay
}
}
class TestOptionalTrySub : TestOptionalTry {
init(a: Int) { // expected-note {{propagate the failure with 'init?'}} {{7-7=?}}
try? super.init() // expected-error {{a non-failable initializer cannot use 'try?' to chain to another initializer}}
// expected-note@-1 {{force potentially-failing result with 'try!'}} {{5-9=try!}}
}
}
struct X { init() {} }
func +(lhs: X, rhs: X) -> X { return lhs }
func testInsideOperator(x: X) {
x.init() + x // expected-error {{'init' is a member of the type; use 'type(of: ...)' to initialize a new object of the same dynamic type}} {{3-3=type(of: }} {{4-4=)}}
x + x.init() // expected-error {{'init' is a member of the type; use 'type(of: ...)' to initialize a new object of the same dynamic type}} {{7-7=type(of: }} {{8-8=)}}
x.init() + x.init() // expected-error {{'init' is a member of the type; use 'type(of: ...)' to initialize a new object of the same dynamic type}} {{3-3=type(of: }} {{4-4=)}}
// expected-error@-1 {{'init' is a member of the type; use 'type(of: ...)' to initialize a new object of the same dynamic type}} {{14-14=type(of: }} {{15-15=)}}
}
struct Y {
var x: X
let x2: X
init() {
x.init() // expected-error {{'init' is a member of the type; use assignment to initalize the value instead}} {{6-6= = }}
foo(x.init()) // expected-error {{'init' is a member of the type; use 'type(of: ...)' to initialize a new object of the same dynamic type}} {{9-9=type(of: }} {{10-10=)}}
}
func foo(_: X) {}
func asFunctionReturn() -> X {
var a = X()
return a.init() // expected-error {{'init' is a member of the type; use 'type(of: ...)' to initialize a new object of the same dynamic type}} {{12-12=type(of: }} {{13-13=)}}
}
}
struct MultipleMemberAccesses {
var y: Y
let y2: Y
init() {
y = Y()
y2 = Y()
y.x.init() // expected-error {{'init' is a member of the type; use assignment to initalize the value instead}} {{8-8= = }}
y2.x2.init() // expected-error {{'init' is a member of the type; use 'type(of: ...)' to initialize a new object of the same dynamic type}} {{5-5=type(of: }} {{10-10=)}}
}
}
func sr10670() {
struct S {
init(_ x: inout String) {} // expected-note {{candidate expects in-out value of type 'String' for parameter #1}}
init(_ x: inout [Int]) {} // expected-note {{candidate expects in-out value of type '[Int]' for parameter #1}}
}
var a = 0
S.init(&a) // expected-error {{no exact matches in call to initializer}}
}
|
apache-2.0
|
38ad78e3eaa88dcd77933a91e9adca1c
| 35.297101 | 190 | 0.619335 | 3.35499 | false | false | false | false |
naokits/my-programming-marathon
|
iPhoneSensorDemo/Pods/RxCocoa/RxCocoa/iOS/UITextView+Rx.swift
|
7
|
1928
|
//
// UITextView+Rx.swift
// RxCocoa
//
// Created by Yuta ToKoRo on 7/19/15.
// Copyright © 2015 Krunoslav Zaher. All rights reserved.
//
#if os(iOS) || os(tvOS)
import Foundation
import UIKit
#if !RX_NO_MODULE
import RxSwift
#endif
extension UITextView {
/**
Factory method that enables subclasses to implement their own `rx_delegate`.
- returns: Instance of delegate proxy that wraps `delegate`.
*/
public override func rx_createDelegateProxy() -> RxScrollViewDelegateProxy {
return RxTextViewDelegateProxy(parentObject: self)
}
/**
Reactive wrapper for `text` property.
*/
public var rx_text: ControlProperty<String> {
let source: Observable<String> = Observable.deferred { [weak self] in
let text = self?.text ?? ""
let textChanged = self?.textStorage
// This project uses text storage notifications because
// that's the only way to catch autocorrect changes
// in all cases. Other suggestions are welcome.
.rx_didProcessEditingRangeChangeInLength
// This observe on is here because text storage
// will emit event while process is not completely done,
// so rebinding a value will cause an exception to be thrown.
.observeOn(MainScheduler.asyncInstance)
.map { _ in
return self?.textStorage.string ?? ""
}
?? Observable.empty()
return textChanged
.startWith(text)
.distinctUntilChanged()
}
let bindingObserver = UIBindingObserver(UIElement: self) { (textView, text: String) in
textView.text = text
}
return ControlProperty(values: source, valueSink: bindingObserver)
}
}
#endif
|
mit
|
eab517befea5fa1efb9f226ffd7d2325
| 28.646154 | 94 | 0.586923 | 5.19407 | false | false | false | false |
robconrad/fledger-common
|
FledgerCommon/services/models/StandardPersistenceEngine.swift
|
1
|
9048
|
//
// StandardPersistenceEngine.swift
// FledgerCommon
//
// Created by Robert Conrad on 10/4/15.
// Copyright © 2015 Robert Conrad. All rights reserved.
//
import SQLite
#if os(iOS)
import Parse
#elseif os(OSX)
import ParseOSX
#endif
class StandardPersistenceEngine<M where M: PFModel, M: SqlModel>: PersistenceEngine {
private let _modelType: ModelType
private let _fromPFObject: PFObject -> M
private let _fromRow: Row -> M
private let _table: SchemaType
private let _defaultOrder: SchemaType -> SchemaType
private let _baseFilter: SchemaType -> SchemaType
required init(
modelType: ModelType,
fromPFObject: PFObject -> M,
fromRow: Row -> M,
table: SchemaType,
defaultOrder: SchemaType -> SchemaType = { q in q.order(Fields.id.desc) },
baseFilter: SchemaType -> SchemaType = { q in q }
) {
self._modelType = modelType
self._fromPFObject = fromPFObject
self._table = table
self._fromRow = fromRow
self._defaultOrder = defaultOrder
self._baseFilter = baseFilter
}
func modelType() -> ModelType {
return _modelType
}
func fromPFObject(pf: PFObject) -> M {
return _fromPFObject(pf)
}
internal func table() -> SchemaType {
return _table
}
func withId(id: Int64) -> M? {
let filters = Filters()
filters.ids = [id]
return DatabaseSvc().db.pluck(baseQuery(filters)).map(_fromRow)
}
func all() -> [M] {
return select(nil)
}
func defaultOrder(query: SchemaType) -> SchemaType {
return _defaultOrder(query)
}
func baseFilter(query: SchemaType) -> SchemaType {
return _baseFilter(query)
}
func baseQuery(filters: Filters? = nil, limit: Bool = true) -> SchemaType {
var query = defaultOrder(baseFilter(table()))
if let f = filters {
query = f.toQuery(query, limit: limit, table: table())
}
return query
}
func select(filters: Filters?) -> [M] {
var elements: [M] = []
for row in DatabaseSvc().db.prepare(baseQuery(filters)) {
elements.append(_fromRow(row))
}
return elements
}
func count(filters: Filters?) -> Int {
return DatabaseSvc().db.scalar(baseQuery(filters, limit: false).count)
}
func insert(e: M) -> Int64? {
return insert(e, fromRemote: false)
}
internal func insert(e: M, fromRemote: Bool) -> Int64? {
var id: Int64?
if fromRemote {
assert(e.pf != nil, "pf may not be empty if insert is fromRemote")
}
do {
try DatabaseSvc().db.transaction { _ in
let modelId = try DatabaseSvc().db.run(self.table().insert(e.toSetters()))
id = modelId
try DatabaseSvc().db.run(DatabaseSvc().parse.insert([
Fields.model <- self.modelType().rawValue,
Fields.modelId <- modelId,
Fields.parseId <- e.pf?.objectId,
Fields.synced <- fromRemote,
Fields.deleted <- false,
Fields.updatedAt <- e.pf?.updatedAt.map { NSDateTime($0) }
]))
}
}
catch {
print("caught error")
return nil
}
if !fromRemote {
UserSvc().syncAllToRemoteInBackground()
}
return id
}
func update(e: M) -> Bool {
return update(e, fromRemote: false)
}
internal func update(e: M, fromRemote: Bool) -> Bool {
do {
try DatabaseSvc().db.transaction { _ in
let modelRows = try DatabaseSvc().db.run(self.table().filter(Fields.id == e.id!).update(e.toSetters()))
if modelRows == 1 {
let query: QueryType = DatabaseSvc().parse.filter(Fields.model == self.modelType().rawValue && Fields.modelId == e.id!)
var setters = [Fields.synced <- fromRemote]
if let parseId = e.pf?.objectId, updatedAt = e.pf?.updatedAt {
setters.append(Fields.parseId <- parseId)
setters.append(Fields.updatedAt <- NSDateTime(updatedAt))
}
if try DatabaseSvc().db.run(query.update(setters)) != 1 {
throw NSError(domain: "", code: 1, userInfo: nil)
}
}
else {
throw NSError(domain: "", code: 1, userInfo: nil)
}
}
}
catch {
print("caught error")
return false
}
if !fromRemote {
UserSvc().syncAllToRemoteInBackground()
}
return true
}
func delete(e: M) -> Bool {
return delete(e.id!)
}
func delete(id: Int64) -> Bool {
return delete(id, fromRemote: false)
}
internal func delete(id: Int64, fromRemote: Bool, updatedAt: NSDate? = nil) -> Bool {
do {
try DatabaseSvc().db.transaction { _ in
let modelRows = try DatabaseSvc().db.run(self.table().filter(Fields.id == id).delete())
if modelRows == 1 {
let query: QueryType = DatabaseSvc().parse.filter(Fields.model == self.modelType().rawValue && Fields.modelId == id)
var setters = [
Fields.synced <- fromRemote,
Fields.deleted <- true
]
if let date = updatedAt {
setters.append(Fields.updatedAt <- NSDateTime(date))
}
if try DatabaseSvc().db.run(query.update(setters)) != 1 {
throw NSError(domain: "", code: 1, userInfo: nil)
}
}
else {
throw NSError(domain: "", code: 1, userInfo: nil)
}
}
}
catch {
print("caught error")
return false
}
if !fromRemote {
UserSvc().syncAllToRemoteInBackground()
}
return true
}
func invalidate() {
// standard model always talks to db and thus doesn't require invalidation
}
func syncToRemote() {
let parseFilters = ParseFilters()
parseFilters.synced = false
parseFilters.modelType = modelType()
let parseModels = ParseSvc().select(parseFilters)
let modelFilters = Filters()
modelFilters.ids = Set(parseModels.filter { !$0.deleted }.map { $0.modelId })
for model in select(modelFilters) {
if let pf = ParseSvc().save(model) {
ParseSvc().markSynced(model.id!, modelType(), pf)
}
}
let deletedModels = parseModels.filter { $0.deleted }.map { DeletedModel(id: $0.modelId, parseId: $0.parseId!, modelType: self.modelType()) }
for model in deletedModels {
if let pf = ParseSvc().save(model) {
ParseSvc().markSynced(model.id, modelType(), pf)
}
}
}
func syncFromRemote() {
var pfObjects: [PFObject] = ParseSvc().remote(modelType(), updatedOnly: true) ?? []
// sort by date ascending so that we don't miss any if this gets interrupted and we try syncIncoming again
pfObjects.sortInPlace { ($0.updatedAt ?? NSDate()).compare($1.updatedAt!) == .OrderedAscending }
let models = pfObjects.map { self.fromPFObject($0) }
for i in 0..<pfObjects.count {
let model = models[i]
if model.id == nil {
if let id = insert(model, fromRemote: true) {
if (pfObjects[i]["deleted"] as? Bool) == true {
if !delete(id, fromRemote: true) {
fatalError(__FUNCTION__ + " failed to delete \(model)")
}
}
}
else {
fatalError(__FUNCTION__ + " failed to insert \(model)")
}
}
else {
if (pfObjects[i]["deleted"] as? Bool) == true {
if !delete(model.id!, fromRemote: true, updatedAt: pfObjects[i].updatedAt) {
fatalError(__FUNCTION__ + " failed to delete \(model)")
}
}
else {
if !update(model, fromRemote: true) {
fatalError(__FUNCTION__ + " failed to update \(model)")
}
}
}
}
invalidate()
}
}
|
mit
|
0de923fe7f9f1e6705c666aec05c0ac7
| 31.543165 | 149 | 0.497402 | 4.729221 | false | false | false | false |
zoonooz/ZFRippleButton
|
Classes/ZFRippleButton.swift
|
1
|
6829
|
//
// ZFRippleButton.swift
// ZFRippleButtonDemo
//
// Created by Amornchai Kanokpullwad on 6/26/14.
// Copyright (c) 2014 zoonref. All rights reserved.
//
import UIKit
import QuartzCore
@IBDesignable
open class ZFRippleButton: UIButton {
@IBInspectable open var ripplePercent: Float = 0.8 {
didSet {
setupRippleView()
}
}
@IBInspectable open var rippleColor: UIColor = UIColor(white: 0.9, alpha: 1) {
didSet {
rippleView.backgroundColor = rippleColor
}
}
@IBInspectable open var rippleBackgroundColor: UIColor = UIColor(white: 0.95, alpha: 1) {
didSet {
rippleBackgroundView.backgroundColor = rippleBackgroundColor
}
}
@IBInspectable open var buttonCornerRadius: Float = 0 {
didSet{
layer.cornerRadius = CGFloat(buttonCornerRadius)
}
}
@IBInspectable open var rippleOverBounds: Bool = false
@IBInspectable open var shadowRippleRadius: Float = 1
@IBInspectable open var shadowRippleEnable: Bool = true
@IBInspectable open var trackTouchLocation: Bool = false
@IBInspectable open var touchUpAnimationTime: Double = 0.6
let rippleView = UIView()
let rippleBackgroundView = UIView()
fileprivate var tempShadowRadius: CGFloat = 0
fileprivate var tempShadowOpacity: Float = 0
fileprivate var touchCenterLocation: CGPoint?
fileprivate var rippleMask: CAShapeLayer? {
get {
if !rippleOverBounds {
let maskLayer = CAShapeLayer()
maskLayer.path = UIBezierPath(roundedRect: bounds,
cornerRadius: layer.cornerRadius).cgPath
return maskLayer
} else {
return nil
}
}
}
convenience init() {
self.init(frame: CGRect.zero)
}
required public init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
setup()
}
public override init(frame: CGRect) {
super.init(frame: frame)
setup()
}
fileprivate func setup() {
setupRippleView()
rippleBackgroundView.backgroundColor = rippleBackgroundColor
rippleBackgroundView.frame = bounds
rippleBackgroundView.addSubview(rippleView)
rippleBackgroundView.alpha = 0
addSubview(rippleBackgroundView)
layer.shadowRadius = 0
layer.shadowOffset = CGSize(width: 0, height: 1)
layer.shadowColor = UIColor(white: 0.0, alpha: 0.5).cgColor
}
fileprivate func setupRippleView() {
let size: CGFloat = bounds.width * CGFloat(ripplePercent)
let x: CGFloat = (bounds.width/2) - (size/2)
let y: CGFloat = (bounds.height/2) - (size/2)
let corner: CGFloat = size/2
rippleView.backgroundColor = rippleColor
rippleView.frame = CGRect(x: x, y: y, width: size, height: size)
rippleView.layer.cornerRadius = corner
}
override open func beginTracking(_ touch: UITouch, with event: UIEvent?) -> Bool {
if trackTouchLocation {
touchCenterLocation = touch.location(in: self)
} else {
touchCenterLocation = nil
}
UIView.animate(withDuration: 0.1, delay: 0, options: UIViewAnimationOptions.allowUserInteraction, animations: {
self.rippleBackgroundView.alpha = 1
}, completion: nil)
rippleView.transform = CGAffineTransform(scaleX: 0.5, y: 0.5)
UIView.animate(withDuration: 0.7, delay: 0, options: [UIViewAnimationOptions.curveEaseOut, UIViewAnimationOptions.allowUserInteraction],
animations: {
self.rippleView.transform = CGAffineTransform.identity
}, completion: nil)
if shadowRippleEnable {
tempShadowRadius = layer.shadowRadius
tempShadowOpacity = layer.shadowOpacity
let shadowAnim = CABasicAnimation(keyPath:"shadowRadius")
shadowAnim.toValue = shadowRippleRadius
let opacityAnim = CABasicAnimation(keyPath:"shadowOpacity")
opacityAnim.toValue = 1
let groupAnim = CAAnimationGroup()
groupAnim.duration = 0.7
groupAnim.fillMode = kCAFillModeForwards
groupAnim.isRemovedOnCompletion = false
groupAnim.animations = [shadowAnim, opacityAnim]
layer.add(groupAnim, forKey:"shadow")
}
return super.beginTracking(touch, with: event)
}
override open func cancelTracking(with event: UIEvent?) {
super.cancelTracking(with: event)
animateToNormal()
}
override open func endTracking(_ touch: UITouch?, with event: UIEvent?) {
super.endTracking(touch, with: event)
animateToNormal()
}
fileprivate func animateToNormal() {
UIView.animate(withDuration: 0.1, delay: 0, options: UIViewAnimationOptions.allowUserInteraction, animations: {
self.rippleBackgroundView.alpha = 1
}, completion: {(success: Bool) -> () in
UIView.animate(withDuration: self.touchUpAnimationTime, delay: 0, options: UIViewAnimationOptions.allowUserInteraction, animations: {
self.rippleBackgroundView.alpha = 0
}, completion: nil)
})
UIView.animate(withDuration: 0.7, delay: 0,
options: [.curveEaseOut, .beginFromCurrentState, .allowUserInteraction],
animations: {
self.rippleView.transform = CGAffineTransform.identity
let shadowAnim = CABasicAnimation(keyPath:"shadowRadius")
shadowAnim.toValue = self.tempShadowRadius
let opacityAnim = CABasicAnimation(keyPath:"shadowOpacity")
opacityAnim.toValue = self.tempShadowOpacity
let groupAnim = CAAnimationGroup()
groupAnim.duration = 0.7
groupAnim.fillMode = kCAFillModeForwards
groupAnim.isRemovedOnCompletion = false
groupAnim.animations = [shadowAnim, opacityAnim]
self.layer.add(groupAnim, forKey:"shadowBack")
}, completion: nil)
}
override open func layoutSubviews() {
super.layoutSubviews()
setupRippleView()
if let knownTouchCenterLocation = touchCenterLocation {
rippleView.center = knownTouchCenterLocation
}
rippleBackgroundView.layer.frame = bounds
rippleBackgroundView.layer.mask = rippleMask
}
}
|
mit
|
120ffff5f6430d14b2fb684067ce4742
| 33.664975 | 149 | 0.606677 | 5.437102 | false | false | false | false |
zmarvin/EnjoyMusic
|
Pods/Macaw/Source/model/draw/RadialGradient.swift
|
1
|
450
|
import Foundation
open class RadialGradient: Gradient {
open let cx: Double
open let cy: Double
open let fx: Double
open let fy: Double
open let r: Double
public init(cx: Double = 0.5, cy: Double = 0.5, fx: Double = 0.5, fy: Double = 0.5, r: Double = 0.5, userSpace: Bool = false, stops: [Stop] = []) {
self.cx = cx
self.cy = cy
self.fx = fx
self.fy = fy
self.r = r
super.init(
userSpace: userSpace,
stops: stops
)
}
}
|
mit
|
ce66be7e44820f9cd2822c5630936c44
| 18.565217 | 148 | 0.626667 | 2.662722 | false | false | false | false |
NextFaze/FazeKit
|
Sources/FazeKit/Classes/ThreadSafeHashTable.swift
|
2
|
2966
|
//
// ThreadSafeHashTable.swift
// FazeKit
//
// Created by Shane Woolcock on 10/10/19.
//
import Foundation
open class ThreadSafeHashTable<ObjectType: AnyObject> {
public typealias HashTableType = NSHashTable<ObjectType>
private let lock = NSLock()
private let hashTable: HashTableType
open var timeout: TimeInterval
public init(_ hashTable: HashTableType, timeout: TimeInterval = 0) {
self.hashTable = hashTable
self.timeout = timeout
}
public init(weakObjects: Bool, timeout: TimeInterval = 0) {
self.hashTable = weakObjects ? HashTableType.weakObjects() : HashTableType()
self.timeout = timeout
}
open var allObjects: [ObjectType] {
var rv: [ObjectType] = []
self.lock.lockAndExecute(timeout: self.timeout) {
rv = self.hashTable.allObjects
}
return rv
}
open var count: Int {
var rv: Int = 0
self.lock.lockAndExecute(timeout: self.timeout) {
rv = self.hashTable.count
}
return rv
}
open func add(_ object: ObjectType?) {
guard let object = object else { return }
self.lock.lockAndExecute(timeout: self.timeout) {
self.hashTable.add(object)
}
}
open func add(contentsOf array: [ObjectType]) {
guard !array.isEmpty else { return }
self.lock.lockAndExecute(timeout: self.timeout) {
array.forEach { self.hashTable.add($0) }
}
}
open func remove(_ object: ObjectType?) {
guard let object = object else { return }
self.lock.lockAndExecute(timeout: self.timeout) {
self.hashTable.remove(object)
}
}
open func remove(contentsOf array: [ObjectType]) {
guard !array.isEmpty else { return }
self.lock.lockAndExecute(timeout: self.timeout) {
array.forEach { self.hashTable.remove($0) }
}
}
open func removeAllObjects() {
self.lock.lockAndExecute(timeout: self.timeout) {
self.hashTable.removeAllObjects()
}
}
open func contains(_ object: ObjectType?) -> Bool {
guard let object = object else { return false }
var rv: Bool = false
self.lock.lockAndExecute(timeout: self.timeout) {
rv = self.hashTable.contains(object)
}
return rv
}
open func contains(where predicate: (ObjectType) -> Bool) -> Bool {
var rv: Bool = false
self.lock.lockAndExecute(timeout: self.timeout) {
rv = self.hashTable.allObjects.contains(where: predicate)
}
return rv
}
open func first(where predicate: (ObjectType) -> Bool) -> ObjectType? {
var rv: ObjectType?
self.lock.lockAndExecute(timeout: self.timeout) {
rv = self.hashTable.allObjects.first(where: predicate)
}
return rv
}
}
|
apache-2.0
|
702e95f01de3ba7afa71fcd839d12e3d
| 28.078431 | 84 | 0.592717 | 4.336257 | false | false | false | false |
kyouko-taiga/anzen
|
Sources/AST/ModuleIdentifier.swift
|
1
|
1064
|
import SystemKit
import Utils
/// Enum representing a module identifier.
public enum ModuleIdentifier: Hashable {
/// Identifies Anzen's built-in module.
case builtin
/// Identifies Anzen's standard library module.
case stdlib
/// Identifies a module by its path.
case local(Path)
/// The qualified name corresponding to this module identifier.
public var qualifiedName: String {
switch self {
case .builtin : return "__builtin"
case .stdlib : return "__stdlib"
case .local(let path):
let relative = path.relative(to: .workingDirectory)
return relative.pathname
.dropLast(relative.fileExtension.map { $0.count + 1 } ?? 0)
.replacing("../", with: ".")
.replacing("/", with: ".")
}
}
public static func == (lhs: ModuleIdentifier, rhs: ModuleIdentifier) -> Bool {
switch (lhs, rhs) {
case (.builtin, .builtin): return true
case (.stdlib, .stdlib): return true
case (.local(let lhs), .local(let rhs)): return lhs == rhs
default: return false
}
}
}
|
apache-2.0
|
89b44a2199d95ec9faa799577db296a6
| 27.756757 | 80 | 0.638158 | 4.239044 | false | false | false | false |
imxieyi/iosu
|
iosu/StoryBoard/Renderer/SBCommand.swift
|
1
|
672
|
//
// SBCommand.swift
// iosu
//
// Created by xieyi on 2017/5/16.
// Copyright © 2017年 xieyi. All rights reserved.
//
import Foundation
import SpriteKit
protocol SBCAction {
func toAction()->SKAction
}
class SBCommand {
var type:StoryBoardCommand
var easing:Easing
var starttime:Int
var endtime:Int
var duration:Double
//var sprite:SKSpriteNode?
init(type:StoryBoardCommand,easing:Int,starttime:Int,endtime:Int) {
self.type=type
self.easing=SBCHelper.num2easing(easing)
self.starttime=starttime
self.endtime=endtime
duration=(Double(endtime)-Double(starttime))/1000
}
}
|
mit
|
8120631043066f9186a69f9246537b03
| 19.272727 | 71 | 0.668161 | 3.596774 | false | false | false | false |
DianQK/Flix
|
Example/Example/CalendarEvent/Options/EventOptionsViewController.swift
|
1
|
2846
|
//
// EventOptionsViewController.swift
// Example
//
// Created by DianQK on 29/10/2017.
// Copyright © 2017 DianQK. All rights reserved.
//
import UIKit
import RxSwift
import RxCocoa
import Flix
class EventOptionsProvider<T: EventOptionType>: AnimatableTableViewProvider {
func configureCell(_ tableView: UITableView, cell: UITableViewCell, indexPath: IndexPath, value: T) {
if !cell.hasConfigured {
cell.hasConfigured = true
let titleLabel = UILabel()
cell.contentView.addSubview(titleLabel)
titleLabel.translatesAutoresizingMaskIntoConstraints = false
titleLabel.leadingAnchor.constraint(equalTo: cell.contentView.leadingAnchor, constant: 20).isActive = true
titleLabel.centerYAnchor.constraint(equalTo: cell.contentView.centerYAnchor).isActive = true
titleLabel.text = value.name
if let selectedOption = selectedOption, selectedOption == value {
cell.accessoryType = .checkmark
}
}
}
func createValues() -> Observable<[T]> {
return Observable.just(options)
}
let options: [T]
let selectedOption: T?
init(options: [T], selectedOption: T?) {
self.options = options
self.selectedOption = selectedOption
}
typealias Value = T
typealias Cell = UITableViewCell
}
class EventOptionsViewController<T: EventOptionType>: TableViewController {
let selectedOption: T?
let optionSelected = PublishSubject<T>()
init(selectedOption: T?) {
self.selectedOption = selectedOption
super.init(nibName: nil, bundle: nil)
self.title = T.title
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func viewDidLoad() {
super.viewDidLoad()
let selectedOption = self.selectedOption
let providers = T.allOptions.map { EventOptionsProvider(options: $0, selectedOption: selectedOption) }
for provider in providers {
provider.event.modelSelected.asObservable()
.subscribe(onNext: { [weak self] (option) in
guard let `self` = self else { return }
self.optionSelected.onNext(option)
self.optionSelected.onCompleted()
self.navigationController?.popViewController(animated: true)
})
.disposed(by: disposeBag)
}
let sectionProviders = providers
.map { SpacingSectionProvider(providers: [$0], headerHeight: 18, footerHeight: 18) }
self.tableView.flix.build(sectionProviders)
}
override func viewWillDisappear(_ animated: Bool) {
super.viewDidDisappear(animated)
self.optionSelected.onCompleted()
}
}
|
mit
|
9bb98a7181dea5b1778442295422a45f
| 29.923913 | 118 | 0.64464 | 4.991228 | false | false | false | false |
apple/swift-nio
|
Tests/NIOPosixTests/PendingDatagramWritesManagerTests+XCTest.swift
|
1
|
2282
|
//===----------------------------------------------------------------------===//
//
// This source file is part of the SwiftNIO open source project
//
// Copyright (c) 2017-2021 Apple Inc. and the SwiftNIO project authors
// Licensed under Apache License v2.0
//
// See LICENSE.txt for license information
// See CONTRIBUTORS.txt for the list of SwiftNIO project authors
//
// SPDX-License-Identifier: Apache-2.0
//
//===----------------------------------------------------------------------===//
//
// PendingDatagramWritesManagerTests+XCTest.swift
//
import XCTest
///
/// NOTE: This file was generated by generate_linux_tests.rb
///
/// Do NOT edit this file directly as it will be regenerated automatically when needed.
///
extension PendingDatagramWritesManagerTests {
@available(*, deprecated, message: "not actually deprecated. Just deprecated to allow deprecated tests (which test deprecated functionality) without warnings")
static var allTests : [(String, (PendingDatagramWritesManagerTests) -> () throws -> Void)] {
return [
("testPendingWritesEmptyWritesWorkAndWeDontWriteUnflushedThings", testPendingWritesEmptyWritesWorkAndWeDontWriteUnflushedThings),
("testPendingWritesUsesVectorWriteOperationAndDoesntWriteTooMuch", testPendingWritesUsesVectorWriteOperationAndDoesntWriteTooMuch),
("testPendingWritesWorkWithPartialWrites", testPendingWritesWorkWithPartialWrites),
("testPendingWritesSpinCountWorksForSingleWrites", testPendingWritesSpinCountWorksForSingleWrites),
("testPendingWritesCancellationWorksCorrectly", testPendingWritesCancellationWorksCorrectly),
("testPendingWritesNoMoreThanWritevLimitIsWritten", testPendingWritesNoMoreThanWritevLimitIsWritten),
("testPendingWritesNoMoreThanWritevLimitIsWrittenInOneMassiveChunk", testPendingWritesNoMoreThanWritevLimitIsWrittenInOneMassiveChunk),
("testPendingWritesWorksWithManyEmptyWrites", testPendingWritesWorksWithManyEmptyWrites),
("testPendingWritesCloseDuringVectorWrite", testPendingWritesCloseDuringVectorWrite),
("testPendingWritesMoreThanWritevIOVectorLimit", testPendingWritesMoreThanWritevIOVectorLimit),
]
}
}
|
apache-2.0
|
37a641621e5fd6a5f1afc204f43bca69
| 52.069767 | 162 | 0.7156 | 5.210046 | false | true | false | false |
RobinChao/DKImagePickerController
|
DKImagePickerController/DKImagePickerController.swift
|
3
|
7714
|
//
// DKImagePickerController.swift
// DKImagePickerController
//
// Created by ZhangAo on 14-10-2.
// Copyright (c) 2014年 ZhangAo. All rights reserved.
//
import UIKit
import AssetsLibrary
// MARK: - Public DKAsset
/**
* An `DKAsset` object represents a photo or a video managed by the `DKImagePickerController`.
*/
public class DKAsset: NSObject {
/// Returns a CGImage of the representation that is appropriate for displaying full screen.
public private(set) lazy var fullScreenImage: UIImage? = {
return UIImage(CGImage: self.originalAsset?.defaultRepresentation().fullScreenImage().takeUnretainedValue())
}()
/// Returns a CGImage representation of the asset.
public private(set) lazy var fullResolutionImage: UIImage? = {
return UIImage(CGImage: self.originalAsset?.defaultRepresentation().fullResolutionImage().takeUnretainedValue())
}()
/// The url uniquely identifies an asset that is an image or a video.
public private(set) var url: NSURL?
/// It's a square thumbnail of the asset.
public private(set) var thumbnailImage: UIImage?
/// When the asset was an image, it's false. Otherwise true.
public private(set) var isVideo: Bool = false
/// play time duration(seconds) of a video.
public private(set) var duration: Double?
internal var isFromCamera: Bool = false
internal var originalAsset: ALAsset?
internal init(originalAsset: ALAsset) {
super.init()
self.thumbnailImage = UIImage(CGImage:originalAsset.thumbnail().takeUnretainedValue())
self.url = originalAsset.valueForProperty(ALAssetPropertyAssetURL) as? NSURL
self.originalAsset = originalAsset
let assetType = originalAsset.valueForProperty(ALAssetPropertyType) as! NSString
if assetType == ALAssetTypeVideo {
let duration = originalAsset.valueForProperty(ALAssetPropertyDuration) as! NSNumber
self.isVideo = true
self.duration = duration.doubleValue
}
}
internal init(image: UIImage) {
super.init()
self.isFromCamera = true
self.fullScreenImage = image
self.fullResolutionImage = image
self.thumbnailImage = image
}
// Compare two DKAssets
override public func isEqual(object: AnyObject?) -> Bool {
let another = object as! DKAsset!
if let url = self.url, anotherUrl = another.url {
return url.isEqual(anotherUrl)
} else {
return false
}
}
}
/**
* allPhotos: Get all photos assets in the assets group.
* allVideos: Get all video assets in the assets group.
* allAssets: Get all assets in the group.
*/
public enum DKImagePickerControllerAssetType : Int {
case allPhotos, allVideos, allAssets
}
internal extension UIViewController {
var imagePickerController: DKImagePickerController? {
get {
let nav = self.navigationController
if nav is DKImagePickerController {
return nav as? DKImagePickerController
} else {
return nil
}
}
}
}
// MARK: - Public DKImagePickerController
/**
* The `DKImagePickerController` class offers the all public APIs which will affect the UI.
*/
public class DKImagePickerController: UINavigationController {
/// The maximum count of assets which the user will be able to select.
public var maxSelectableCount = 999
/// The type of picker interface to be displayed by the controller.
public var assetType = DKImagePickerControllerAssetType.allAssets
/// Whether allows to select photos and videos at the same time.
public var allowMultipleType = true
/// The callback block is executed when user pressed the select button.
public var didSelectedAssets: ((assets: [DKAsset]) -> Void)?
/// The callback block is executed when user pressed the cancel button.
public var didCancelled: (() -> Void)?
/// It will have selected the specific assets.
public var defaultSelectedAssets: [DKAsset]? {
didSet {
if let defaultSelectedAssets = self.defaultSelectedAssets {
for (index, asset) in enumerate(defaultSelectedAssets) {
if asset.isFromCamera {
self.defaultSelectedAssets!.removeAtIndex(index)
}
}
self.selectedAssets = defaultSelectedAssets
self.updateDoneButtonTitle()
}
}
}
internal var selectedAssets = [DKAsset]()
private lazy var doneButton: UIButton = {
let button = UIButton.buttonWithType(UIButtonType.Custom) as! UIButton
button.setTitle("", forState: UIControlState.Normal)
button.setTitleColor(self.navigationBar.tintColor, forState: UIControlState.Normal)
button.reversesTitleShadowWhenHighlighted = true
button.addTarget(self, action: "done", forControlEvents: UIControlEvents.TouchUpInside)
return button
}()
public convenience init() {
let rootVC = DKAssetGroupDetailVC()
self.init(rootViewController: rootVC)
rootVC.navigationItem.rightBarButtonItem = UIBarButtonItem(customView: self.doneButton)
rootVC.navigationItem.leftBarButtonItem = UIBarButtonItem(barButtonSystemItem: .Cancel,
target: self,
action: "dismiss")
}
deinit {
NSNotificationCenter.defaultCenter().removeObserver(self)
}
override public func viewDidLoad() {
super.viewDidLoad()
NSNotificationCenter.defaultCenter().addObserver(self, selector: "selectedImage:",
name: DKImageSelectedNotification,
object: nil)
NSNotificationCenter.defaultCenter().addObserver(self, selector: "unselectedImage:",
name: DKImageUnselectedNotification,
object: nil)
}
private func updateDoneButtonTitle() {
if self.selectedAssets.count > 0 {
self.doneButton.setTitle(DKImageLocalizedString.localizedStringForKey("select") + "(\(selectedAssets.count))", forState: UIControlState.Normal)
} else {
self.doneButton.setTitle("", forState: UIControlState.Normal)
}
self.doneButton.sizeToFit()
}
internal func dismiss() {
self.dismissViewControllerAnimated(true, completion: nil)
if let didCancelled = self.didCancelled {
didCancelled()
}
}
internal func done() {
self.dismissViewControllerAnimated(true, completion: nil)
if let didSelectedAssets = self.didSelectedAssets {
didSelectedAssets(assets: self.selectedAssets)
}
}
// MARK: - Notifications
internal func selectedImage(noti: NSNotification) {
if let asset = noti.object as? DKAsset {
selectedAssets.append(asset)
if asset.isFromCamera {
self.done()
} else {
updateDoneButtonTitle()
}
}
}
internal func unselectedImage(noti: NSNotification) {
if let asset = noti.object as? DKAsset {
selectedAssets.removeAtIndex(find(selectedAssets, asset)!)
updateDoneButtonTitle()
}
}
}
|
mit
|
78df670772e608312e748551080fcc4b
| 33.428571 | 155 | 0.622407 | 5.629197 | false | false | false | false |
athiercelin/ATSketchKit
|
ATSketchKit/ATUnistrokeTemplate.swift
|
1
|
2636
|
//
// ATUnistrokeTemplate.swift
// ATSketchKit
//
// Created by Arnaud Thiercelin on 12/31/15.
// Copyright © 2015 Arnaud Thiercelin. All rights reserved.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this software
// and associated documentation files (the "Software"), to deal in the Software without restriction,
// including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense,
// and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so,
// subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or substantial
// portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT
// NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
// IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE
// OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
import UIKit
class ATUnistrokeTemplate: NSObject {
var name = "Unnamed"
var points = [CGPoint]()
var recognizedPathWithRect: ((_ rect: CGRect) -> UIBezierPath)!
convenience init(json filePath: String) {
self.init()
let fileURL = URL(fileURLWithPath: filePath)
do {
let fileData = try Data(contentsOf: fileURL)
let jsonObject = try JSONSerialization.jsonObject(with: fileData, options: .mutableContainers) as! Dictionary <String, AnyObject>
self.name = jsonObject["name"] as! String
let jsonPoints = jsonObject["points"] as! [Dictionary <String, Double>]
for point in jsonPoints {
let x = point["x"]!
let y = point["y"]!
self.points.append(CGPoint(x: x, y: y))
}
} catch {
// Error handling here if necessary
}
}
override var description: String {
get {
return self.debugDescription
}
}
override var debugDescription: String {
get {
return "ATUnistrokeTemplate \n" +
"Name: \(self.name)\n" +
"Point: \(self.points)\n" +
"Clean Path Making Closure: \(String(describing: self.recognizedPathWithRect))\n"
}
}
}
|
mit
|
8bdbc04bf1a02bc71cd0c59d44d1b69c
| 37.75 | 141 | 0.636053 | 4.630931 | false | false | false | false |
kongmingstrap/ODDSessionDemo-iOS
|
Pods/OAuthSwift/OAuthSwift/OAuthSwiftClient.swift
|
2
|
6259
|
//
// OAuthSwiftClient.swift
// OAuthSwift
//
// Created by Dongri Jin on 6/21/14.
// Copyright (c) 2014 Dongri Jin. All rights reserved.
//
import Foundation
import Accounts
var dataEncoding: NSStringEncoding = NSUTF8StringEncoding
public class OAuthSwiftClient {
struct OAuth {
static let version = "1.0"
static let signatureMethod = "HMAC-SHA1"
}
var credential: OAuthSwiftCredential
init(consumerKey: String, consumerSecret: String) {
self.credential = OAuthSwiftCredential(consumer_key: consumerKey, consumer_secret: consumerSecret)
}
init(consumerKey: String, consumerSecret: String, accessToken: String, accessTokenSecret: String) {
self.credential = OAuthSwiftCredential(oauth_token: accessToken, oauth_token_secret: accessTokenSecret)
self.credential.consumer_key = consumerKey
self.credential.consumer_secret = consumerSecret
}
public func get(urlString: String, parameters: Dictionary<String, AnyObject>, success: OAuthSwiftHTTPRequest.SuccessHandler?, failure: OAuthSwiftHTTPRequest.FailureHandler?) {
self.request(urlString, method: "GET", parameters: parameters, success, failure)
}
public func post(urlString: String, parameters: Dictionary<String, AnyObject>, success: OAuthSwiftHTTPRequest.SuccessHandler?, failure: OAuthSwiftHTTPRequest.FailureHandler?) {
self.request(urlString, method: "POST", parameters: parameters, success, failure)
}
public func put(urlString: String, parameters: Dictionary<String, AnyObject>, success: OAuthSwiftHTTPRequest.SuccessHandler?, failure: OAuthSwiftHTTPRequest.FailureHandler?) {
self.request(urlString, method: "PUT", parameters: parameters, success, failure)
}
public func delete(urlString: String, parameters: Dictionary<String, AnyObject>, success: OAuthSwiftHTTPRequest.SuccessHandler?, failure: OAuthSwiftHTTPRequest.FailureHandler?) {
self.request(urlString, method: "DELETE", parameters: parameters, success, failure)
}
public func patch(urlString: String, parameters: Dictionary<String, AnyObject>, success: OAuthSwiftHTTPRequest.SuccessHandler?, failure: OAuthSwiftHTTPRequest.FailureHandler?) {
self.request(urlString, method: "PATCH", parameters: parameters, success, failure)
}
func request(url: String, method: String, parameters: Dictionary<String, AnyObject>, success: OAuthSwiftHTTPRequest.SuccessHandler?, failure: OAuthSwiftHTTPRequest.FailureHandler?) {
let url = NSURL(string: url)
let request = OAuthSwiftHTTPRequest(URL: url!, method: method, parameters: parameters)
request.headers = ["Authorization": OAuthSwiftClient.authorizationHeaderForMethod(method, url: url!, parameters: parameters, credential: self.credential)]
request.successHandler = success
request.failureHandler = failure
request.dataEncoding = dataEncoding
request.encodeParameters = true
request.start()
}
class func authorizationHeaderForMethod(method: String, url: NSURL, parameters: Dictionary<String, AnyObject>, credential: OAuthSwiftCredential) -> String {
var authorizationParameters = Dictionary<String, AnyObject>()
authorizationParameters["oauth_version"] = OAuth.version
authorizationParameters["oauth_signature_method"] = OAuth.signatureMethod
authorizationParameters["oauth_consumer_key"] = credential.consumer_key
authorizationParameters["oauth_timestamp"] = String(Int64(NSDate().timeIntervalSince1970))
authorizationParameters["oauth_nonce"] = (NSUUID().UUIDString as NSString).substringToIndex(8)
if (credential.oauth_token != ""){
authorizationParameters["oauth_token"] = credential.oauth_token
}
for (key, value: AnyObject) in parameters {
if key.hasPrefix("oauth_") {
authorizationParameters.updateValue(value, forKey: key)
}
}
let combinedParameters = authorizationParameters.join(parameters)
let finalParameters = combinedParameters
authorizationParameters["oauth_signature"] = self.signatureForMethod(method, url: url, parameters: finalParameters, credential: credential)
var parameterComponents = authorizationParameters.urlEncodedQueryStringWithEncoding(dataEncoding).componentsSeparatedByString("&") as [String]
parameterComponents.sort { $0 < $1 }
var headerComponents = [String]()
for component in parameterComponents {
let subcomponent = component.componentsSeparatedByString("=") as [String]
if subcomponent.count == 2 {
headerComponents.append("\(subcomponent[0])=\"\(subcomponent[1])\"")
}
}
return "OAuth " + ", ".join(headerComponents)
}
class func signatureForMethod(method: String, url: NSURL, parameters: Dictionary<String, AnyObject>, credential: OAuthSwiftCredential) -> String {
var tokenSecret: NSString = ""
tokenSecret = credential.oauth_token_secret.urlEncodedStringWithEncoding(dataEncoding)
let encodedConsumerSecret = credential.consumer_secret.urlEncodedStringWithEncoding(dataEncoding)
let signingKey = "\(encodedConsumerSecret)&\(tokenSecret)"
var parameterComponents = parameters.urlEncodedQueryStringWithEncoding(dataEncoding).componentsSeparatedByString("&") as [String]
parameterComponents.sort { $0 < $1 }
let parameterString = "&".join(parameterComponents)
let encodedParameterString = parameterString.urlEncodedStringWithEncoding(dataEncoding)
let encodedURL = url.absoluteString!.urlEncodedStringWithEncoding(dataEncoding)
let signatureBaseString = "\(method)&\(encodedURL)&\(encodedParameterString)"
let key = signingKey.dataUsingEncoding(NSUTF8StringEncoding)!
let msg = signatureBaseString.dataUsingEncoding(NSUTF8StringEncoding)!
let sha1 = HMAC.sha1(key: key, message: msg)!
return sha1.base64EncodedStringWithOptions(nil)
}
}
|
apache-2.0
|
18e7722f78c5ef9d45c3fe45b2318104
| 47.146154 | 186 | 0.703307 | 5.633663 | false | false | false | false |
Snowy1803/BreakBaloon-mobile
|
BreakBaloon/BBStore/FileSaveHelper.swift
|
1
|
5335
|
//
// FileSaveHelper.swift
// BreakBaloon
//
// Created by Emil on 27/06/2016.
// Copyright © 2016 Snowy_1803. All rights reserved.
//
import Foundation
import UIKit
class FileSaveHelper {
fileprivate enum FileErrors: Error {
case fileNotSaved
case imageNotConvertedToData
case fileNotRead
case fileNotFound
}
enum FileExtension: String {
case none = ""
case txt = ".txt"
case bbtheme = ".bbtheme"
case bbtc = ".bbtc"
case png = ".png"
case gif = ".gif"
case wav = ".wav"
case m4a = ".m4a"
case zip = ".zip"
case jar = ".jar"
case json = ".json"
}
private let directory: FileManager.SearchPathDirectory
private let directoryPath: String
private let fileManager = FileManager.default
private let fileName: String
private let filePath: String
let fullyQualifiedPath: String
private let subDirectory: String
var fileExists: Bool {
fileManager.fileExists(atPath: fullyQualifiedPath)
}
var directoryExists: Bool {
var isDir = ObjCBool(true)
return fileManager.fileExists(atPath: filePath, isDirectory: &isDir)
}
init(fileName: String, fileExtension: FileExtension, subDirectory: String?, directory: FileManager.SearchPathDirectory) {
self.fileName = fileName + fileExtension.rawValue
self.subDirectory = (subDirectory == nil ? "" : "/\(subDirectory!)")
self.directory = directory
directoryPath = NSSearchPathForDirectoriesInDomains(directory, .userDomainMask, true)[0]
filePath = directoryPath + self.subDirectory
fullyQualifiedPath = "\(filePath)/\(self.fileName)"
createDirectory()
}
convenience init(fileName: String, fileExtension: FileExtension, subDirectory: String?) {
self.init(fileName: fileName, fileExtension: fileExtension, subDirectory: subDirectory, directory: .documentDirectory)
}
convenience init(fileName: String, fileExtension: FileExtension) {
self.init(fileName: fileName, fileExtension: fileExtension, subDirectory: nil)
}
private func createDirectory() {
if !directoryExists {
do {
try fileManager.createDirectory(atPath: filePath, withIntermediateDirectories: false, attributes: nil)
} catch {
print("An error occured when creating directory")
}
}
}
func saveFile(string fileContents: String) throws {
do {
try fileContents.write(toFile: fullyQualifiedPath, atomically: true, encoding: String.Encoding.utf8)
} catch {
throw error
}
}
func saveFile(image: UIImage) throws {
guard let data = image.pngData() else {
throw FileErrors.imageNotConvertedToData
}
if !fileManager.createFile(atPath: fullyQualifiedPath, contents: data, attributes: nil) {
throw FileErrors.fileNotSaved
}
}
func saveFile(data: Data) throws {
if !fileManager.createFile(atPath: fullyQualifiedPath, contents: data, attributes: nil) {
throw FileErrors.fileNotSaved
}
print("Saved file!")
}
func getContentsOfFile() throws -> String {
guard fileExists else {
throw FileErrors.fileNotFound
}
var returnString: String
do {
returnString = try String(contentsOfFile: fullyQualifiedPath, encoding: String.Encoding.utf8)
} catch {
throw FileErrors.fileNotRead
}
return returnString
}
func getImage() throws -> UIImage {
guard fileExists else {
throw FileErrors.fileNotFound
}
guard let image = UIImage(contentsOfFile: fullyQualifiedPath) else {
throw FileErrors.fileNotRead
}
return image
}
func getData() throws -> Data {
guard fileExists else {
throw FileErrors.fileNotFound
}
guard let data = try? Data(contentsOf: URL(fileURLWithPath: fullyQualifiedPath)) else {
throw FileErrors.fileNotRead
}
return data
}
func download(_ URL: Foundation.URL, completion: @escaping (Error?) -> Void) {
createDirectory()
let sessionConfig = URLSessionConfiguration.default
let session = URLSession(configuration: sessionConfig, delegate: nil, delegateQueue: nil)
var request = URLRequest(url: URL)
request.httpMethod = "GET"
let task = session.dataTask(with: request) { data, response, error in
if let error = error {
// Failure
print("DL Failure")
print(error)
completion(error)
return
}
// Success
let statusCode = (response as? HTTPURLResponse)?.statusCode ?? -1
print("Success: \(statusCode)")
do {
try self.saveFile(data: data!)
completion(nil)
} catch {
print(error)
completion(error)
}
}
task.resume()
}
}
|
mit
|
5046fcf46e0dd1bd6f61657fbaee9cac
| 30.56213 | 126 | 0.592988 | 5.133782 | false | false | false | false |
tristanchu/FlavorFinder
|
FlavorFinder/FlavorFinder/TextUtils.swift
|
1
|
772
|
//
// TextUtils.swift
// FlavorFinder
//
// Created by Jaki Kimball on 2/15/16.
// Copyright © 2016 TeamFive. All rights reserved.
//
import Foundation
import UIKit
/* emptyBackgroundText
- returns a UILabel for when there is no data to display that is centered in view
- recommended for calling VC to set view background to the returned label
- text = text to display
*/
func emptyBackgroundText(text: String, view: UIView) -> UILabel {
let noDataLabel: UILabel = UILabel(frame: CGRectMake(
0, 0, view.bounds.size.width,
view.bounds.size.height))
noDataLabel.text = text
noDataLabel.textColor = EMPTY_SET_TEXT_COLOR
noDataLabel.textAlignment = NSTextAlignment.Center
noDataLabel.font = EMPTY_SET_FONT
return noDataLabel
}
|
mit
|
13f2ad224ed4abe7f5a68ea3057eee87
| 28.692308 | 82 | 0.722438 | 3.994819 | false | false | false | false |
lkzhao/Hero
|
Examples/AppStoreCardExample.swift
|
1
|
10081
|
import UIKit
import Hero
import CollectionKit
/*:
# App Store Transition
This is a much more advanced transition mimicking the iOS 11 App Store.
It is intended to demostrate Hero's ability in creating an advance transition.
It does not look 100% like the app store and the article page currently doesn't scroll.
There are a few advance technique that is used in this example:
1. Interactive transition
When dismissing, a pan gesture recognizer is used to adjust the progress of the transition.
When user lift its finger, we determine whether or not we should cancel or finish the
transition by how far the user have moved and how fast the user is moving.
See `@objc func handlePan(gr: UIPanGestureRecognizer)` down below for detail.
2. The `.useNoSnapshot` modifier
Whenever this modifier is used on a view, Hero won't create snapshot for that view during
the transition. Instead, hero will grab the view from its superview, insert it into the
transition container view, and use it directly during the transition.
A few things to point out when using `.useNoSnapshot`:
1. It improves the performance a lot! since snapshot takes a long time to create.
2. It doesn't work with auto layout.
This is because Hero will remove the view from its original view hierarchy.
Therefore, breaking all the constraints.
3. Becareful of when to layout the cell. Do not set the `frame` of the cell when Hero is
using it for transition. Otherwise it will create weird effect during the transition.
If you are using `layoutSubviews` to layout a child view with `.useNoSnapshot`, first check
whether or not the child view is still your child by verifying `childView.superview == self`
before actually setting the frame of the child view. This way, you won't accidentally
modify the child view's frame during the transition. The child view's superview
will not be the original superview during a transiton, but when it finishes, Hero
will insert the view back to its original view hierarchy.
3. Setting `hero.modalAnimationType` to `.none`
without this, a fade animation will be applied to the destination root view.
Since we use a visual effect view as our background and applied `.fade` hero modifier manually,
we don't need the builtin fade animation anymore. Also when dismissing,
we don't want the background view to fade in, instead, we want it to be opaque through
out the transition.
*/
class CardView: UIView {
let titleLabel = UILabel()
let subtitleLabel = UILabel()
let imageView = UIImageView(image: #imageLiteral(resourceName: "Unsplash6"))
let visualEffectView = UIVisualEffectView(effect: UIBlurEffect(style: .light))
required init?(coder aDecoder: NSCoder) { fatalError() }
override init(frame: CGRect) {
super.init(frame: frame)
clipsToBounds = true
titleLabel.font = UIFont.boldSystemFont(ofSize: 32)
subtitleLabel.font = UIFont.systemFont(ofSize: 17)
imageView.contentMode = .scaleAspectFill
addSubview(imageView)
addSubview(visualEffectView)
addSubview(titleLabel)
addSubview(subtitleLabel)
}
override func layoutSubviews() {
super.layoutSubviews()
imageView.frame = bounds
visualEffectView.frame = CGRect(x: 0, y: 0, width: bounds.width, height: 90)
titleLabel.frame = CGRect(x: 20, y: 20, width: bounds.width - 40, height: 30)
subtitleLabel.frame = CGRect(x: 20, y: 50, width: bounds.width - 40, height: 30)
}
}
class RoundedCardWrapperView: UIView {
let cardView = CardView()
var isTouched: Bool = false {
didSet {
var transform = CGAffineTransform.identity
if isTouched { transform = transform.scaledBy(x: 0.96, y: 0.96) }
UIView.animate(withDuration: 0.3, delay: 0, usingSpringWithDamping: 0.8, initialSpringVelocity: 0, options: [], animations: {
self.transform = transform
}, completion: nil)
}
}
required init?(coder aDecoder: NSCoder) { fatalError() }
override init(frame: CGRect) {
super.init(frame: frame)
cardView.layer.cornerRadius = 16
layer.shadowColor = UIColor.black.cgColor
layer.shadowRadius = 12
layer.shadowOpacity = 0.15
layer.shadowOffset = CGSize(width: 0, height: 8)
addSubview(cardView)
}
override func layoutSubviews() {
super.layoutSubviews()
if cardView.superview == self {
// this is necessary because we used `.useNoSnapshot` modifier on cardView.
// we don't want cardView to be resized when Hero is using it for transition
cardView.frame = bounds
}
layer.shadowPath = UIBezierPath(roundedRect: bounds, cornerRadius: layer.cornerRadius).cgPath
}
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
super.touchesBegan(touches, with: event)
isTouched = true
}
override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
super.touchesEnded(touches, with: event)
isTouched = false
}
override func touchesCancelled(_ touches: Set<UITouch>, with event: UIEvent?) {
super.touchesCancelled(touches, with: event)
isTouched = false
}
}
class AppStoreViewController1: ExampleBaseViewController {
let collectionView = CollectionView()
override func viewDidLoad() {
super.viewDidLoad()
collectionView.delaysContentTouches = false
view.insertSubview(collectionView, belowSubview: dismissButton)
setupCollection()
}
func setupCollection() {
let dataSource = ArrayDataSource<Int>(data: Array(0..<10))
let viewSource = ClosureViewSource { (view: RoundedCardWrapperView, data: Int, index) in
view.cardView.titleLabel.text = "Hero"
view.cardView.subtitleLabel.text = "App Store Card Transition"
view.cardView.imageView.image = UIImage(named: "Unsplash\(data)")
}
let sizeSource = { (i: Int, data: Int, size: CGSize) -> CGSize in
return CGSize(width: size.width, height: size.width + 20)
}
let provider = BasicProvider<Int, RoundedCardWrapperView>(
dataSource: dataSource,
viewSource: viewSource,
sizeSource: sizeSource,
layout: FlowLayout(spacing: 30).inset(by: UIEdgeInsets(top: 100, left: 20, bottom: 30, right: 20))
)
provider.tapHandler = { (context) in
self.cellTapped(cell: context.view, data: context.data)
}
collectionView.provider = provider
}
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
collectionView.frame = view.bounds
}
func cellTapped(cell: RoundedCardWrapperView, data: Int) {
// MARK: Hero configuration
let cardHeroId = "card\(data)"
cell.cardView.hero.modifiers = [.useNoSnapshot, .spring(stiffness: 250, damping: 25)]
cell.cardView.hero.id = cardHeroId
let vc = AppStoreViewController2()
vc.hero.isEnabled = true
vc.hero.modalAnimationType = .none
vc.cardView.hero.id = cardHeroId
vc.cardView.hero.modifiers = [.useNoSnapshot, .spring(stiffness: 250, damping: 25)]
vc.cardView.imageView.image = UIImage(named: "Unsplash\(data)")
vc.contentCard.hero.modifiers = [.source(heroID: cardHeroId), .spring(stiffness: 250, damping: 25)]
vc.contentView.hero.modifiers = [.useNoSnapshot, .forceAnimate, .spring(stiffness: 250, damping: 25)]
vc.visualEffectView.hero.modifiers = [.fade, .useNoSnapshot]
present(vc, animated: true, completion: nil)
}
}
class AppStoreViewController2: ExampleBaseViewController {
let visualEffectView = UIVisualEffectView(effect: UIBlurEffect(style: .light))
let contentCard = UIView()
let cardView = CardView()
let contentView = UILabel()
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = .clear
view.addSubview(visualEffectView)
cardView.titleLabel.text = "Hero 2"
cardView.subtitleLabel.text = "App Store Card Transition"
contentView.numberOfLines = 0
contentView.text = """
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Praesent neque est, hendrerit vitae nibh ultrices, accumsan elementum ante. Phasellus fringilla sapien non lorem consectetur, in ullamcorper tortor condimentum. Nulla tincidunt iaculis maximus. Sed ut urna urna. Nulla at sem vel neque scelerisque imperdiet. Donec ornare luctus dapibus. Donec aliquet ante augue, at pellentesque ipsum mollis eget. Cras vulputate mauris ac eleifend sollicitudin. Vivamus ut posuere odio. Suspendisse vulputate sem vel felis vehicula iaculis. Fusce sagittis, eros quis consequat tincidunt, arcu nunc ornare nulla, non egestas dolor ex at ipsum. Cras et massa sit amet quam imperdiet viverra. Mauris vitae finibus nibh, ac vulputate sapien.
"""
if #available(iOS 13.0, tvOS 13, *) {
contentCard.backgroundColor = .systemBackground
} else {
contentCard.backgroundColor = .white
}
contentCard.clipsToBounds = true
contentCard.addSubview(contentView)
contentCard.addSubview(cardView)
view.addSubview(contentCard)
// add a pan gesture recognizer for the interactive dismiss transition
view.addGestureRecognizer(UIPanGestureRecognizer(target: self, action: #selector(handlePan(gr:))))
}
@objc func handlePan(gr: UIPanGestureRecognizer) {
let translation = gr.translation(in: view)
switch gr.state {
case .began:
dismiss(animated: true, completion: nil)
case .changed:
Hero.shared.update(translation.y / view.bounds.height)
default:
let velocity = gr.velocity(in: view)
if ((translation.y + velocity.y) / view.bounds.height) > 0.5 {
Hero.shared.finish()
} else {
Hero.shared.cancel()
}
}
}
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
let bounds = view.bounds
visualEffectView.frame = bounds
contentCard.frame = bounds
cardView.frame = CGRect(x: 0, y: 0, width: bounds.width, height: bounds.width)
contentView.frame = CGRect(x: 20, y: bounds.width + 20, width: bounds.width - 40, height: bounds.height - bounds.width - 20)
}
}
|
mit
|
b07f2d9ae9454bc91f389f5dc8793558
| 37.624521 | 732 | 0.717092 | 4.429262 | false | false | false | false |
priyax/RecipeRater
|
RecipeRater/RecipeRater/MealViewController.swift
|
1
|
4548
|
//
// MealViewController.swift
// RecipeRater
//
// Created by Priya Xavier on 9/14/16.
// Copyright © 2016 Guild/SA. All rights reserved.
//
import UIKit
class MealViewController: UIViewController, UITextFieldDelegate, UIImagePickerControllerDelegate, UINavigationControllerDelegate {
// MARK: Properties
@IBOutlet weak var nameTextField: UITextField!
@IBOutlet weak var ratingControl: RatingControl!
@IBAction func cancel(_ sender: UIBarButtonItem) {
// Depending on style of presentation (modal or push presentation), this view controller needs to be dismissed in two different ways.
let isPresentingInAddMealMode = presentingViewController is UINavigationController
if isPresentingInAddMealMode {
dismiss(animated: true, completion: nil)
}
else {
navigationController!.popViewController(animated: true)
}
}
@IBOutlet weak var save: UIBarButtonItem!
/*
This value is either passed by `MealTableViewController` in `prepareForSegue(_:sender:)`
or constructed as part of adding a new meal.
*/
var meal: Meal?
// MARK: UITextFieldDelegate
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
nameTextField.resignFirstResponder()
return true
}
func textFieldDidEndEditing(_ textField: UITextField) {
checkValidMealName()
navigationItem.title = textField.text
}
func textFieldDidBeginEditing(_ textField: UITextField) {
// Disable the Save button while editing.
save.isEnabled = false
}
func checkValidMealName() {
// Disable the Save button if the text field is empty.
let text = nameTextField.text ?? ""
save.isEnabled = !text.isEmpty
}
@IBOutlet weak var photoImageView: UIImageView!
// MARK: Navigation
// This method lets you configure a view controller before it's presented.
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if save === sender as! UIBarButtonItem {
let name = nameTextField.text ?? ""
let photo = photoImageView.image
let rating = ratingControl.rating
// Set the meal to be passed to MealTableViewController after the unwind segue.
meal = Meal(name: name, photo: photo, rating: rating)
}
}
// MARK: Action
@IBAction func selectImageFromPhotoLibrary(_ sender: UITapGestureRecognizer) {
// Hide the keyboard.
nameTextField.resignFirstResponder()
// UIImagePickerController is a view controller that lets a user pick media from their photo library.
let imagePickerController = UIImagePickerController()
// Only allow photos to be picked, not taken.
imagePickerController.sourceType = .photoLibrary
// Make sure ViewController is notified when the user picks an image.
imagePickerController.delegate = self
present(imagePickerController, animated: true, completion: nil)
}
// MARK: UIImagePickerControllerDelegate
func imagePickerControllerDidCancel(_ picker: UIImagePickerController) {
// Dismiss the picker if the user canceled.
dismiss(animated: true, completion: nil)}
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any])
{// The info dictionary contains multiple representations of the image, and this uses the original.
let selectedImage = info[UIImagePickerControllerOriginalImage] as! UIImage
// Set photoImageView to display the selected image.
photoImageView.image = selectedImage
// Dismiss the picker.
dismiss(animated: true, completion: nil)
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
nameTextField.delegate = self
// Set up views if editing an existing Meal.
if let meal = meal {
navigationItem.title = meal.name
nameTextField.text = meal.name
photoImageView.image = meal.photo
ratingControl.rating = meal.rating
}
checkValidMealName()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
|
mit
|
ef20d6dda92458c0255a818998b962ef
| 33.44697 | 141 | 0.658896 | 5.762991 | false | false | false | false |
Natoto/SWIFTMIAPP
|
swiftmi/swiftmi/PostTableViewController.swift
|
1
|
10412
|
//
// PostTableViewController.swift
// swiftmi
//
// Created by yangyin on 15/3/23.
// Copyright (c) 2015year swiftmi. All rights reserved.
//
import UIKit
import Alamofire
import SwiftyJSON
import Kingfisher
class PostTableViewController: UITableViewController {
internal var data:[AnyObject] = [AnyObject]()
var loading:Bool = false
private func getDefaultData(){
let dalPost = PostDal()
let result = dalPost.getPostList()
if result != nil {
self.data = result!
self.tableView.reloadData()
}
}
override func viewDidLoad() {
super.viewDidLoad()
// self.view.backgroundColor = UIColor.greenColor()
self.tableView.estimatedRowHeight = 120;
self.tableView.rowHeight = UITableViewAutomaticDimension
//读取默认数据
getDefaultData()
self.tableView.addHeaderWithCallback{
self.loadData(0, isPullRefresh: true)
}
self.tableView.addFooterWithCallback{
if(self.data.count>0) {
let maxId = self.data.last!.valueForKey("postId") as! Int
self.loadData(maxId, isPullRefresh: false)
}
}
self.tableView.headerBeginRefreshing()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: - Table view data source
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
// #warning Potentially incomplete method implementation.
// Return the number of sections.
return 1
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// #warning Incomplete method implementation.
// Return the number of rows in the section.
return self.data.count
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
//let cell = self.tableView.dequeueReusableCellWithIdentifier("Cell") as! PostCell
let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) as! PostCell
let item: AnyObject = self.data[indexPath.row]
let commentCount = item.valueForKey("viewCount") as? Int
cell.commentCount.text = "\(commentCount!)"
let pubTime = item.valueForKey("createTime") as! Double
let createDate = NSDate(timeIntervalSince1970: pubTime)
cell.timeLabel.text = Utility.formatDate(createDate)
//println(item.valueForKey("commentCount") as? Int)
cell.title.text = item.valueForKey("title") as? String
cell.authorName.text = item.valueForKey("authorName") as? String
cell.channelName.text = item.valueForKey("channelName") as? String
cell.avatar.kf_setImageWithURL(NSURL(string: item.valueForKey("avatar") as! String+"-a80")!, placeholderImage: nil)
cell.avatar.layer.cornerRadius = 5
cell.avatar.layer.masksToBounds = true
// cell.avatar.set
// Configure the cell...
cell.selectionStyle = .None;
cell.updateConstraintsIfNeeded()
// cell.contentView.backgroundColor = UIColor.grayColor()
// cell.selectedBackgroundView = cell.containerView
return cell
}
override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) as! PostCell
cell.containerView.backgroundColor = UIColor(red: 0.85, green: 0.85, blue:0.85, alpha: 0.9)
}
var prototypeCell:PostCell?
private func configureCell(cell:PostCell,indexPath: NSIndexPath,isForOffscreenUse:Bool){
let item: AnyObject = self.data[indexPath.row]
cell.title.text = item.valueForKey("title") as? String
cell.channelName.text = item.valueForKey("channelName") as? String
cell.selectionStyle = .None;
}
override func tableView(tableView: UITableView, estimatedHeightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
if prototypeCell == nil
{
self.prototypeCell = self.tableView.dequeueReusableCellWithIdentifier("Cell") as? PostCell
}
self.configureCell(prototypeCell!, indexPath: indexPath, isForOffscreenUse: false)
self.prototypeCell?.setNeedsUpdateConstraints()
self.prototypeCell?.updateConstraintsIfNeeded()
self.prototypeCell?.setNeedsLayout()
self.prototypeCell?.layoutIfNeeded()
let size = self.prototypeCell!.contentView.systemLayoutSizeFittingSize(UILayoutFittingCompressedSize)
return size.height;
}
override func tableView(tableView: UITableView, willDisplayCell cell: UITableViewCell, forRowAtIndexPath indexPath: NSIndexPath) {
if indexPath.row == self.data.count-1 {
// self.tableView.footerBeginRefreshing()
// loadData(self.data[indexPath.row].valueForKey("postId") as! Int,isPullRefresh:false)
}
}
func loadData(maxId:Int,isPullRefresh:Bool){
if self.loading {
return
}
self.loading = true
Alamofire.request(Router.TopicList(maxId: maxId, count: 16)).responseJSON(options: NSJSONReadingOptions.AllowFragments) { (request, closureResponse, Result) -> Void in
self.loading = false
if(isPullRefresh){
self.tableView.headerEndRefreshing()
}
else{
self.tableView.footerEndRefreshing()
}
if Result.isFailure {
let alert = UIAlertView(title: "网络异常", message: "请检查网络设置", delegate: nil, cancelButtonTitle: "确定")
alert.show()
return
}
let json = Result.value //. .result.value
var result = JSON(json!)
if result["isSuc"].boolValue {
let items = result["result"].object as! [AnyObject]
if(items.count==0){
return
}
if(isPullRefresh){
let dalPost = PostDal()
dalPost.deleteAll()
dalPost.addPostList(items)
self.data.removeAll(keepCapacity: false)
}
for it in items {
self.data.append(it);
}
dispatch_async(dispatch_get_main_queue()) {
self.tableView.reloadData()
}
}
}
}
/*
// Override to support conditional editing of the table view.
override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool {
// Return NO if you do not want the specified item to be editable.
return true
}
*/
/*
// Override to support editing the table view.
override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
if editingStyle == .Delete {
// Delete the row from the data source
tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade)
} else if editingStyle == .Insert {
// Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
}
}
*/
/*
// 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
}
*/
@IBAction func addTopic(sender: UIButton) {
if KeychainWrapper.stringForKey("token") == nil {
//未登录
let loginController:LoginController = Utility.GetViewController("loginController")
self.navigationController?.pushViewController(loginController, animated: true)
}
}
override func shouldPerformSegueWithIdentifier(identifier: String, sender: AnyObject?) -> Bool {
if identifier == "toAddTopic" {
if KeychainWrapper.stringForKey("token") == nil {
//未登录
return false
}
}
return true
}
// 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.
if segue.identifier == "PostDetail" {
if segue.destinationViewController is PostDetailController {
let view = segue.destinationViewController as! PostDetailController
let indexPath = self.tableView.indexPathForSelectedRow
let article: AnyObject = self.data[indexPath!.row]
view.article = article
}
}
}
}
|
mit
|
8d5e1203c3e4a1fdd942b1064eafded2
| 31.280374 | 175 | 0.578942 | 5.747088 | false | false | false | false |
Johennes/firefox-ios
|
Client/Frontend/Intro/IntroViewController.swift
|
2
|
20759
|
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
import UIKit
import SnapKit
struct IntroViewControllerUX {
static let Width = 375
static let Height = 667
static let CardSlides = ["organize", "customize", "share", "choose", "sync"]
static let NumberOfCards = CardSlides.count
static let PagerCenterOffsetFromScrollViewBottom = 30
static let StartBrowsingButtonTitle = NSLocalizedString("Start Browsing", tableName: "Intro", comment: "See http://mzl.la/1T8gxwo")
static let StartBrowsingButtonColor = UIColor(rgb: 0x363B40)
static let StartBrowsingButtonHeight = 56
static let SignInButtonTitle = NSLocalizedString("Sign in to Firefox", tableName: "Intro", comment: "See http://mzl.la/1T8gxwo")
static let SignInButtonColor = UIColor(red: 0.259, green: 0.49, blue: 0.831, alpha: 1.0)
static let SignInButtonHeight = 46
static let SignInButtonCornerRadius = CGFloat(4)
static let CardTextLineHeight = CGFloat(6)
static let CardTitleOrganize = NSLocalizedString("Organize", tableName: "Intro", comment: "Title for one of the panels in the First Run tour.")
static let CardTitleCustomize = NSLocalizedString("Customize", tableName: "Intro", comment: "Title for one of the panels in the First Run tour.")
static let CardTitleShare = NSLocalizedString("Share", tableName: "Intro", comment: "Title for one of the panels in the First Run tour.")
static let CardTitleChoose = NSLocalizedString("Choose", tableName: "Intro", comment: "Title for one of the panels in the First Run tour.")
static let CardTitleSync = NSLocalizedString("Sync your Devices.", tableName: "Intro", comment: "Title for one of the panels in the First Run tour.")
static let CardTextOrganize = NSLocalizedString("Easily switch between open pages with tabs.", tableName: "Intro", comment: "Description for the 'Organize' panel in the First Run tour.")
static let CardTextCustomize = NSLocalizedString("Personalize your default search engine and more in Settings.", tableName: "Intro", comment: "Description for the 'Customize' panel in the First Run tour.")
static let CardTextShare = NSLocalizedString("Use the share sheet to send links from other apps to Firefox.", tableName: "Intro", comment: "Description for the 'Share' panel in the First Run tour.")
static let CardTextChoose = NSLocalizedString("Tap, hold and move the Firefox icon into your dock for easy access.", tableName: "Intro", comment: "Description for the 'Choose' panel in the First Run tour.")
static let Card1ImageLabel = NSLocalizedString("The Show Tabs button is next to the Address and Search text field and displays the current number of open tabs.", tableName: "Intro", comment: "Accessibility label for the UI element used to display the number of open tabs, and open the tab tray.")
static let Card2ImageLabel = NSLocalizedString("The Settings button is at the beginning of the Tabs Tray.", tableName: "Intro", comment: "Accessibility label for the Settings button in the tab tray.")
static let Card3ImageLabel = NSLocalizedString("Firefox and the cloud", tableName: "Intro", comment: "Accessibility label for the image displayed in the 'Sync' panel of the First Run tour.")
static let CardTextSyncOffsetFromCenter = 25
static let Card3ButtonOffsetFromCenter = -10
static let FadeDuration = 0.25
static let BackForwardButtonEdgeInset = 20
static let Card1Color = UIColor(rgb: 0xFFC81E)
static let Card2Color = UIColor(rgb: 0x41B450)
static let Card3Color = UIColor(rgb: 0x0096DD)
}
let IntroViewControllerSeenProfileKey = "IntroViewControllerSeen"
protocol IntroViewControllerDelegate: class {
func introViewControllerDidFinish(introViewController: IntroViewController)
func introViewControllerDidRequestToLogin(introViewController: IntroViewController)
}
class IntroViewController: UIViewController, UIScrollViewDelegate {
weak var delegate: IntroViewControllerDelegate?
var slides = [UIImage]()
var cards = [UIImageView]()
var introViews = [UIView]()
var titleLabels = [UILabel]()
var textLabels = [UILabel]()
var startBrowsingButton: UIButton!
var introView: UIView?
var slideContainer: UIView!
var pageControl: UIPageControl!
var backButton: UIButton!
var forwardButton: UIButton!
var signInButton: UIButton!
private var scrollView: IntroOverlayScrollView!
var slideVerticalScaleFactor: CGFloat = 1.0
override func viewDidLoad() {
view.backgroundColor = UIColor.whiteColor()
// scale the slides down for iPhone 4S
if view.frame.height <= 480 {
slideVerticalScaleFactor = 1.33
}
for slideName in IntroViewControllerUX.CardSlides {
slides.append(UIImage(named: slideName)!)
}
startBrowsingButton = UIButton()
startBrowsingButton.backgroundColor = IntroViewControllerUX.StartBrowsingButtonColor
startBrowsingButton.setTitle(IntroViewControllerUX.StartBrowsingButtonTitle, forState: UIControlState.Normal)
startBrowsingButton.setTitleColor(UIColor.whiteColor(), forState: UIControlState.Normal)
startBrowsingButton.addTarget(self, action: #selector(IntroViewController.SELstartBrowsing), forControlEvents: UIControlEvents.TouchUpInside)
startBrowsingButton.accessibilityIdentifier = "IntroViewController.startBrowsingButton"
view.addSubview(startBrowsingButton)
startBrowsingButton.snp_makeConstraints { (make) -> Void in
make.left.right.bottom.equalTo(self.view)
make.height.equalTo(IntroViewControllerUX.StartBrowsingButtonHeight)
}
scrollView = IntroOverlayScrollView()
scrollView.backgroundColor = UIColor.clearColor()
scrollView.accessibilityLabel = NSLocalizedString("Intro Tour Carousel", comment: "Accessibility label for the introduction tour carousel")
scrollView.delegate = self
scrollView.bounces = false
scrollView.pagingEnabled = true
scrollView.showsHorizontalScrollIndicator = false
scrollView.contentSize = CGSize(width: scaledWidthOfSlide * CGFloat(IntroViewControllerUX.NumberOfCards), height: scaledHeightOfSlide)
view.addSubview(scrollView)
slideContainer = UIView()
slideContainer.backgroundColor = IntroViewControllerUX.Card1Color
for i in 0..<IntroViewControllerUX.NumberOfCards {
let imageView = UIImageView(frame: CGRect(x: CGFloat(i)*scaledWidthOfSlide, y: 0, width: scaledWidthOfSlide, height: scaledHeightOfSlide))
imageView.image = slides[i]
slideContainer.addSubview(imageView)
}
scrollView.addSubview(slideContainer)
scrollView.snp_makeConstraints { (make) -> Void in
make.left.right.top.equalTo(self.view)
make.bottom.equalTo(startBrowsingButton.snp_top)
}
pageControl = UIPageControl()
pageControl.pageIndicatorTintColor = UIColor.blackColor().colorWithAlphaComponent(0.3)
pageControl.currentPageIndicatorTintColor = UIColor.blackColor()
pageControl.numberOfPages = IntroViewControllerUX.NumberOfCards
pageControl.accessibilityIdentifier = "pageControl"
pageControl.addTarget(self, action: #selector(IntroViewController.changePage), forControlEvents: UIControlEvents.ValueChanged)
view.addSubview(pageControl)
pageControl.snp_makeConstraints { (make) -> Void in
make.centerX.equalTo(self.scrollView)
make.centerY.equalTo(self.startBrowsingButton.snp_top).offset(-IntroViewControllerUX.PagerCenterOffsetFromScrollViewBottom)
}
func addCard(text: String, title: String) {
let introView = UIView()
self.introViews.append(introView)
self.addLabelsToIntroView(introView, text: text, title: title)
}
addCard(IntroViewControllerUX.CardTextOrganize, title: IntroViewControllerUX.CardTitleOrganize)
addCard(IntroViewControllerUX.CardTextCustomize, title: IntroViewControllerUX.CardTitleCustomize)
addCard(IntroViewControllerUX.CardTextShare, title: IntroViewControllerUX.CardTitleShare)
addCard(IntroViewControllerUX.CardTextChoose, title: IntroViewControllerUX.CardTitleChoose)
// Sync card, with sign in to sync button.
signInButton = UIButton()
signInButton.backgroundColor = IntroViewControllerUX.SignInButtonColor
signInButton.setTitle(IntroViewControllerUX.SignInButtonTitle, forState: .Normal)
signInButton.setTitleColor(UIColor.whiteColor(), forState: .Normal)
signInButton.layer.cornerRadius = IntroViewControllerUX.SignInButtonCornerRadius
signInButton.clipsToBounds = true
signInButton.addTarget(self, action: #selector(IntroViewController.SELlogin), forControlEvents: UIControlEvents.TouchUpInside)
signInButton.snp_makeConstraints { (make) -> Void in
make.height.equalTo(IntroViewControllerUX.SignInButtonHeight)
}
let syncCardView = UIView()
addViewsToIntroView(syncCardView, view: signInButton, title: IntroViewControllerUX.CardTitleSync)
introViews.append(syncCardView)
// Add all the cards to the view, make them invisible with zero alpha
for introView in introViews {
introView.alpha = 0
self.view.addSubview(introView)
introView.snp_makeConstraints { (make) -> Void in
make.top.equalTo(self.slideContainer.snp_bottom)
make.bottom.equalTo(self.startBrowsingButton.snp_top)
make.left.right.equalTo(self.view)
}
}
// Make whole screen scrollable by bringing the scrollview to the top
view.bringSubviewToFront(scrollView)
view.bringSubviewToFront(pageControl)
// Activate the first card
setActiveIntroView(introViews[0], forPage: 0)
setupDynamicFonts()
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(IntroViewController.SELDynamicFontChanged(_:)), name: NotificationDynamicFontChanged, object: nil)
}
override func viewWillDisappear(animated: Bool) {
super.viewWillDisappear(animated)
NSNotificationCenter.defaultCenter().removeObserver(self, name: NotificationDynamicFontChanged, object: nil)
}
func SELDynamicFontChanged(notification: NSNotification) {
guard notification.name == NotificationDynamicFontChanged else { return }
setupDynamicFonts()
}
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
scrollView.snp_remakeConstraints { (make) -> Void in
make.left.right.top.equalTo(self.view)
make.bottom.equalTo(self.startBrowsingButton.snp_top)
}
for i in 0..<IntroViewControllerUX.NumberOfCards {
if let imageView = slideContainer.subviews[i] as? UIImageView {
imageView.frame = CGRect(x: CGFloat(i)*scaledWidthOfSlide, y: 0, width: scaledWidthOfSlide, height: scaledHeightOfSlide)
imageView.contentMode = UIViewContentMode.ScaleAspectFit
}
}
slideContainer.frame = CGRect(x: 0, y: 0, width: scaledWidthOfSlide * CGFloat(IntroViewControllerUX.NumberOfCards), height: scaledHeightOfSlide)
scrollView.contentSize = CGSize(width: slideContainer.frame.width, height: slideContainer.frame.height)
}
override func prefersStatusBarHidden() -> Bool {
return true
}
override func shouldAutorotate() -> Bool {
return false
}
override func supportedInterfaceOrientations() -> UIInterfaceOrientationMask {
// This actually does the right thing on iPad where the modally
// presented version happily rotates with the iPad orientation.
return UIInterfaceOrientationMask.Portrait
}
func SELstartBrowsing() {
delegate?.introViewControllerDidFinish(self)
}
func SELback() {
if introView == introViews[1] {
setActiveIntroView(introViews[0], forPage: 0)
scrollView.scrollRectToVisible(scrollView.subviews[0].frame, animated: true)
pageControl.currentPage = 0
} else if introView == introViews[2] {
setActiveIntroView(introViews[1], forPage: 1)
scrollView.scrollRectToVisible(scrollView.subviews[1].frame, animated: true)
pageControl.currentPage = 1
}
}
func SELforward() {
if introView == introViews[0] {
setActiveIntroView(introViews[1], forPage: 1)
scrollView.scrollRectToVisible(scrollView.subviews[1].frame, animated: true)
pageControl.currentPage = 1
} else if introView == introViews[1] {
setActiveIntroView(introViews[2], forPage: 2)
scrollView.scrollRectToVisible(scrollView.subviews[2].frame, animated: true)
pageControl.currentPage = 2
}
}
func SELlogin() {
delegate?.introViewControllerDidRequestToLogin(self)
}
private var accessibilityScrollStatus: String {
return String(format: NSLocalizedString("Introductory slide %@ of %@", tableName: "Intro", comment: "String spoken by assistive technology (like VoiceOver) stating on which page of the intro wizard we currently are. E.g. Introductory slide 1 of 3"), NSNumberFormatter.localizedStringFromNumber(pageControl.currentPage+1, numberStyle: .DecimalStyle), NSNumberFormatter.localizedStringFromNumber(IntroViewControllerUX.NumberOfCards, numberStyle: .DecimalStyle))
}
func changePage() {
let swipeCoordinate = CGFloat(pageControl.currentPage) * scrollView.frame.size.width
scrollView.setContentOffset(CGPointMake(swipeCoordinate, 0), animated: true)
}
func scrollViewDidEndDragging(scrollView: UIScrollView, willDecelerate decelerate: Bool) {
// Need to add this method so that when forcibly dragging, instead of letting deceleration happen, should also calculate what card it's on.
// This especially affects sliding to the last or first slides.
if !decelerate {
scrollViewDidEndDecelerating(scrollView)
}
}
func scrollViewDidEndScrollingAnimation(scrollView: UIScrollView) {
// Need to add this method so that tapping the pageControl will also change the card texts.
// scrollViewDidEndDecelerating waits until the end of the animation to calculate what card it's on.
scrollViewDidEndDecelerating(scrollView)
}
func scrollViewDidEndDecelerating(scrollView: UIScrollView) {
let page = Int(scrollView.contentOffset.x / scrollView.frame.size.width)
setActiveIntroView(introViews[page], forPage: page)
}
func scrollViewDidScroll(scrollView: UIScrollView) {
let maximumHorizontalOffset = scrollView.contentSize.width - CGRectGetWidth(scrollView.frame)
let currentHorizontalOffset = scrollView.contentOffset.x
var percentage = currentHorizontalOffset / maximumHorizontalOffset
var startColor: UIColor, endColor: UIColor
let page = Int(scrollView.contentOffset.x / scrollView.frame.size.width)
pageControl.currentPage = page
if(percentage < 0.5) {
startColor = IntroViewControllerUX.Card1Color
endColor = IntroViewControllerUX.Card2Color
percentage = percentage * 2
} else {
startColor = IntroViewControllerUX.Card2Color
endColor = IntroViewControllerUX.Card3Color
percentage = (percentage - 0.5) * 2
}
slideContainer.backgroundColor = colorForPercentage(percentage, start: startColor, end: endColor)
}
private func colorForPercentage(percentage: CGFloat, start: UIColor, end: UIColor) -> UIColor {
let s = start.components
let e = end.components
let newRed = (1.0 - percentage) * s.red + percentage * e.red
let newGreen = (1.0 - percentage) * s.green + percentage * e.green
let newBlue = (1.0 - percentage) * s.blue + percentage * e.blue
return UIColor(red: newRed, green: newGreen, blue: newBlue, alpha: 1.0)
}
private func setActiveIntroView(newIntroView: UIView, forPage page: Int) {
if introView != newIntroView {
UIView.animateWithDuration(IntroViewControllerUX.FadeDuration, animations: { () -> Void in
self.introView?.alpha = 0
self.introView = newIntroView
newIntroView.alpha = 1.0
}, completion: { _ in
if page == (IntroViewControllerUX.NumberOfCards - 1) {
self.scrollView.signinButton = self.signInButton
} else {
self.scrollView.signinButton = nil
}
})
}
}
private var scaledWidthOfSlide: CGFloat {
return view.frame.width
}
private var scaledHeightOfSlide: CGFloat {
return (view.frame.width / slides[0].size.width) * slides[0].size.height / slideVerticalScaleFactor
}
private func attributedStringForLabel(text: String) -> NSMutableAttributedString {
let paragraphStyle = NSMutableParagraphStyle()
paragraphStyle.lineSpacing = IntroViewControllerUX.CardTextLineHeight
paragraphStyle.alignment = .Center
let string = NSMutableAttributedString(string: text)
string.addAttribute(NSParagraphStyleAttributeName, value: paragraphStyle, range: NSMakeRange(0, string.length))
return string
}
private func addLabelsToIntroView(introView: UIView, text: String, title: String = "") {
let label = UILabel()
label.numberOfLines = 0
label.attributedText = attributedStringForLabel(text)
textLabels.append(label)
addViewsToIntroView(introView, view: label, title: title)
}
private func addViewsToIntroView(introView: UIView, view: UIView, title: String = "") {
introView.addSubview(view)
view.snp_makeConstraints { (make) -> Void in
make.center.equalTo(introView)
make.width.equalTo(self.view.frame.width <= 320 ? 240 : 280) // TODO Talk to UX about small screen sizes
}
if !title.isEmpty {
let titleLabel = UILabel()
titleLabel.numberOfLines = 0
titleLabel.textAlignment = NSTextAlignment.Center
titleLabel.text = title
titleLabels.append(titleLabel)
introView.addSubview(titleLabel)
titleLabel.snp_makeConstraints { (make) -> Void in
make.top.equalTo(introView)
make.bottom.equalTo(view.snp_top)
make.centerX.equalTo(introView)
make.width.equalTo(self.view.frame.width <= 320 ? 240 : 280) // TODO Talk to UX about small screen sizes
}
}
}
private func setupDynamicFonts() {
startBrowsingButton.titleLabel?.font = UIFont.systemFontOfSize(DynamicFontHelper.defaultHelper.IntroBigFontSize)
signInButton.titleLabel?.font = UIFont.systemFontOfSize(DynamicFontHelper.defaultHelper.IntroStandardFontSize, weight: UIFontWeightMedium)
for titleLabel in titleLabels {
titleLabel.font = UIFont.systemFontOfSize(DynamicFontHelper.defaultHelper.IntroBigFontSize, weight: UIFontWeightBold)
}
for label in textLabels {
label.font = UIFont.systemFontOfSize(DynamicFontHelper.defaultHelper.IntroStandardFontSize)
}
}
}
private class IntroOverlayScrollView: UIScrollView {
weak var signinButton: UIButton?
private override func pointInside(point: CGPoint, withEvent event: UIEvent?) -> Bool {
if let signinFrame = signinButton?.frame {
let convertedFrame = convertRect(signinFrame, fromView: signinButton?.superview)
if CGRectContainsPoint(convertedFrame, point) {
return false
}
}
return CGRectContainsPoint(CGRect(origin: self.frame.origin, size: CGSize(width: self.contentSize.width, height: self.frame.size.height)), point)
}
}
extension UIColor {
var components:(red: CGFloat, green: CGFloat, blue: CGFloat, alpha: CGFloat) {
var r: CGFloat = 0
var g: CGFloat = 0
var b: CGFloat = 0
var a: CGFloat = 0
getRed(&r, green: &g, blue: &b, alpha: &a)
return (r, g, b, a)
}
}
|
mpl-2.0
|
9714de146621f1e725a77752e5f55113
| 45.860045 | 467 | 0.700371 | 5.059469 | false | false | false | false |
CaiMiao/CGSSGuide
|
DereGuide/Model/Favorite/RemoteFavoriteChara.swift
|
1
|
1429
|
//
// RemoteFavoriteChara.swift
// DereGuide
//
// Created by zzk on 2017/7/26.
// Copyright © 2017年 zzk. All rights reserved.
//
import UIKit
import CoreData
import CloudKit
struct RemoteFavoriteChara: RemoteRecord {
var id: String
var creatorID: String
var charaID: Int64
var localCreatedAt: Date
}
extension RemoteFavoriteChara {
static var recordType: String { return "FavoriteChara" }
init?(record: CKRecord) {
guard record.recordType == RemoteFavoriteChara.recordType else { return nil }
guard
let localCreatedAt = record["localCreatedAt"] as? Date,
let charaID = record["charaID"] as? NSNumber,
let creatorID = record.creatorUserRecordID?.recordName else {
return nil
}
self.id = record.recordID.recordName
self.creatorID = creatorID
self.localCreatedAt = localCreatedAt
self.charaID = charaID.int64Value
}
}
extension RemoteFavoriteChara {
func insert(into context: NSManagedObjectContext, completion: @escaping (Bool) -> ()) {
context.perform {
let chara = FavoriteChara.insert(into: context, charaID: Int(self.charaID))
chara.creatorID = self.creatorID
chara.remoteIdentifier = self.id
chara.createdAt = self.localCreatedAt
completion(true)
}
}
}
|
mit
|
420b7ba56821625fc769f9dc423dde51
| 24.464286 | 91 | 0.631837 | 4.321212 | false | false | false | false |
MiMo42/XLForm
|
Examples/Swift/SwiftExample/RealExamples/NativeEventFormViewController.swift
|
2
|
11156
|
//
// NativeEventNavigationViewController.swift
// XLForm ( https://github.com/xmartlabs/XLForm )
//
// Copyright (c) 2014-2015 Xmartlabs ( http://xmartlabs.com )
//
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
class NativeEventFormViewController : XLFormViewController {
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
initializeForm()
}
override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: Bundle?) {
super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil)
initializeForm()
}
func initializeForm() {
let form : XLFormDescriptor
var section : XLFormSectionDescriptor
var row : XLFormRowDescriptor
form = XLFormDescriptor(title: "Add Event")
section = XLFormSectionDescriptor.formSection()
form.addFormSection(section)
// Title
row = XLFormRowDescriptor(tag: "title", rowType: XLFormRowDescriptorTypeText)
row.cellConfigAtConfigure["textField.placeholder"] = "Title"
row.isRequired = true
section.addFormRow(row)
// Location
row = XLFormRowDescriptor(tag: "location", rowType: XLFormRowDescriptorTypeText)
row.cellConfigAtConfigure["textField.placeholder"] = "Location"
section.addFormRow(row)
section = XLFormSectionDescriptor.formSection()
form.addFormSection(section)
// All-day
row = XLFormRowDescriptor(tag: "all-day", rowType: XLFormRowDescriptorTypeBooleanSwitch, title: "All-day")
section.addFormRow(row)
// Starts
row = XLFormRowDescriptor(tag: "starts", rowType: XLFormRowDescriptorTypeDateTimeInline, title: "Starts")
row.value = Date(timeIntervalSinceNow: 60*60*24)
section.addFormRow(row)
// Ends
row = XLFormRowDescriptor(tag: "ends", rowType: XLFormRowDescriptorTypeDateTimeInline, title: "Ends")
row.value = Date(timeIntervalSinceNow: 60*60*25)
section.addFormRow(row)
section = XLFormSectionDescriptor.formSection()
form.addFormSection(section)
// Repeat
row = XLFormRowDescriptor(tag: "repeat", rowType:XLFormRowDescriptorTypeSelectorPush, title:"Repeat")
row.value = XLFormOptionsObject(value: 0, displayText: "Never")
row.selectorTitle = "Repeat"
row.selectorOptions = [XLFormOptionsObject(value: 0, displayText: "Never"),
XLFormOptionsObject(value: 1, displayText: "Every Day"),
XLFormOptionsObject(value: 2, displayText: "Every Week"),
XLFormOptionsObject(value: 3, displayText: "Every 2 Weeks"),
XLFormOptionsObject(value: 4, displayText: "Every Month"),
XLFormOptionsObject(value: 5, displayText: "Every Year")]
section.addFormRow(row)
section = XLFormSectionDescriptor.formSection()
form.addFormSection(section)
// Alert
row = XLFormRowDescriptor(tag: "alert", rowType:XLFormRowDescriptorTypeSelectorPush, title:"Alert")
row.value = XLFormOptionsObject(value: 0, displayText: "None")
row.selectorTitle = "Event Alert"
row.selectorOptions = [
XLFormOptionsObject(value: 0, displayText: "None"),
XLFormOptionsObject(value: 1, displayText: "At time of event"),
XLFormOptionsObject(value: 2, displayText: "5 minutes before"),
XLFormOptionsObject(value: 3, displayText: "15 minutes before"),
XLFormOptionsObject(value: 4, displayText: "30 minutes before"),
XLFormOptionsObject(value: 5, displayText: "1 hour before"),
XLFormOptionsObject(value: 6, displayText: "2 hours before"),
XLFormOptionsObject(value: 7, displayText: "1 day before"),
XLFormOptionsObject(value: 8, displayText: "2 days before")]
section.addFormRow(row)
section = XLFormSectionDescriptor.formSection()
form.addFormSection(section)
// Show As
row = XLFormRowDescriptor(tag: "showAs", rowType:XLFormRowDescriptorTypeSelectorPush, title:"Show As")
row.value = XLFormOptionsObject(value: 0, displayText: "Busy")
row.selectorTitle = "Show As"
row.selectorOptions = [XLFormOptionsObject(value: 0, displayText:"Busy"),
XLFormOptionsObject(value: 1, displayText:"Free")]
section.addFormRow(row)
section = XLFormSectionDescriptor.formSection()
form.addFormSection(section)
// URL
row = XLFormRowDescriptor(tag: "url", rowType:XLFormRowDescriptorTypeURL)
row.cellConfigAtConfigure["textField.placeholder"] = "URL"
section.addFormRow(row)
// Notes
row = XLFormRowDescriptor(tag: "notes", rowType:XLFormRowDescriptorTypeTextView)
row.cellConfigAtConfigure["textView.placeholder"] = "Notes"
section.addFormRow(row)
self.form = form
}
override func viewDidLoad(){
super.viewDidLoad()
navigationItem.leftBarButtonItem = UIBarButtonItem(barButtonSystemItem: .cancel, target: self, action: #selector(NativeEventFormViewController.cancelPressed(_:)))
navigationItem.rightBarButtonItem = UIBarButtonItem(barButtonSystemItem: .save, target: self, action: #selector(NativeEventFormViewController.savePressed(_:)))
}
// MARK: XLFormDescriptorDelegate
override func formRowDescriptorValueHasChanged(_ formRow: XLFormRowDescriptor!, oldValue: Any!, newValue: Any!) {
super.formRowDescriptorValueHasChanged(formRow, oldValue: oldValue, newValue: newValue)
if formRow.tag == "alert" {
if !((formRow.value! as AnyObject).valueData() as AnyObject).isEqual(0) && ((oldValue as AnyObject).valueData() as AnyObject).isEqual(0) {
let newRow = formRow.copy() as! XLFormRowDescriptor
newRow.tag = "secondAlert"
newRow.title = "Second Alert"
form.addFormRow(newRow, afterRow:formRow)
}
else if !((oldValue as AnyObject).valueData() as AnyObject).isEqual(0) && ((newValue as AnyObject).valueData() as AnyObject).isEqual(0) {
form.removeFormRow(withTag: "secondAlert")
}
}
else if formRow.tag == "all-day" {
let startDateDescriptor = form.formRow(withTag: "starts")!
let endDateDescriptor = form.formRow(withTag: "ends")!
let dateStartCell: XLFormDateCell = startDateDescriptor.cell(forForm: self) as! XLFormDateCell
let dateEndCell: XLFormDateCell = endDateDescriptor.cell(forForm: self) as! XLFormDateCell
if (formRow.value! as AnyObject).valueData() as? Bool == true {
startDateDescriptor.valueTransformer = DateValueTrasformer.self
endDateDescriptor.valueTransformer = DateValueTrasformer.self
dateStartCell.formDatePickerMode = .date
dateEndCell.formDatePickerMode = .date
}
else{
startDateDescriptor.valueTransformer = DateTimeValueTrasformer.self
endDateDescriptor.valueTransformer = DateTimeValueTrasformer.self
dateStartCell.formDatePickerMode = .dateTime
dateEndCell.formDatePickerMode = .dateTime
}
updateFormRow(startDateDescriptor)
updateFormRow(endDateDescriptor)
}
else if formRow.tag == "starts" {
let startDateDescriptor = form.formRow(withTag: "starts")!
let endDateDescriptor = form.formRow(withTag: "ends")!
if (startDateDescriptor.value! as AnyObject).compare(endDateDescriptor.value as! Date) == .orderedDescending {
// startDateDescriptor is later than endDateDescriptor
endDateDescriptor.value = Date(timeInterval: 60*60*24, since: startDateDescriptor.value as! Date)
endDateDescriptor.cellConfig.removeObject(forKey: "detailTextLabel.attributedText")
updateFormRow(endDateDescriptor)
}
}
else if formRow.tag == "ends" {
let startDateDescriptor = form.formRow(withTag: "starts")!
let endDateDescriptor = form.formRow(withTag: "ends")!
let dateEndCell = endDateDescriptor.cell(forForm: self) as! XLFormDateCell
if (startDateDescriptor.value! as AnyObject).compare(endDateDescriptor.value as! Date) == .orderedDescending {
// startDateDescriptor is later than endDateDescriptor
dateEndCell.update()
let newDetailText = dateEndCell.detailTextLabel!.text!
let strikeThroughAttribute = [NSStrikethroughStyleAttributeName : NSUnderlineStyle.styleSingle.rawValue]
let strikeThroughText = NSAttributedString(string: newDetailText, attributes: strikeThroughAttribute)
endDateDescriptor.cellConfig["detailTextLabel.attributedText"] = strikeThroughText
updateFormRow(endDateDescriptor)
}
else{
let endDateDescriptor = self.form.formRow(withTag: "ends")!
endDateDescriptor.cellConfig.removeObject(forKey: "detailTextLabel.attributedText")
updateFormRow(endDateDescriptor)
}
}
}
func cancelPressed(_ button: UIBarButtonItem){
dismiss(animated: true, completion: nil)
}
func savePressed(_ button: UIBarButtonItem){
let validationErrors : Array<NSError> = formValidationErrors() as! Array<NSError>
if (validationErrors.count > 0){
showFormValidationError(validationErrors.first)
return
}
tableView.endEditing(true)
}
}
class NativeEventNavigationViewController : UINavigationController {
override func viewDidLoad(){
super.viewDidLoad()
view.tintColor = .red
}
}
|
mit
|
cd85d8ad80f8cb5bf53f763128b47555
| 46.271186 | 170 | 0.657673 | 5.327603 | false | false | false | false |
takasek/konjac
|
Konjac/Konjac/GoogleTranslateViewController.swift
|
1
|
1229
|
//
// GoogleTranslateViewController.swift
// Konjac
//
// Created by Yoshitaka Seki on 2017/03/04.
// Copyright © 2017年 trySwiftHackathon. All rights reserved.
//
import UIKit
import SwiftyJSON
final class GoogleTranslateViewController: UIViewController {
@IBOutlet weak var sourceTextView: UITextView! {
didSet {
sourceTextView.text = ""
}
}
@IBOutlet weak var destinationTextView: UITextView! {
didSet {
destinationTextView.text = ""
}
}
@IBOutlet weak var translateButton: UIButton! {
didSet {
translateButton.setCornerRadius(with: 20)
}
}
private let tranlsater = GoogleTranslater()
@IBAction func saveDidTap(_ sender: UIBarButtonItem) {
print("action!", sourceTextView.text, destinationTextView.text)
}
@IBAction func viewDidTap(_ sender: Any) {
view.endEditing(true)
}
@IBAction func translateButtonDidTap(_ sender: Any) {
view.endEditing(true)
if let source = sourceTextView.text {
tranlsater.tranlate(source: source) { [weak self] (result) in
self?.destinationTextView.text = result
}
}
}
}
|
mit
|
40ff0c15ae498557dc830f0f22dcb208
| 25.085106 | 73 | 0.624796 | 4.442029 | false | false | false | false |
CNKCQ/oschina
|
Pods/UI+/UI+/UIImageView+.swift
|
1
|
1384
|
//
// UIImageView+.swift
// Elegant
//
// Created by Steve on 2017/5/22.
// Copyright © 2017年 KingCQ. All rights reserved.
//
import UIKit
public extension UIImageView {
/// ImageView are created with an iamge witch is instance by a `String`
convenience init?(imageNamed: String) {
self.init(image: UIImage(named: imageNamed))
}
/// Set UIImageView with rounded corners for aspect fit mode
func roundCornersForAspectFit(radius: CGFloat)
{
if let image = self.image {
//calculate drawingRect
let boundsScale = self.bounds.size.width / self.bounds.size.height
let imageScale = image.size.width / image.size.height
var drawingRect: CGRect = self.bounds
if boundsScale > imageScale {
drawingRect.size.width = drawingRect.size.height * imageScale
drawingRect.origin.x = (self.bounds.size.width - drawingRect.size.width) / 2
} else {
drawingRect.size.height = drawingRect.size.width / imageScale
drawingRect.origin.y = (self.bounds.size.height - drawingRect.size.height) / 2
}
let path = UIBezierPath(roundedRect: drawingRect, cornerRadius: radius)
let mask = CAShapeLayer()
mask.path = path.cgPath
self.layer.mask = mask
}
}
}
|
mit
|
efa68ff48e7e07008c54841ff432dfe0
| 32.682927 | 94 | 0.617668 | 4.329154 | false | false | false | false |
clayellis/AudioRecorder
|
AudioRecorderFramework/Sources/UIViewExtensions.swift
|
1
|
13385
|
//
// UIView+Extras.swift
// Clay Ellis
// gist.github.com/clayellis/0cf1b1092b6a08cb4c5b2da9abee5ed9
//
import UIKit
extension UIView {
// MARK: - NSLayoutConstraint Convenience Methods
func addAutoLayoutSubview(_ subview: UIView) {
addSubview(subview)
subview.translatesAutoresizingMaskIntoConstraints = false
}
func insertAutoLayoutSubview(_ view: UIView, at index: Int) {
insertSubview(view, at: index)
view.translatesAutoresizingMaskIntoConstraints = false
}
func insertAutoLayoutSubview(_ view: UIView, belowSubview: UIView) {
insertSubview(view, belowSubview: belowSubview)
view.translatesAutoresizingMaskIntoConstraints = false
}
func insertAutoLayoutSubview(_ view: UIView, aboveSubview: UIView) {
insertSubview(view, aboveSubview: aboveSubview)
view.translatesAutoresizingMaskIntoConstraints = false
}
// MARK: Layout Macros
func fillSuperview() {
guard let superview = self.superview else { return }
NSLayoutConstraint.activate([
leftAnchor.constraint(equalTo: superview.leftAnchor),
rightAnchor.constraint(equalTo: superview.rightAnchor),
topAnchor.constraint(equalTo: superview.topAnchor),
bottomAnchor.constraint(equalTo: superview.bottomAnchor)
])
}
func fillSuperviewLayoutMargins() {
guard let superview = self.superview else { return }
NSLayoutConstraint.activate([
leftAnchor.constraint(equalTo: superview.leftMargin),
rightAnchor.constraint(equalTo: superview.rightMargin),
topAnchor.constraint(equalTo: superview.topMargin),
bottomAnchor.constraint(equalTo: superview.bottomMargin)
])
}
func centerInSuperview() {
guard let superview = self.superview else { return }
NSLayoutConstraint.activate([
centerXAnchor.constraint(equalTo: superview.centerXAnchor),
centerYAnchor.constraint(equalTo: superview.centerYAnchor)
])
}
func centerInSuperviewLayoutMargins() {
guard let superview = self.superview else { return }
NSLayoutConstraint.activate([
centerXAnchor.constraint(equalTo: superview.centerXMargin),
centerYAnchor.constraint(equalTo: superview.centerYMargin)
])
}
// MARK: Layout Margins Guide Shortcut
var leftMargin: NSLayoutXAxisAnchor {
return layoutMarginsGuide.leftAnchor
}
var rightMargin: NSLayoutXAxisAnchor {
return layoutMarginsGuide.rightAnchor
}
var centerXMargin: NSLayoutXAxisAnchor {
return layoutMarginsGuide.centerXAnchor
}
var widthMargin: NSLayoutDimension {
return layoutMarginsGuide.widthAnchor
}
var topMargin: NSLayoutYAxisAnchor {
return layoutMarginsGuide.topAnchor
}
var bottomMargin: NSLayoutYAxisAnchor {
return layoutMarginsGuide.bottomAnchor
}
var centerYMargin: NSLayoutYAxisAnchor {
return layoutMarginsGuide.centerYAnchor
}
var heightMargin: NSLayoutDimension {
return layoutMarginsGuide.heightAnchor
}
// MARK: Subview Retrieval
func subviewWithClassName(_ className: String) -> UIView? {
for subview in subviews {
if type(of: subview).description() == className {
return subview
} else if let found = subview.subviewWithClassName(className) {
return found
}
}
return nil
}
func subviewWithClassType(_ classType: AnyClass) -> UIView? {
for subview in subviews {
if subview.isKind(of: classType) {
return subview
} else if let found = subview.subviewWithClassType(classType) {
return found
}
}
return nil
}
func indexOfSubview(_ subview: UIView) -> Int? {
return subviews.index(of: subview)
}
func exchangeSubview(_ subviewOne: UIView, withSubview subviewTwo: UIView) {
if let subviewOneIndex = indexOfSubview(subviewOne),
let subviewTwoIndex = indexOfSubview(subviewTwo) {
self.exchangeSubview(at: subviewOneIndex, withSubviewAt: subviewTwoIndex)
}
}
var currentFirstResponder: UIResponder? {
if isFirstResponder {
return self
}
for view in self.subviews {
if let responder = view.currentFirstResponder {
return responder
}
}
return nil
}
// Useful, but commenting out to avoid warnings
// func printRecursiveDescription() {
// print(perform("recursiveDescription"))
// }
// func printAutolayoutTrace() {
// print(perform("_autolayoutTrace"))
// }
}
extension NSLayoutDimension {
// Anchor
func constraint(equalTo anchor: NSLayoutDimension, priority p: Float) -> NSLayoutConstraint {
let cst = constraint(equalTo: anchor)
cst.priority = UILayoutPriority(rawValue: p)
return cst
}
func constraint(lessThanOrEqualTo anchor: NSLayoutDimension, priority p: Float) -> NSLayoutConstraint {
let cst = constraint(lessThanOrEqualTo: anchor)
cst.priority = UILayoutPriority(rawValue: p)
return cst
}
func constraint(greaterThanOrEqualTo anchor: NSLayoutDimension, priority p: Float) -> NSLayoutConstraint {
let cst = constraint(greaterThanOrEqualTo: anchor)
cst.priority = UILayoutPriority(rawValue: p)
return cst
}
// Constant
func constraint(equalToConstant c: CGFloat, priority p: Float) -> NSLayoutConstraint {
let cst = constraint(equalToConstant: c)
cst.priority = UILayoutPriority(rawValue: p)
return cst
}
func constraint(greaterThanOrEqualToConstant c: CGFloat, priority p: Float) -> NSLayoutConstraint {
let cst = constraint(greaterThanOrEqualToConstant: c)
cst.priority = UILayoutPriority(rawValue: p)
return cst
}
func constraint(lessThanOrEqualToConstant c: CGFloat, priority p: Float) -> NSLayoutConstraint {
let cst = constraint(lessThanOrEqualToConstant: c)
cst.priority = UILayoutPriority(rawValue: p)
return cst
}
// Anchor, Constant
func constraint(equalTo anchor: NSLayoutDimension, constant c: CGFloat, priority p: Float) -> NSLayoutConstraint {
let cst = constraint(equalTo: anchor, constant: c)
cst.priority = UILayoutPriority(rawValue: p)
return cst
}
func constraint(lessThanOrEqualTo anchor: NSLayoutDimension, constant c: CGFloat, priority p: Float) -> NSLayoutConstraint {
let cst = constraint(lessThanOrEqualTo: anchor, constant: c)
cst.priority = UILayoutPriority(rawValue: p)
return cst
}
func constraint(greaterThanOrEqualTo anchor: NSLayoutDimension, constant c: CGFloat, priority p: Float) -> NSLayoutConstraint {
let cst = constraint(greaterThanOrEqualTo: anchor, constant: c)
cst.priority = UILayoutPriority(rawValue: p)
return cst
}
// Anchor, Multiplier
func constraint(equalTo anchor: NSLayoutDimension, multiplier m: CGFloat, priority p: Float) -> NSLayoutConstraint {
let cst = constraint(equalTo: anchor, multiplier: m)
cst.priority = UILayoutPriority(rawValue: p)
return cst
}
func constraint(greaterThanOrEqualTo anchor: NSLayoutDimension, multiplier m: CGFloat, priority p: Float) -> NSLayoutConstraint {
let cst = constraint(greaterThanOrEqualTo: anchor, multiplier: m)
cst.priority = UILayoutPriority(rawValue: p)
return cst
}
func constraint(lessThanOrEqualTo anchor: NSLayoutDimension, multiplier m: CGFloat, priority p: Float) -> NSLayoutConstraint {
let cst = constraint(lessThanOrEqualTo: anchor, multiplier: m)
cst.priority = UILayoutPriority(rawValue: p)
return cst
}
// Anchor, Multiplier, Constant
func constraint(equalTo anchor: NSLayoutDimension, multiplier m: CGFloat, constant c: CGFloat, priority p: Float) -> NSLayoutConstraint {
let cst = constraint(equalTo: anchor, multiplier: m, constant: c)
cst.priority = UILayoutPriority(rawValue: p)
return cst
}
func constraint(greaterThanOrEqualTo anchor: NSLayoutDimension, multiplier m: CGFloat, constant c: CGFloat, priority p: Float) -> NSLayoutConstraint {
let cst = constraint(greaterThanOrEqualTo: anchor, multiplier: m, constant: c)
cst.priority = UILayoutPriority(rawValue: p)
return cst
}
func constraint(lessThanOrEqualTo anchor: NSLayoutDimension, multiplier m: CGFloat, constant c: CGFloat, priority p: Float) -> NSLayoutConstraint {
let cst = constraint(lessThanOrEqualTo: anchor, multiplier: m, constant: c)
cst.priority = UILayoutPriority(rawValue: p)
return cst
}
}
enum LayoutPriority {
case required
case high
case low
case fittingSizeLevel
case custom(priority: Float)
var floatValue: Float {
switch self {
case .required: return UILayoutPriority.required.rawValue
case .high: return UILayoutPriority.defaultHigh.rawValue
case .low: return UILayoutPriority.defaultLow.rawValue
case .fittingSizeLevel: return UILayoutPriority.fittingSizeLevel.rawValue
case .custom(let priority): return priority
}
}
}
extension NSLayoutDimension {
// Anchor
func constraint(equalTo anchor: NSLayoutDimension, priority p: LayoutPriority) -> NSLayoutConstraint {
return constraint(equalTo: anchor, priority: p.floatValue)
}
func constraint(lessThanOrEqualTo anchor: NSLayoutDimension, priority p: LayoutPriority) -> NSLayoutConstraint {
return constraint(lessThanOrEqualTo: anchor, priority: p.floatValue)
}
func constraint(greaterThanOrEqualTo anchor: NSLayoutDimension, priority p: LayoutPriority) -> NSLayoutConstraint {
return constraint(greaterThanOrEqualTo: anchor, priority: p.floatValue)
}
// Constant
func constraint(equalToConstant c: CGFloat, priority p: LayoutPriority) -> NSLayoutConstraint {
return constraint(equalToConstant: c, priority: p.floatValue)
}
func constraint(greaterThanOrEqualToConstant c: CGFloat, priority p: LayoutPriority) -> NSLayoutConstraint {
return constraint(greaterThanOrEqualToConstant: c, priority: p.floatValue)
}
func constraint(lessThanOrEqualToConstant c: CGFloat, priority p: LayoutPriority) -> NSLayoutConstraint {
return constraint(lessThanOrEqualToConstant: c, priority: p.floatValue)
}
// Anchor, Constant
func constraint(equalTo anchor: NSLayoutDimension, constant c: CGFloat, priority p: LayoutPriority) -> NSLayoutConstraint {
return constraint(equalTo: anchor, constant: c, priority: p.floatValue)
}
func constraint(lessThanOrEqualTo anchor: NSLayoutDimension, constant c: CGFloat, priority p: LayoutPriority) -> NSLayoutConstraint {
return constraint(lessThanOrEqualTo: anchor, constant: c, priority: p.floatValue)
}
func constraint(greaterThanOrEqualTo anchor: NSLayoutDimension, constant c: CGFloat, priority p: LayoutPriority) -> NSLayoutConstraint {
return constraint(greaterThanOrEqualTo: anchor, constant: c, priority: p.floatValue)
}
// Anchor, Multiplier
func constraint(equalTo anchor: NSLayoutDimension, multiplier m: CGFloat, priority p: LayoutPriority) -> NSLayoutConstraint {
return constraint(equalTo: anchor, multiplier: m, priority: p.floatValue)
}
func constraint(greaterThanOrEqualTo anchor: NSLayoutDimension, multiplier m: CGFloat, priority p: LayoutPriority) -> NSLayoutConstraint {
return constraint(greaterThanOrEqualTo: anchor, multiplier: m, priority: p.floatValue)
}
func constraint(lessThanOrEqualTo anchor: NSLayoutDimension, multiplier m: CGFloat, priority p: LayoutPriority) -> NSLayoutConstraint {
return constraint(lessThanOrEqualTo: anchor, multiplier: m, priority: p.floatValue)
}
// Anchor, Multiplier, Constant
func constraint(equalTo anchor: NSLayoutDimension, multiplier m: CGFloat, constant c: CGFloat, priority p: LayoutPriority) -> NSLayoutConstraint {
return constraint(equalTo: anchor, multiplier: m, constant: c, priority: p.floatValue)
}
func constraint(greaterThanOrEqualTo anchor: NSLayoutDimension, multiplier m: CGFloat, constant c: CGFloat, priority p: LayoutPriority) -> NSLayoutConstraint {
return constraint(greaterThanOrEqualTo: anchor, multiplier: m, constant: c, priority: p.floatValue)
}
func constraint(lessThanOrEqualTo anchor: NSLayoutDimension, multiplier m: CGFloat, constant c: CGFloat, priority p: LayoutPriority) -> NSLayoutConstraint {
return constraint(lessThanOrEqualTo: anchor, multiplier: m, constant: c, priority: p.floatValue)
}
}
|
mit
|
5910fdd625a9a2553d819e4e9f60eae5
| 36.284123 | 163 | 0.675159 | 5.463265 | false | false | false | false |
Petapton/touch-bar-simulator
|
Touch Bar Simulator/ToolbarSlider.swift
|
1
|
993
|
//
// ToolbarSlider.swift
// Touch Bar Simulator
//
// Created by Wayne Yeh on 2017/3/20
// MIT License © Sindre Sorhus
//
import Cocoa
private final class ToolbarSliderCell: NSSliderCell {
private static let knob: NSImage = {
let frame = NSRect(x: 0, y: 0, width: 32, height: 32)
let image = NSImage(size: frame.size)
image.lockFocus()
// Circle
let path = NSBezierPath(roundedRect: frame, xRadius: 4, yRadius: 12)
NSColor.lightGray.set()
path.fill()
// Border
NSColor.black.set()
path.lineWidth = 2
path.stroke()
image.unlockFocus()
return image
}()
override func drawKnob(_ knobRect: NSRect) {
ToolbarSliderCell.knob.draw(in: knobRect.insetBy(dx: 0, dy: 6.5))
}
}
final class ToolbarSlider: NSSlider {
override init(frame: CGRect) {
super.init(frame: frame)
cell = ToolbarSliderCell()
}
convenience init() {
self.init(frame: CGRect.zero)
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
|
mit
|
870448b4fb0584abe291fcb3be10f0fd
| 18.84 | 70 | 0.683468 | 3.119497 | false | false | false | false |
ldt25290/MyInstaMap
|
MyInstaMap/CustomMKAnnotationView.swift
|
1
|
1338
|
//
// CustomMKAnnotationView.swift
// MyInstaMap
//
// Created by DucTran on 9/1/17.
// Copyright © 2017 User. All rights reserved.
//
import UIKit
import MapKit
class CustomMKAnnotationView: MKAnnotationView {
override init(annotation: MKAnnotation?, reuseIdentifier: String?) {
super.init(annotation: annotation, reuseIdentifier: reuseIdentifier)
self.backgroundColor = UIColor.clear
self.canShowCallout = true
self.frame = CGRect(x: 0, y: 0, width: 50, height: 30)
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
override func hitTest(_ point: CGPoint, with event: UIEvent?) -> UIView? {
let hitView = super.hitTest(point, with: event)
if (hitView != nil)
{
self.superview?.bringSubview(toFront: self)
}
return hitView
}
override func point(inside point: CGPoint, with event: UIEvent?) -> Bool {
let rect = self.bounds;
var isInside: Bool = rect.contains(point);
if(!isInside)
{
for view in self.subviews
{
isInside = view.frame.contains(point);
if isInside
{
break;
}
}
}
return isInside;
}
}
|
mit
|
5ee16103d9257a39fefca41722456e06
| 25.74 | 78 | 0.566941 | 4.532203 | false | false | false | false |
coach-plus/ios
|
CoachPlus/app/events/EventDetailViewController.swift
|
1
|
11716
|
//
// EventDetailViewController.swift
// CoachPlus
//
// Created by Maurice Breit on 17.04.17.
// Copyright © 2017 Mathandoro GbR. All rights reserved.
//
import Foundation
import UIKit
class EventDetailViewController: CoachPlusViewController, UITableViewDelegate, UITableViewDataSource, TableHeaderViewButtonDelegate, NewNewsDelegate, ParticipationTableViewCellDelegate, EventDetailCellReminderDelegate, EventDetailCellDeleteDelegate, CreateEventViewControllerDelegate {
func eventCreated() {
return
}
func eventChanged(newEvent: Event) {
self.gotNewEvent(event: newEvent)
}
func eventDeleted() {
self.navigationController?.popViewController(animated: true)
}
enum Section:Int {
case general = 0
case news = 1
case participation = 2
}
var event:Event?
var news = [News]()
var participationItems = [ParticipationItem]()
private let refreshControl = UIRefreshControl()
@IBOutlet weak var tableView: UITableView!
override func viewDidLoad() {
super.viewDidLoad()
//self.view.heroID = self.heroId
self.tableView.register(nib: "ParticipationTableViewCell", reuseIdentifier: "ParticipationTableViewCell")
self.tableView.register(nib: "NewsTableViewCell", reuseIdentifier: "NewsTableViewCell")
self.tableView.register(nib: "EventDetailCell", reuseIdentifier: "EventDetailCell")
self.tableView.register(nib: "BannerTableViewCell", reuseIdentifier: "BannerTableViewCell")
let nib = UINib(nibName: "ReusableTableHeader", bundle: nil)
self.tableView.register(nib, forHeaderFooterViewReuseIdentifier: "TableHeader")
let pNib = UINib(nibName: "ReusableParticipationHeaderView", bundle: nil)
self.tableView.register(pNib, forHeaderFooterViewReuseIdentifier: "ReusableParticipationHeaderView")
self.tableView.rowHeight = UITableView.automaticDimension
self.tableView.estimatedRowHeight = 70
if #available(iOS 10.0, *) {
tableView.refreshControl = refreshControl
} else {
tableView.addSubview(refreshControl)
}
refreshControl.addTarget(self, action: #selector(refresh(_:)), for: .valueChanged)
self.gotNewEvent(event: self.event!)
}
@objc private func refresh(_ sender: Any) {
guard self.event != nil else {
self.dismiss(animated: true, completion: nil)
return
}
self.loadData(text: nil, promise: DataHandler.def.getEvent(teamId: event!.teamId, eventId: event!.id)).done({ event in
self.gotNewEvent(event: event)
})
}
func gotNewEvent(event: Event) {
self.event = event
self.loadParticipations()
self.loadNews()
self.tableView.reloadData()
self.navigationItem.title = self.event?.name
self.refreshControl.endRefreshing()
}
func loadParticipations() {
DataHandler.def.getParticipations(event: self.event!).done({ participationItems in
self.participationItems = participationItems
self.tableView.reloadData()
}).catch({ err in
print(err)
});
}
func loadNews() {
DataHandler.def.getNews(event: self.event!).done({ news in
self.news = news
self.tableView.reloadData()
}).catch({ err in
print(err)
});
}
func hasNews() -> Bool {
return self.news.count > 0
}
func numberOfSections(in tableView: UITableView) -> Int {
return 3
}
func getSectionType(section:Int) -> Section {
return Section(rawValue: section)!
}
func showHeaderRow() -> Bool {
return ((event!.startedInPast() && self.userIsCoach()) || (self.participationItems.count > 0 && event!.startedInPast() == false))
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
let sectionType = self.getSectionType(section: section)
switch sectionType {
case .general:
return 1
case .news:
if (!self.hasNews()) {
return 1
}
return self.news.count
case .participation:
if (self.showHeaderRow()) {
return self.participationItems.count + 1
}
return self.participationItems.count
}
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
switch getSectionType(section: indexPath.section) {
case .general:
return self.generalCell(indexPath: indexPath)
case .news:
return self.newsCell(indexPath: indexPath)
case .participation:
if (self.showHeaderRow()) {
if (indexPath.row == 0) {
return self.bannerCell(indexPath: indexPath)
} else {
return self.participationCell(indexPath: indexPath)
}
} else {
return self.participationCell(indexPath: indexPath)
}
}
}
func bannerCell(indexPath: IndexPath) -> BannerTableViewCell {
let cell = self.tableView.dequeueReusableCell(withIdentifier: "BannerTableViewCell", for: indexPath) as! BannerTableViewCell
var text = L10n.pleaseSetParticipation
var bgColor = UIColor.coachPlusBannerBackgroundColor
var textColor = UIColor.coachPlusBlue
if (self.userIsCoach() && event!.startedInPast()) {
text = L10n.youCanNowSelectWhoParticipated
textColor = UIColor.coachPlusBlue
}
cell.configure(text: text, bgColor: bgColor, textColor: textColor)
cell.separatorInset = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: .greatestFiniteMagnitude)
return cell
}
func participationCell(indexPath:IndexPath) -> ParticipationTableViewCell {
let cell = self.tableView.dequeueReusableCell(withIdentifier: "ParticipationTableViewCell", for: indexPath) as! ParticipationTableViewCell
var row = indexPath.row
if (self.showHeaderRow()) {
row = row - 1
}
let participationItem = self.participationItems[row]
cell.configure(delegate: self, participationItem: participationItem, event: self.event!)
return cell
}
func newsCell(indexPath:IndexPath) -> UITableViewCell {
if (!self.hasNews()) {
let cell = UITableViewCell(style: .default, reuseIdentifier: "DefaultCell")
cell.textLabel?.text = L10n.noNews
return cell
}
let cell = self.tableView.dequeueReusableCell(withIdentifier: "NewsTableViewCell", for: indexPath) as! NewsTableViewCell
let news = self.news[indexPath.row]
cell.configure(news: news)
return cell
}
func generalCell(indexPath:IndexPath) -> UITableViewCell {
let cell = self.tableView.dequeueReusableCell(withIdentifier: "EventDetailCell", for: indexPath) as! EventDetailCell
cell.configure(event: self.event!, team: self.membership!.team!, isCoach: self.membership?.isCoach(), vc: self)
cell.reminderDelegate = self
return cell
}
func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
let sectionType = getSectionType(section: section)
switch sectionType {
case .news:
let cell = self.tableView.dequeueReusableHeaderFooterView(withIdentifier: "TableHeader")
let view = cell as! ReusableTableHeader
if (self.userIsCoach()) {
view.tableHeader.btn.tag = Section.news.rawValue
view.tableHeader.delegate = self
view.tableHeader.showBtn = true
} else {
view.tableHeader.showBtn = false
}
view.tableHeader.title = L10n.news
return view
case .participation:
let cell = self.tableView.dequeueReusableHeaderFooterView(withIdentifier: "ReusableParticipationHeaderView")
let view = cell as! ReusableParticipationHeaderView
view.tableHeader.setTitle(title: L10n.participation)
view.tableHeader.eventIsInPast = self.event!.isInPast()
view.tableHeader.setLabels(participations: self.participationItems)
return view
default:
return nil
}
}
func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
let sectionType = getSectionType(section: section)
switch sectionType {
case .general:
return 0
default:
return 45
}
}
func tableViewHeaderBtnTap(_ sender: Any) {
let section = Section(rawValue: (sender as AnyObject).tag)
guard (section != nil) else {
return
}
if (section == .news) {
self.newNews()
}
}
func newNews() {
let vc = UIStoryboard(name: "NewNews", bundle: nil).instantiateInitialViewController() as! NewNewsViewController
vc.delegate = self
vc.event = self.event
self.navigationController?.pushViewController(vc, animated: true)
}
func newsCreated() {
self.loadNews()
}
func tableView(_ tableView: UITableView, editActionsForRowAt indexPath: IndexPath) -> [UITableViewRowAction]? {
let sectionType = self.getSectionType(section: indexPath.section)
if (sectionType == .news && (self.membership?.isCoach())!) {
let delete = UITableViewRowAction(style: .destructive, title: L10n.delete) { (action, indexPath) in
self.deleteNews(indexPath: indexPath)
}
return [delete]
}
return []
}
func deleteNews(indexPath:IndexPath) {
guard indexPath.row < self.news.count else {
return
}
let news = self.news[indexPath.row]
DataHandler.def.deleteNews(teamId: (self.event?.teamId)!, news: news).done({ response in
if (self.news.count > 1) {
self.news.remove(at: indexPath.row)
self.tableView.deleteRows(at: [indexPath], with: .fade)
}
self.loadNews()
}).catch({ err in
})
}
func participationChanged() {
if let headerView = self.tableView.headerView(forSection: Section.participation.rawValue) as? ReusableParticipationHeaderView {
headerView.tableHeader.refresh()
}
}
func delete(event: Event) {
if let delegate = self.previousVC as? EventDetailCellDeleteDelegate {
delegate.delete(event: self.event!)
}
}
func userIsCoach() -> Bool {
return (self.membership?.team?.id == self.event?.teamId && (self.membership?.isCoach())!)
}
func sendReminder(event: Event) {
self.loadData(text: nil, promise: DataHandler.def.sendReminder(teamId: self.event!.teamId, eventId: self.event!.id)).done({_ in
DropdownAlert.success(message: L10n.theReminderWasSentSuccessfully)
})
}
}
|
mit
|
a034ca56517103081ecc132cf71dcd37
| 33.659763 | 285 | 0.604524 | 5.071429 | false | false | false | false |
EvanJq/JQNavigationController
|
JQNavigationController/Classes/WrapNavigationController.swift
|
1
|
2486
|
//
// WrapNavigationController.swift
// WrapNavigationController
//
// Created by Evan on 2017/7/5.
// Copyright © 2017年 ChenJianqiang. All rights reserved.
//
import UIKit
/// 中间控制器,只负责navbar,导航栏事件传递至JQNavigationController处理
class WrapNavigationController: UINavigationController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
self.navigationBar.barTintColor = UIColor.white
self.navigationBar.isTranslucent = true
}
override var interactivePopGestureRecognizer: UIGestureRecognizer? {
get {
return self.navigationController?.interactivePopGestureRecognizer
}
}
override var delegate: UINavigationControllerDelegate? {
set {
self.navigationController?.delegate = newValue
}
get {
return self.navigationController?.delegate
}
}
override var visibleViewController: UIViewController? {
get {
if let viewController = self.navigationController?.visibleViewController as? WrapViewController {
return viewController.rootViewController
}
return nil
}
}
override var isToolbarHidden: Bool {
set {
self.navigationController?.isToolbarHidden = isToolbarHidden
}
get {
if let isToolbarHidden = self.navigationController?.isToolbarHidden {
return isToolbarHidden
}
return true
}
}
override func pushViewController(_ viewController: UIViewController, animated: Bool) {
if viewControllers.count > 0 {
self.navigationController?.pushViewController(viewController, animated: true)
} else {
super.pushViewController(viewController, animated: true)
}
}
override func popViewController(animated: Bool) -> UIViewController? {
return self.navigationController?.popViewController(animated: animated)
}
override func popToViewController(_ viewController: UIViewController, animated: Bool) -> [UIViewController]? {
return self.navigationController?.popToViewController(viewController, animated: animated)
}
override func popToRootViewController(animated: Bool) -> [UIViewController]? {
return self.navigationController?.popToRootViewController(animated: animated)
}
}
|
mit
|
f2dd2ab0a3c68395309076241abad84c
| 29.5375 | 114 | 0.669259 | 5.944039 | false | false | false | false |
LiulietLee/Pick-Color
|
Pick Color/AboutViewController.swift
|
1
|
2447
|
//
// AboutViewController.swift
// Pick Color
//
// Created by Liuliet.Lee on 11/9/2016.
// Copyright © 2016 Liuliet.Lee. All rights reserved.
//
import UIKit
import MessageUI
class AboutViewController: UIViewController, MFMailComposeViewControllerDelegate {
@IBOutlet weak var menu: UIBarButtonItem!
override func viewDidLoad() {
super.viewDidLoad()
menu.target = self.revealViewController()
menu.action = #selector(SWRevealViewController.revealToggle(_:))
view.addGestureRecognizer(revealViewController().panGestureRecognizer())
}
private let links = [
"https://www.facebook.com/liuliet.lee",
"http://space.bilibili.com/4056345/#!/index",
"https://plus.google.com/u/0/+LiulietLee",
]
private let mailAddress = "[email protected]"
@IBAction func openLink(associatedWith button: UIButton){
UIApplication.shared.openURL(URL(string: links[(button.tag < links.count ? button.tag : 0)])!)
}
@IBAction func emailButtonTapped() {
let sheet = UIAlertController(title: nil, message: nil, preferredStyle: .actionSheet)
sheet.addAction(UIAlertAction(title: sendMailString, style: .default, handler: { (action) in
self.sendMail()
}))
sheet.addAction(UIAlertAction(title: copyMailAddrString, style: .default, handler: { (action) in
UIPasteboard.general.string = self.mailAddress
}))
sheet.addAction(UIAlertAction(title: negativeButtonString, style: .cancel, handler: nil))
present(sheet, animated: true, completion: nil)
}
fileprivate func sendMail() {
if MFMailComposeViewController.canSendMail() {
let mail = MFMailComposeViewController()
mail.mailComposeDelegate = self
mail.setToRecipients([mailAddress])
present(mail, animated: true, completion: nil)
} else {
print("cannot send email")
let dialog = LLDialog()
dialog.title = titleOfCannotSendMailString
dialog.message = messageOfCannotSendMailString
dialog.setNegativeButton(withTitle: " ")
dialog.show()
}
}
func mailComposeController(_ controller: MFMailComposeViewController, didFinishWith result: MFMailComposeResult, error: Error?) {
controller.dismiss(animated: true, completion: nil)
}
}
|
mit
|
034e23cc0e6ffa55ddd1e47fa76750b5
| 34.449275 | 133 | 0.655356 | 4.805501 | false | false | false | false |
ZhiQiang-Yang/pppt
|
v2exProject 2/Pods/Kingfisher/Sources/UIButton+Kingfisher.swift
|
8
|
30815
|
//
// UIButton+Kingfisher.swift
// Kingfisher
//
// Created by Wei Wang on 15/4/13.
//
// Copyright (c) 2016 Wei Wang <[email protected]>
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
#if os(iOS) || os(tvOS)
import UIKit
/**
* Set image to use from web for a specified state.
*/
extension UIButton {
/**
Set an image to use for a specified state with a resource.
It will ask for Kingfisher's manager to get the image for the `cacheKey` property in `resource` and then set it for a button state.
The memory and disk will be searched first. If the manager does not find it, it will try to download the image at the `resource.downloadURL` and store it with `resource.cacheKey` for next use.
- parameter resource: Resource object contains information such as `cacheKey` and `downloadURL`.
- parameter state: The state that uses the specified image.
- returns: A task represents the retrieving process.
*/
public func kf_setImageWithResource(resource: Resource,
forState state: UIControlState) -> RetrieveImageTask
{
return kf_setImageWithResource(resource, forState: state, placeholderImage: nil, optionsInfo: nil, progressBlock: nil, completionHandler: nil)
}
/**
Set an image to use for a specified state with a URL.
It will ask for Kingfisher's manager to get the image for the URL and then set it for a button state.
The memory and disk will be searched first with `URL.absoluteString` as the cache key. If the manager does not find it, it will try to download the image at this URL and store the image with `URL.absoluteString` as cache key for next use.
If you need to specify the key other than `URL.absoluteString`, please use resource version of these APIs with `resource.cacheKey` set to what you want.
- parameter URL: The URL of image for specified state.
- parameter state: The state that uses the specified image.
- returns: A task represents the retrieving process.
*/
public func kf_setImageWithURL(URL: NSURL,
forState state: UIControlState) -> RetrieveImageTask
{
return kf_setImageWithURL(URL, forState: state, placeholderImage: nil, optionsInfo: nil, progressBlock: nil, completionHandler: nil)
}
/**
Set an image to use for a specified state with a resource and a placeholder image.
- parameter resource: Resource object contains information such as `cacheKey` and `downloadURL`.
- parameter state: The state that uses the specified image.
- parameter placeholderImage: A placeholder image when retrieving the image at URL.
- returns: A task represents the retrieving process.
*/
public func kf_setImageWithResource(resource: Resource,
forState state: UIControlState,
placeholderImage: UIImage?) -> RetrieveImageTask
{
return kf_setImageWithResource(resource, forState: state, placeholderImage: placeholderImage, optionsInfo: nil, progressBlock: nil, completionHandler: nil)
}
/**
Set an image to use for a specified state with a URL and a placeholder image.
- parameter URL: The URL of image for specified state.
- parameter state: The state that uses the specified image.
- parameter placeholderImage: A placeholder image when retrieving the image at URL.
- returns: A task represents the retrieving process.
*/
public func kf_setImageWithURL(URL: NSURL,
forState state: UIControlState,
placeholderImage: UIImage?) -> RetrieveImageTask
{
return kf_setImageWithURL(URL, forState: state, placeholderImage: placeholderImage, optionsInfo: nil, progressBlock: nil, completionHandler: nil)
}
/**
Set an image to use for a specified state with a resource, a placeholder image and options.
- parameter resource: Resource object contains information such as `cacheKey` and `downloadURL`.
- parameter state: The state that uses the specified image.
- parameter placeholderImage: A placeholder image when retrieving the image at URL.
- parameter optionsInfo: A dictionary could control some behaviors. See `KingfisherOptionsInfo` for more.
- returns: A task represents the retrieving process.
*/
public func kf_setImageWithResource(resource: Resource,
forState state: UIControlState,
placeholderImage: UIImage?,
optionsInfo: KingfisherOptionsInfo?) -> RetrieveImageTask
{
return kf_setImageWithResource(resource, forState: state, placeholderImage: placeholderImage, optionsInfo: optionsInfo, progressBlock: nil, completionHandler: nil)
}
/**
Set an image to use for a specified state with a URL, a placeholder image and options.
- parameter URL: The URL of image for specified state.
- parameter state: The state that uses the specified image.
- parameter placeholderImage: A placeholder image when retrieving the image at URL.
- parameter optionsInfo: A dictionary could control some behaviors. See `KingfisherOptionsInfo` for more.
- returns: A task represents the retrieving process.
*/
public func kf_setImageWithURL(URL: NSURL,
forState state: UIControlState,
placeholderImage: UIImage?,
optionsInfo: KingfisherOptionsInfo?) -> RetrieveImageTask
{
return kf_setImageWithURL(URL, forState: state, placeholderImage: placeholderImage, optionsInfo: optionsInfo, progressBlock: nil, completionHandler: nil)
}
/**
Set an image to use for a specified state with a resource, a placeholder image, options and completion handler.
- parameter resource: Resource object contains information such as `cacheKey` and `downloadURL`.
- parameter state: The state that uses the specified image.
- parameter placeholderImage: A placeholder image when retrieving the image at URL.
- parameter optionsInfo: A dictionary could control some behaviors. See `KingfisherOptionsInfo` for more.
- parameter completionHandler: Called when the image retrieved and set.
- returns: A task represents the retrieving process.
- note: `completionHandler` will be invoked in main thread.
The `CallbackDispatchQueue` specified in `optionsInfo` will not be used in callbacks of this method.
*/
public func kf_setImageWithResource(resource: Resource,
forState state: UIControlState,
placeholderImage: UIImage?,
optionsInfo: KingfisherOptionsInfo?,
completionHandler: CompletionHandler?) -> RetrieveImageTask
{
return kf_setImageWithResource(resource, forState: state, placeholderImage: placeholderImage, optionsInfo: optionsInfo, progressBlock: nil, completionHandler: completionHandler)
}
/**
Set an image to use for a specified state with a URL, a placeholder image, options and completion handler.
- parameter URL: The URL of image for specified state.
- parameter state: The state that uses the specified image.
- parameter placeholderImage: A placeholder image when retrieving the image at URL.
- parameter optionsInfo: A dictionary could control some behaviors. See `KingfisherOptionsInfo` for more.
- parameter completionHandler: Called when the image retrieved and set.
- returns: A task represents the retrieving process.
- note: `completionHandler` will be invoked in main thread.
The `CallbackDispatchQueue` specified in `optionsInfo` will not be used in callbacks of this method.
*/
public func kf_setImageWithURL(URL: NSURL,
forState state: UIControlState,
placeholderImage: UIImage?,
optionsInfo: KingfisherOptionsInfo?,
completionHandler: CompletionHandler?) -> RetrieveImageTask
{
return kf_setImageWithURL(URL, forState: state, placeholderImage: placeholderImage, optionsInfo: optionsInfo, progressBlock: nil, completionHandler: completionHandler)
}
/**
Set an image to use for a specified state with a resource, a placeholder image, options, progress handler and completion handler.
- parameter resource: Resource object contains information such as `cacheKey` and `downloadURL`.
- parameter state: The state that uses the specified image.
- parameter placeholderImage: A placeholder image when retrieving the image at URL.
- parameter optionsInfo: A dictionary could control some behaviors. See `KingfisherOptionsInfo` for more.
- parameter progressBlock: Called when the image downloading progress gets updated.
- parameter completionHandler: Called when the image retrieved and set.
- returns: A task represents the retrieving process.
- note: Both the `progressBlock` and `completionHandler` will be invoked in main thread.
The `CallbackDispatchQueue` specified in `optionsInfo` will not be used in callbacks of this method.
*/
public func kf_setImageWithResource(resource: Resource,
forState state: UIControlState,
placeholderImage: UIImage?,
optionsInfo: KingfisherOptionsInfo?,
progressBlock: DownloadProgressBlock?,
completionHandler: CompletionHandler?) -> RetrieveImageTask
{
setImage(placeholderImage, forState: state)
kf_setWebURL(resource.downloadURL, forState: state)
let task = KingfisherManager.sharedManager.retrieveImageWithResource(resource, optionsInfo: optionsInfo,
progressBlock: { receivedSize, totalSize in
if let progressBlock = progressBlock {
progressBlock(receivedSize: receivedSize, totalSize: totalSize)
}
},
completionHandler: {[weak self] image, error, cacheType, imageURL in
dispatch_async_safely_to_main_queue {
if let sSelf = self {
sSelf.kf_setImageTask(nil)
if imageURL == sSelf.kf_webURLForState(state) && image != nil {
sSelf.setImage(image, forState: state)
}
completionHandler?(image: image, error: error, cacheType: cacheType, imageURL: imageURL)
}
}
})
kf_setImageTask(task)
return task
}
/**
Set an image to use for a specified state with a URL, a placeholder image, options, progress handler and completion handler.
- parameter URL: The URL of image for specified state.
- parameter state: The state that uses the specified image.
- parameter placeholderImage: A placeholder image when retrieving the image at URL.
- parameter optionsInfo: A dictionary could control some behaviors. See `KingfisherOptionsInfo` for more.
- parameter progressBlock: Called when the image downloading progress gets updated.
- parameter completionHandler: Called when the image retrieved and set.
- returns: A task represents the retrieving process.
- note: Both the `progressBlock` and `completionHandler` will be invoked in main thread.
The `CallbackDispatchQueue` specified in `optionsInfo` will not be used in callbacks of this method.
*/
public func kf_setImageWithURL(URL: NSURL,
forState state: UIControlState,
placeholderImage: UIImage?,
optionsInfo: KingfisherOptionsInfo?,
progressBlock: DownloadProgressBlock?,
completionHandler: CompletionHandler?) -> RetrieveImageTask
{
return kf_setImageWithResource(Resource(downloadURL: URL),
forState: state,
placeholderImage: placeholderImage,
optionsInfo: optionsInfo,
progressBlock: progressBlock,
completionHandler: completionHandler)
}
}
private var lastURLKey: Void?
private var imageTaskKey: Void?
// MARK: - Runtime for UIButton image
extension UIButton {
/**
Get the image URL binded to this button for a specified state.
- parameter state: The state that uses the specified image.
- returns: Current URL for image.
*/
public func kf_webURLForState(state: UIControlState) -> NSURL? {
return kf_webURLs[NSNumber(unsignedLong:state.rawValue)] as? NSURL
}
private func kf_setWebURL(URL: NSURL, forState state: UIControlState) {
kf_webURLs[NSNumber(unsignedLong:state.rawValue)] = URL
}
private var kf_webURLs: NSMutableDictionary {
var dictionary = objc_getAssociatedObject(self, &lastURLKey) as? NSMutableDictionary
if dictionary == nil {
dictionary = NSMutableDictionary()
kf_setWebURLs(dictionary!)
}
return dictionary!
}
private func kf_setWebURLs(URLs: NSMutableDictionary) {
objc_setAssociatedObject(self, &lastURLKey, URLs, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
}
private var kf_imageTask: RetrieveImageTask? {
return objc_getAssociatedObject(self, &imageTaskKey) as? RetrieveImageTask
}
private func kf_setImageTask(task: RetrieveImageTask?) {
objc_setAssociatedObject(self, &imageTaskKey, task, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
}
}
/**
* Set background image to use from web for a specified state.
*/
extension UIButton {
/**
Set the background image to use for a specified state with a resource.
It will ask for Kingfisher's manager to get the image for the `cacheKey` property in `resource` and then set it for a button state.
The memory and disk will be searched first. If the manager does not find it, it will try to download the image at the `resource.downloadURL` and store it with `resource.cacheKey` for next use.
- parameter resource: Resource object contains information such as `cacheKey` and `downloadURL`.
- parameter state: The state that uses the specified image.
- returns: A task represents the retrieving process.
*/
public func kf_setBackgroundImageWithResource(resource: Resource,
forState state: UIControlState) -> RetrieveImageTask
{
return kf_setBackgroundImageWithResource(resource, forState: state, placeholderImage: nil, optionsInfo: nil, progressBlock: nil, completionHandler: nil)
}
/**
Set the background image to use for a specified state with a URL.
It will ask for Kingfisher's manager to get the image for the URL and then set it for a button state.
The memory and disk will be searched first with `URL.absoluteString` as the cache key. If the manager does not find it, it will try to download the image at this URL and store the image with `URL.absoluteString` as cache key for next use.
If you need to specify the key other than `URL.absoluteString`, please use resource version of these APIs with `resource.cacheKey` set to what you want.
- parameter URL: The URL of image for specified state.
- parameter state: The state that uses the specified image.
- returns: A task represents the retrieving process.
*/
public func kf_setBackgroundImageWithURL(URL: NSURL,
forState state: UIControlState) -> RetrieveImageTask
{
return kf_setBackgroundImageWithURL(URL, forState: state, placeholderImage: nil, optionsInfo: nil, progressBlock: nil, completionHandler: nil)
}
/**
Set the background image to use for a specified state with a resource and a placeholder image.
- parameter resource: Resource object contains information such as `cacheKey` and `downloadURL`.
- parameter state: The state that uses the specified image.
- parameter placeholderImage: A placeholder image when retrieving the image at URL.
- returns: A task represents the retrieving process.
*/
public func kf_setBackgroundImageWithResource(resource: Resource,
forState state: UIControlState,
placeholderImage: UIImage?) -> RetrieveImageTask
{
return kf_setBackgroundImageWithResource(resource, forState: state, placeholderImage: placeholderImage, optionsInfo: nil, progressBlock: nil, completionHandler: nil)
}
/**
Set the background image to use for a specified state with a URL and a placeholder image.
- parameter URL: The URL of image for specified state.
- parameter state: The state that uses the specified image.
- parameter placeholderImage: A placeholder image when retrieving the image at URL.
- returns: A task represents the retrieving process.
*/
public func kf_setBackgroundImageWithURL(URL: NSURL,
forState state: UIControlState,
placeholderImage: UIImage?) -> RetrieveImageTask
{
return kf_setBackgroundImageWithURL(URL, forState: state, placeholderImage: placeholderImage, optionsInfo: nil, progressBlock: nil, completionHandler: nil)
}
/**
Set the background image to use for a specified state with a resource, a placeholder image and options.
- parameter resource: Resource object contains information such as `cacheKey` and `downloadURL`.
- parameter state: The state that uses the specified image.
- parameter placeholderImage: A placeholder image when retrieving the image at URL.
- parameter optionsInfo: A dictionary could control some behaviors. See `KingfisherOptionsInfo` for more.
- returns: A task represents the retrieving process.
*/
public func kf_setBackgroundImageWithResource(resource: Resource,
forState state: UIControlState,
placeholderImage: UIImage?,
optionsInfo: KingfisherOptionsInfo?) -> RetrieveImageTask
{
return kf_setBackgroundImageWithResource(resource, forState: state, placeholderImage: placeholderImage, optionsInfo: optionsInfo, progressBlock: nil, completionHandler: nil)
}
/**
Set the background image to use for a specified state with a URL, a placeholder image and options.
- parameter URL: The URL of image for specified state.
- parameter state: The state that uses the specified image.
- parameter placeholderImage: A placeholder image when retrieving the image at URL.
- parameter optionsInfo: A dictionary could control some behaviors. See `KingfisherOptionsInfo` for more.
- returns: A task represents the retrieving process.
*/
public func kf_setBackgroundImageWithURL(URL: NSURL,
forState state: UIControlState,
placeholderImage: UIImage?,
optionsInfo: KingfisherOptionsInfo?) -> RetrieveImageTask
{
return kf_setBackgroundImageWithURL(URL, forState: state, placeholderImage: placeholderImage, optionsInfo: optionsInfo, progressBlock: nil, completionHandler: nil)
}
/**
Set the background image to use for a specified state with a resource, a placeholder image, options and completion handler.
- parameter resource: Resource object contains information such as `cacheKey` and `downloadURL`.
- parameter state: The state that uses the specified image.
- parameter placeholderImage: A placeholder image when retrieving the image at URL.
- parameter optionsInfo: A dictionary could control some behaviors. See `KingfisherOptionsInfo` for more.
- parameter completionHandler: Called when the image retrieved and set.
- returns: A task represents the retrieving process.
- note: `completionHandler` will be invoked in main thread.
The `CallbackDispatchQueue` specified in `optionsInfo` will not be used in callbacks of this method.
*/
public func kf_setBackgroundImageWithResource(resource: Resource,
forState state: UIControlState,
placeholderImage: UIImage?,
optionsInfo: KingfisherOptionsInfo?,
completionHandler: CompletionHandler?) -> RetrieveImageTask
{
return kf_setBackgroundImageWithResource(resource, forState: state, placeholderImage: placeholderImage, optionsInfo: optionsInfo, progressBlock: nil, completionHandler: completionHandler)
}
/**
Set the background image to use for a specified state with a URL, a placeholder image, options and completion handler.
- parameter URL: The URL of image for specified state.
- parameter state: The state that uses the specified image.
- parameter placeholderImage: A placeholder image when retrieving the image at URL.
- parameter optionsInfo: A dictionary could control some behaviors. See `KingfisherOptionsInfo` for more.
- parameter completionHandler: Called when the image retrieved and set.
- returns: A task represents the retrieving process.
- note: `completionHandler` will be invoked in main thread.
The `CallbackDispatchQueue` specified in `optionsInfo` will not be used in callbacks of this method.
*/
public func kf_setBackgroundImageWithURL(URL: NSURL,
forState state: UIControlState,
placeholderImage: UIImage?,
optionsInfo: KingfisherOptionsInfo?,
completionHandler: CompletionHandler?) -> RetrieveImageTask
{
return kf_setBackgroundImageWithURL(URL, forState: state, placeholderImage: placeholderImage, optionsInfo: optionsInfo, progressBlock: nil, completionHandler: completionHandler)
}
/**
Set the background image to use for a specified state with a resource,
a placeholder image, options progress handler and completion handler.
- parameter resource: Resource object contains information such as `cacheKey` and `downloadURL`.
- parameter state: The state that uses the specified image.
- parameter placeholderImage: A placeholder image when retrieving the image at URL.
- parameter optionsInfo: A dictionary could control some behaviors. See `KingfisherOptionsInfo` for more.
- parameter progressBlock: Called when the image downloading progress gets updated.
- parameter completionHandler: Called when the image retrieved and set.
- returns: A task represents the retrieving process.
- note: Both the `progressBlock` and `completionHandler` will be invoked in main thread.
The `CallbackDispatchQueue` specified in `optionsInfo` will not be used in callbacks of this method.
*/
public func kf_setBackgroundImageWithResource(resource: Resource,
forState state: UIControlState,
placeholderImage: UIImage?,
optionsInfo: KingfisherOptionsInfo?,
progressBlock: DownloadProgressBlock?,
completionHandler: CompletionHandler?) -> RetrieveImageTask
{
setBackgroundImage(placeholderImage, forState: state)
kf_setBackgroundWebURL(resource.downloadURL, forState: state)
let task = KingfisherManager.sharedManager.retrieveImageWithResource(resource, optionsInfo: optionsInfo,
progressBlock: { receivedSize, totalSize in
if let progressBlock = progressBlock {
progressBlock(receivedSize: receivedSize, totalSize: totalSize)
}
},
completionHandler: { [weak self] image, error, cacheType, imageURL in
dispatch_async_safely_to_main_queue {
if let sSelf = self {
sSelf.kf_setBackgroundImageTask(nil)
if imageURL == sSelf.kf_backgroundWebURLForState(state) && image != nil {
sSelf.setBackgroundImage(image, forState: state)
}
completionHandler?(image: image, error: error, cacheType: cacheType, imageURL: imageURL)
}
}
})
kf_setBackgroundImageTask(task)
return task
}
/**
Set the background image to use for a specified state with a URL,
a placeholder image, options progress handler and completion handler.
- parameter URL: The URL of image for specified state.
- parameter state: The state that uses the specified image.
- parameter placeholderImage: A placeholder image when retrieving the image at URL.
- parameter optionsInfo: A dictionary could control some behaviors. See `KingfisherOptionsInfo` for more.
- parameter progressBlock: Called when the image downloading progress gets updated.
- parameter completionHandler: Called when the image retrieved and set.
- returns: A task represents the retrieving process.
- note: Both the `progressBlock` and `completionHandler` will be invoked in main thread.
The `CallbackDispatchQueue` specified in `optionsInfo` will not be used in callbacks of this method.
*/
public func kf_setBackgroundImageWithURL(URL: NSURL,
forState state: UIControlState,
placeholderImage: UIImage?,
optionsInfo: KingfisherOptionsInfo?,
progressBlock: DownloadProgressBlock?,
completionHandler: CompletionHandler?) -> RetrieveImageTask
{
return kf_setBackgroundImageWithResource(Resource(downloadURL: URL),
forState: state,
placeholderImage: placeholderImage,
optionsInfo: optionsInfo,
progressBlock: progressBlock,
completionHandler: completionHandler)
}
}
private var lastBackgroundURLKey: Void?
private var backgroundImageTaskKey: Void?
// MARK: - Runtime for UIButton background image
extension UIButton {
/**
Get the background image URL binded to this button for a specified state.
- parameter state: The state that uses the specified background image.
- returns: Current URL for background image.
*/
public func kf_backgroundWebURLForState(state: UIControlState) -> NSURL? {
return kf_backgroundWebURLs[NSNumber(unsignedLong:state.rawValue)] as? NSURL
}
private func kf_setBackgroundWebURL(URL: NSURL, forState state: UIControlState) {
kf_backgroundWebURLs[NSNumber(unsignedLong:state.rawValue)] = URL
}
private var kf_backgroundWebURLs: NSMutableDictionary {
var dictionary = objc_getAssociatedObject(self, &lastBackgroundURLKey) as? NSMutableDictionary
if dictionary == nil {
dictionary = NSMutableDictionary()
kf_setBackgroundWebURLs(dictionary!)
}
return dictionary!
}
private func kf_setBackgroundWebURLs(URLs: NSMutableDictionary) {
objc_setAssociatedObject(self, &lastBackgroundURLKey, URLs, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
}
private var kf_backgroundImageTask: RetrieveImageTask? {
return objc_getAssociatedObject(self, &backgroundImageTaskKey) as? RetrieveImageTask
}
private func kf_setBackgroundImageTask(task: RetrieveImageTask?) {
objc_setAssociatedObject(self, &backgroundImageTaskKey, task, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
}
}
// MARK: - Cancel image download tasks.
extension UIButton {
/**
Cancel the image download task bounded to the image view if it is running.
Nothing will happen if the downloading has already finished.
*/
public func kf_cancelImageDownloadTask() {
kf_imageTask?.downloadTask?.cancel()
}
/**
Cancel the background image download task bounded to the image view if it is running.
Nothing will happen if the downloading has already finished.
*/
public func kf_cancelBackgroundImageDownloadTask() {
kf_backgroundImageTask?.downloadTask?.cancel()
}
}
#elseif os(OSX)
import AppKit
extension NSButton {
// Not Implemented yet.
}
#endif
|
apache-2.0
|
524f08a75fc2cf1680a68847b475d3db
| 49.766063 | 242 | 0.656596 | 5.849468 | false | false | false | false |
parrotbait/CorkWeather
|
Pods/GooglePlacePicker/Example/GooglePlacePickerDemos/AppDelegate.swift
|
1
|
2953
|
/*
* Copyright 2016 Google Inc. All rights reserved.
*
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this
* file except in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under
* the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF
* ANY KIND, either express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
import UIKit
import GoogleMaps
import GooglePlaces
/// Application delegate for the PlacePicker demo app.
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication,
didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
// Do a quick check to see if you've provided an API key, in a real app you wouldn't need this
// but for the demo it means we can provide a better error message if you haven't.
if kMapsAPIKey.isEmpty || kPlacesAPIKey.isEmpty {
// Blow up if API keys have not yet been set.
let bundleId = Bundle.main.bundleIdentifier!
let msg = "Configure API keys inside SDKDemoAPIKey.swift for your bundle `\(bundleId)`, " +
"see README.GooglePlacePickerDemos for more information"
fatalError(msg)
}
// Provide the Places API with your API key.
GMSPlacesClient.provideAPIKey(kPlacesAPIKey)
// Provide the Maps API with your API key. We need to provide this as well because the Place
// Picker displays a Google Map.
GMSServices.provideAPIKey(kMapsAPIKey)
// Log the required open source licenses! Yes, just logging them is not enough but is good for
// a demo.
print(GMSPlacesClient.openSourceLicenseInfo())
print(GMSServices.openSourceLicenseInfo())
// Construct a window and the split split pane view controller we are going to embed our UI in.
let window = UIWindow(frame: UIScreen.main.bounds)
let rootViewController = PickAPlaceViewController()
let splitPaneViewController = SplitPaneViewController(rootViewController: rootViewController)
// Wrap the split pane controller in a inset controller to get the map displaying behind our
// content on iPad devices.
let mapController = BackgroundMapViewController()
rootViewController.mapViewController = mapController
let insetController = InsetViewController(backgroundViewController: mapController,
contentViewController: splitPaneViewController)
window.rootViewController = insetController
// Make the window visible and allow the app to continue initialization.
window.makeKeyAndVisible()
self.window = window
return true
}
}
|
mit
|
92136ba5fc556a74b8c37e704fa5b852
| 42.426471 | 112 | 0.732814 | 4.979764 | false | false | false | false |
dbruzzone/wishing-tree
|
iOS/Annotate/Annotate/MediaItemTableViewController.swift
|
1
|
3721
|
//
// MediaItemTableViewController.swift
// Annotate
//
// Created by Davide Bruzzone on 11/14/15.
// Copyright © 2015 Bitwise Samurai. All rights reserved.
//
import UIKit
class MediaItemTableViewController: UITableViewController {
var mediaItem: MediaItem?
// MARK: - Outlets
@IBOutlet weak var mediaItemTitle: UILabel!
@IBOutlet weak var mediaItemArtist: UILabel!
@IBOutlet weak var currentPosition: UISlider!
@IBOutlet weak var ribbonControllerLabel: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
// Uncomment the following line to preserve selection between presentations
// self.clearsSelectionOnViewWillAppear = false
// Uncomment the following line to display an Edit button in the navigation bar for this view controller.
// self.navigationItem.rightBarButtonItem = self.editButtonItem()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: - Table view data source
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
// #warning Incomplete implementation, return the number of sections
return 0
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// #warning Incomplete implementation, return the number of rows
return 0
}
/*
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath)
// Configure the cell...
return cell
}
*/
/*
// Override to support conditional editing of the table view.
override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool {
// Return false if you do not want the specified item to be editable.
return true
}
*/
/*
// Override to support editing the table view.
override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
if editingStyle == .Delete {
// Delete the row from the data source
tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade)
} else if editingStyle == .Insert {
// Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
}
}
*/
/*
// 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 false if you do not want the item to be re-orderable.
return true
}
*/
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
// MARK: - Actions
@IBAction func back(sender: AnyObject) {
}
@IBAction func forward(sender: AnyObject) {
}
@IBAction func note(sender: AnyObject) {
}
}
|
gpl-3.0
|
f8d2d940542e991192e67bc53955f811
| 30.525424 | 157 | 0.67957 | 5.446559 | false | false | false | false |
sviatoslav/EndpointProcedure
|
Sources/Decoding/DataDecoder.swift
|
3
|
3600
|
//
// DataDecoder.swift
// EndpointProcedure
//
// Created by Sviatoslav Yakymiv on 8/29/18.
// Copyright © 2018 Sviatoslav Yakymiv. All rights reserved.
//
import Foundation
public protocol DataDecoder {
func decode<T>(_ type: T.Type, from data: Data) throws -> T where T : Decodable
func decode<T>(_ type: T.Type, from data: Data, codingPath: [CodingKey]) throws -> T where T : Decodable
}
extension DataDecoder {
fileprivate func object(at codingPath: [CodingKey], of object: Any) throws -> Any {
var innerObject = object
var iterator = codingPath.makeIterator()
var currentPath: [CodingKey] = []
while let currentKey = iterator.next() {
currentPath.append(currentKey)
guard let newInnerObject = (innerObject as? [AnyHashable: Any])?[currentKey.stringValue] else {
throw DecodingError.keyNotFound(currentKey, DecodingError.Context(codingPath: currentPath,
debugDescription: "Key not found"))
}
innerObject = newInnerObject
}
return innerObject
}
func decode<T>(_ type: T.Type, from data: Data, codingPath: [CodingKey],
formatName: String,
deserialization: (Data) throws -> Any,
serialization: (Any) throws -> Data) throws -> T where T : Decodable {
guard !codingPath.isEmpty else {
return try self.decode(type, from: data)
}
let result: T
do {
let object = try deserialization(data)
let innerObject = try self.object(at: codingPath, of: object)
let innerData = try serialization(innerObject)
result = try self.decode(type, from: innerData)
} catch let error where !(error is DecodingError) {
let description = "The given data was not valid \(formatName)."
throw DecodingError.dataCorrupted(DecodingError.Context(codingPath: [], debugDescription: description,
underlyingError: error))
}
return result
}
}
extension DataDecoder where Self: JSONDecoder {
public func decode<T>(_ type: T.Type, from data: Data, codingPath: [CodingKey]) throws -> T where T : Decodable {
return try self.decode(type, from: data, codingPath: codingPath, formatName: "JSON",
deserialization: { return try JSONSerialization.jsonObject(with: $0, options: []) },
serialization: { return try JSONSerialization.data(withJSONObject: $0) })
}
}
extension DataDecoder where Self: PropertyListDecoder {
public func decode<T>(_ type: T.Type, from data: Data, codingPath: [CodingKey]) throws -> T where T : Decodable {
var plistFormat = PropertyListSerialization.PropertyListFormat.binary
let deserialization: (Data) throws -> Any = {
return try PropertyListSerialization.propertyList(from: $0, format: &plistFormat)
}
let serialization: (Any) throws -> Data = {
return try PropertyListSerialization.data(fromPropertyList: $0, format: plistFormat, options: 0)
}
return try self.decode(type, from: data, codingPath: codingPath, formatName: "property list",
deserialization: deserialization, serialization: serialization)
}
}
extension JSONDecoder: DataDecoder {}
extension PropertyListDecoder: DataDecoder {}
|
mit
|
538c9799cb1ae33f18c3da413b7756a9
| 45.74026 | 117 | 0.60878 | 5.054775 | false | false | false | false |
pyconjp/pyconjp-ios
|
PyConJP/View/SpreadsheetViewCell/TimetableTimeAxisCell.swift
|
1
|
706
|
//
// TimetableTimeAxisCell.swift
// PyConJP
//
// Created by Yutaro Muta on 2017/06/18.
// Copyright © 2017 PyCon JP. All rights reserved.
//
import UIKit
import SpreadsheetView
final class TimetableTimeAxisCell: Cell, NibInstantitable {
@IBOutlet weak var timeLabel: UILabel!
static let width: CGFloat = 44.0
static let height: CGFloat = 3.0
override func awakeFromNib() {
super.awakeFromNib()
gridlines = Gridlines.all(.solid(width: 1.0, color: .gray))
}
override func prepareForReuse() {
super.prepareForReuse()
timeLabel.text = nil
}
func fill(_ hour: String) {
timeLabel.text = hour
}
}
|
mit
|
5e8e15895ba47922be194aca6be214fd
| 20.363636 | 67 | 0.62695 | 4.051724 | false | false | false | false |
Ramesh-P/on-the-spot
|
On the Spot/GooglePlaces.swift
|
1
|
1484
|
//
// GooglePlaces.swift
// On the Spot
//
// Created by Ramesh Parthasarathy on 4/30/17.
// Copyright © 2017 Ramesh Parthasarathy. All rights reserved.
//
import Foundation
import UIKit
import CoreLocation
import SwiftyJSON
// MARK: GooglePlaces
struct GooglePlaces {
// MARK: Properties
let name: String
let address: String
let latitude: Double
let longitude: Double
let isOpen: Bool
let rating: Double
// MARK: Initializer
init(dictionary: [String:Any]) {
// Initialize
let json = JSON(dictionary)
name = json[Google.Places.name].stringValue
address = json[Google.Places.address].stringValue
latitude = json[Google.Places.geometry][Google.Places.location][Google.Places.latitude].doubleValue
longitude = json[Google.Places.geometry][Google.Places.location][Google.Places.longitude].doubleValue
isOpen = json[Google.Places.open][Google.Places.now].boolValue
rating = json[Google.Places.rating].doubleValue
}
// MARK: Class Functions
static func allPlacesFrom(_ results: Array<NSDictionary>) -> [GooglePlaces] {
var googlePlaces = [GooglePlaces]()
// Iterate through the result array, each place information is a dictionary
for result in results {
googlePlaces.append(GooglePlaces(dictionary: result as! [String : Any]))
}
return googlePlaces
}
}
|
mit
|
8619fab3bf0944554a64d944d28a1049
| 27.519231 | 109 | 0.654754 | 4.619938 | false | false | false | false |
XeresRazor/SwiftRaytracer
|
src/pathtracer/BVHNode.swift
|
1
|
2884
|
//
// BVHNode.swift
// Raytracer
//
// Created by David Green on 4/16/16.
// Copyright © 2016 David Green. All rights reserved.
//
import Foundation
import simd
public class BVHNode: Traceable {
public var left: Traceable
public var right: Traceable
public var box: AABB
public init(list l: [Traceable], time0: Double, time1: Double) {
var list = l
let axis = Int(3 * drand48())
if axis == 0 {
list.sort(isOrderedBefore: { (ah, bh) -> Bool in
let leftBox = ah.boundingBox(t0: 0, t1: 0)
let rightBox = bh.boundingBox(t0: 0, t1: 0)
if leftBox == nil || rightBox == nil {
print("No bounding box in BVHNode init()")
}
if leftBox!.minimum.x - rightBox!.minimum.x < 0.0 {
return false
} else {
return true
}
})
} else if axis == 1 {
list.sort(isOrderedBefore: { (ah, bh) -> Bool in
let leftBox = ah.boundingBox(t0: 0, t1: 0)
let rightBox = bh.boundingBox(t0: 0, t1: 0)
if leftBox == nil || rightBox == nil {
print("No bounding box in BVHNode init()")
}
if leftBox!.minimum.y - rightBox!.minimum.y < 0.0 {
return false
} else {
return true
}
})
} else {
list.sort(isOrderedBefore: { (ah, bh) -> Bool in
let leftBox = ah.boundingBox(t0: 0, t1: 0)
let rightBox = bh.boundingBox(t0: 0, t1: 0)
if leftBox == nil || rightBox == nil {
fatalError("No bounding box in BVHNode init()")
}
if leftBox!.minimum.z - rightBox!.minimum.z < 0.0 {
return false
} else {
return true
}
})
}
if list.count == 1 {
left = list[0]
right = list[0]
} else if list.count == 2 {
left = list[0]
right = list[1]
} else {
let leftArray = Array(list[0 ..< list.count / 2])
let rightArray = Array(list[(list.count / 2) ..< list.count])
left = BVHNode(list: leftArray, time0: time0, time1: time1)
right = BVHNode(list: rightArray, time0: time0, time1: time1)
}
let boxLeft = left.boundingBox(t0: time0, t1: time1)
let boxRight = right.boundingBox(t0: time0, t1: time1)
if boxLeft == nil || boxRight == nil {
fatalError("No bounding box in BVHNode init()")
}
box = surroundingBox(box0: boxLeft!, box1: boxRight!)
}
public override func trace(r: Ray, minimumT tMin: Double, maximumT tMax: Double) -> HitRecord? {
if box.hit(ray: r, tMin: tMin, tMax: tMax) {
let leftRec = left.trace(r: r, minimumT: tMin, maximumT: tMax)
let rightRec = right.trace(r: r, minimumT: tMin, maximumT: tMax)
if leftRec != nil && rightRec != nil {
if leftRec!.time < rightRec!.time {
return leftRec!
} else {
return rightRec!
}
} else if leftRec != nil {
return leftRec!
} else if rightRec != nil {
return rightRec!
} else {
return nil
}
} else {
return nil
}
}
public override func boundingBox(t0: Double, t1: Double) -> AABB? {
return box
}
}
|
mit
|
076a51144bedf58c0c2848d1b92d318a
| 25.943925 | 97 | 0.605272 | 2.826471 | false | false | false | false |
zach-unbounded/MineSweeper
|
MineSweeper/MSGridCell.swift
|
1
|
685
|
//
// MSGridCellModel.swift
// MineSweeper
//
// Created by Zachary Burgess on 01/12/2015.
// Copyright © 2015 V.Rei Ltd. All rights reserved.
//
import Foundation
enum GridCellState {
case GridCellStateEmpty
case GridCellStateCovered
case GridCellStateMined
case GridCellStateFlagged
}
class MSGridCell : Hashable {
var uuid: String;
var state : GridCellState;
var hashValue: Int {
return self.uuid.hashValue
}
init () {
uuid = NSUUID().UUIDString
state = .GridCellStateCovered
}
}
func == (lhs: MSGridCell, rhs: MSGridCell) -> Bool {
return lhs.state == rhs.state && lhs.uuid == rhs.uuid
}
|
gpl-3.0
|
891fcc1e713c888259b1947c8cca13db
| 18.542857 | 58 | 0.643275 | 3.677419 | false | false | false | false |
Masteryyz/CSYMicroBlockSina
|
CSYMicroBlockSina/CSYMicroBlockSina/Classes/Tools/Extension/DownLoadImageTools.swift
|
1
|
9103
|
//
// DownLoadImageTools.swift
// CSYMicroBlockSina
//
// Created by 姚彦兆 on 15/11/17.
// Copyright © 2015年 姚彦兆. All rights reserved.
//
import UIKit
class DownLoadImageTools: NSObject {
func downLoadImage ( imageUrl : NSString , finishedBlock : ( image : UIImage? ) -> ()) -> () {
let image = imageCacheDictionary[imageUrl as String];
if image != nil {
print("内存载入图片")
resultImage = image as! UIImage
finishedBlock(image: resultImage) ;
return
}else{
print("检测沙盒 == : \(imageUrl.appendCachePath())")
//尝试从沙盒中取出图片
// UIImage * sadboxImage = [UIImage imageWithContentsOfFile:model.icon.appendCachePath] ;
let sadboxImage : UIImage? = UIImage(contentsOfFile: (imageUrl.appendCachePath() as String))
if sadboxImage != nil {
print("从沙盒中取出图片")
// [self.imageCache setObject:sadboxImage forKey:model.icon];
imageCacheDictionary[imageUrl as String] = sadboxImage!
resultImage = sadboxImage! as UIImage
finishedBlock(image: resultImage)
return
}
}
if operationCacheDictionary[imageUrl as String] != nil {
//self.operationCache[model.icon]
print("正在下载中........")
finishedBlock(image: nil)
}
//开始下载图片的进程
let downloadImageOperation : NSBlockOperation = NSBlockOperation { () -> Void in
print("开始下载图片")
let imageURL = NSURL(string: imageUrl as String)
let imageData = NSData(contentsOfURL: imageURL!)
let image : UIImage? = UIImage(data: imageData!)
if image != nil {
NSOperationQueue.mainQueue().addOperationWithBlock({ () -> Void in
self.operationCacheDictionary.removeValueForKey(imageUrl as String)
imageData?.writeToFile(imageUrl.appendCachePath() as String, atomically: true)
if image != nil {
self.imageCacheDictionary[imageUrl as String] = image
self.resultImage = self.imageCacheDictionary[imageUrl as String] as! UIImage
print("-----------图片下载完成")
finishedBlock(image: self.resultImage)
return
}
})
}else{
print("URL 地址无法获取二进制图片数据")
}
}
operationCacheDictionary[imageUrl as String] = downloadImageOperation
myQueue.addOperation(downloadImageOperation)
// if (imageCacheDictionary[imageUrl as String] != nil) {
//
// let image = imageCacheDictionary[image as! String]
//
// resultImage = image as! UIImage
//
// }else{
//
// print("下载错误....")
//
// }
}
// func downLoadImage( imageUrl : NSString ) -> (UIImage?) {
//
// let image = imageCacheDictionary[imageUrl as String];
//
// if image != nil {
//
// print("内存载入图片")
//
// resultImage = image as! UIImage
//
// return resultImage ;
//
// }else{
//
// print("检测沙盒")
//
// //尝试从沙盒中取出图片
//
//// UIImage * sadboxImage = [UIImage imageWithContentsOfFile:model.icon.appendCachePath] ;
//
// let sadboxImage : UIImage? = UIImage(contentsOfFile: (imageUrl.appendCachePath() as String))
//
// if sadboxImage != nil {
//
// print("从沙盒中取出图片")
//
//// [self.imageCache setObject:sadboxImage forKey:model.icon];
//
// imageCacheDictionary[imageUrl as String] = sadboxImage!
//
// resultImage = sadboxImage! as UIImage
//
// return resultImage
// }
//
// }
//
// if operationCacheDictionary[imageUrl as String] != nil {
//
// //self.operationCache[model.icon]
//
// print("正在下载中........")
//
// return nil ;
//
// }
//
// dispatch_group_enter(group)
//
// //开始下载图片的进程
// let downloadImageOperation : NSBlockOperation = NSBlockOperation { () -> Void in
//
// print("开始下载图片")
//
// let imageURL = NSURL(string: imageUrl as String)
//
// let imageData = NSData(contentsOfURL: imageURL!)
//
// let image : UIImage? = UIImage(data: imageData!)
//
// if image != nil {
//
// NSOperationQueue.mainQueue().addOperationWithBlock({ () -> Void in
//
// self.operationCacheDictionary.removeValueForKey(imageUrl as String)
//
// imageData?.writeToFile(imageUrl.appendCachePath() as String, atomically: true)
//
// if image != nil {
//
// self.imageCacheDictionary[imageUrl as String] = image
//
// }
//
// })
//
// }else{
//
// print("URL 地址无法获取二进制图片数据")
//
// }
//
// dispatch_group_leave(self.group)
//
// }
//
// operationCacheDictionary[imageUrl as String] = downloadImageOperation
//
// myQueue.addOperation(downloadImageOperation)
//
// dispatch_group_notify(group, dispatch_get_main_queue()) { () -> Void in
//
// if (self.imageCacheDictionary[imageUrl as String] != nil) {
//
// let image = self.imageCacheDictionary[image as! String]
//
// self.resultImage = image as! UIImage
//
// }else{
//
// print("下载错误....")
//
// }
//
// }
//
// return resultImage
//
//}
lazy var myQueue : NSOperationQueue = {
let myQ = NSOperationQueue()
return myQ
}()
//图片缓存字典
lazy var imageCacheDictionary : [String : AnyObject] = [String : AnyObject]()
//线程操作缓存字典
lazy var operationCacheDictionary : [String : AnyObject] = [String : AnyObject]()
lazy var resultImage : UIImage = UIImage()
}
// NSBlockOperation * downloadImageOp = [NSBlockOperation blockOperationWithBlock:^{
//
// NSLog(@" >>>>>开始下载图片 %@ " , model.name);
//
// [NSThread sleepForTimeInterval:3];
//
// //分支下载图片
// NSString * imageStr = model.icon;
//
// NSURL * imageUrl = [NSURL URLWithString:imageStr];
//
// NSData * imageData = [NSData dataWithContentsOfURL:imageUrl];
//
// UIImage * image = [UIImage imageWithData:imageData];
//
// //下载完成之后通知主线程
// [[NSOperationQueue mainQueue] addOperationWithBlock:^{
//
// [self.operationCache removeObjectForKey:model.icon] ;
//
// //保存到沙盒(Save in sadbox)
//
// [imageData writeToFile:model.icon.appendCachePath atomically:NO];
//
// if (image)
// [self.imageCache setObject:image forKeyedSubscript:model.icon];
//
// [tableView reloadRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationNone];
//
// }];
//
// }];
//
// [self.operationCache setObject:downloadImageOp forKeyedSubscript:model.icon];
//
// [self.myQueue addOperation:downloadImageOp];
//
//}
|
mit
|
83206bf66de44af0cd175bc495263afe
| 28.302013 | 112 | 0.44984 | 5.070848 | false | false | false | false |
avito-tech/Marshroute
|
Example/NavigationDemo/Common/Services/ServiceFactoryImpl.swift
|
1
|
4394
|
import Marshroute
final class ServiceFactoryImpl: ServiceFactory {
// MARK: - Private properties
private let searchResultsCacherInstance: SearchResultsCacher
private let advertisementCacherInstance: AdvertisementCacher
private let touchEventObserverInstance: TouchEventObserver
private let touchEventForwarderInstance: TouchEventForwarder
private let topViewControllerFindingServiceInstance: TopViewControllerFindingService
private let moduleRegisteringServiceInstance: ModuleRegisteringServiceImpl
// MARK: - Init
init(topViewControllerFinder: TopViewControllerFinder,
rootTransitionsHandlerProvider: @escaping (() -> (ContainingTransitionsHandler?)),
transitionsMarker: TransitionsMarker,
transitionsTracker: TransitionsTracker,
transitionsCoordinatorDelegateHolder: TransitionsCoordinatorDelegateHolder)
{
searchResultsCacherInstance = SearchResultsCacherImpl()
advertisementCacherInstance = AdvertisementCacherImpl()
let touchEventObserverAndForwarder = TouchEventObserverImpl()
touchEventObserverInstance = touchEventObserverAndForwarder
touchEventForwarderInstance = touchEventObserverAndForwarder
topViewControllerFindingServiceInstance = TopViewControllerFindingServiceImpl(
topViewControllerFinder: topViewControllerFinder,
rootTransitionsHandlerProvider: rootTransitionsHandlerProvider
)
let moduleRegisteringServiceInstance = ModuleRegisteringServiceImpl(
transitionsTracker: transitionsTracker,
transitionsMarker: transitionsMarker,
// `1` means, that if previous module is `bananas` (distance to it from current module is 1),
// then attempt to open a new `bananas` module will open previous module instead of a new one.
// In contrast, if `bananas` module is preceding a previous module (distance to it from current module is 2),
// then attempt to open a new `bananas` module will succeed.
distanceThresholdBetweenSiblingModules: 1,
rootTransitionsHandlerProvider: rootTransitionsHandlerProvider
)
self.moduleRegisteringServiceInstance = moduleRegisteringServiceInstance
transitionsCoordinatorDelegateHolder.transitionsCoordinatorDelegate = moduleRegisteringServiceInstance
}
// MARK: - ServiceFactory
func categoriesProvider() -> CategoriesProvider {
return CategoriesProviderImpl()
}
func searchResultsProvider() -> SearchResultsProvider {
return SearchResultsProviderImpl(
searchResultsCacher: searchResultsCacher(),
categoriesProvider: categoriesProvider()
)
}
func advertisementProvider() -> AdvertisementProvider {
return AdvertisementProviderImpl(
searchResultsProvider: searchResultsProvider(),
advertisementCacher: advertisementCacher()
)
}
func rootModulesProvider() -> RootModulesProvider {
return RootModulesProviderImpl()
}
func timerService() -> TimerService {
return TimerServiceImpl()
}
func searchResultsCacher() -> SearchResultsCacher {
return searchResultsCacherInstance
}
func advertisementCacher() -> AdvertisementCacher {
return advertisementCacherInstance
}
func touchEventObserver() -> TouchEventObserver {
return touchEventObserverInstance
}
func touchEventForwarder() -> TouchEventForwarder {
return touchEventForwarderInstance
}
func topViewControllerFindingService() -> TopViewControllerFindingService {
return topViewControllerFindingServiceInstance
}
func moduleRegisteringService() -> ModuleRegisteringService {
return moduleRegisteringServiceInstance
}
func moduleTrackingService() -> ModuleTrackingService {
return moduleRegisteringServiceInstance
}
func authorizationModuleRegisteringService() -> AuthorizationModuleRegisteringService {
return moduleRegisteringServiceInstance
}
func authorizationModuleTrackingService() -> AuthorizationModuleTrackingService {
return moduleRegisteringServiceInstance
}
}
|
mit
|
d6ce52f81d780bec7c947087d12a1105
| 38.232143 | 121 | 0.717569 | 6.597598 | false | false | false | false |
tptee/Kenny
|
NerdCam/Util.swift
|
1
|
598
|
import UIKit
extension CALayer {
convenience init(contents: AnyObject?, contentsGravity: String) {
self.init()
self.contents = contents
self.contentsGravity = contentsGravity
}
}
extension UILabel {
convenience init(
frame: CGRect,
text: String,
textAlignment: NSTextAlignment,
textColor: UIColor,
backgroundColor: UIColor
) {
self.init(frame: frame)
self.text = text
self.textAlignment = textAlignment
self.textColor = textColor
self.backgroundColor = backgroundColor
}
}
|
mit
|
9f98bf61ace450998840ee1cf1602e08
| 22.96 | 69 | 0.628763 | 5.245614 | false | false | false | false |
Sticky-Gerbil/furry-adventure
|
FurryAdventure/RecipeSearchTableViewCell.swift
|
1
|
1120
|
//
// RecipeSearchTableViewCell.swift
// FurryAdventure
//
// Created by Sang Saephan on 3/31/17.
// Copyright © 2017 Sticky Gerbils. All rights reserved.
//
import UIKit
class RecipeSearchTableViewCell: UITableViewCell {
@IBOutlet weak var recipeImageView: UIImageView!
@IBOutlet weak var recipeNameLabel: UILabel!
@IBOutlet weak var recipeTimerLabel: UILabel!
@IBOutlet weak var numberOfIngredientsLabel: UILabel!
var currentIngredients = [Ingredient]()
func configureCell(recipe: Recipe, ingredients: [Ingredient]) {
if let image = recipe.imageUrl {
recipeImageView.setImageWith(image)
}
recipeNameLabel.text = recipe.name!
if recipe.cookTime != 0 {
recipeTimerLabel.text = "\((recipe.cookTime)!/60) Minutes"
} else {
recipeTimerLabel.text = "N/A"
}
currentIngredients = recipe.getIngredients()
numberOfIngredientsLabel.text = "Missing \(currentIngredients.count-ingredients.count) of \(currentIngredients.count) Ingredients"
}
}
|
apache-2.0
|
a4b195c2c6cf33a29a63701779ca2460
| 28.447368 | 138 | 0.654155 | 4.6625 | false | false | false | false |
bigbossstudio-dev/BBSInspector
|
Library/Classes/BBSInspectorBottomView.swift
|
1
|
7527
|
//
// BBSInspectorBottomView.swift
// BBSInspector
//
// Created by Cyril Chandelier on 05/03/15.
// Copyright (c) 2015 Big Boss Studio. All rights reserved.
//
import Foundation
import UIKit
let BBSInspectorBottomViewGapX = CGFloat(10.0)
let BBSInspectorBottomViewCornerSide = CGFloat(30.0)
let BBSInspectorBottomViewRatioPixelDifference = CGFloat(1.0)
internal class BBSInspectorBottomView: UIView
{
/**
Delegate
*/
internal var delegate: BBSInspectorBottomViewDelegate?
/**
Internal views
*/
private var contentLabel: UILabel!
private var stripView: UIView!
private var cornerButton: BBSInspectorCornerButton!
/**
Content displayed in bottom view label
*/
private var content: String? {
if let infoDictionary = NSBundle.mainBundle().infoDictionary {
let appName = infoDictionary[kCFBundleNameKey as String] as! String
let appVersion = infoDictionary["CFBundleShortVersionString"] as! String
let appBuild = infoDictionary[kCFBundleVersionKey as String] as! String
return "\(appName) (\(appVersion) | \(appBuild))"
}
return nil
}
/**
Current state of opening
*/
var opened: Bool = false
// MARK: - Initializers
override internal init(frame: CGRect)
{
super.init(frame: frame)
commonInit()
}
required internal init?(coder aDecoder: NSCoder)
{
super.init(coder: aDecoder)
commonInit()
}
private func commonInit()
{
self.autoresizingMask = [UIViewAutoresizing.FlexibleWidth, UIViewAutoresizing.FlexibleTopMargin]
}
// MARK: - Setup
private func setup()
{
reset()
let stripViewFrame = CGRectMake(0, 0, CGRectGetWidth(self.bounds) - BBSInspectorBottomViewCornerSide / 2 + BBSInspectorBottomViewRatioPixelDifference,
CGRectGetHeight(self.bounds))
// Content label
let delegateContent = delegate?.contentToDisplayInInspectorBottomView(self)
let content = delegateContent == nil ? self.content : delegateContent
let contentLabel = UILabel(frame: CGRectMake(BBSInspectorBottomViewGapX,
0,
CGRectGetWidth(stripViewFrame) - 2 * BBSInspectorBottomViewGapX,
CGRectGetHeight(stripViewFrame)))
contentLabel.autoresizingMask = [UIViewAutoresizing.FlexibleWidth, UIViewAutoresizing.FlexibleHeight]
contentLabel.font = UIFont.systemFontOfSize(12.0)
contentLabel.textColor = UIColor.whiteColor()
contentLabel.text = content
// Use blur for strip view on iOS 8+ systems, a simple semi-transparent view otherwise
var stripView: UIView
if #available(iOS 8.0, *)
{
stripView = UIVisualEffectView(effect: UIBlurEffect(style: UIBlurEffectStyle.Dark))
stripView.frame = stripViewFrame
(stripView as! UIVisualEffectView).contentView .addSubview(contentLabel)
}
else
{
stripView = UIView(frame: stripViewFrame)
let transparentView = UIView(frame: stripView.bounds)
transparentView.backgroundColor = UIColor.blackColor()
transparentView.alpha = 0.5
transparentView.autoresizingMask = [UIViewAutoresizing.FlexibleWidth, UIViewAutoresizing.FlexibleHeight]
stripView.addSubview(transparentView)
stripView.addSubview(contentLabel)
}
stripView.autoresizingMask = [UIViewAutoresizing.FlexibleWidth, UIViewAutoresizing.FlexibleHeight]
stripView.hidden = true
self.addSubview(stripView)
// Corner button
let cornerButton = BBSInspectorCornerButton(frame: CGRectMake(CGRectGetWidth(self.bounds) - BBSInspectorBottomViewCornerSide, 0, BBSInspectorBottomViewCornerSide, CGRectGetHeight(self.bounds)))
cornerButton.setStyle(style: BBSInspectorCornerButtonStyle.Plus, animated: false)
cornerButton.addTarget(self, action: "toggle", forControlEvents: UIControlEvents.TouchUpInside)
cornerButton.autoresizingMask = [UIViewAutoresizing.FlexibleLeftMargin, UIViewAutoresizing.FlexibleTopMargin]
self.addSubview(cornerButton)
// Gesture
let tapGestureRecognizer = UITapGestureRecognizer(target: self, action: "tapDetected:")
stripView.addGestureRecognizer(tapGestureRecognizer)
// Hold important views
self.contentLabel = contentLabel
self.stripView = stripView
self.cornerButton = cornerButton
}
private func reset()
{
contentLabel = nil
stripView = nil
cornerButton = nil
}
// MARK: - State management
/**
Add inspector bottom view to screen
*/
internal func show(inView view: UIView)
{
self.frame = CGRectMake(0, CGRectGetHeight(view.frame) - BBSInspectorBottomViewCornerSide + BBSInspectorBottomViewRatioPixelDifference, CGRectGetWidth(view.frame), BBSInspectorBottomViewCornerSide)
setup()
view.addSubview(self)
}
/**
Remove inspector bottom view from screen
*/
internal func hide()
{
self.removeFromSuperview()
}
/**
Open or close inspector bottom view according to its current state
*/
internal func toggle()
{
if self.superview == nil {
return
}
// Animation variables
let initialY = (opened ? 0 : CGRectGetHeight(self.bounds) + BBSInspectorBottomViewRatioPixelDifference)
let finalY = (opened ? CGRectGetHeight(self.bounds) + BBSInspectorBottomViewRatioPixelDifference : 0)
// Prepare animation
stripView.frame.origin.y = initialY
stripView.hidden = false
// Animate
UIView.animateWithDuration(0.3, animations: { () -> Void in
self.stripView.frame.origin.y = finalY
}) { (finished) -> Void in
self.opened = !self.opened
if !self.opened {
self.stripView.hidden = true
}
}
// Update corner button style
cornerButton.setStyle(style: (opened ? BBSInspectorCornerButtonStyle.Plus : BBSInspectorCornerButtonStyle.Close), animated: true)
}
// MARK: - UI Actions
internal func tapDetected(gesture: UITapGestureRecognizer)
{
delegate?.inspectorBottomViewTapped(self)
}
override func hitTest(point: CGPoint, withEvent event: UIEvent?) -> UIView?
{
if opened {
return super.hitTest(point, withEvent: event)
} else {
return CGRectContainsPoint(cornerButton.frame, self.convertPoint(point, toView: self)) ? self.cornerButton : nil
}
}
}
protocol BBSInspectorBottomViewDelegate
{
/**
Called when user tap on an open inspector bottom view
- parameter inspectorBottomView: The touched inspector bottom view
*/
func inspectorBottomViewTapped(bottomView: BBSInspectorBottomView)
/**
Called when configuring the bottom view, default content will be used if return string is empty
- parameter bottomView: The calling InspectorBottomView object
- returns: a string to be displayed in bottom view label
*/
func contentToDisplayInInspectorBottomView(bottomView: BBSInspectorBottomView) -> String?
}
|
mit
|
40566dc75aafc67d7bea409684b9e8f5
| 33.213636 | 205 | 0.657234 | 5.252617 | false | false | false | false |
coderwjq/swiftweibo
|
SwiftWeibo/SwiftWeibo/Classes/Home/PhotoBrowser/PhotoBrowserController.swift
|
1
|
5267
|
//
// PhotoBrowserController.swift
// SwiftWeibo
//
// Created by mzzdxt on 2016/11/11.
// Copyright © 2016年 wjq. All rights reserved.
//
import UIKit
import SnapKit
import SVProgressHUD
private let PhotoBrowserCell = "PhotoBrowserCell"
class PhotoBrowserController: UIViewController {
// MARK:- 定义属性
var indexPath: IndexPath
var picURLs: [URL]
// MARK:- 懒加载属性
fileprivate lazy var collectionView: UICollectionView = UICollectionView(frame: CGRect.zero, collectionViewLayout: PhotoBrowserCollectionViewLayout())
fileprivate lazy var closeBtn: UIButton = UIButton(bgColor: UIColor.darkGray, fontSize: 14, title: "关 闭")
fileprivate lazy var saveBtn: UIButton = UIButton(bgColor: UIColor.darkGray, fontSize: 14, title: "保 存")
// MARK:- 自定义构造函数
init(indexPath: IndexPath, picURLs: [URL]) {
self.indexPath = indexPath
self.picURLs = picURLs
super.init(nibName: nil, bundle: nil)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
// MARK:- 系统回调函数
override func loadView() {
super.loadView()
view.frame.size.width += 20
}
override func viewDidLoad() {
super.viewDidLoad()
// 设置UI界面
setupUI()
// 滚动到对应的图片
collectionView.scrollToItem(at: indexPath, at: .left, animated: false)
}
}
// MARK:- 设置UI界面
extension PhotoBrowserController {
fileprivate func setupUI() {
// 添加子控件
view.addSubview(collectionView)
view.addSubview(closeBtn)
view.addSubview(saveBtn)
// 设置子控件的frame
collectionView.frame = view.bounds
closeBtn.snp.makeConstraints { (make) in
make.left.equalTo(20)
make.bottom.equalTo(-20)
make.size.equalTo(CGSize(width: 90, height: 32))
}
saveBtn.snp.makeConstraints { (make) in
make.right.equalTo(-40)
make.bottom.equalTo(closeBtn.snp.bottom)
make.size.equalTo(closeBtn.snp.size)
}
// 设置collectionView的属性
collectionView.register(PhotoBrowserViewCell.self, forCellWithReuseIdentifier: PhotoBrowserCell)
collectionView.dataSource = self
// 监听两个按钮的点击
closeBtn.addTarget(self, action: #selector(closeBtnClick), for: .touchUpInside)
saveBtn.addTarget(self, action: #selector(saveBtnClick), for: .touchUpInside)
}
}
// MARK:- 事件监听函数
extension PhotoBrowserController {
@objc fileprivate func closeBtnClick() {
dismiss(animated: true, completion: nil)
}
@objc fileprivate func saveBtnClick() {
// 获取当前正在显示的image
let cell = collectionView.visibleCells.first as! PhotoBrowserViewCell
guard let image = cell.imageView.image else {
return
}
// 将iamge对象保存到相册
UIImageWriteToSavedPhotosAlbum(image, self, #selector(image(image:error:contextInfo:)), nil)
}
@objc fileprivate func image(image: UIImage, error: NSError?, contextInfo: Any) {
var showInfo = ""
if error != nil {
showInfo = "保存失败"
} else {
showInfo = "保存失败"
}
SVProgressHUD.showInfo(withStatus: showInfo)
}
}
// MARK:- 实现collectionView的数据源方法
extension PhotoBrowserController: UICollectionViewDataSource {
@available(iOS 6.0, *)
public func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return picURLs.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
// 创建cell
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: PhotoBrowserCell, for: indexPath) as! PhotoBrowserViewCell
// 给cell设置数据
cell.picURL = picURLs[indexPath.item]
cell.delegate = self
return cell
}
}
// MARK:- PhotoBrowserViewCell的代理方法
extension PhotoBrowserController: PhotoBrowserViewCellDelegate {
func imageViewClick() {
closeBtnClick()
}
}
// MARK:- 遵守
extension PhotoBrowserController: AnimatorDismissDelegate {
func indexPathForDismissView() -> IndexPath {
// 获取当前正在显示的indexPath
let cell = collectionView.visibleCells.first!
return collectionView.indexPath(for: cell)!
}
func imageViewForDismissView() -> UIImageView {
// 创建UIImageView对象
let imageView = UIImageView()
// 设置imageView的frame
let cell = collectionView.visibleCells.first as! PhotoBrowserViewCell
imageView.frame = cell.imageView.frame
imageView.image = cell.imageView.image
// 设置imageView的属性
imageView.contentMode = .scaleAspectFill
imageView.clipsToBounds = true
return imageView
}
}
|
apache-2.0
|
6f02acc1357350d1459de4cecf7bb331
| 28.654762 | 154 | 0.638699 | 5.04251 | false | false | false | false |
mitochrome/complex-gestures-demo
|
apps/GestureRecognizer/Carthage/Checkouts/RxSwift/RxExample/RxExample/Observable+Extensions.swift
|
12
|
3627
|
//
// Observable+Extensions.swift
// RxExample
//
// Created by Krunoslav Zaher on 3/14/17.
// Copyright © 2017 Krunoslav Zaher. All rights reserved.
//
import RxSwift
import RxCocoa
extension Observable {
/**
Simulation of a discrete system with feedback loops.
Interpretations:
- [system with feedback loops](https://en.wikipedia.org/wiki/Control_theory)
- [fixpoint solver](https://en.wikipedia.org/wiki/Fixed_point)
- [local equilibrium point calculator](https://en.wikipedia.org/wiki/Mechanical_equilibrium)
- ....
System simulation will be started upon subscription and stopped after subscription is disposed.
System state is represented as a `State` parameter.
Commands are represented by `Element` parameter.
- parameter initialState: Initial state of the system.
- parameter accumulator: Calculates new system state from existing state and a transition command (system integrator, reducer).
- parameter feedback: Feedback loops that produce commands depending on current system state.
- returns: Current state of the system.
*/
public static func system<State>(
_ initialState: State,
accumulator: @escaping (State, Element) -> State,
scheduler: SchedulerType,
feedback: (Observable<State>) -> Observable<Element>...
) -> Observable<State> {
return Observable<State>.deferred {
let replaySubject = ReplaySubject<State>.create(bufferSize: 1)
let inputs: Observable<Element> = Observable.merge(feedback.map { $0(replaySubject.asObservable()) })
.observeOn(scheduler)
return inputs.scan(initialState, accumulator: accumulator)
.startWith(initialState)
.do(onNext: { output in
replaySubject.onNext(output)
})
}
}
}
extension SharedSequence {
/**
Simulation of a discrete system with feedback loops.
Interpretations:
- [system with feedback loops](https://en.wikipedia.org/wiki/Control_theory)
- [fixpoint solver](https://en.wikipedia.org/wiki/Fixed_point)
- [local equilibrium point calculator](https://en.wikipedia.org/wiki/Mechanical_equilibrium)
- ....
System simulation will be started upon subscription and stopped after subscription is disposed.
System state is represented as a `State` parameter.
Commands are represented by `E` parameter.
- parameter initialState: Initial state of the system.
- parameter accumulator: Calculates new system state from existing state and a transition command (system integrator, reducer).
- parameter feedback: Feedback loops that produce commands depending on current system state.
- returns: Current state of the system.
*/
public static func system<State>(
_ initialState: State,
accumulator: @escaping (State, Element) -> State,
feedback: (SharedSequence<S, State>) -> SharedSequence<S, Element>...
) -> SharedSequence<S, State> {
return SharedSequence<S, State>.deferred {
let replaySubject = ReplaySubject<State>.create(bufferSize: 1)
let outputDriver = replaySubject.asSharedSequence(onErrorDriveWith: SharedSequence<S, State>.empty())
let inputs = SharedSequence.merge(feedback.map { $0(outputDriver) })
return inputs.scan(initialState, accumulator: accumulator)
.startWith(initialState)
.do(onNext: { output in
replaySubject.onNext(output)
})
}
}
}
|
mit
|
205ccda4e47ffa6e880950667824d68b
| 39.288889 | 132 | 0.667126 | 4.783641 | false | false | false | false |
zisko/swift
|
test/SILGen/super_init_refcounting.swift
|
1
|
4329
|
// RUN: %target-swift-frontend -emit-silgen %s | %FileCheck %s
class Foo {
init() {}
init(_ x: Foo) {}
init(_ x: Int) {}
}
class Bar: Foo {
// CHECK-LABEL: sil hidden @$S22super_init_refcounting3BarC{{[_0-9a-zA-Z]*}}fc
// CHECK: bb0([[INPUT_SELF:%.*]] : $Bar):
// CHECK: [[SELF_BOX:%.*]] = alloc_box ${ var Bar }
// CHECK: [[MARKED_SELF_BOX:%.*]] = mark_uninitialized [derivedself] [[SELF_BOX]]
// CHECK: [[PB_SELF_BOX:%.*]] = project_box [[MARKED_SELF_BOX]]
// CHECK: store [[INPUT_SELF]] to [init] [[PB_SELF_BOX]]
// CHECK: [[ORIG_SELF:%.*]] = load [take] [[PB_SELF_BOX]]
// CHECK-NOT: copy_value [[ORIG_SELF]]
// CHECK: [[ORIG_SELF_UP:%.*]] = upcast [[ORIG_SELF]]
// CHECK-NOT: copy_value [[ORIG_SELF_UP]]
// CHECK: [[SUPER_INIT:%[0-9]+]] = function_ref @$S22super_init_refcounting3FooCACycfc : $@convention(method) (@owned Foo) -> @owned Foo
// CHECK: [[NEW_SELF:%.*]] = apply [[SUPER_INIT]]([[ORIG_SELF_UP]])
// CHECK: [[NEW_SELF_DOWN:%.*]] = unchecked_ref_cast [[NEW_SELF]]
// CHECK: store [[NEW_SELF_DOWN]] to [init] [[PB_SELF_BOX]]
override init() {
super.init()
}
}
extension Foo {
// CHECK-LABEL: sil hidden @$S22super_init_refcounting3FooC{{[_0-9a-zA-Z]*}}fc
// CHECK: [[SELF_BOX:%.*]] = alloc_box ${ var Foo }
// CHECK: [[MARKED_SELF_BOX:%.*]] = mark_uninitialized [delegatingself] [[SELF_BOX]]
// CHECK: [[PB_SELF_BOX:%.*]] = project_box [[MARKED_SELF_BOX]]
// CHECK: [[ORIG_SELF:%.*]] = load [take] [[PB_SELF_BOX]]
// CHECK-NOT: copy_value [[ORIG_SELF]]
// CHECK: [[SUPER_INIT:%.*]] = class_method
// CHECK: [[NEW_SELF:%.*]] = apply [[SUPER_INIT]]([[ORIG_SELF]])
// CHECK: store [[NEW_SELF]] to [init] [[PB_SELF_BOX]]
convenience init(x: Int) {
self.init()
}
}
class Zim: Foo {
var foo = Foo()
// CHECK-LABEL: sil hidden @$S22super_init_refcounting3ZimC{{[_0-9a-zA-Z]*}}fc
// CHECK-NOT: copy_value
// CHECK-NOT: destroy_value
// CHECK: function_ref @$S22super_init_refcounting3FooCACycfc : $@convention(method) (@owned Foo) -> @owned Foo
}
class Zang: Foo {
var foo: Foo
override init() {
foo = Foo()
super.init()
}
// CHECK-LABEL: sil hidden @$S22super_init_refcounting4ZangC{{[_0-9a-zA-Z]*}}fc
// CHECK-NOT: copy_value
// CHECK-NOT: destroy_value
// CHECK: function_ref @$S22super_init_refcounting3FooCACycfc : $@convention(method) (@owned Foo) -> @owned Foo
}
class Bad: Foo {
// Invalid code, but it's not diagnosed till DI. We at least shouldn't
// crash on it.
override init() {
super.init(self)
}
}
class Good: Foo {
let x: Int
// CHECK-LABEL: sil hidden @$S22super_init_refcounting4GoodC{{[_0-9a-zA-Z]*}}fc
// CHECK: [[SELF_BOX:%.*]] = alloc_box ${ var Good }
// CHECK: [[MARKED_SELF_BOX:%.*]] = mark_uninitialized [derivedself] [[SELF_BOX]]
// CHECK: [[PB_SELF_BOX:%.*]] = project_box [[MARKED_SELF_BOX]]
// CHECK: store %0 to [init] [[PB_SELF_BOX]]
// CHECK: [[SELF_OBJ:%.*]] = load_borrow [[PB_SELF_BOX]]
// CHECK: [[X_ADDR:%.*]] = ref_element_addr [[SELF_OBJ]] : $Good, #Good.x
// CHECK: [[WRITE:%.*]] = begin_access [modify] [dynamic] [[X_ADDR]] : $*Int
// CHECK: assign {{.*}} to [[WRITE]] : $*Int
// CHECK: [[SELF_OBJ:%.*]] = load [take] [[PB_SELF_BOX]] : $*Good
// CHECK: [[SUPER_OBJ:%.*]] = upcast [[SELF_OBJ]] : $Good to $Foo
// CHECK: [[BORROWED_SUPER:%.*]] = begin_borrow [[SUPER_OBJ]]
// CHECK: [[DOWNCAST_BORROWED_SUPER:%.*]] = unchecked_ref_cast [[BORROWED_SUPER]] : $Foo to $Good
// CHECK: [[X_ADDR:%.*]] = ref_element_addr [[DOWNCAST_BORROWED_SUPER]] : $Good, #Good.x
// CHECK: [[READ:%.*]] = begin_access [read] [dynamic] [[X_ADDR]] : $*Int
// CHECK: [[X:%.*]] = load [trivial] [[READ]] : $*Int
// CHECK: end_borrow [[BORROWED_SUPER]] from [[SUPER_OBJ]]
// CHECK: [[SUPER_INIT:%.*]] = function_ref @$S22super_init_refcounting3FooCyACSicfc : $@convention(method) (Int, @owned Foo) -> @owned Foo
// CHECK: apply [[SUPER_INIT]]([[X]], [[SUPER_OBJ]])
override init() {
x = 10
super.init(x)
}
}
|
apache-2.0
|
71a7c94133f4a115ceab34abdf5f8ec9
| 42.727273 | 149 | 0.541003 | 3.22338 | false | false | false | false |
SwiftTools/Switt
|
SwittTests/UnitTests/Grammar/Swift/Grammar/CustomParsers/BinaryOperator/BinaryOperatorTokenParserTests.swift
|
1
|
4122
|
import Quick
import Nimble
@testable import Switt
class BinaryOperatorTokenParserTests: QuickSpec {
override func spec() {
describe("") {
var parser: BinaryOperatorTokenParser!
var result: [SyntaxTree]?
beforeEach {
parser = BinaryOperatorTokenParser(
operatorRule: ParserRule.Terminal(terminal: "+"),
tokenParserFactory: TokenParserFactoryImpl(parserRules: ParserRules())
)
}
it("parses binary operator if it has whitespaces on both sides") {
result = parser.parse(TokenStreamHelper.tokenStream([" ", "+", " "]))
expect(result).toNot(beNil())
}
it("parses binary operator if it has whitespaces on neither side") {
result = parser.parse(TokenStreamHelper.tokenStream(["a", "+", "b"], currentIndex: 1))
expect(result).toNot(beNil())
}
it("fails to parse binary operator if it has whitespace only on one side") {
result = parser.parse(TokenStreamHelper.tokenStream(["a", "+", " "], currentIndex: 1))
expect(result).to(beNil())
result = parser.parse(TokenStreamHelper.tokenStream([" ", "+", "a"]))
expect(result).to(beNil())
}
it("fails to parse different operator than passed in constructor") {
result = parser.parse(TokenStreamHelper.tokenStream([" ", "-", " "]))
expect(result).to(beNil())
}
it("parses binary operator successfully if there are more than 1 whitespaces on sides") {
result = parser.parse(TokenStreamHelper.tokenStream([" ", " ", "+", " ", " "]))
expect(result).toNot(beNil())
result = parser.parse(TokenStreamHelper.tokenStream([" ", " ", "+", " "]))
expect(result).toNot(beNil())
result = parser.parse(TokenStreamHelper.tokenStream([" ", "+", " ", " "]))
expect(result).toNot(beNil())
}
it("take comments into account") {
let validStreams: [[TokenConvertible]] = [
[RuleName.Line_comment, " ", "+", " "],
[" ", RuleName.Line_comment, " ", "+", " "],
[" ", "+", " ", RuleName.Line_comment],
[" ", "+", " ", RuleName.Line_comment, " "],
[" ", RuleName.Line_comment, " ", "+", " ", RuleName.Line_comment, " "],
// Has no whitespaces on left and right
[" ", RuleName.Line_comment, "+", RuleName.Line_comment, " "],
[" ", RuleName.Block_comment, "+", RuleName.Block_comment, " "]
]
let invalidStreams: [[TokenConvertible]] = [
[" ", RuleName.Line_comment, "+", " "],
[" ", "+", RuleName.Line_comment, " "],
[" ", RuleName.Line_comment, "+", " ", RuleName.Line_comment],
[RuleName.Line_comment, " ", "+", RuleName.Line_comment, " "],
]
for (i, stream) in validStreams.enumerate() {
result = parser.parse(TokenStreamHelper.tokenStream(stream))
expect(result).toNot(beNil(), description: "stream id: \(i)")
}
for (i, stream) in invalidStreams.enumerate() {
result = parser.parse(TokenStreamHelper.tokenStream(stream))
expect(result).to(beNil(), description: "stream id: \(i)")
}
}
}
}
}
|
mit
|
9d6fd6abc124caa9fdde559031ed2153
| 41.947917 | 102 | 0.442504 | 5.510695 | false | false | false | false |
oisdk/SwiftSequence
|
Sources/Cycle.swift
|
1
|
1895
|
// MARK: - Eager
// MARK: Cycle n
public extension CollectionType {
/// Returns an array of n cycles of self.
/// ```swift
/// [1, 2, 3].cycle(2)
///
/// [1, 2, 3, 1, 2, 3]
/// ```
@warn_unused_result
func cycle(n: Int) -> [Generator.Element] {
var cycled: [Generator.Element] = []
cycled.reserveCapacity(underestimateCount() * n)
for _ in 0..<n {
cycled.appendContentsOf(self)
}
return cycled
}
}
// MARK: - Lazy
// MARK: Cycle n
/// :nodoc:
public struct CycleNGen<C: CollectionType> : GeneratorType, LazySequenceType {
private let inner: C
private var innerGen: C.Generator
private var n: Int
/// :nodoc:
public mutating func next() -> C.Generator.Element? {
while true {
if let next = innerGen.next() { return next }
n -= 1
if n > 0 { innerGen = inner.generate() }
else { return nil }
}
}
}
public extension LazySequenceType where Self : CollectionType {
/// Returns a generator of n cycles of self.
/// ```swift
/// [1, 2, 3].lazy.cycle(2)
///
/// 1, 2, 3, 1, 2, 3
/// ```
@warn_unused_result
func cycle(n: Int) -> CycleNGen<Self> {
return CycleNGen(inner: self, innerGen: generate(), n: n)
}
}
// MARK: Cycle infinite
/// :nodoc:
public struct CycleGen<C: CollectionType> : GeneratorType, LazySequenceType {
private let inner: C
private var innerGen: C.Generator
/// :nodoc:
public mutating func next() -> C.Generator.Element? {
while true {
if let next = innerGen.next() {
return next
}
innerGen = inner.generate()
}
}
}
public extension CollectionType {
/// Returns an infinite generator of cycles of self.
/// ```swift
/// [1, 2, 3].cycle()
///
/// 1, 2, 3, 1, 2, 3, 1...
/// ```
@warn_unused_result
func cycle() -> CycleGen<Self> {
return CycleGen(inner: self, innerGen: generate())
}
}
|
mit
|
08933c7303c2dcb036d90312b47c6eb2
| 20.781609 | 78 | 0.588918 | 3.445455 | false | false | false | false |
DoubleSha/BitcoinSwift
|
BitcoinSwift/Models/PeerAddress.swift
|
1
|
2654
|
//
// PeerAddress.swift
// BitcoinSwift
//
// Created by Kevin Greene on 7/4/14.
// Copyright (c) 2014 DoubleSha. All rights reserved.
//
import Foundation
public func ==(left: PeerAddress, right: PeerAddress) -> Bool {
return left.services == right.services &&
left.IP == right.IP &&
left.port == right.port &&
left.timestamp == right.timestamp
}
/// Used to represent networks addresses of peers over the wire.
/// https://en.bitcoin.it/wiki/Protocol_specification#Network_address
public struct PeerAddress: Equatable {
public let services: PeerServices
public let IP: IPAddress
public let port: UInt16
public var timestamp: NSDate?
public init(services: PeerServices, IP: IPAddress, port: UInt16, timestamp: NSDate? = nil) {
self.services = services
self.IP = IP
self.port = port
self.timestamp = timestamp
}
}
extension PeerAddress: BitcoinSerializable {
public var bitcoinData: NSData {
return bitcoinDataWithTimestamp(true)
}
public static func fromBitcoinStream(stream: NSInputStream) -> PeerAddress? {
return PeerAddress.fromBitcoinStream(stream, includeTimestamp: true)
}
public func bitcoinDataWithTimestamp(includeTimestamp: Bool) -> NSData {
let data = NSMutableData()
if includeTimestamp {
if let timestamp = timestamp {
data.appendDateAs32BitUnixTimestamp(timestamp)
} else {
data.appendDateAs32BitUnixTimestamp(NSDate())
}
}
data.appendUInt64(services.rawValue)
data.appendData(IP.bitcoinData)
data.appendUInt16(port, endianness: .BigEndian) // Network byte order.
return data
}
public static func fromBitcoinStream(stream: NSInputStream,
includeTimestamp: Bool) -> PeerAddress? {
var timestamp: NSDate? = nil
if includeTimestamp {
timestamp = stream.readDateFrom32BitUnixTimestamp()
if timestamp == nil {
Logger.warn("Failed to parse timestamp from PeerAddress")
return nil
}
}
let servicesRaw = stream.readUInt64()
if servicesRaw == nil {
Logger.warn("Failed to parse servicesRaw from PeerAddress")
return nil
}
let services = PeerServices(rawValue: servicesRaw!)
let IP = IPAddress.fromBitcoinStream(stream)
if IP == nil {
Logger.warn("Failed to parse IP from PeerAddress")
return nil
}
let port = stream.readUInt16(.BigEndian) // Network byte order.
if port == nil {
Logger.warn("Failed to parse port from PeerAddress")
return nil
}
return PeerAddress(services: services, IP: IP!, port: port!, timestamp: timestamp)
}
}
|
apache-2.0
|
5a4937bd912a2c6d6131a9e07e40e5d2
| 29.159091 | 94 | 0.679729 | 4.322476 | false | false | false | false |
Bunn/macGist
|
macGist/LoginViewController.swift
|
1
|
3900
|
//
// LoginViewController.swift
// macGist
//
// Created by Fernando Bunn on 20/06/17.
// Copyright © 2017 Fernando Bunn. All rights reserved.
//
import Cocoa
class LoginViewController: NSViewController {
@IBOutlet private weak var passwordTextField: NSSecureTextField!
@IBOutlet private weak var usernameTextField: NSTextField!
@IBOutlet private weak var spinner: NSProgressIndicator!
@IBOutlet private weak var loginButton: NSButton!
@IBOutlet private weak var githubClientIdTextField: NSTextField!
@IBOutlet private weak var githubClientSecretTextField: NSTextField!
@IBOutlet weak var errorLabel: NSTextField!
weak var delegate: LoginViewControllerDelegate?
private let githubAPI = GitHubAPI()
override func viewDidLoad() {
super.viewDidLoad()
setupUI()
setupCredentialsUI()
}
@IBAction private func loginButtonClicked(_ sender: NSButton) {
setupUI()
authenticate()
}
@IBAction private func cancelButtonClicked(_ sender: NSButton) {
delegate?.didFinish(controller: self)
}
@IBAction func saveButtonClicked(_ sender: NSButton) {
GitHubCredentialManager.clientId = githubClientIdTextField.stringValue
GitHubCredentialManager.clientSecret = githubClientSecretTextField.stringValue
}
fileprivate func setupUI() {
spinner.isHidden = true
errorLabel.isHidden = true
}
private func showSpinner(show: Bool) {
spinner.isHidden = !show
loginButton.isHidden = show
if show {
spinner.startAnimation(nil)
} else {
spinner.stopAnimation(nil)
}
}
fileprivate func displayError(message: String) {
showSpinner(show: false)
errorLabel.isHidden = false
errorLabel.stringValue = message
}
private func openTwoFactorController() {
let twoFactorController = TwoFactorViewController()
twoFactorController.delegate = self
presentAsSheet(twoFactorController)
}
fileprivate func authenticate(twoFactorCode: String? = nil) {
showSpinner(show: true)
githubAPI.authenticate(username: usernameTextField.stringValue, password: passwordTextField.stringValue, twoFactorCode: twoFactorCode) { (error: Error?) in
print("Error \(String(describing: error))")
DispatchQueue.main.async {
if error != nil {
if let apiError = error as? GitHubAPI.GitHubAPIError {
switch apiError {
case .twoFactorRequired:
self.openTwoFactorController()
return
default: break
}
}
self.displayError(message: "Bad username or password")
} else {
UserDefaults.standard.set(self.usernameTextField.stringValue, forKey: UserDefaultKeys.usernameKey.rawValue)
self.delegate?.didFinish(controller: self)
}
}
}
}
private func setupCredentialsUI() {
githubClientIdTextField.stringValue = GitHubCredentialManager.clientId ?? ""
githubClientSecretTextField.stringValue = GitHubCredentialManager.clientSecret ?? ""
}
}
protocol LoginViewControllerDelegate: class {
func didFinish(controller: LoginViewController)
}
extension LoginViewController: TwoFactorViewControllerDelegate {
func didEnter(code: String, controller: TwoFactorViewController) {
authenticate(twoFactorCode: code)
controller.dismiss(nil)
}
func didCancel(controller: TwoFactorViewController) {
setupUI()
displayError(message: "Two-Factor cancelled")
controller.dismiss(nil)
}
}
|
mit
|
d96a3d00652cd330457f08c07b8fb095
| 32.612069 | 163 | 0.640934 | 5.634393 | false | false | false | false |
michael-yuji/spartanX
|
Sources/SXRuntime.swift
|
2
|
10065
|
// Copyright (c) 2016, Yuji
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// 1. Redistributions of source code must retain the above copyright notice, this
// list of conditions and the following disclaimer.
// 2. Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 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.
//
// The views and conclusions contained in the software and documentation are those
// of the authors and should not be interpreted as representing official policies,
// either expressed or implied, of the FreeBSD Project.
//
// Created by Yuji on 6/3/16.
// Copyright © 2016 yuuji. All rights reserved.
//
import struct Foundation.Data
import func CKit.pointer
import xlibc
#if os(Linux)
public typealias event = epoll_event
#else
public typealias event = Darwin.kevent
#endif
import struct Foundation.Data
import func CKit.pointer
public protocol KqueueManagable {
var ident: Int32 { get }
var hashValue: Int { get }
func runloop(manager: SXKernel, _ ev: event)
}
public struct SXKernelManager {
public static var `default`: SXKernelManager?
var kernels = [SXKernel]()
var map = [Int32 : SXKernel]()
}
public extension SXKernelManager {
public static func initializeDefault() {
`default` = SXKernelManager(maxCPU: 1, evs_cpu: 5120)
}
public mutating func manage<Managable: KqueueManagable>(_ managable: Managable, setup: ((inout Managable) -> ())?) {
var target = managable
setup?(&target)
self.register(target)
}
@inline(__always)
internal mutating func register(_ queue: KqueueManagable) {
//debugLog("registering \(queue.ident): \(#function): \(#file): \(#line)")
let _leastBusyKernel = leastBusyKernel()
//map[queue.ident] = _leastBusyKernel
map[queue.ident] = _leastBusyKernel
_leastBusyKernel?.register(queue)
//debugLog("returns: registering \(queue.ident): \(#function): \(#file): \(#line)")
}
internal mutating func unregister(ident: Int32, of filter: SXKernel.Filter) {
//debugLog("unregistering \(ident): \(#function): \(#file): \(#line)")
let kernel = map[ident]
kernel?.remove(ident: ident, for: filter)
//debugLog("returns: unregistering \(ident): \(#function): \(#file): \(#line)")
map[ident] = nil
}
@inline(__always)
func leastBusyKernel() -> SXKernel? {
return kernels.sorted {
$0.queues.count < $1.queues.count
}.first
}
}
public extension SXKernelManager {
init(maxCPU: Int, evs_cpu: Int) {
self.kernels = [SXKernel](count: maxCPU) {_ in
return SXKernel(events_count: evs_cpu)
}
}
}
public final class SXKernel {
public var thread: SXThread
var mutex: pthread_mutex_t
var kq: Int32
var events: [event]
// user queues
var queues: [Int32 : KqueueManagable]
// events count
var count = 0
// active events count
var actived = false
#if os(Linux)
fileprivate typealias ev_raw_t = UInt32
#else
fileprivate typealias ev_raw_t = Int16
#endif
enum Filter {
case read
case write
case vnode
fileprivate var value: ev_raw_t {
#if os(Linux)
switch self {
case .read: return EPOLLIN.rawValue
case .write: return EPOLLOUT.rawValue
case .vnode: return EPOLLOUT.rawValue | EPOLLIN.rawValue | EPOLLET.rawValue
}
#else
switch self {
case .read: return Int16(EVFILT_READ)
case .write: return Int16(EVFILT_WRITE)
case .vnode: return Int16(EVFILT_VNODE)
}
#endif
}
fileprivate var internalVal: Int32 {
switch self {
case .read: return 1
case .write: return 2
case .vnode: return 3
}
}
}
init(events_count: Int) {
thread = SXThread()
mutex = pthread_mutex_t()
self.queues = [:]
#if os(Linux)
kq = epoll_create1(0)
#else
kq = kqueue()
#endif
self.events = [event](repeating: event(), count: events_count)
pthread_mutex_init(&mutex, nil)
}
}
extension SXKernel {
func withMutex<Result>(_ execute: () -> Result) -> Result {
pthread_mutex_lock(&mutex)
let r = execute()
pthread_mutex_unlock(&mutex)
return r
}
}
// Kevent
extension SXKernel {
private func kqueue_end() {
//debugLog("ending: \(#function): \(#file): \(#line)")
self.withMutex {
self.actived = false
}
//debugLog("return: ending: \(#function): \(#file): \(#line)")
}
private func kqueue_runloop() {
if (self.withMutex { () -> Bool in
if self.count == 0 {
return true
}
return false
}) {
//debugLog("events count == 0: \(#function): \(#file): \(#line)")
kqueue_end()
return
}
//debugLog("event_waiting: \(#function): \(#file): \(#line)")
#if os(Linux)
let nev = epoll_wait(self.kq, &self.events, Int32(self.events.count), -1)
#else
let nev = kevent(self.kq, nil, 0, &self.events, Int32(self.events.count), nil)
#endif
//debugLog("event_found_active: fd_count: \(nev): \(#function): \(#file): \(#line)")
if nev < 0 {
self.thread.exec {
self.kqueue_runloop()
}
}
if nev == 0 {
kqueue_end()
}
if nev == -1 {
perror("kqueue")
}
for i in 0..<Int(nev) {
let event = self.events[i]
#if os(Linux)
let queue = self.queues[Int32(event.data.fd)]
#else
let queue = self.queues[Int32(event.ident)]
#endif
//#if os(Linux)
//debugLog("queue \(event.data.fd) runloop_start: \(#function): \(#file): \(#line)")
//#else
//debugLog("queue \(event.ident) runloop_start: \(#function): \(#file): \(#line)")
//#endif
queue?.runloop(manager: self, event)
//#if os(Linux)
//debugLog("queue \(event.data.fd) runloop_ends: \(#function): \(#file): \(#line)")
//#else
//debugLog("queue \(event.ident) runloop_ends: \(#function): \(#file): \(#line)")
//#endif
}
self.thread.exec {
debugLog("queue up kqueue: \(#file): \(#line)")
self.kqueue_runloop()
}
}
func activate() {
self.withMutex{
actived = true
}
self.thread.execute {
self.kqueue_runloop()
}
}
func register(_ queue: KqueueManagable, for kind: Filter = .read) {
withMutex {
self.queues[queue.ident] = queue
#if os(Linux)
var ev = epoll_event()
ev.events = kind.value;
ev.data.fd = queue.ident
epoll_ctl(kq, EPOLL_CTL_ADD, queue.ident, &ev)
#else
var k = event(ident: UInt(queue.ident),
filter: kind.value,
flags: UInt16(EV_ADD | EV_ENABLE | EV_ONESHOT),
fflags: 0, data: 0,
udata: nil)
kevent(kq, &k, 1, nil, 0, nil)
#endif
debugLog("\(#function): \(#file): \(#line)")
count += 1
}
if !actived {
activate()
}
debugLog("returned: \(#function): \(#file): \(#line)")
}
func remove(ident: Int32, for filter: Filter) {
withMutex {
self.queues[ident] = nil
//#if debug
//print("\(#function): \(#file): \(#line)")
//#endif
#if os(Linux)
var ev = epoll_event()
ev.events = filter.value;
ev.data.fd = ident
epoll_ctl(kq, EPOLL_CTL_DEL, ident, &ev)
#else
var k = event(ident: UInt(ident),
filter: filter.value,
flags: UInt16(EV_DELETE | EV_DISABLE | EV_RECEIPT),
fflags: 0,
data: 0,
udata: nil)
kevent(kq, &k, 1, nil, 0, nil)
#endif
count -= 1
}
// debugLog("returned: \(#function): \(#file): \(#line)")
}
}
|
bsd-2-clause
|
7aa99b3fbfa9b2c4396a7519794926e0
| 29.776758 | 120 | 0.527623 | 4.253593 | false | false | false | false |
farshadtx/Fleet
|
Fleet/CoreExtensions/UITableViewRowAction+Fleet.swift
|
1
|
1871
|
import UIKit
import ObjectiveC
private var handlerAssociatedKey: UInt = 0
fileprivate var didSwizzle = false
@objc private class ObjectifiedBlock: NSObject {
var block: ((UITableViewRowAction, IndexPath) -> Void)?
init(block: ((UITableViewRowAction, IndexPath) -> Void)?) {
self.block = block
}
}
extension UITableViewRowAction {
var handler: ((UITableViewRowAction, IndexPath) -> Void)? {
get {
return fleet_property_handler
}
}
override open class func initialize() {
super.initialize()
if !didSwizzle {
swizzleInit()
didSwizzle = true
}
}
fileprivate var fleet_property_handler: ((UITableViewRowAction, IndexPath) -> Void)? {
get {
let block = objc_getAssociatedObject(self, &handlerAssociatedKey) as? ObjectifiedBlock
return block?.block
}
set {
let block = ObjectifiedBlock(block: newValue)
objc_setAssociatedObject(self, &handlerAssociatedKey, block, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN)
}
}
fileprivate class func swizzleInit() {
let originalSelector = Selector(("_initWithStyle:title:handler:"))
let swizzledSelector = #selector(UITableViewRowAction.fleet_init(withStyle:title:handler:))
let originalMethod = class_getInstanceMethod(self, originalSelector)
let swizzledMethod = class_getInstanceMethod(self, swizzledSelector)
method_exchangeImplementations(originalMethod, swizzledMethod)
}
func fleet_init(withStyle style: UITableViewRowActionStyle, title: String?, handler: @escaping ((UITableViewRowAction, IndexPath) -> Swift.Void)) -> UITableViewRowAction {
fleet_property_handler = handler
return fleet_init(withStyle: style, title: title, handler: handler)
}
}
|
apache-2.0
|
b5e8163c39952ef529e3a9364af2c520
| 31.824561 | 175 | 0.671299 | 5.15427 | false | false | false | false |
Codigami/CFAlertViewController
|
CFAlertViewController/Subclass/CFPushButton/CFPushButton.swift
|
1
|
6713
|
//
// CFPushButton.swift
// CFAlertViewControllerDemo
//
// Created by Shivam Bhalla on 1/18/17.
// Copyright © 2017 Codigami Inc. All rights reserved.
//
import UIKit
open class CFPushButton: UIButton {
// MARK: - Declarations
@objc public static let CF_PUSH_BUTTON_DEFAULT_TOUCH_DOWN_DURATION: CGFloat = 0.22
@objc public static let CF_PUSH_BUTTON_DEFAULT_TOUCH_DOWN_DELAY: CGFloat = 0.0
@objc public static let CF_PUSH_BUTTON_DEFAULT_TOUCH_DOWN_DAMPING: CGFloat = 0.6
@objc public static let CF_PUSH_BUTTON_DEFAULT_TOUCH_DOWN_VELOCITY: CGFloat = 0.0
@objc public static let CF_PUSH_BUTTON_DEFAULT_TOUCH_UP_DURATION: CGFloat = 0.7
@objc public static let CF_PUSH_BUTTON_DEFAULT_TOUCH_UP_DELAY: CGFloat = 0.0
@objc public static let CF_PUSH_BUTTON_DEFAULT_TOUCH_UP_DAMPING: CGFloat = 0.65
@objc public static let CF_PUSH_BUTTON_DEFAULT_TOUCH_UP_VELOCITY: CGFloat = 0.0
// MARK: - Variables
// Original Transform Property
@objc open var originalTransform = CGAffineTransform.identity {
didSet {
// Update Button Transform
transform = originalTransform
}
}
// Set Highlight Property
@objc open var highlightStateBackgroundColor: UIColor?
// Push Transform Property
@objc open var pushTransformScaleFactor: CGFloat = 0.8
// Touch Handler Blocks
@objc open var touchDownHandler: ((_ button: CFPushButton) -> Void)?
@objc open var touchUpHandler: ((_ button: CFPushButton) -> Void)?
// Push Transition Animation Properties
@objc open var touchDownDuration: CGFloat = CF_PUSH_BUTTON_DEFAULT_TOUCH_DOWN_DURATION
@objc open var touchDownDelay: CGFloat = CF_PUSH_BUTTON_DEFAULT_TOUCH_DOWN_DELAY
@objc open var touchDownDamping: CGFloat = CF_PUSH_BUTTON_DEFAULT_TOUCH_DOWN_DAMPING
@objc open var touchDownVelocity: CGFloat = CF_PUSH_BUTTON_DEFAULT_TOUCH_DOWN_VELOCITY
@objc open var touchUpDuration: CGFloat = CF_PUSH_BUTTON_DEFAULT_TOUCH_UP_DURATION
@objc open var touchUpDelay: CGFloat = CF_PUSH_BUTTON_DEFAULT_TOUCH_UP_DELAY
@objc open var touchUpDamping: CGFloat = CF_PUSH_BUTTON_DEFAULT_TOUCH_UP_DAMPING
@objc open var touchUpVelocity: CGFloat = CF_PUSH_BUTTON_DEFAULT_TOUCH_UP_VELOCITY
// Add Extra Parameters
@objc open var extraParam: Any?
private var normalStateBackgroundColor: UIColor?
@objc open override var backgroundColor: UIColor? {
didSet {
// Store Normal State Background Color
normalStateBackgroundColor = backgroundColor
}
}
// MARK: - Initialization Methods
public required init?(coder: NSCoder) {
super.init(coder: coder)
basicInitialisation()
}
public override init(frame: CGRect) {
super.init(frame: frame)
basicInitialisation()
}
open func basicInitialisation() {
// Set Default Original Transform
originalTransform = CGAffineTransform.identity
}
// MARK: - Touch Events
open override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
super.touchesBegan(touches, with: event)
pushButton(pushButton: true, shouldAnimate: true, completion: nil)
}
open override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
super.touchesEnded(touches, with: event)
pushButton(pushButton: false, shouldAnimate: true, completion: nil)
}
open override func touchesCancelled(_ touches: Set<UITouch>, with event: UIEvent?) {
super.touchesCancelled(touches, with: event)
pushButton(pushButton: false, shouldAnimate: true, completion: nil)
}
// MARK: - Animation Method
@objc open func pushButton(pushButton: Bool, shouldAnimate: Bool, completion: (() -> Void)?) {
// Call Touch Events
if pushButton {
// Call Touch Down Handler
if let touchDownHandler = touchDownHandler {
touchDownHandler(self)
}
}
else {
// Call Touch Up Handler
if let touchUpHandler = touchUpHandler {
touchUpHandler(self)
}
}
// Animation Block
let animate: (() -> Void)? = {() -> Void in
if pushButton {
// Set Transform
self.transform = self.originalTransform.scaledBy(x: self.pushTransformScaleFactor, y: self.pushTransformScaleFactor)
// Update Background Color
if (self.highlightStateBackgroundColor != nil) {
super.backgroundColor = self.highlightStateBackgroundColor
}
}
else {
// Set Transform
self.transform = self.originalTransform
// Set Background Color
super.backgroundColor = self.normalStateBackgroundColor
}
// Layout
self.setNeedsLayout()
self.layoutIfNeeded()
}
if shouldAnimate {
// Configure Animation Properties
var duration: CGFloat
var delay: CGFloat
var damping: CGFloat
var velocity: CGFloat
if pushButton {
duration = touchDownDuration
delay = touchDownDelay
damping = touchDownDamping
velocity = touchDownVelocity
}
else {
duration = touchUpDuration
delay = touchUpDelay
damping = touchUpDamping
velocity = touchUpVelocity
}
DispatchQueue.main.async {
// Animate
UIView.animate(withDuration: TimeInterval(duration), delay: TimeInterval(delay), usingSpringWithDamping: damping, initialSpringVelocity: velocity, options: [.curveEaseOut, .beginFromCurrentState, .allowUserInteraction], animations: {() -> Void in
animate!()
}, completion: {(_ finished: Bool) -> Void in
if let completion = completion, finished {
completion()
}
})
}
}
else {
animate!()
// Call Completion Block
if let completion = completion {
completion()
}
}
}
// MARK: - Dealloc
deinit {
// Remove Touch Handlers
touchDownHandler = nil
touchUpHandler = nil
}
}
|
mit
|
8a4b5c0830bb20e2ad04f7afe59d7b88
| 34.326316 | 262 | 0.595054 | 4.997766 | false | false | false | false |
kstaring/swift
|
test/SILGen/witness_same_type.swift
|
3
|
1192
|
// RUN: %target-swift-frontend -emit-silgen %s | %FileCheck %s
// RUN: %target-swift-frontend -emit-ir %s
protocol Fooable {
associatedtype Bar
func foo<T: Fooable where T.Bar == Self.Bar>(x x: T) -> Self.Bar
}
struct X {}
// Ensure that the protocol witness for requirements with same-type constraints
// is set correctly. <rdar://problem/16369105>
// CHECK-LABEL: sil hidden [transparent] [thunk] @_TTWV17witness_same_type3FooS_7FooableS_FS1_3foouRd__S1_wx3Barzwd__S2_rfT1xqd___wxS2_ : $@convention(witness_method) <τ_0_0 where τ_0_0 : Fooable, τ_0_0.Bar == X> (@in τ_0_0, @in_guaranteed Foo) -> @out X
struct Foo: Fooable {
typealias Bar = X
func foo<T: Fooable where T.Bar == X>(x x: T) -> X { return X() }
}
// rdar://problem/19049566
// CHECK-LABEL: sil [transparent] [thunk] @_TTWu0_Rxs8Sequence_zWx8Iterator7Element_rGV17witness_same_type14LazySequenceOfxq__S_S2_FS_12makeIterator
public struct LazySequenceOf<SS : Sequence, A where SS.Iterator.Element == A> : Sequence {
public func makeIterator() -> AnyIterator<A> {
var opt: AnyIterator<A>?
return opt!
}
public subscript(i : Int) -> A {
get {
var opt: A?
return opt!
}
}
}
|
apache-2.0
|
d2fbdcd10be1921fb444dd45234b68f3
| 33.941176 | 254 | 0.675084 | 3 | false | false | false | false |
overtake/TelegramSwift
|
packages/TGUIKit/Sources/TextView.swift
|
1
|
97350
|
//
// TextView.swift
// TGUIKit
//
// Created by keepcoder on 15/09/16.
// Copyright © 2016 Telegram. All rights reserved.
//
import Cocoa
import SwiftSignalKit
import ColorPalette
public enum LinkType {
case plain
case email
case username
case hashtag
case command
case stickerPack
case emojiPack
case inviteLink
case code
}
public func isValidEmail(_ checkString:String) -> Bool {
let emailRegex = ".+@([A-Za-z0-9-]+\\.)+[A-Za-z]{2}[A-Za-z]*"
let emailTest = NSPredicate(format: "SELF MATCHES %@", emailRegex)
return emailTest.evaluate(with: checkString)
}
private enum CornerType {
case topLeft
case topRight
case bottomLeft
case bottomRight
}
public extension NSAttributedString.Key {
static let hexColorMark = NSAttributedString.Key("TextViewHexColorMarkAttribute")
static let hexColorMarkDimensions = NSAttributedString.Key("TextViewHexColorMarkAttributeDimensions")
}
private final class TextViewEmbeddedItem {
let range: NSRange
let frame: CGRect
let item: AnyHashable
init(range: NSRange, frame: CGRect, item: AnyHashable) {
self.range = range
self.frame = frame
self.item = item
}
}
private func drawFullCorner(context: CGContext, color: NSColor, at point: CGPoint, type: CornerType, radius: CGFloat) {
context.setFillColor(color.cgColor)
switch type {
case .topLeft:
context.clear(CGRect(origin: point, size: CGSize(width: radius, height: radius)))
context.fillEllipse(in: CGRect(origin: point, size: CGSize(width: radius * 2.0, height: radius * 2.0)))
case .topRight:
context.clear(CGRect(origin: CGPoint(x: point.x - radius, y: point.y), size: CGSize(width: radius, height: radius)))
context.fillEllipse(in: CGRect(origin: CGPoint(x: point.x - radius * 2.0, y: point.y), size: CGSize(width: radius * 2.0, height: radius * 2.0)))
case .bottomLeft:
context.clear(CGRect(origin: CGPoint(x: point.x, y: point.y - radius), size: CGSize(width: radius, height: radius)))
context.fillEllipse(in: CGRect(origin: CGPoint(x: point.x, y: point.y - radius * 2.0), size: CGSize(width: radius * 2.0, height: radius * 2.0)))
case .bottomRight:
context.clear(CGRect(origin: CGPoint(x: point.x - radius, y: point.y - radius), size: CGSize(width: radius, height: radius)))
context.fillEllipse(in: CGRect(origin: CGPoint(x: point.x - radius * 2.0, y: point.y - radius * 2.0), size: CGSize(width: radius * 2.0, height: radius * 2.0)))
}
}
private func drawConnectingCorner(context: CGContext, color: NSColor, at point: CGPoint, type: CornerType, radius: CGFloat) {
context.setFillColor(color.cgColor)
switch type {
case .topLeft:
context.fill(CGRect(origin: CGPoint(x: point.x - radius, y: point.y), size: CGSize(width: radius, height: radius)))
context.setFillColor(NSColor.clear.cgColor)
context.fillEllipse(in: CGRect(origin: CGPoint(x: point.x - radius * 2.0, y: point.y), size: CGSize(width: radius * 2.0, height: radius * 2.0)))
case .topRight:
context.fill(CGRect(origin: CGPoint(x: point.x, y: point.y), size: CGSize(width: radius, height: radius)))
context.setFillColor(NSColor.clear.cgColor)
context.fillEllipse(in: CGRect(origin: CGPoint(x: point.x, y: point.y), size: CGSize(width: radius * 2.0, height: radius * 2.0)))
case .bottomLeft:
context.fill(CGRect(origin: CGPoint(x: point.x - radius, y: point.y - radius), size: CGSize(width: radius, height: radius)))
context.setFillColor(NSColor.clear.cgColor)
context.fillEllipse(in: CGRect(origin: CGPoint(x: point.x - radius * 2.0, y: point.y - radius * 2.0), size: CGSize(width: radius * 2.0, height: radius * 2.0)))
case .bottomRight:
context.fill(CGRect(origin: CGPoint(x: point.x, y: point.y - radius), size: CGSize(width: radius, height: radius)))
context.setFillColor(NSColor.clear.cgColor)
context.fillEllipse(in: CGRect(origin: CGPoint(x: point.x, y: point.y - radius * 2.0), size: CGSize(width: radius * 2.0, height: radius * 2.0)))
}
}
private func generateRectsImage(color: NSColor, rects: [CGRect], inset: CGFloat, outerRadius: CGFloat, innerRadius: CGFloat) -> (CGPoint, CGImage?) {
if rects.isEmpty {
return (CGPoint(), nil)
}
var topLeft = rects[0].origin
var bottomRight = CGPoint(x: rects[0].maxX, y: rects[0].maxY)
for i in 1 ..< rects.count {
topLeft.x = min(topLeft.x, rects[i].origin.x)
topLeft.y = min(topLeft.y, rects[i].origin.y)
bottomRight.x = max(bottomRight.x, rects[i].maxX)
bottomRight.y = max(bottomRight.y, rects[i].maxY)
}
topLeft.x -= inset
topLeft.y -= inset
bottomRight.x += inset
bottomRight.y += inset
return (topLeft, generateImage(CGSize(width: bottomRight.x - topLeft.x, height: bottomRight.y - topLeft.y), contextGenerator: { size, context in
context.clear(CGRect(origin: CGPoint(), size: size))
context.setFillColor(color.cgColor)
context.setBlendMode(.copy)
for i in 0 ..< rects.count {
let rect = rects[i].insetBy(dx: -inset, dy: -inset)
context.fill(rect.offsetBy(dx: -topLeft.x, dy: -topLeft.y))
}
for i in 0 ..< rects.count {
let rect = rects[i].insetBy(dx: -inset, dy: -inset).offsetBy(dx: -topLeft.x, dy: -topLeft.y)
var previous: CGRect?
if i != 0 {
previous = rects[i - 1].insetBy(dx: -inset, dy: -inset).offsetBy(dx: -topLeft.x, dy: -topLeft.y)
}
var next: CGRect?
if i != rects.count - 1 {
next = rects[i + 1].insetBy(dx: -inset, dy: -inset).offsetBy(dx: -topLeft.x, dy: -topLeft.y)
}
if let previous = previous {
if previous.contains(rect.topLeft) {
if abs(rect.topLeft.x - previous.minX) >= innerRadius {
var radius = innerRadius
if let next = next {
radius = min(radius, floor((next.minY - previous.maxY) / 2.0))
}
drawConnectingCorner(context: context, color: color, at: CGPoint(x: rect.topLeft.x, y: previous.maxY), type: .topLeft, radius: radius)
}
} else {
drawFullCorner(context: context, color: color, at: rect.topLeft, type: .topLeft, radius: outerRadius)
}
if previous.contains(rect.topRight.offsetBy(dx: -1.0, dy: 0.0)) {
if abs(rect.topRight.x - previous.maxX) >= innerRadius {
var radius = innerRadius
if let next = next {
radius = min(radius, floor((next.minY - previous.maxY) / 2.0))
}
drawConnectingCorner(context: context, color: color, at: CGPoint(x: rect.topRight.x, y: previous.maxY), type: .topRight, radius: radius)
}
} else {
drawFullCorner(context: context, color: color, at: rect.topRight, type: .topRight, radius: outerRadius)
}
} else {
drawFullCorner(context: context, color: color, at: rect.topLeft, type: .topLeft, radius: outerRadius)
drawFullCorner(context: context, color: color, at: rect.topRight, type: .topRight, radius: outerRadius)
}
if let next = next {
if next.contains(rect.bottomLeft) {
if abs(rect.bottomRight.x - next.maxX) >= innerRadius {
var radius = innerRadius
if let previous = previous {
radius = min(radius, floor((next.minY - previous.maxY) / 2.0))
}
drawConnectingCorner(context: context, color: color, at: CGPoint(x: rect.bottomLeft.x, y: next.minY), type: .bottomLeft, radius: radius)
}
} else {
drawFullCorner(context: context, color: color, at: rect.bottomLeft, type: .bottomLeft, radius: outerRadius)
}
if next.contains(rect.bottomRight.offsetBy(dx: -1.0, dy: 0.0)) {
if abs(rect.bottomRight.x - next.maxX) >= innerRadius {
var radius = innerRadius
if let previous = previous {
radius = min(radius, floor((next.minY - previous.maxY) / 2.0))
}
drawConnectingCorner(context: context, color: color, at: CGPoint(x: rect.bottomRight.x, y: next.minY), type: .bottomRight, radius: radius)
}
} else {
drawFullCorner(context: context, color: color, at: rect.bottomRight, type: .bottomRight, radius: outerRadius)
}
} else {
drawFullCorner(context: context, color: color, at: rect.bottomLeft, type: .bottomLeft, radius: outerRadius)
drawFullCorner(context: context, color: color, at: rect.bottomRight, type: .bottomRight, radius: outerRadius)
}
}
}))
}
public enum LinkHoverValue {
case entered(Any)
case exited
}
public final class TextViewInteractions {
public var processURL:(Any)->Void // link, isPresent
public var copy:(()->Bool)?
public var menuItems:((LinkType?)->Signal<[ContextMenuItem], NoError>)?
public var isDomainLink:(Any, String?)->Bool
public var makeLinkType:((Any, String))->LinkType
public var localizeLinkCopy:(LinkType)-> String
public var resolveLink:(Any)->String?
public var copyAttributedString:(NSAttributedString)->Bool
public var copyToClipboard:((String)->Void)?
public var hoverOnLink: (LinkHoverValue)->Void
public var topWindow:(()->Signal<Window?, NoError>)? = nil
public var translate:((String, Window)->ContextMenuItem?)? = nil
public init(processURL:@escaping (Any)->Void = {_ in}, copy:(()-> Bool)? = nil, menuItems:((LinkType?)->Signal<[ContextMenuItem], NoError>)? = nil, isDomainLink:@escaping(Any, String?)->Bool = {_, _ in return true}, makeLinkType:@escaping((Any, String)) -> LinkType = {_ in return .plain}, localizeLinkCopy:@escaping(LinkType)-> String = {_ in return localizedString("Text.Copy")}, resolveLink: @escaping(Any)->String? = { _ in return nil }, copyAttributedString: @escaping(NSAttributedString)->Bool = { _ in return false}, copyToClipboard: ((String)->Void)? = nil, hoverOnLink: @escaping(LinkHoverValue)->Void = { _ in }, topWindow:(()->Signal<Window?, NoError>)? = nil, translate:((String, Window)->ContextMenuItem?)? = nil) {
self.processURL = processURL
self.copy = copy
self.menuItems = menuItems
self.isDomainLink = isDomainLink
self.makeLinkType = makeLinkType
self.localizeLinkCopy = localizeLinkCopy
self.resolveLink = resolveLink
self.copyAttributedString = copyAttributedString
self.copyToClipboard = copyToClipboard
self.hoverOnLink = hoverOnLink
self.topWindow = topWindow
self.translate = translate
}
}
struct TextViewStrikethrough {
let color: NSColor
let frame: NSRect
init(color: NSColor, frame: NSRect) {
self.color = color
self.frame = frame
}
}
public final class TextViewLine {
public let line: CTLine
public let frame: NSRect
public let range: NSRange
public var penFlush: CGFloat
let isRTL: Bool
let isBlocked: Bool
let strikethrough:[TextViewStrikethrough]
fileprivate let embeddedItems:[TextViewEmbeddedItem]
fileprivate init(line: CTLine, frame: CGRect, range: NSRange, penFlush: CGFloat, isBlocked: Bool = false, isRTL: Bool = false, strikethrough: [TextViewStrikethrough] = [], embeddedItems:[TextViewEmbeddedItem] = []) {
self.line = line
self.frame = frame
self.range = range
self.penFlush = penFlush
self.isBlocked = isBlocked
self.strikethrough = strikethrough
self.isRTL = isRTL
self.embeddedItems = embeddedItems
}
}
public enum TextViewCutoutPosition {
case TopLeft
case TopRight
case BottomRight
}
public struct TextViewCutout: Equatable {
public var topLeft: CGSize?
public var topRight: CGSize?
public var bottomRight: CGSize?
public init(topLeft: CGSize? = nil, topRight: CGSize? = nil, bottomRight: CGSize? = nil) {
self.topLeft = topLeft
self.topRight = topRight
self.bottomRight = bottomRight
}
}
private let defaultFont:NSFont = .normal(.text)
public final class TextViewLayout : Equatable {
public final class EmbeddedItem: Equatable {
public let range: NSRange
public let rect: CGRect
public let value: AnyHashable
public init(range: NSRange, rect: CGRect, value: AnyHashable) {
self.range = range
self.rect = rect
self.value = value
}
public static func ==(lhs: EmbeddedItem, rhs: EmbeddedItem) -> Bool {
if lhs.range != rhs.range {
return false
}
if lhs.rect != rhs.rect {
return false
}
if lhs.value != rhs.value {
return false
}
return true
}
}
public class Spoiler {
public let range: NSRange
public let color: NSColor
public fileprivate(set) var isRevealed: Bool = false
public init(range: NSRange, color: NSColor, isRevealed: Bool = false) {
self.range = range
self.color = color.withAlphaComponent(1.0)
self.isRevealed = isRevealed
}
}
public var mayItems: Bool = true
public var selectWholeText: Bool = false
public fileprivate(set) var attributedString:NSAttributedString
public fileprivate(set) var constrainedWidth:CGFloat = 0
public var interactions:TextViewInteractions = TextViewInteractions()
public var selectedRange:TextSelectedRange
public var additionalSelections:[TextSelectedRange] = []
public var penFlush:CGFloat
fileprivate var insets:NSSize = NSZeroSize
public fileprivate(set) var lines:[TextViewLine] = []
public fileprivate(set) var isPerfectSized:Bool = true
public var maximumNumberOfLines:Int32
public let truncationType:CTLineTruncationType
public var cutout:TextViewCutout?
public var mayBlocked: Bool = false
fileprivate var blockImage:(CGPoint, CGImage?) = (CGPoint(), nil)
public fileprivate(set) var lineSpacing:CGFloat?
public private(set) var layoutSize:NSSize = NSZeroSize
public private(set) var perfectSize:NSSize = NSZeroSize
public var alwaysStaticItems: Bool
fileprivate var selectText: NSColor
public var strokeLinks: Bool
fileprivate var strokeRects: [(NSRect, NSColor)] = []
fileprivate var hexColorsRect: [(NSRect, NSColor, String)] = []
fileprivate var toolTipRects:[NSRect] = []
private let disableTooltips: Bool
public fileprivate(set) var isBigEmoji: Bool = false
fileprivate let spoilers:[Spoiler]
private let onSpoilerReveal: ()->Void
public private(set) var embeddedItems: [EmbeddedItem] = []
public init(_ attributedString:NSAttributedString, constrainedWidth:CGFloat = 0, maximumNumberOfLines:Int32 = INT32_MAX, truncationType: CTLineTruncationType = .end, cutout:TextViewCutout? = nil, alignment:NSTextAlignment = .left, lineSpacing:CGFloat? = nil, selectText: NSColor = presentation.colors.selectText, strokeLinks: Bool = false, alwaysStaticItems: Bool = false, disableTooltips: Bool = true, mayItems: Bool = true, spoilers:[Spoiler] = [], onSpoilerReveal: @escaping()->Void = {}) {
self.spoilers = spoilers
self.truncationType = truncationType
self.maximumNumberOfLines = maximumNumberOfLines
self.cutout = cutout
self.disableTooltips = disableTooltips
self.attributedString = attributedString
self.constrainedWidth = constrainedWidth
self.selectText = selectText
self.alwaysStaticItems = alwaysStaticItems
self.selectedRange = TextSelectedRange(color: selectText)
self.strokeLinks = strokeLinks
self.mayItems = mayItems
self.onSpoilerReveal = onSpoilerReveal
switch alignment {
case .center:
penFlush = 0.5
case .right:
penFlush = 1.0
default:
penFlush = 0.0
}
self.lineSpacing = lineSpacing
}
func revealSpoiler() -> Void {
for spoiler in spoilers {
spoiler.isRevealed = true
}
onSpoilerReveal()
}
public func dropLayoutSize() {
self.layoutSize = .zero
}
func calculateLayout(isBigEmoji: Bool = false) -> Void {
self.isBigEmoji = isBigEmoji
isPerfectSized = true
self.insets = .zero
let font: CTFont
if attributedString.length != 0 {
if let stringFont = attributedString.attribute(NSAttributedString.Key(kCTFontAttributeName as String), at: 0, effectiveRange: nil) {
font = stringFont as! CTFont
} else {
font = defaultFont
}
} else {
font = defaultFont
}
self.lines.removeAll()
let fontAscent = CTFontGetAscent(font)
let fontDescent = CTFontGetDescent(font)
let fontLineHeight = floor(fontAscent + (isBigEmoji ? fontDescent / 2 : fontDescent)) + (lineSpacing ?? 0)
var monospacedRects:[NSRect] = []
var fontLineSpacing:CGFloat = floor(fontLineHeight * 0.12)
var maybeTypesetter: CTTypesetter?
let copy = attributedString.mutableCopy() as! NSMutableAttributedString
copy.removeAttribute(.strikethroughStyle, range: copy.range)
maybeTypesetter = CTTypesetterCreateWithAttributedString(copy as CFAttributedString)
let typesetter = maybeTypesetter!
var lastLineCharacterIndex: CFIndex = 0
var layoutSize = NSSize()
var cutoutEnabled = false
var cutoutMinY: CGFloat = 0.0
var cutoutMaxY: CGFloat = 0.0
var cutoutWidth: CGFloat = 0.0
var cutoutOffset: CGFloat = 0.0
var bottomCutoutEnabled = false
var bottomCutoutSize = CGSize()
if let topLeft = cutout?.topLeft {
cutoutMinY = -fontLineSpacing
cutoutMaxY = topLeft.height + fontLineSpacing
cutoutWidth = topLeft.width
cutoutOffset = cutoutWidth
cutoutEnabled = true
} else if let topRight = cutout?.topRight {
cutoutMinY = -fontLineSpacing
cutoutMaxY = topRight.height + fontLineSpacing
cutoutWidth = topRight.width
cutoutEnabled = true
}
if let bottomRight = cutout?.bottomRight {
bottomCutoutSize = bottomRight
bottomCutoutEnabled = true
}
var first = true
var breakInset: CGFloat = 0
var isWasPreformatted: Bool = false
while true {
var strikethroughs: [TextViewStrikethrough] = []
var embeddedItems: [TextViewEmbeddedItem] = []
func addEmbeddedItem(item: AnyHashable, line: CTLine, ascent: CGFloat, descent: CGFloat, startIndex: Int, endIndex: Int, rightInset: CGFloat = 0.0) {
var secondaryLeftOffset: CGFloat = 0.0
let rawLeftOffset = CTLineGetOffsetForStringIndex(line, startIndex, &secondaryLeftOffset)
var leftOffset = floor(rawLeftOffset)
if !rawLeftOffset.isEqual(to: secondaryLeftOffset) {
leftOffset = floor(secondaryLeftOffset)
}
var secondaryRightOffset: CGFloat = 0.0
let rawRightOffset = CTLineGetOffsetForStringIndex(line, endIndex, &secondaryRightOffset)
var rightOffset = ceil(rawRightOffset)
if !rawRightOffset.isEqual(to: secondaryRightOffset) {
rightOffset = ceil(secondaryRightOffset)
}
if rightOffset > leftOffset, abs(rightOffset - leftOffset) < 150 {
embeddedItems.append(TextViewEmbeddedItem(range: NSMakeRange(startIndex, endIndex - startIndex), frame: CGRect(x: floor(min(leftOffset, rightOffset)), y: floor(descent - (ascent + descent)), width: floor(abs(rightOffset - leftOffset) + rightInset), height: floor(ascent + descent)), item: item))
}
}
var lineConstrainedWidth = constrainedWidth
var lineOriginY: CGFloat = 0
var lineCutoutOffset: CGFloat = 0.0
var lineAdditionalWidth: CGFloat = 0.0
var isPreformattedLine: CGFloat? = nil
fontLineSpacing = isBigEmoji ? 0 : floor(fontLineHeight * 0.12)
if isBigEmoji {
lineOriginY += 2
}
if attributedString.length > 0, let space = (attributedString.attribute(.preformattedPre, at: min(lastLineCharacterIndex, attributedString.length - 1), effectiveRange: nil) as? NSNumber), mayBlocked {
breakInset = CGFloat(space.floatValue * 2)
lineCutoutOffset += CGFloat(space.floatValue)
lineAdditionalWidth += breakInset
lineOriginY += CGFloat(space.floatValue/2)
if !isWasPreformatted && !first {
lineOriginY += CGFloat(space.floatValue)
fontLineSpacing = CGFloat(space.floatValue) - fontLineSpacing
} else {
if isWasPreformatted || first {
fontLineSpacing = -CGFloat(space.floatValue/2)
lineOriginY -= (CGFloat(space.floatValue + space.floatValue/2))
}
}
isPreformattedLine = CGFloat(space.floatValue)
isWasPreformatted = true
} else {
if isWasPreformatted && !first {
lineOriginY -= (2 - fontLineSpacing)
}
isWasPreformatted = false
}
lineOriginY += floor(layoutSize.height + fontLineHeight - fontLineSpacing * 2.0)
if !first {
lineOriginY += fontLineSpacing
}
if cutoutEnabled {
if lineOriginY < cutoutMaxY && lineOriginY + fontLineHeight > cutoutMinY {
lineConstrainedWidth = max(1.0, lineConstrainedWidth - cutoutWidth)
lineCutoutOffset = cutoutOffset
lineAdditionalWidth = cutoutWidth
}
}
let lineCharacterCount = CTTypesetterSuggestLineBreak(typesetter, lastLineCharacterIndex, Double(lineConstrainedWidth - breakInset))
var lineRange = CFRange(location: lastLineCharacterIndex, length: lineCharacterCount)
var lineHeight = fontLineHeight
let lineString = attributedString.attributedSubstring(from: NSMakeRange(lastLineCharacterIndex, lineCharacterCount))
if lineString.string.containsEmoji, !isBigEmoji {
if first {
lineHeight += floor(fontDescent)
lineOriginY += floor(fontDescent)
}
}
if maximumNumberOfLines != 0 && lines.count == (Int(maximumNumberOfLines) - 1) && lineCharacterCount > 0 {
if first {
first = false
} else {
layoutSize.height += fontLineSpacing
}
let coreTextLine: CTLine
let originalLine = CTTypesetterCreateLineWithOffset(typesetter, CFRange(location: lastLineCharacterIndex, length: attributedString.length - lastLineCharacterIndex), 0.0)
if CTLineGetTypographicBounds(originalLine, nil, nil, nil) - CTLineGetTrailingWhitespaceWidth(originalLine) < Double(constrainedWidth) {
coreTextLine = originalLine
} else {
var truncationTokenAttributes: [NSAttributedString.Key : Any] = [:]
truncationTokenAttributes[NSAttributedString.Key(kCTFontAttributeName as String)] = font
truncationTokenAttributes[NSAttributedString.Key(kCTForegroundColorAttributeName as String)] = attributedString.attribute(.foregroundColor, at: min(lastLineCharacterIndex, attributedString.length - 1), effectiveRange: nil) as? NSColor ?? NSColor.black
let tokenString = "\u{2026}"
let truncatedTokenString = NSAttributedString(string: tokenString, attributes: truncationTokenAttributes)
let truncationToken = CTLineCreateWithAttributedString(truncatedTokenString)
var lineConstrainedWidth = constrainedWidth
if bottomCutoutEnabled {
lineConstrainedWidth -= bottomCutoutSize.width
}
coreTextLine = CTLineCreateTruncatedLine(originalLine, Double(lineConstrainedWidth), truncationType, truncationToken) ?? truncationToken
isPerfectSized = false
}
lineRange = CTLineGetStringRange(coreTextLine)
let lineWidth = ceil(CGFloat(CTLineGetTypographicBounds(coreTextLine, nil, nil, nil) - CTLineGetTrailingWhitespaceWidth(coreTextLine)))
let lineFrame = CGRect(x: lineCutoutOffset, y: lineOriginY, width: lineWidth, height: lineHeight)
layoutSize.height += lineHeight + fontLineSpacing
layoutSize.width = max(layoutSize.width, lineWidth + lineAdditionalWidth)
attributedString.enumerateAttributes(in: NSMakeRange(lineRange.location, lineRange.length), options: []) { attributes, range, _ in
if let _ = attributes[.strikethroughStyle] {
let color = attributes[.foregroundColor] as? NSColor ?? presentation.colors.text
let lowerX = floor(CTLineGetOffsetForStringIndex(coreTextLine, range.location, nil))
let upperX = ceil(CTLineGetOffsetForStringIndex(coreTextLine, range.location + range.length, nil))
let x = lowerX < upperX ? lowerX : upperX
strikethroughs.append(TextViewStrikethrough(color: color, frame: CGRect(x: x, y: 0.0, width: abs(upperX - lowerX), height: fontLineHeight)))
} else if let embeddedItem = attributes[NSAttributedString.Key(rawValue: "Attribute__EmbeddedItem")] as? AnyHashable {
var ascent: CGFloat = 0.0
var descent: CGFloat = 0.0
CTLineGetTypographicBounds(coreTextLine, &ascent, &descent, nil)
addEmbeddedItem(item: embeddedItem, line: coreTextLine, ascent: ascent, descent: descent, startIndex: range.location, endIndex: range.location + range.length)
}
}
var isRTL = false
let glyphRuns = CTLineGetGlyphRuns(coreTextLine) as NSArray
if glyphRuns.count != 0 {
let run = glyphRuns[0] as! CTRun
if CTRunGetStatus(run).contains(CTRunStatus.rightToLeft) {
isRTL = true
}
}
lines.append(TextViewLine(line: coreTextLine, frame: lineFrame, range: NSMakeRange(lineRange.location, lineRange.length), penFlush: self.penFlush, isBlocked: isWasPreformatted, isRTL: isRTL, strikethrough: strikethroughs, embeddedItems: embeddedItems))
break
} else {
if lineCharacterCount > 0 {
if first {
first = false
} else {
layoutSize.height += fontLineSpacing
}
let coreTextLine = CTTypesetterCreateLineWithOffset(typesetter, CFRangeMake(lastLineCharacterIndex, lineCharacterCount), 100.0)
let lineWidth = ceil(CGFloat(CTLineGetTypographicBounds(coreTextLine, nil, nil, nil) - CTLineGetTrailingWhitespaceWidth(coreTextLine)))
let lineFrame = CGRect(x: lineCutoutOffset, y: lineOriginY - (isBigEmoji ? fontDescent / 3 : 0), width: lineWidth, height: lineHeight)
layoutSize.height += lineHeight
layoutSize.width = max(layoutSize.width, lineWidth + lineAdditionalWidth)
if let space = lineString.attribute(.preformattedPre, at: 0, effectiveRange: nil) as? NSNumber, mayBlocked {
layoutSize.width = self.constrainedWidth
let preformattedSpace = CGFloat(space.floatValue) * 2
monospacedRects.append(NSMakeRect(0, lineFrame.minY - lineFrame.height, layoutSize.width, lineFrame.height + preformattedSpace))
}
attributedString.enumerateAttributes(in: NSMakeRange(lineRange.location, lineRange.length), options: []) { attributes, range, _ in
if let _ = attributes[.strikethroughStyle] {
let color = attributes[.foregroundColor] as? NSColor ?? presentation.colors.text
let lowerX = floor(CTLineGetOffsetForStringIndex(coreTextLine, range.location, nil))
let upperX = ceil(CTLineGetOffsetForStringIndex(coreTextLine, range.location + range.length, nil))
let x = lowerX < upperX ? lowerX : upperX
strikethroughs.append(TextViewStrikethrough(color: color, frame: CGRect(x: x, y: 0.0, width: abs(upperX - lowerX), height: fontLineHeight)))
} else if let embeddedItem = attributes[NSAttributedString.Key(rawValue: "Attribute__EmbeddedItem")] as? AnyHashable {
var ascent: CGFloat = 0.0
var descent: CGFloat = 0.0
CTLineGetTypographicBounds(coreTextLine, &ascent, &descent, nil)
addEmbeddedItem(item: embeddedItem, line: coreTextLine, ascent: ascent, descent: descent, startIndex: range.location, endIndex: range.location + range.length)
}
}
var isRTL = false
let glyphRuns = CTLineGetGlyphRuns(coreTextLine) as NSArray
if glyphRuns.count != 0 {
let run = glyphRuns[0] as! CTRun
if CTRunGetStatus(run).contains(CTRunStatus.rightToLeft) {
isRTL = true
}
}
lines.append(TextViewLine(line: coreTextLine, frame: lineFrame, range: NSMakeRange(lineRange.location, lineRange.length), penFlush: self.penFlush, isBlocked: isWasPreformatted, isRTL: isRTL, strikethrough: strikethroughs, embeddedItems: embeddedItems))
lastLineCharacterIndex += lineCharacterCount
} else {
if !lines.isEmpty {
layoutSize.height += fontLineSpacing
}
break
}
}
if mayBlocked {
if let isPreformattedLine = isPreformattedLine {
layoutSize.height += isPreformattedLine * 2
if lastLineCharacterIndex == attributedString.length {
layoutSize.height += isPreformattedLine/2
}
// fontLineSpacing = isPreformattedLine
}
}
}
if mayBlocked {
let sortedIndices = (0 ..< monospacedRects.count).sorted(by: { monospacedRects[$0].width > monospacedRects[$1].width })
for i in 0 ..< sortedIndices.count {
let index = sortedIndices[i]
for j in -1 ... 1 {
if j != 0 && index + j >= 0 && index + j < sortedIndices.count {
if abs(monospacedRects[index + j].width - monospacedRects[index].width) < 40.0 {
monospacedRects[index + j].size.width = max(monospacedRects[index + j].width, monospacedRects[index].width)
}
}
}
}
self.blockImage = generateRectsImage(color: presentation.colors.grayBackground, rects: monospacedRects, inset: 0, outerRadius: .cornerRadius, innerRadius: .cornerRadius)
}
var embeddedItems: [EmbeddedItem] = []
for line in lines {
for embeddedItem in line.embeddedItems {
let penOffset = floor(CGFloat(CTLineGetPenOffsetForFlush(line.line, line.penFlush, Double(layoutSize.width))))
embeddedItems.append(EmbeddedItem(range: embeddedItem.range, rect: embeddedItem.frame.offsetBy(dx: line.frame.minX, dy: line.frame.minY).offsetBy(dx: penOffset, dy: 0), value: embeddedItem.item))
}
}
if lines.count == 1 {
let line = lines[0]
if !line.embeddedItems.isEmpty {
layoutSize.height += isBigEmoji ? 8 : 2
}
// if isBigEmoji {
// layoutSize.width += 5
// }
} else {
if isBigEmoji, let line = lines.last {
if !line.embeddedItems.isEmpty {
layoutSize.height += 4
}
} else if let line = lines.last, !line.embeddedItems.isEmpty {
layoutSize.height += 1
}
}
self.embeddedItems = embeddedItems
//self.monospacedStrokeImage = generateRectsImage(color: presentation.colors.border, rects: monospacedRects, inset: 0, outerRadius: .cornerRadius, innerRadius: .cornerRadius)
self.layoutSize = layoutSize
}
public func generateAutoBlock(backgroundColor: NSColor) {
var rects = self.lines.map({$0.frame})
if !rects.isEmpty {
let sortedIndices = (0 ..< rects.count).sorted(by: { rects[$0].width > rects[$1].width })
for i in 0 ..< sortedIndices.count {
let index = sortedIndices[i]
for j in -1 ... 1 {
if j != 0 && index + j >= 0 && index + j < sortedIndices.count {
if abs(rects[index + j].width - rects[index].width) < 40.0 {
rects[index + j].size.width = max(rects[index + j].width, rects[index].width)
}
}
}
}
for i in 0 ..< rects.count {
let height = rects[i].size.height + 7
rects[i] = rects[i].insetBy(dx: 0, dy: floor((rects[i].height - height) / 2.0))
rects[i].size.height = height
rects[i].origin.x = floor((layoutSize.width - rects[i].width) / 2.0)
rects[i].size.width += 20
}
self.blockImage = generateRectsImage(color: backgroundColor, rects: rects, inset: 0, outerRadius: rects[0].height / 2, innerRadius: .cornerRadius)
self.blockImage.0 = NSMakePoint(0, 0)
layoutSize.width += 20
lines[0] = TextViewLine(line: lines[0].line, frame: lines[0].frame.offsetBy(dx: 0, dy: 2), range: lines[0].range, penFlush: self.penFlush, strikethrough: lines[0].strikethrough, embeddedItems: lines[0].embeddedItems)
layoutSize.height = rects.last!.maxY
}
}
public func selectNextChar() {
var range = selectedRange.range
switch selectedRange.cursorAlignment {
case let .min(cursorAlignment), let .max(cursorAlignment):
if range.min >= cursorAlignment {
range.length += 1
} else {
range.location += 1
if range.length > 1 {
range.length -= 1
}
}
}
let location = min(max(0, range.location), attributedString.length)
let length = max(min(range.length, attributedString.length - location), 0)
selectedRange.range = NSMakeRange(location, length)
}
public func selectPrevChar() {
var range = selectedRange.range
switch selectedRange.cursorAlignment {
case let .min(cursorAlignment), let .max(cursorAlignment):
if range.location >= cursorAlignment {
if range.length > 1 {
range.length -= 1
} else {
range.location -= 1
}
} else {
if range.location > 0 {
range.location -= 1
range.length += 1
}
}
}
let location = min(max(0, range.location), attributedString.length)
let length = max(min(range.length, attributedString.length - location), 0)
selectedRange.range = NSMakeRange(location, length)
}
public func measure(width: CGFloat = 0, isBigEmoji: Bool = false) -> Void {
if width != 0 {
constrainedWidth = width
}
toolTipRects.removeAll()
calculateLayout(isBigEmoji: isBigEmoji)
strokeRects.removeAll()
attributedString.enumerateAttribute(NSAttributedString.Key.link, in: attributedString.range, options: NSAttributedString.EnumerationOptions(rawValue: 0), using: { value, range, stop in
if let value = value {
if interactions.isDomainLink(value, attributedString.attributedSubstring(from: range).string) && strokeLinks {
for line in lines {
let lineRange = NSIntersectionRange(range, line.range)
if lineRange.length != 0 {
var leftOffset: CGFloat = 0.0
if lineRange.location != line.range.location {
leftOffset = floor(CTLineGetOffsetForStringIndex(line.line, lineRange.location, nil))
}
let rightOffset: CGFloat = ceil(CTLineGetOffsetForStringIndex(line.line, lineRange.location + lineRange.length, nil))
let color: NSColor = attributedString.attribute(NSAttributedString.Key.foregroundColor, at: range.location, effectiveRange: nil) as? NSColor ?? presentation.colors.link
let rect = NSMakeRect(line.frame.minX + leftOffset, line.frame.minY + 1, rightOffset - leftOffset, 1.0)
strokeRects.append((rect, color))
if !disableTooltips, interactions.resolveLink(value) != attributedString.string.nsstring.substring(with: range) {
var leftOffset: CGFloat = 0.0
if lineRange.location != line.range.location {
leftOffset = floor(CTLineGetOffsetForStringIndex(line.line, lineRange.location, nil))
}
let rightOffset: CGFloat = ceil(CTLineGetOffsetForStringIndex(line.line, lineRange.location + lineRange.length, nil))
toolTipRects.append(NSMakeRect(line.frame.minX + leftOffset, line.frame.minY - line.frame.height, rightOffset - leftOffset, line.frame.height))
}
}
}
}
if !disableTooltips, interactions.resolveLink(value) != attributedString.string.nsstring.substring(with: range) {
for line in lines {
let lineRange = NSIntersectionRange(range, line.range)
if lineRange.length != 0 {
var leftOffset: CGFloat = 0.0
if lineRange.location != line.range.location {
leftOffset = floor(CTLineGetOffsetForStringIndex(line.line, lineRange.location, nil))
}
let rightOffset: CGFloat = ceil(CTLineGetOffsetForStringIndex(line.line, lineRange.location + lineRange.length, nil))
toolTipRects.append(NSMakeRect(line.frame.minX + leftOffset, line.frame.minY - line.frame.height, rightOffset - leftOffset, line.frame.height))
}
}
}
}
})
hexColorsRect.removeAll()
attributedString.enumerateAttribute(NSAttributedString.Key.hexColorMark, in: attributedString.range, options: NSAttributedString.EnumerationOptions(rawValue: 0), using: { value, range, stop in
if let color = value as? NSColor, let size = attributedString.attribute(.hexColorMarkDimensions, at: range.location, effectiveRange: nil) as? NSSize {
for line in lines {
let lineRange = NSIntersectionRange(range, line.range)
if lineRange.length != 0 {
var leftOffset: CGFloat = 0
if lineRange.location != line.range.location {
leftOffset += floor(CTLineGetOffsetForStringIndex(line.line, lineRange.location, nil))
}
let rect = NSMakeRect(line.frame.minX + leftOffset + 10, line.frame.minY - (size.height - 7) + 2, size.width - 8, size.height - 8)
hexColorsRect.append((rect, color, attributedString.attributedSubstring(from: range).string))
}
}
}
})
attributedString.enumerateAttribute(NSAttributedString.Key.underlineStyle, in: attributedString.range, options: NSAttributedString.EnumerationOptions(rawValue: 0), using: { value, range, stop in
if let _ = value {
for line in lines {
let lineRange = NSIntersectionRange(range, line.range)
if lineRange.length != 0 {
var leftOffset: CGFloat = 0.0
if lineRange.location != line.range.location {
leftOffset = floor(CTLineGetOffsetForStringIndex(line.line, lineRange.location, nil))
}
let rightOffset: CGFloat = ceil(CTLineGetOffsetForStringIndex(line.line, lineRange.location + lineRange.length, nil))
let color: NSColor = attributedString.attribute(NSAttributedString.Key.foregroundColor, at: range.location, effectiveRange: nil) as? NSColor ?? presentation.colors.text
let rect = NSMakeRect(line.frame.minX + leftOffset, line.frame.minY + 1, rightOffset - leftOffset, 1.0)
strokeRects.append((rect, color))
}
}
}
})
}
public func clearSelect() {
self.selectedRange.range = NSMakeRange(NSNotFound, 0)
}
public func selectedRange(startPoint:NSPoint, currentPoint:NSPoint) -> NSRange {
var selectedRange:NSRange = NSMakeRange(NSNotFound, 0)
if (currentPoint.x != -1 && currentPoint.y != -1 && !lines.isEmpty && startPoint.x != -1 && startPoint.y != -1) {
let startSelectLineIndex = findIndex(location: startPoint)
let currentSelectLineIndex = findIndex(location: currentPoint)
let dif = abs(startSelectLineIndex - currentSelectLineIndex)
let isReversed = currentSelectLineIndex < startSelectLineIndex
var i = startSelectLineIndex
while isReversed ? i >= currentSelectLineIndex : i <= currentSelectLineIndex {
let line = lines[i].line
let lineRange = CTLineGetStringRange(line)
var startIndex: CFIndex = CTLineGetStringIndexForPosition(line, startPoint)
var endIndex: CFIndex = CTLineGetStringIndexForPosition(line, currentPoint)
if dif > 0 {
if i != currentSelectLineIndex {
endIndex = (lineRange.length + lineRange.location)
}
if i != startSelectLineIndex {
startIndex = lineRange.location
}
if isReversed {
if i == startSelectLineIndex {
endIndex = startIndex
startIndex = lineRange.location
}
if i == currentSelectLineIndex {
startIndex = endIndex
endIndex = (lineRange.length + lineRange.location)
}
}
}
if startIndex > endIndex {
startIndex = endIndex + startIndex
endIndex = startIndex - endIndex
startIndex = startIndex - endIndex
}
if abs(Int(startIndex) - Int(endIndex)) > 0 && (selectedRange.location == NSNotFound || selectedRange.location > startIndex) {
selectedRange.location = startIndex
}
selectedRange.length += (endIndex - startIndex)
i += isReversed ? -1 : 1
}
}
return selectedRange
}
public func findIndex(location:NSPoint) -> Int {
if location.y == .greatestFiniteMagnitude {
return lines.count - 1
} else if location.y == 0 {
return 0
}
//var previous:NSRect = lines[0].frame
for idx in 0 ..< lines.count {
if isCurrentLine(pos: location, index: idx) {
return idx
}
}
return location.y <= layoutSize.height ? 0 : (lines.count - 1)
}
public func inSelectedRange(_ location:NSPoint) -> Bool {
let index = findCharacterIndex(at: location)
return selectedRange.range.indexIn(index)
}
public func isCurrentLine(pos:NSPoint, index:Int) -> Bool {
let line = lines[index]
var rect = line.frame
var ascent:CGFloat = 0
var descent:CGFloat = 0
var leading:CGFloat = 0
CTLineGetTypographicBounds(line.line, &ascent, &descent, &leading)
rect.origin.y = rect.minY - rect.height + ceil(descent - leading)
rect.size.height += ceil(descent - leading)
if line.isBlocked {
rect.size.height += 2
}
return (pos.y > rect.minY) && pos.y < rect.maxY
}
fileprivate func color(at point: NSPoint) -> (NSColor, String)? {
for value in self.hexColorsRect {
if NSPointInRect(point, value.0) {
return (value.1, value.2)
}
}
return nil
}
func spoiler(at point: NSPoint) -> Spoiler? {
let index = self.findCharacterIndex(at: point)
for spoiler in spoilers {
if spoiler.range.contains(index) {
if !spoiler.isRevealed {
return spoiler
}
}
}
return nil
}
func spoilerRects(_ checkRevealed: Bool = true) -> [CGRect] {
var rects:[CGRect] = []
for i in 0 ..< lines.count {
let line = lines[i]
for spoiler in spoilers.filter({ !$0.isRevealed || !checkRevealed }) {
if let spoilerRange = spoiler.range.intersection(line.range) {
let range = spoilerRange.intersection(selectedRange.range)
var ranges:[(NSRange, NSColor)] = []
if let range = range {
ranges.append((NSMakeRange(spoiler.range.lowerBound, range.lowerBound - spoiler.range.lowerBound), spoiler.color))
ranges.append((NSMakeRange(spoiler.range.upperBound, range.upperBound - spoiler.range.upperBound), spoiler.color))
} else {
ranges.append((spoilerRange, spoiler.color))
}
for range in ranges {
let startOffset = CTLineGetOffsetForStringIndex(line.line, range.0.lowerBound, nil);
let endOffset = CTLineGetOffsetForStringIndex(line.line, range.0.upperBound, nil);
var ascent:CGFloat = 0
var descent:CGFloat = 0
var leading:CGFloat = 0
_ = CGFloat(CTLineGetTypographicBounds(line.line, &ascent, &descent, &leading));
var rect:NSRect = line.frame
rect.size.width = abs(endOffset - startOffset)
rect.origin.x = min(startOffset, endOffset)
rect.origin.y = rect.minY - rect.height + 2
rect.size.height += ceil(descent - leading)
rects.append(rect)
}
}
}
}
return rects
}
public func link(at point:NSPoint) -> (Any, LinkType, NSRange, NSRect)? {
let index = findIndex(location: point)
guard index != -1, !lines.isEmpty else {
return nil
}
let line = lines[index]
var ascent:CGFloat = 0
var descent:CGFloat = 0
var leading:CGFloat = 0
let width:CGFloat = CGFloat(CTLineGetTypographicBounds(line.line, &ascent, &descent, &leading));
var point = point
//point.x -= floorToScreenPixels(System.backingScale, (frame.width - line.frame.width) / 2)
// var penOffset = CGFloat( CTLineGetPenOffsetForFlush(line.line, line.penFlush, Double(frame.width))) + line.frame.minX
// if layout.penFlush == 0.5, line.penFlush != 0.5 {
// penOffset = startPosition.x
// } else if layout.penFlush == 0.0 {
// penOffset = startPosition.x
// }
point.x -= ((layoutSize.width - line.frame.width) * line.penFlush)
if width > point.x, point.x >= 0 {
var pos = CTLineGetStringIndexForPosition(line.line, point);
pos = min(max(0,pos),attributedString.length - 1)
var range:NSRange = NSMakeRange(NSNotFound, 0)
let attrs = attributedString.attributes(at: pos, effectiveRange: &range)
let link:Any? = attrs[NSAttributedString.Key.link]
if let link = link {
let startOffset = CTLineGetOffsetForStringIndex(line.line, range.location, nil);
let endOffset = CTLineGetOffsetForStringIndex(line.line, range.location + range.length, nil);
return (link, interactions.makeLinkType((link, attributedString.attributedSubstring(from: range).string)), range, NSMakeRect(startOffset, line.frame.minY, endOffset - startOffset, ceil(ascent + ceil(descent) + leading)))
}
}
return nil
}
func findCharacterIndex(at point:NSPoint) -> Int {
let index = findIndex(location: point)
guard index != -1 else {
return -1
}
let line = lines[index]
let width:CGFloat = CGFloat(CTLineGetTypographicBounds(line.line, nil, nil, nil));
if width > point.x {
let charIndex = Int(CTLineGetStringIndexForPosition(line.line, point))
return charIndex == attributedString.length ? charIndex - 1 : charIndex
}
return -1
}
public func offset(for index: Int) -> CGFloat? {
let line = self.lines.first(where: {
$0.range.indexIn(index)
})
if let line = line {
return CTLineGetOffsetForStringIndex(line.line, index, nil)
}
return nil
}
public func selectAll(at point:NSPoint) -> Void {
let startIndex = findCharacterIndex(at: point)
if startIndex == -1 {
return
}
var blockRange: NSRange = NSMakeRange(NSNotFound, 0)
if let _ = attributedString.attribute(.preformattedPre, at: startIndex, effectiveRange: &blockRange) {
self.selectedRange = TextSelectedRange(range: blockRange, color: selectText, def: true)
} else {
var firstIndex: Int = startIndex
var lastIndex: Int = startIndex
var firstFound: Bool = false
var lastFound: Bool = false
while (firstIndex > 0 && !firstFound) || (lastIndex < self.attributedString.length - 1 && !lastFound) {
let firstSymbol = self.attributedString.string.nsstring.substring(with: NSMakeRange(firstIndex, 1))
let lastSymbol = self.attributedString.string.nsstring.substring(with: NSMakeRange(lastIndex, 1))
firstFound = firstSymbol == "\n"
lastFound = lastSymbol == "\n"
if firstIndex > 0, !firstFound {
firstIndex -= 1
}
if lastIndex < self.attributedString.length - 1, !lastFound {
lastIndex += 1
}
}
if lastFound {
lastIndex = max(lastIndex - 1, 0)
}
if firstFound {
firstIndex = min(firstIndex + 1, self.attributedString.length - 1)
}
self.selectedRange = TextSelectedRange(range: NSMakeRange(firstIndex, (lastIndex + 1) - firstIndex), color: selectText, def: true)
}
}
public func selectWord(at point:NSPoint) -> Void {
if selectWholeText {
self.selectedRange = TextSelectedRange(range: attributedString.range, color: selectText, def: true)
return
}
let startIndex = findCharacterIndex(at: point)
if startIndex == -1 {
return
}
var prev = startIndex
var next = startIndex
var range = NSMakeRange(startIndex, 1)
let char:NSString = attributedString.string.nsstring.substring(with: range) as NSString
var effectiveRange:NSRange = NSMakeRange(NSNotFound, 0)
let check = attributedString.attribute(NSAttributedString.Key.link, at: range.location, effectiveRange: &effectiveRange)
if check != nil && effectiveRange.location != NSNotFound {
self.selectedRange = TextSelectedRange(range: effectiveRange, color: selectText, def: true)
return
}
if char == "" {
self.selectedRange = TextSelectedRange(color: selectText)
return
}
let tidyChar = char.trimmingCharacters(in: NSCharacterSet.alphanumerics)
let valid:Bool = tidyChar == "" || tidyChar == "_" || tidyChar == "\u{FFFD}"
let string:NSString = attributedString.string.nsstring
while valid {
let prevChar = string.substring(with: NSMakeRange(prev, 1))
let nextChar = string.substring(with: NSMakeRange(next, 1))
let tidyPrev = prevChar.trimmingCharacters(in: NSCharacterSet.alphanumerics)
let tidyNext = nextChar.trimmingCharacters(in: NSCharacterSet.alphanumerics)
var prevValid:Bool = tidyPrev == "" || tidyPrev == "_" || tidyPrev == "\u{FFFD}"
var nextValid:Bool = tidyNext == "" || tidyNext == "_" || tidyNext == "\u{FFFD}"
if (prevValid && prev > 0) {
prev -= 1
}
if(nextValid && next < string.length - 1) {
next += 1
}
range.location = prevValid ? prev : prev + 1;
range.length = next - range.location;
if prev == 0 {
prevValid = false
}
if(next == string.length - 1) {
nextValid = false
let nextChar = string.substring(with: NSMakeRange(next, 1))
let nextTidy = nextChar.trimmingCharacters(in: NSCharacterSet.alphanumerics)
if nextTidy == "" || nextTidy == "_" || nextTidy == "\u{FFFD}" {
range.length += 1
}
}
if !prevValid && !nextValid {
break
}
if prev == 0 && !nextValid {
break
}
}
self.selectedRange = TextSelectedRange(range: NSMakeRange(max(range.location, 0), min(max(range.length, 0), string.length)), color: selectText, def: true)
}
}
public func ==(lhs:TextViewLayout, rhs:TextViewLayout) -> Bool {
return lhs.constrainedWidth == rhs.constrainedWidth && lhs.attributedString.isEqual(to: rhs.attributedString) && lhs.selectedRange == rhs.selectedRange && lhs.maximumNumberOfLines == rhs.maximumNumberOfLines && lhs.cutout == rhs.cutout && lhs.truncationType == rhs.truncationType && lhs.constrainedWidth == rhs.constrainedWidth
}
public enum CursorSelectAlignment {
case min(Int)
case max(Int)
}
public struct TextSelectedRange: Equatable {
public var range:NSRange = NSMakeRange(NSNotFound, 0) {
didSet {
var bp:Int = 0
bp += 1
}
}
public var color:NSColor = presentation.colors.selectText
public var def:Bool = true
public init(range: NSRange = NSMakeRange(NSNotFound, 0), color: NSColor = presentation.colors.selectText, def: Bool = true, cursorAlignment: CursorSelectAlignment = .min(0)) {
self.range = range
self.color = color
self.def = def
self.cursorAlignment = cursorAlignment
}
public var cursorAlignment: CursorSelectAlignment = .min(0)
public var hasSelectText:Bool {
return range.location != NSNotFound
}
}
public func ==(lhs:TextSelectedRange, rhs:TextSelectedRange) -> Bool {
return lhs.def == rhs.def && lhs.range.location == rhs.range.location && lhs.range.length == rhs.range.length && lhs.color.hexString == rhs.color.hexString
}
//private extension TextView : NSMenuDelegate {
//
//}
public class TextView: Control, NSViewToolTipOwner, ViewDisplayDelegate {
public func view(_ view: NSView, stringForToolTip tag: NSView.ToolTipTag, point: NSPoint, userData data: UnsafeMutableRawPointer?) -> String {
guard let layout = self.textLayout else { return "" }
if let link = layout.link(at: point), let resolved = layout.interactions.resolveLink(link.0)?.removingPercentEncoding {
return resolved.prefixWithDots(70)
}
return ""
}
private class InkContainer : View {
required init(frame frameRect: NSRect) {
super.init(frame: frameRect)
isEventLess = true
}
required public init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
private class EmbeddedContainer : View {
required init(frame frameRect: NSRect) {
super.init(frame: frameRect)
isEventLess = true
}
required public init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
private var inkViews: [InvisibleInkDustView] = []
private let inkContainer = InkContainer(frame: .zero)
private let embeddedContainer = InkContainer(frame: .zero)
private var clearExceptRevealed: Bool = false
private var inAnimation: Bool = false {
didSet {
needsDisplay = true
}
}
private var visualEffect: VisualEffect? = nil
private var textView: View? = nil
private var blockMask: CALayer?
public var blurBackground: NSColor? = nil {
didSet {
updateBackgroundBlur()
if blurBackground != nil {
self.backgroundColor = .clear
}
}
}
private let menuDisposable = MetaDisposable()
private(set) public var textLayout:TextViewLayout?
private var beginSelect:NSPoint = NSZeroPoint
private var endSelect:NSPoint = NSZeroPoint
public var canBeResponder:Bool = true
public var isSelectable:Bool = true {
didSet {
if oldValue != isSelectable {
self.setNeedsDisplayLayer()
}
}
}
public override init() {
super.init();
initialize()
// wantsLayer = false
// self.layer?.delegate = nil
}
public override var isFlipped: Bool {
return true
}
private func initialize() {
layer?.disableActions()
self.style = ControlStyle(backgroundColor: .clear)
addSubview(embeddedContainer)
addSubview(inkContainer)
}
public required init(frame frameRect: NSRect) {
super.init(frame:frameRect)
initialize()
}
private var _disableBackgroundDrawing: Bool = false
public var disableBackgroundDrawing: Bool {
set {
_disableBackgroundDrawing = newValue
}
get {
return _disableBackgroundDrawing || blurBackground != nil
}
}
public override func draw(_ layer: CALayer, in ctx: CGContext) {
//backgroundColor = .random
super.draw(layer, in: ctx)
if blurBackground != nil, layer != textView?.layer {
return
}
if let layout = textLayout {
ctx.setAllowsFontSubpixelPositioning(true)
ctx.setShouldSubpixelPositionFonts(true)
if clearExceptRevealed {
let path = CGMutablePath()
for spoiler in layout.spoilerRects(false) {
path.addRect(spoiler)
}
ctx.addPath(path)
ctx.clip()
}
if !System.supportsTransparentFontDrawing {
ctx.setAllowsAntialiasing(true)
ctx.setAllowsFontSmoothing(backingScaleFactor == 1.0)
ctx.setShouldSmoothFonts(backingScaleFactor == 1.0)
if backingScaleFactor == 1.0 && !disableBackgroundDrawing {
ctx.setFillColor(backgroundColor.cgColor)
for line in layout.lines {
ctx.fill(NSMakeRect(0, line.frame.minY - line.frame.height - 2, line.frame.width, line.frame.height + 6))
}
}
} else {
ctx.setAllowsAntialiasing(true)
ctx.setShouldAntialias(true)
ctx.setAllowsFontSmoothing(backingScaleFactor == 1.0)
ctx.setShouldSmoothFonts(backingScaleFactor == 1.0)
}
if let image = layout.blockImage.1, blurBackground == nil {
ctx.draw(image, in: NSMakeRect(layout.blockImage.0.x, layout.blockImage.0.y, image.backingSize.width, image.backingSize.height))
}
var ranges:[(TextSelectedRange, Bool)] = [(layout.selectedRange, true)]
ranges += layout.additionalSelections.map { ($0, false) }
for range in ranges {
if range.0.range.location != NSNotFound && (range.1 && isSelectable || !range.1) {
var lessRange = range.0.range
let lines:[TextViewLine] = layout.lines
let beginIndex:Int = 0
let endIndex:Int = layout.lines.count - 1
let isReversed = endIndex < beginIndex
var i:Int = beginIndex
while isReversed ? i >= endIndex : i <= endIndex {
let line = lines[i].line
var rect:NSRect = lines[i].frame
let lineRange = lines[i].range
var beginLineIndex:CFIndex = 0
var endLineIndex:CFIndex = 0
if (lineRange.location + lineRange.length >= lessRange.location) && lessRange.length > 0 {
beginLineIndex = lessRange.location
let max = lineRange.length + lineRange.location
let maxSelect = max - beginLineIndex
let selectLength = min(maxSelect,lessRange.length)
lessRange.length-=selectLength
lessRange.location+=selectLength
endLineIndex = min(beginLineIndex + selectLength, lineRange.max)
var ascent:CGFloat = 0
var descent:CGFloat = 0
var leading:CGFloat = 0
var width:CGFloat = CGFloat(CTLineGetTypographicBounds(line, &ascent, &descent, &leading));
let startOffset = CTLineGetOffsetForStringIndex(line, beginLineIndex, nil);
var endOffset = CTLineGetOffsetForStringIndex(line, endLineIndex, nil);
if beginLineIndex < endLineIndex {
var index = endLineIndex - 1
while endOffset == 0 && index > 0 {
endOffset = CTLineGetOffsetForStringIndex(line, index, nil);
index -= 1
}
}
width = endOffset - startOffset;
if beginLineIndex == -1 {
beginLineIndex = 0
} else if beginLineIndex >= layout.attributedString.length {
beginLineIndex = layout.attributedString.length - 1
}
let blockValue:CGFloat = layout.mayBlocked ? CGFloat((layout.attributedString.attribute(.preformattedPre, at: beginLineIndex, effectiveRange: nil) as? NSNumber)?.floatValue ?? 0) : 0
rect.size.width = width - blockValue / 2
rect.origin.x = startOffset + blockValue
rect.origin.y = rect.minY - rect.height + blockValue / 2
rect.size.height += ceil(descent - leading)
let color:NSColor = window?.isKeyWindow == true || !range.1 ? range.0.color : NSColor.lightGray
ctx.setFillColor(color.cgColor)
ctx.fill(rect)
}
i += isReversed ? -1 : 1
}
}
}
let startPosition = focus(layout.layoutSize).origin
ctx.textMatrix = CGAffineTransform(scaleX: 1.0, y: -1.0)
// ctx.textMatrix = textMatrix
// ctx.textPosition = CGPoint(x: textPosition.x, y: textPosition.y)
//
for stroke in layout.strokeRects {
ctx.setFillColor(stroke.1.cgColor)
ctx.fill(stroke.0)
}
for hexColor in layout.hexColorsRect {
ctx.setFillColor(hexColor.1.cgColor)
ctx.fill(hexColor.0)
}
for i in 0 ..< layout.lines.count {
let line = layout.lines[i]
var penOffset = CGFloat( CTLineGetPenOffsetForFlush(line.line, line.penFlush, Double(frame.width))) + line.frame.minX
if layout.penFlush == 0.5, line.penFlush != 0.5 {
penOffset = startPosition.x
} else if layout.penFlush == 0.0 {
penOffset = startPosition.x
}
var additionY: CGFloat = 0
if layout.isBigEmoji {
additionY -= 4
}
ctx.textPosition = CGPoint(x: penOffset + line.frame.minX, y: startPosition.y + line.frame.minY + additionY)
let glyphRuns = CTLineGetGlyphRuns(line.line) as NSArray
if glyphRuns.count != 0 {
for run in glyphRuns {
let run = run as! CTRun
let glyphCount = CTRunGetGlyphCount(run)
let range = CTRunGetStringRange(run)
let under = line.embeddedItems.contains(where: { value in
return value.range == NSMakeRange(range.location, range.length)
})
if !under {
CTRunDraw(run, ctx, CFRangeMake(0, glyphCount))
}
}
}
for strikethrough in line.strikethrough {
ctx.setFillColor(strikethrough.color.cgColor)
ctx.fill(NSMakeRect(strikethrough.frame.minX, line.frame.minY - line.frame.height / 2 + 2, strikethrough.frame.width, .borderSize))
}
// for embeddedItem in line.embeddedItems {
// ctx.clear(embeddedItem.frame.offsetBy(dx: ctx.textPosition.x, dy: ctx.textPosition.y).insetBy(dx: -1.5, dy: -1.5))
// }
// spoiler was here
}
for spoiler in layout.spoilerRects(!inAnimation) {
ctx.clear(spoiler)
}
}
}
public override func rightMouseDown(with event: NSEvent) {
if let layout = textLayout, userInteractionEnabled, layout.mayItems, mouseInside() {
let location = convert(event.locationInWindow, from: nil)
if (!layout.selectedRange.hasSelectText || !layout.inSelectedRange(location)) && (!layout.alwaysStaticItems || layout.link(at: location) != nil) {
layout.selectWord(at : location)
}
self.setNeedsDisplayLayer()
if (layout.selectedRange.hasSelectText && isSelectable) || !layout.alwaysStaticItems {
let link = layout.link(at: convert(event.locationInWindow, from: nil))
if let menuItems = layout.interactions.menuItems?(link?.1) {
let window = layout.interactions.topWindow?() ?? .single(nil)
menuDisposable.set(combineLatest(queue: .mainQueue(), menuItems, window).start(next:{ [weak self] items, topWindow in
if let strongSelf = self {
let menu = ContextMenu()
for item in items {
menu.addItem(item)
}
menu.topWindow = topWindow
AppMenu.show(menu: menu, event: event, for: strongSelf)
}
}))
} else {
let window = (layout.interactions.topWindow?() ?? .single(nil)) |> deliverOnMainQueue
menuDisposable.set(window.start(next: { [weak self] topWindow in
let link = layout.link(at: location)
let resolved: String? = link != nil ? layout.interactions.resolveLink(link!.0) : nil
let menu = ContextMenu()
let copy = ContextMenuItem(link?.1 != nil ? layout.interactions.localizeLinkCopy(link!.1) : localizedString("Text.Copy"), handler: { [weak self] in
guard let `self` = self else {return}
if let resolved = resolved {
let pb = NSPasteboard.general
pb.clearContents()
pb.declareTypes([.string], owner: self)
pb.setString(resolved, forType: .string)
} else {
self.copy(self)
}
}, itemImage: TextView.context_copy_animation)
menu.addItem(copy)
if resolved == nil, let window = self?.kitWindow {
if let text = self?.effectiveText, let translate = layout.interactions.translate?(text, window) {
menu.addItem(translate)
}
}
menu.topWindow = topWindow
if let strongSelf = self {
AppMenu.show(menu: menu, event: event, for: strongSelf)
}
}))
}
} else {
layout.selectedRange.range = NSMakeRange(NSNotFound, 0)
needsDisplay = true
super.rightMouseDown(with: event)
}
} else {
super.rightMouseDown(with: event)
}
}
public static var context_copy_animation: ((NSColor, ContextMenuItem)->AppMenuItemImageDrawable)?
public func menuDidClose(_ menu: NSMenu) {
}
/*
var view: NSTextView? = (self.window?.fieldEditor(true, forObject: self) as? NSTextView)
view?.isEditable = false
view?.isSelectable = true
view?.string = layout.attributedString.string
view?.selectedRange = NSRange(location: 0, length: view?.string?.length)
NSMenu.popUpContextMenu(view?.menu(for: event), with: event, for: view)
*/
public override func menu(for event: NSEvent) -> NSMenu? {
return nil
}
deinit {
menuDisposable.dispose()
NotificationCenter.default.removeObserver(self)
}
public func isEqual(to layout:TextViewLayout) -> Bool {
return self.textLayout == layout
}
//
private func updateInks(_ layout: TextViewLayout?, animated: Bool = false) {
if let layout = layout {
let spoilers = layout.spoilers
let rects = layout.spoilerRects()
while rects.count > self.inkViews.count {
let inkView = InvisibleInkDustView(textView: nil)
self.inkViews.append(inkView)
self.addSubview(inkView)
}
if rects.count < self.inkViews.count, animated {
let fake = TextView(frame: self.bounds)
fake.update(layout)
fake.userInteractionEnabled = false
fake.isSelectable = false
addSubview(fake, positioned: .below, relativeTo: self.subviews.first)
fake.layer?.animateAlpha(from: 0, to: 1, duration: 0.2, timingFunction: .easeInEaseOut, removeOnCompletion: false, completion: { [weak fake, weak self] _ in
fake?.removeFromSuperview()
self?.inAnimation = false
})
self.inAnimation = true
fake.clearExceptRevealed = true
}
while rects.count < self.inkViews.count {
performSubviewRemoval(self.inkViews.removeLast(), animated: animated)
}
for (i, inkView) in inkViews.enumerated() {
let rect = rects[i]
let color = spoilers[0].color
inkView.update(size: rect.size, color: color, textColor: color, rects: [rect.size.bounds], wordRects: [rect.size.bounds.insetBy(dx: 2, dy: 2)])
inkView.frame = rect
}
} else {
while !inkViews.isEmpty {
performSubviewRemoval(inkViews.removeLast(), animated: animated)
}
}
self.checkEmbeddedUnderSpoiler()
}
public func update(_ layout:TextViewLayout?, origin:NSPoint? = nil) -> Void {
self.textLayout = layout
self.updateInks(layout)
if let layout = layout {
self.set(selectedRange: layout.selectedRange.range, display: false)
let point:NSPoint
if let origin = origin {
point = origin
} else {
point = frame.origin
}
self.frame = NSMakeRect(point.x, point.y, layout.layoutSize.width + layout.insets.width, layout.layoutSize.height + layout.insets.height)
removeAllToolTips()
for rect in layout.toolTipRects {
addToolTip(rect, owner: self, userData: nil)
}
} else {
self.set(selectedRange: NSMakeRange(NSNotFound, 0), display: false)
self.frame = NSZeroRect
}
updateBackgroundBlur()
self.setNeedsDisplayLayer()
}
public func set(layout:TextViewLayout?) {
self.textLayout = layout
self.setNeedsDisplayLayer()
}
public override func setNeedsDisplayLayer() {
super.setNeedsDisplayLayer()
self.textView?.layer?.setNeedsDisplay()
}
func set(selectedRange range:NSRange, display:Bool = true) -> Void {
if let layout = textLayout {
layout.selectedRange = TextSelectedRange(range:range, color: layout.selectText, def:true)
}
beginSelect = NSMakePoint(-1, -1)
endSelect = NSMakePoint(-1, -1)
if display {
self.setNeedsDisplayLayer()
}
}
public override func mouseDown(with event: NSEvent) {
if event.modifierFlags.contains(.control) {
rightMouseDown(with: event)
return
}
if isSelectable && !event.modifierFlags.contains(.shift) {
self.window?.makeFirstResponder(nil)
}
if !userInteractionEnabled {
super.mouseDown(with: event)
} else if let layout = textLayout {
let point = self.convert(event.locationInWindow, from: nil)
let index = layout.findIndex(location: point)
if point.x > layout.lines[index].frame.maxX {
superview?.mouseDown(with: event)
}
}
_mouseDown(with: event)
}
public override func viewWillMove(toWindow newWindow: NSWindow?) {
if let newWindow = newWindow {
NotificationCenter.default.addObserver(self, selector: #selector(windowDidBecomeKey), name: NSWindow.didBecomeKeyNotification, object: newWindow)
NotificationCenter.default.addObserver(self, selector: #selector(windowDidResignKey), name: NSWindow.didResignKeyNotification, object: newWindow)
} else {
NotificationCenter.default.removeObserver(self, name: NSWindow.didBecomeKeyNotification, object: window)
NotificationCenter.default.removeObserver(self, name: NSWindow.didResignKeyNotification, object: window)
}
}
@objc open func windowDidBecomeKey() {
needsDisplay = true
}
@objc open func windowDidResignKey() {
needsDisplay = true
}
private var locationInWindow:NSPoint? = nil
func _mouseDown(with event: NSEvent) -> Void {
self.locationInWindow = event.locationInWindow
if !isSelectable || !userInteractionEnabled || event.modifierFlags.contains(.shift) {
super.mouseDown(with: event)
return
}
_ = self.becomeFirstResponder()
set(selectedRange: NSMakeRange(NSNotFound, 0), display: false)
self.beginSelect = self.convert(event.locationInWindow, from: nil)
self.setNeedsDisplayLayer()
}
public override func mouseDragged(with event: NSEvent) {
super.mouseDragged(with: event)
checkCursor(event)
_mouseDragged(with: event)
}
func _mouseDragged(with event: NSEvent) -> Void {
if !isSelectable || !userInteractionEnabled {
return
}
if let locationInWindow = self.locationInWindow {
let old = (ceil(locationInWindow.x), ceil(locationInWindow.y))
let new = (ceil(event.locationInWindow.x), round(event.locationInWindow.y))
if abs(old.0 - new.0) <= 1 && abs(old.1 - new.1) <= 1 {
return
}
}
endSelect = self.convert(event.locationInWindow, from: nil)
if let layout = textLayout {
layout.selectedRange.range = layout.selectedRange(startPoint: beginSelect, currentPoint: endSelect)
layout.selectedRange.cursorAlignment = beginSelect.x > endSelect.x ? .min(layout.selectedRange.range.max) : .max(layout.selectedRange.range.min)
}
self.setNeedsDisplayLayer()
}
public override func mouseEntered(with event: NSEvent) {
if userInteractionEnabled {
checkCursor(event)
} else {
super.mouseEntered(with: event)
}
}
public override func mouseExited(with event: NSEvent) {
if userInteractionEnabled {
checkCursor(event)
} else {
super.mouseExited(with: event)
}
}
public override func mouseMoved(with event: NSEvent) {
if userInteractionEnabled {
checkCursor(event)
} else {
super.mouseMoved(with: event)
}
}
public override func mouseUp(with event: NSEvent) {
self.locationInWindow = nil
if let layout = textLayout, userInteractionEnabled {
let point = self.convert(event.locationInWindow, from: nil)
if let _ = layout.spoiler(at: point) {
layout.revealSpoiler()
needsDisplay = true
self.updateInks(layout, animated: true)
return
}
if event.clickCount == 3, isSelectable {
layout.selectAll(at: point)
layout.selectedRange.cursorAlignment = .max(layout.selectedRange.range.min)
} else if isSelectable, event.clickCount == 2 || (event.type == .rightMouseUp && !layout.selectedRange.hasSelectText) {
layout.selectWord(at : point)
layout.selectedRange.cursorAlignment = .max(layout.selectedRange.range.min)
} else if !layout.selectedRange.hasSelectText || !isSelectable && (event.clickCount == 1 || !isSelectable) {
if let color = layout.color(at: point), let copyToClipboard = layout.interactions.copyToClipboard {
copyToClipboard(color.0.hexString.lowercased())
} else if let (link, _, _, _) = layout.link(at: point) {
if event.clickCount == 1 {
layout.interactions.processURL(link)
}
} else {
super.mouseUp(with: event)
}
} else if layout.selectedRange.hasSelectText && event.clickCount == 1 && event.modifierFlags.contains(.shift) {
var range = layout.selectedRange.range
let index = layout.findCharacterIndex(at: point)
if index < range.min {
range.length += (range.location - index)
range.location = index
} else if index > range.max {
range.length = (index - range.location)
}
layout.selectedRange.range = range
} else {
super.mouseUp(with: event)
}
setNeedsDisplay()
} else {
super.mouseUp(with: event)
}
self.beginSelect = NSMakePoint(-1, -1)
}
public override func cursorUpdate(with event: NSEvent) {
if userInteractionEnabled {
checkCursor(event)
} else {
super.cursorUpdate(with: event)
}
}
func checkCursor(_ event:NSEvent) -> Void {
let location = self.convert(event.locationInWindow, from: nil)
if self.isMousePoint(location , in: self.visibleRect) && mouseInside() && userInteractionEnabled {
if textLayout?.spoiler(at: location) != nil {
NSCursor.pointingHand.set()
} else if textLayout?.color(at: location) != nil {
NSCursor.pointingHand.set()
textLayout?.interactions.hoverOnLink(.exited)
} else if let layout = textLayout, let (value, _, _, _) = layout.link(at: location) {
NSCursor.pointingHand.set()
layout.interactions.hoverOnLink(.entered(value))
} else if isSelectable {
NSCursor.iBeam.set()
textLayout?.interactions.hoverOnLink(.exited)
} else {
NSCursor.arrow.set()
textLayout?.interactions.hoverOnLink(.exited)
}
} else {
NSCursor.arrow.set()
textLayout?.interactions.hoverOnLink(.exited)
}
}
private func updateBackgroundBlur() {
if let blurBackground = blurBackground {
if self.visualEffect == nil {
self.visualEffect = VisualEffect(frame: self.bounds)
addSubview(self.visualEffect!, positioned: .below, relativeTo: self.embeddedContainer)
self.textView = View(frame: self.bounds)
addSubview(self.textView!)
}
self.visualEffect?.bgColor = blurBackground
self.textView?.displayDelegate = self
if let textlayout = self.textLayout, let blockImage = textlayout.blockImage.1 {
if blockMask == nil {
blockMask = CALayer()
}
CATransaction.begin()
CATransaction.setDisableActions(true)
var fr = CATransform3DIdentity
fr = CATransform3DTranslate(fr, blockImage.backingSize.width / 2, 0, 0)
fr = CATransform3DScale(fr, 1, -1, 1)
fr = CATransform3DTranslate(fr, -(blockImage.backingSize.width / 2), 0, 0)
blockMask?.transform = fr
blockMask?.contentsScale = 2.0
blockMask?.contents = blockImage
blockMask?.frame = CGRect(origin: .zero, size: blockImage.backingSize)
self.layer?.mask = blockMask
CATransaction.commit()
} else {
self.blockMask = nil
self.layer?.mask = nil
}
} else {
self.textView?.removeFromSuperview()
self.textView = nil
self.visualEffect?.removeFromSuperview()
self.visualEffect = nil
self.blockMask?.removeFromSuperlayer()
self.blockMask = nil
self.layer?.mask = nil
}
needsLayout = true
}
public override var needsDisplay: Bool {
didSet {
textView?.needsDisplay = needsDisplay
}
}
public func addEmbeddedView(_ view: NSView) {
embeddedContainer.addSubview(view)
}
public func addEmbeddedLayer(_ layer: CALayer) {
embeddedContainer.layer?.addSublayer(layer)
}
public override func layout() {
super.layout()
self.visualEffect?.frame = bounds
self.textView?.frame = bounds
embeddedContainer.frame = bounds
inkContainer.frame = bounds
self.updateInks(self.textLayout)
}
public func resize(_ width: CGFloat, blockColor: NSColor? = nil) {
self.textLayout?.measure(width: width)
if let blockColor = blockColor {
self.textLayout?.generateAutoBlock(backgroundColor: blockColor)
}
self.update(self.textLayout)
}
public override func becomeFirstResponder() -> Bool {
if canBeResponder {
if let window = self.window {
return window.makeFirstResponder(self)
}
}
return false
}
public override func accessibilityLabel() -> String? {
return self.textLayout?.attributedString.string
}
// public override var isOpaque: Bool {
// return false
// }
public override func resignFirstResponder() -> Bool {
_resignFirstResponder()
return super.resignFirstResponder()
}
func _resignFirstResponder() -> Void {
self.set(selectedRange: NSMakeRange(NSNotFound, 0))
}
public override func responds(to aSelector: Selector!) -> Bool {
if NSStringFromSelector(aSelector) == "copy:" {
return self.textLayout?.selectedRange.range.location != NSNotFound
}
return super.responds(to: aSelector)
}
private var effectiveText: String? {
if let layout = textLayout {
if layout.selectedRange.range.location != NSNotFound {
return layout.attributedString.string.nsstring.substring(with: layout.selectedRange.range)
} else {
return layout.attributedString.string
}
} else {
return nil
}
}
@objc public func copy(_ sender:Any) -> Void {
if let layout = textLayout {
if let copy = layout.interactions.copy {
if !copy() && layout.selectedRange.range.location != NSNotFound {
if !layout.interactions.copyAttributedString(layout.attributedString.attributedSubstring(from: layout.selectedRange.range)) {
let pb = NSPasteboard.general
pb.clearContents()
pb.declareTypes([.string], owner: self)
pb.setString(layout.attributedString.string.nsstring.substring(with: layout.selectedRange.range), forType: .string)
}
}
} else if layout.selectedRange.range.location != NSNotFound {
if !layout.interactions.copyAttributedString(layout.attributedString.attributedSubstring(from: layout.selectedRange.range)) {
let pb = NSPasteboard.general
pb.clearContents()
pb.declareTypes([.string], owner: self)
pb.setString(layout.attributedString.string.nsstring.substring(with: layout.selectedRange.range), forType: .string)
}
}
}
}
public func checkEmbeddedUnderSpoiler() {
if let layout = self.textLayout {
let rects = layout.spoilerRects()
for subview in embeddedContainer.subviews {
var isHidden = false
loop: for rect in rects {
if NSIntersectsRect(NSMakeRect(subview.frame.midX, subview.frame.midY, 1, 1), rect) {
isHidden = true
break loop
}
}
subview.isHidden = isHidden
// if subview
}
let sublayers = embeddedContainer.layer?.sublayers ?? []
for subview in sublayers {
var isHidden = false
loop: for rect in rects {
if NSIntersectsRect(NSMakeRect(subview.frame.midX, subview.frame.midY, 1, 1), rect) {
isHidden = true
break loop
}
}
subview.opacity = isHidden ? 0 : 1
}
}
}
@objc func paste(_ sender:Any) {
}
public override func removeFromSuperview() {
super.removeFromSuperview()
}
public func updateWithNewWidth(_ width: CGFloat) {
let layout = self.textLayout
layout?.measure(width: width)
self.update(layout)
}
required public init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
/*
for spoiler in layout.spoilers.filter({ !$0.isRevealed }) {
if let spoilerRange = spoiler.range.intersection(line.range) {
let range = spoilerRange.intersection(layout.selectedRange.range)
var ranges:[(NSRange, NSColor)] = []
if let range = range {
ranges.append((NSMakeRange(spoiler.range.lowerBound, range.lowerBound - spoiler.range.lowerBound), spoiler.color))
ranges.append((NSMakeRange(spoiler.range.upperBound, range.upperBound - spoiler.range.upperBound), spoiler.color))
} else {
ranges.append((spoilerRange, spoiler.color))
}
for range in ranges {
let startOffset = CTLineGetOffsetForStringIndex(line.line, range.0.lowerBound, nil);
let endOffset = CTLineGetOffsetForStringIndex(line.line, range.0.upperBound, nil);
var ascent:CGFloat = 0
var descent:CGFloat = 0
var leading:CGFloat = 0
_ = CGFloat(CTLineGetTypographicBounds(line.line, &ascent, &descent, &leading));
var rect:NSRect = line.frame
rect.size.width = endOffset - startOffset
rect.origin.x = startOffset
rect.origin.y = rect.minY - rect.height
rect.size.height += ceil(descent - leading)
ctx.setFillColor(range.1.cgColor)
ctx.fill(rect)
}
}
}
*/
|
gpl-2.0
|
c6e334de6b3df5a8932eb778c5511179
| 41.325652 | 732 | 0.546754 | 5.12741 | false | false | false | false |
GitTennis/SuccessFramework
|
Templates/_BusinessAppSwift_/_BusinessAppSwift_/Core/SFObserverList.swift
|
2
|
7813
|
//
// SFObserverList.swift
// _BusinessAppSwift_
//
// Created by Gytenis Mikulenas on 18/10/2016.
// Copyright © 2016 Gytenis Mikulėnas
// https://github.com/GitTennis/SuccessFramework
//
// 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. All rights reserved.
//
import UIKit
class SFObserverList: ObserverListProtocol {
// MARK: ObserverListProtocol
required init(observedSubject: AnyObject) {
_observedSubject = observedSubject
}
// Observer handling
func observers() -> Array <AnyObject>? {
//let weakObserverList: Array <WeakObserver> = Array(_observers?.values)
var result: Array<AnyObject>? = nil
for weakObserver in (_observers?.values)! {
if (result == nil) {
result = Array()
}
result?.append(weakObserver)
}
return result
}
func add(observer: AnyObject, notificationName:String, callback: @escaping Callback, context: Any?) {
var contains: Bool = false
let key = self.key(observer: observer, notificationName: notificationName)
if (_observers == nil) {
// Create instance of non-retaining array for observers (in order to prevent retain cycles):
//_observers = CFBridgingRelease(CFArrayCreateMutable(NULL, 0, NULL)); // Fixing leak in ARC
_observers = Dictionary()
contains = false;
} else {
if (_observers?[key]) != nil {
contains = true
}
}
// Add if not added yet:
if (!contains) {
// Store observer callback
let wrappedObserver: WeakObserver = self.wrappedWeakObserver(observer: observer, notificationName: notificationName, callback: callback, context: context)
_observers?[key] = wrappedObserver
}
}
func remove(observer: AnyObject, notificationName: String) {
let key = self.key(observer: observer, notificationName: notificationName)
_ = _observers?.removeValue(forKey: key)
}
func remove(observer: AnyObject) {
let observerClassName: String = className(object: observer)
for key in (_observers?.keys)! {
if key.contains(observerClassName) {
_ = _observers?.removeValue(forKey: key)
}
}
}
func contains(observer: AnyObject, notificationName: String)->Bool {
let key = self.key(observer: observer, notificationName: notificationName)
var result: Bool = false
if (_observers?[key]) != nil {
result = true
}
return result
}
// Broadcasting to observers
func notifyObservers(notificationName: String) {
if (_observers == nil) {
return;
}
if (self.isNotEmpty()) {
DDLogDebug(log: "GMObserverList: Will notify observers: " + notificationName)
}
var weakObserver: WeakObserver
for key in (_observers?.keys)! {
if key.contains(notificationName) {
weakObserver = (_observers?[key])!
if let callback = weakObserver.callback {
callback(true, nil, nil, nil)
}
}
}
}
func notifyObservers(notificationName: String, context: Any?) {
if (_observers == nil) {
return;
}
if (self.isNotEmpty()) {
DDLogDebug(log: "GMObserverList: Will notify observers: " + notificationName)
}
var weakObserver: WeakObserver
for key in (_observers?.keys)! {
if key.contains(notificationName) {
weakObserver = (_observers?[key])!
if let callback = weakObserver.callback {
callback(true, nil, context, nil)
}
}
}
}
func notifyObservers(notificationName: String, context: Any?, error: ErrorEntity?) {
if (_observers == nil) {
return;
}
if (self.isNotEmpty()) {
DDLogDebug(log: "GMObserverList: Will notify observers: " + notificationName)
}
var weakObserver: WeakObserver
for key in (_observers?.keys)! {
if key.contains(notificationName) {
weakObserver = (_observers?[key])!
if let callback = weakObserver.callback {
callback(true, nil, context, error)
}
}
}
}
// MARK:
// MARK: Internal
// MARK:
internal weak var _observedSubject: AnyObject!
//var _observers: NSHashTable <AnyObject>?
fileprivate var _observers: Dictionary <String, WeakObserver>?
//var _observerCallbacks: Dictionary <String, Callback>
internal func isNotEmpty() -> Bool {
var result: Bool = false;
if let observers = _observers {
let keys: Array <String> = allKeys(dict: observers)
if (keys.count > 0) {
result = true
}
}
return result
}
internal func key(observer:AnyObject, notificationName: String)->String {
let observerClassName: String = className(object: observer)
let key = observerClassName + notificationName
return key;
}
fileprivate func wrappedWeakObserver(observer: AnyObject, notificationName:String, callback: @escaping Callback, context: Any?) -> WeakObserver {
let wrappedObserver = WeakObserver.init(observer: observer, context: context, callback: callback)
return wrappedObserver
}
}
internal class WeakObserver {
weak var observer : AnyObject?
var context : Any?
var callback: Callback?
init (observer: AnyObject?, context: Any?, callback: Callback?) {
self.observer = observer
self.context = context
self.callback = callback
}
}
|
mit
|
337cd3fa1fd2777ead27f2fba2803263
| 28.587121 | 166 | 0.541672 | 5.520141 | false | false | false | false |
niunaruto/DeDaoAppSwift
|
testSwift/Pods/RxSwift/RxSwift/Observables/CompactMap.swift
|
19
|
2820
|
//
// CompactMap.swift
// RxSwift
//
// Created by Michael Long on 04/09/2019.
// Copyright © 2015 Krunoslav Zaher. All rights reserved.
//
extension ObservableType {
/**
Projects each element of an observable sequence into an optional form and filters all optional results.
Equivalent to:
func compactMap<Result>(_ transform: @escaping (Self.E) throws -> Result?) -> RxSwift.Observable<Result> {
return self.map { try? transform($0) }.filter { $0 != nil }.map { $0! }
}
- parameter transform: A transform function to apply to each source element and which returns an element or nil.
- returns: An observable sequence whose elements are the result of filtering the transform function for each element of the source.
*/
public func compactMap<Result>(_ transform: @escaping (Element) throws -> Result?)
-> Observable<Result> {
return CompactMap(source: self.asObservable(), transform: transform)
}
}
final private class CompactMapSink<SourceType, Observer: ObserverType>: Sink<Observer>, ObserverType {
typealias Transform = (SourceType) throws -> ResultType?
typealias ResultType = Observer.Element
typealias Element = SourceType
private let _transform: Transform
init(transform: @escaping Transform, observer: Observer, cancel: Cancelable) {
self._transform = transform
super.init(observer: observer, cancel: cancel)
}
func on(_ event: Event<SourceType>) {
switch event {
case .next(let element):
do {
if let mappedElement = try self._transform(element) {
self.forwardOn(.next(mappedElement))
}
}
catch let e {
self.forwardOn(.error(e))
self.dispose()
}
case .error(let error):
self.forwardOn(.error(error))
self.dispose()
case .completed:
self.forwardOn(.completed)
self.dispose()
}
}
}
final private class CompactMap<SourceType, ResultType>: Producer<ResultType> {
typealias Transform = (SourceType) throws -> ResultType?
private let _source: Observable<SourceType>
private let _transform: Transform
init(source: Observable<SourceType>, transform: @escaping Transform) {
self._source = source
self._transform = transform
}
override func run<Observer: ObserverType>(_ observer: Observer, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where Observer.Element == ResultType {
let sink = CompactMapSink(transform: self._transform, observer: observer, cancel: cancel)
let subscription = self._source.subscribe(sink)
return (sink: sink, subscription: subscription)
}
}
|
mit
|
2bb7b3b76828731febc906045574cc59
| 33.378049 | 174 | 0.644555 | 4.794218 | false | false | false | false |
netguru/inbbbox-ios
|
Inbbbox/Source Files/Views/Controllers View/ShotBucketsView.swift
|
1
|
3334
|
//
// ShotBucketsView.swift
// Inbbbox
//
// Created by Peter Bruz on 24/02/16.
// Copyright © 2016 Netguru Sp. z o.o. All rights reserved.
//
import UIKit
import PureLayout
class ShotBucketsView: UIView {
let collectionView: UICollectionView
weak var viewController: UIViewController?
fileprivate let offsetToTopLayoutGuide = CGFloat(10)
fileprivate let collectionViewCornerWrapperView = UIView.newAutoLayout()
fileprivate let blurView = UIVisualEffectView(effect: UIBlurEffect(style: ColorModeProvider.current().visualEffectBlurType))
fileprivate var didSetConstraints = false
override init(frame: CGRect) {
collectionView = UICollectionView(frame: CGRect.zero,
collectionViewLayout: ShotDetailsCollectionCollapsableHeader())
collectionView.backgroundColor = UIColor.clear
collectionView.layer.shadowColor = UIColor.gray.cgColor
collectionView.layer.shadowOffset = CGSize(width: 0, height: 0.1)
collectionView.layer.shadowOpacity = 0.3
collectionView.clipsToBounds = true
collectionView.contentInset = UIEdgeInsets(top: 0, left: 0, bottom: 20, right: 0)
super.init(frame: frame)
let currentColorMode = ColorModeProvider.current()
if DeviceInfo.shouldDowngrade() {
backgroundColor = currentColorMode.tableViewBackground
} else {
backgroundColor = currentColorMode.tableViewBlurColor
blurView.configureForAutoLayout()
addSubview(blurView)
}
collectionViewCornerWrapperView.backgroundColor = .clear
collectionViewCornerWrapperView.clipsToBounds = true
collectionViewCornerWrapperView.addSubview(collectionView)
addSubview(collectionViewCornerWrapperView)
}
@available(*, unavailable, message: "Use init(frame:) instead")
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func updateConstraints() {
if !didSetConstraints {
didSetConstraints = true
if !DeviceInfo.shouldDowngrade() {
blurView.autoPinEdgesToSuperviewEdges()
}
if let viewController = viewController {
collectionViewCornerWrapperView.autoPin(toTopLayoutGuideOf: viewController,
withInset: offsetToTopLayoutGuide)
} else {
collectionViewCornerWrapperView.autoPinEdge(toSuperviewEdge: .top, withInset: offsetToTopLayoutGuide)
}
collectionViewCornerWrapperView.autoPinEdge(toSuperviewEdge: .left, withInset: 10)
collectionViewCornerWrapperView.autoPinEdge(toSuperviewEdge: .right, withInset: 10)
collectionViewCornerWrapperView.autoPinEdge(toSuperviewEdge: .bottom)
collectionView.autoPinEdgesToSuperviewEdges()
}
super.updateConstraints()
}
override func draw(_ rect: CGRect) {
super.draw(rect)
let path = UIBezierPath(roundedRect: collectionViewCornerWrapperView.bounds,
byRoundingCorners: [.topLeft, .topRight], cornerRadii: CGSize(width: 15, height: 15))
let mask = CAShapeLayer()
mask.path = path.cgPath
collectionViewCornerWrapperView.layer.mask = mask
}
}
|
gpl-3.0
|
6fe48ed32984b2da29aa9c21a1c879ce
| 35.626374 | 128 | 0.689769 | 5.564274 | false | false | false | false |
ualch9/onebusaway-iphone
|
Carthage/Checkouts/IGListKit/Examples/Examples-iOS/IGListKitExamples-UITests/UITestCase.swift
|
2
|
3114
|
/**
Copyright (c) Facebook, Inc. and its affiliates.
The examples provided by Facebook are for non-commercial testing and evaluation
purposes only. Facebook reserves all rights not expressly granted.
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
FACEBOOK 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 XCTest
class UITestCase: XCTestCase {
override func setUp() {
super.setUp()
continueAfterFailure = false
XCUIApplication().launch()
}
override func tearDown() {
super.tearDown()
}
// Adapted from http://masilotti.com/xctest-helpers/
internal func waitToAppear(element: XCUIElement,
timeout: TimeInterval = 2,
file: String = #file,
line: UInt = #line) {
waitToAppear(elements: [element], timeout: timeout, file: file, line: line)
}
internal func waitToAppear(elements: [XCUIElement],
timeout: TimeInterval = 2,
file: String = #file,
line: UInt = #line) {
waitTo(appear: true, elements: elements, timeout: timeout, file: file, line: line)
}
internal func waitToDisappear(element: XCUIElement,
timeout: TimeInterval = 2,
file: String = #file,
line: UInt = #line) {
waitToDisappear(elements: [element], timeout: timeout, file: file, line: line)
}
internal func waitToDisappear(elements: [XCUIElement],
timeout: TimeInterval = 2,
file: String = #file,
line: UInt = #line) {
waitTo(appear: false, elements: elements, timeout: timeout, file: file, line: line)
}
internal func waitTo(appear: Bool,
elements: [XCUIElement],
timeout: TimeInterval = 2,
file: String = #file,
line: UInt = #line) {
let existsPredicate = NSPredicate(format: "exists == \(appear)")
elements.forEach { element in
expectation(for: existsPredicate, evaluatedWith: element, handler: nil)
}
waitForExpectations(timeout: timeout) { error in
if error != nil {
let message = "Failed to \(appear ? "" : "not ")find element(s) after \(timeout) seconds."
self.recordFailure(withDescription: message,
inFile: file,
atLine: Int(line),
expected: true)
}
}
}
}
|
apache-2.0
|
661e31cae0f2b6b95446430d916e514b
| 38.417722 | 106 | 0.546885 | 5.242424 | false | true | false | false |
sag333ar/GoogleBooksAPIResearch
|
GoogleBooksApp/GoogleBooksUI/UserInterfaceModules/BooksList/View/TableView/Cell/BookListItemView.swift
|
1
|
1977
|
//
// BookListItemView.swift
// GoogleBooksApp
//
// Created by Kothari, Sagar on 9/9/17.
// Copyright © 2017 Sagar Kothari. All rights reserved.
//
import UIKit
import SDWebImage
class BookListItemView: UITableViewCell {
@IBOutlet weak var bookThumbImageView: UIImageView!
@IBOutlet weak var bookTitleLabel: UILabel!
@IBOutlet weak var bookAuthorLabel: UILabel!
@IBOutlet weak var bookSubtitleLabel: UILabel!
override func awakeFromNib() {
super.awakeFromNib()
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
}
func setupCell(_ book: Book) {
if let data = book.volumeInfo?.title {
self.bookTitleLabel.text = data
} else {
self.bookTitleLabel.text = "Title not available"
}
if let data = book.volumeInfo?.subtitle {
self.bookSubtitleLabel.text = data
} else {
self.bookSubtitleLabel.text = "Subtitle not available"
}
if let data = book.volumeInfo?.authors {
self.bookAuthorLabel.text = data.joined(separator: ", ")
} else {
self.bookAuthorLabel.text = "Author not available"
}
self.bookThumbImageView.image = nil
self.bookThumbImageView.sd_setShowActivityIndicatorView(true)
self.bookThumbImageView.sd_setIndicatorStyle(.gray)
if let data = book.volumeInfo?.imageLinks?.smallThumbnail, let url = URL(string: data) {
self.bookThumbImageView.sd_setImage(with: url,
completed: nil)
}
self.applyShadowToBookThumb()
}
func applyShadowToBookThumb() {
self.bookThumbImageView.layer.borderColor = UIColor.black.cgColor
self.bookThumbImageView.layer.borderWidth = 1
self.bookThumbImageView.layer.shadowOffset = CGSize(width: 3, height: 3)
self.bookThumbImageView.layer.shadowRadius = 2
self.bookThumbImageView.layer.shadowOpacity = 10
self.bookThumbImageView.layer.shadowColor = UIColor.black.cgColor
}
}
|
apache-2.0
|
458ee5b024514a33ba4020d97d9669e3
| 28.939394 | 92 | 0.702429 | 4.133891 | false | false | false | false |
xu6148152/binea_project_for_ios
|
ListerforAppleWatchiOSandOSX/Swift/ListerKitOSX/CheckBox.swift
|
1
|
1544
|
/*
Copyright (C) 2015 Apple Inc. All Rights Reserved.
See LICENSE.txt for this sample’s licensing information
Abstract:
A layer-backed custom check box that is IBDesignable and IBInspectable.
*/
import Cocoa
@IBDesignable public class CheckBox: NSButton {
// MARK: Properties
@IBInspectable public var tintColor: NSColor {
get {
return NSColor(CGColor: checkBoxLayer.tintColor)
}
set {
checkBoxLayer.tintColor = newValue.CGColor
}
}
@IBInspectable public var isChecked: Bool {
get {
return checkBoxLayer.isChecked
}
set {
checkBoxLayer.isChecked = newValue
}
}
private var checkBoxLayer: CheckBoxLayer {
return layer as CheckBoxLayer
}
override public var intrinsicContentSize: NSSize {
return NSSize(width: 40, height: 40)
}
// MARK: View Life Cycle
override public func awakeFromNib() {
super.awakeFromNib()
wantsLayer = true
layer = CheckBoxLayer()
layer!.setNeedsDisplay()
}
// MARK: Events
override public func mouseDown(event: NSEvent) {
isChecked = !isChecked
cell()!.performClick(self)
}
override public func viewDidChangeBackingProperties() {
super.viewDidChangeBackingProperties()
if let window = window {
layer?.contentsScale = window.backingScaleFactor
}
}
}
|
mit
|
39d92091dfb40232be976676e34e1609
| 22.378788 | 75 | 0.594682 | 5.607273 | false | false | false | false |
1457792186/JWSwift
|
SwiftLearn/SwiftDemo/Pods/ObjectMapper/Sources/IntegerOperators.swift
|
18
|
3565
|
//
// IntegerOperators.swift
// ObjectMapper
//
// Created by Suyeol Jeon on 17/02/2017.
// Copyright © 2017 hearst. All rights reserved.
//
import Foundation
// MARK: - Signed Integer
/// SignedInteger mapping
public func <- <T: SignedInteger>(left: inout T, right: Map) {
switch right.mappingType {
case .fromJSON where right.isKeyPresent:
let value: T = toSignedInteger(right.currentValue) ?? 0
FromJSON.basicType(&left, object: value)
case .toJSON:
left >>> right
default: ()
}
}
/// Optional SignedInteger mapping
public func <- <T: SignedInteger>(left: inout T?, right: Map) {
switch right.mappingType {
case .fromJSON where right.isKeyPresent:
let value: T? = toSignedInteger(right.currentValue)
FromJSON.basicType(&left, object: value)
case .toJSON:
left >>> right
default: ()
}
}
/// ImplicitlyUnwrappedOptional SignedInteger mapping
public func <- <T: SignedInteger>(left: inout T!, right: Map) {
switch right.mappingType {
case .fromJSON where right.isKeyPresent:
let value: T! = toSignedInteger(right.currentValue)
FromJSON.basicType(&left, object: value)
case .toJSON:
left >>> right
default: ()
}
}
// MARK: - Unsigned Integer
/// UnsignedInteger mapping
public func <- <T: UnsignedInteger>(left: inout T, right: Map) {
switch right.mappingType {
case .fromJSON where right.isKeyPresent:
let value: T = toUnsignedInteger(right.currentValue) ?? 0
FromJSON.basicType(&left, object: value)
case .toJSON:
left >>> right
default: ()
}
}
/// Optional UnsignedInteger mapping
public func <- <T: UnsignedInteger>(left: inout T?, right: Map) {
switch right.mappingType {
case .fromJSON where right.isKeyPresent:
let value: T? = toUnsignedInteger(right.currentValue)
FromJSON.basicType(&left, object: value)
case .toJSON:
left >>> right
default: ()
}
}
/// ImplicitlyUnwrappedOptional UnsignedInteger mapping
public func <- <T: UnsignedInteger>(left: inout T!, right: Map) {
switch right.mappingType {
case .fromJSON where right.isKeyPresent:
let value: T! = toUnsignedInteger(right.currentValue)
FromJSON.basicType(&left, object: value)
case .toJSON:
left >>> right
default: ()
}
}
// MARK: - Casting Utils
/// Convert any value to `SignedInteger`.
private func toSignedInteger<T: SignedInteger>(_ value: Any?) -> T? {
guard
let value = value,
case let number as NSNumber = value
else {
return nil
}
if T.self == Int.self, let x = Int(exactly: number.int64Value) {
return T.init(x)
}
if T.self == Int8.self, let x = Int8(exactly: number.int64Value) {
return T.init(x)
}
if T.self == Int16.self, let x = Int16(exactly: number.int64Value) {
return T.init(x)
}
if T.self == Int32.self, let x = Int32(exactly: number.int64Value) {
return T.init(x)
}
if T.self == Int64.self, let x = Int64(exactly: number.int64Value) {
return T.init(x)
}
return nil
}
/// Convert any value to `UnsignedInteger`.
private func toUnsignedInteger<T: UnsignedInteger>(_ value: Any?) -> T? {
guard
let value = value,
case let number as NSNumber = value
else {
return nil
}
if T.self == UInt.self, let x = UInt(exactly: number.uint64Value) {
return T.init(x)
}
if T.self == UInt8.self, let x = UInt8(exactly: number.uint64Value) {
return T.init(x)
}
if T.self == UInt16.self, let x = UInt16(exactly: number.uint64Value) {
return T.init(x)
}
if T.self == UInt32.self, let x = UInt32(exactly: number.uint64Value) {
return T.init(x)
}
if T.self == UInt64.self, let x = UInt64(exactly: number.uint64Value) {
return T.init(x)
}
return nil
}
|
apache-2.0
|
64678bf17eac91f09a67e825fbb7209c
| 23.57931 | 73 | 0.690516 | 3.162378 | false | false | false | false |
jmgc/swift
|
test/Concurrency/actor_call_implicitly_async.swift
|
1
|
7601
|
// RUN: %target-typecheck-verify-swift -enable-experimental-concurrency
// REQUIRES: concurrency
actor class BankAccount {
private var curBalance : Int
private var accountHolder : String = "unknown"
// expected-note@+1 2 {{mutable state is only available within the actor instance}}
var owner : String {
get { accountHolder }
set { accountHolder = newValue }
}
init(initialDeposit : Int) {
curBalance = initialDeposit
}
// NOTE: this func is accessed through both async and sync calls.
// expected-note@+1 {{calls to instance method 'balance()' from outside of its actor context are implicitly asynchronous}}
func balance() -> Int { return curBalance }
// expected-note@+1 {{calls to instance method 'deposit' from outside of its actor context are implicitly asynchronous}}
func deposit(_ amount : Int) -> Int {
guard amount >= 0 else { return 0 }
curBalance = curBalance + amount
return curBalance
}
func canWithdraw(_ amount : Int) -> Bool {
// call 'balance' from sync through self
return self.balance() >= amount
}
func testSelfBalance() async {
_ = await balance() // expected-warning {{no calls to 'async' functions occur within 'await' expression}}
}
// returns the amount actually withdrawn
func withdraw(_ amount : Int) -> Int {
guard canWithdraw(amount) else { return 0 }
curBalance = curBalance - amount
return amount
}
// returns the balance of this account following the transfer
func transferAll(from : BankAccount) async -> Int {
// call sync methods on another actor
let amountTaken = await from.withdraw(from.balance())
return deposit(amountTaken)
}
func greaterThan(other : BankAccount) async -> Bool {
return await balance() > other.balance()
}
func testTransactions() {
_ = deposit(withdraw(deposit(withdraw(balance()))))
}
} // end actor class
func someAsyncFunc() async {
let deposit1 = 120, deposit2 = 45
let a = BankAccount(initialDeposit: 0)
let b = BankAccount(initialDeposit: deposit2)
let _ = await a.deposit(deposit1)
let afterXfer = await a.transferAll(from: b)
let reportedBal = await a.balance()
// check on account A
guard afterXfer == (deposit1 + deposit2) && afterXfer == reportedBal else {
print("BUG 1!")
return
}
// check on account B
guard await b.balance() == 0 else {
print("BUG 2!")
return
}
_ = await a.deposit(b.withdraw(a.deposit(b.withdraw(b.balance()))))
a.testSelfBalance() // expected-error {{call is 'async' but is not marked with 'await'}}
print("ok!")
}
//////////////////
// check for appropriate error messages
//////////////////
extension BankAccount {
func totalBalance(including other: BankAccount) async -> Int {
return balance()
+ other.balance() // expected-error{{call is 'async' but is not marked with 'await'}}
}
func breakAccounts(other: BankAccount) async {
_ = other.deposit( // expected-error{{call is 'async' but is not marked with 'await'}}
other.withdraw( // expected-error{{call is 'async' but is not marked with 'await'}}
self.deposit(
other.withdraw( // expected-error{{call is 'async' but is not marked with 'await'}}
other.balance())))) // expected-error{{call is 'async' but is not marked with 'await'}}
}
}
func anotherAsyncFunc() async {
let a = BankAccount(initialDeposit: 34)
let b = BankAccount(initialDeposit: 35)
_ = a.deposit(1) // expected-error{{call is 'async' but is not marked with 'await'}}
_ = b.balance() // expected-error{{call is 'async' but is not marked with 'await'}}
_ = b.balance // expected-error {{actor-isolated instance method 'balance()' can only be referenced inside the actor}}
a.owner = "cat" // expected-error{{actor-isolated property 'owner' can only be referenced inside the actor}}
_ = b.owner // expected-error{{actor-isolated property 'owner' can only be referenced inside the actor}}
}
// expected-note@+2 {{add 'async' to function 'regularFunc()' to make it asynchronous}} {{none}}
// expected-note@+1 {{add '@asyncHandler' to function 'regularFunc()' to create an implicit asynchronous context}} {{1-1=@asyncHandler }}
func regularFunc() {
let a = BankAccount(initialDeposit: 34)
_ = a.deposit //expected-error{{actor-isolated instance method 'deposit' can only be referenced inside the actor}}
_ = a.deposit(1) // expected-error{{'async' in a function that does not support concurrency}}
}
actor class TestActor {}
@globalActor
struct BananaActor {
static var shared: TestActor { TestActor() }
}
@globalActor
struct OrangeActor {
static var shared: TestActor { TestActor() }
}
func blender(_ peeler : () -> Void) {
peeler()
}
@BananaActor func wisk(_ something : Any) { } // expected-note 4 {{calls to global function 'wisk' from outside of its actor context are implicitly asynchronous}}
@BananaActor func peelBanana() { } // expected-note 2 {{calls to global function 'peelBanana()' from outside of its actor context are implicitly asynchronous}}
@OrangeActor func makeSmoothie() async {
await wisk({})
await wisk(1)
await (peelBanana)()
await (((((peelBanana)))))()
await (((wisk)))((wisk)((wisk)(1)))
blender((peelBanana)) // expected-error {{global function 'peelBanana()' isolated to global actor 'BananaActor' can not be referenced from different global actor 'OrangeActor'}}
await wisk(peelBanana) // expected-error {{global function 'peelBanana()' isolated to global actor 'BananaActor' can not be referenced from different global actor 'OrangeActor'}}
await wisk(wisk) // expected-error {{global function 'wisk' isolated to global actor 'BananaActor' can not be referenced from different global actor 'OrangeActor'}}
await (((wisk)))(((wisk))) // expected-error {{global function 'wisk' isolated to global actor 'BananaActor' can not be referenced from different global actor 'OrangeActor'}}
// expected-warning@+2 {{no calls to 'async' functions occur within 'await' expression}}
// expected-error@+1 {{global function 'wisk' isolated to global actor 'BananaActor' can not be referenced from different global actor 'OrangeActor'}}
await {wisk}()(1)
// expected-warning@+2 {{no calls to 'async' functions occur within 'await' expression}}
// expected-error@+1 {{global function 'wisk' isolated to global actor 'BananaActor' can not be referenced from different global actor 'OrangeActor'}}
await (true ? wisk : {n in return})(1)
}
// want to make sure there is no note about implicitly async on this func.
@BananaActor func rice() async {}
@OrangeActor func quinoa() async {
rice() // expected-error {{call is 'async' but is not marked with 'await'}}
}
///////////
// check various curried applications to ensure we mark the right expression.
actor class Calculator {
func addCurried(_ x : Int) -> ((Int) -> Int) {
return { (_ y : Int) in x + y }
}
func add(_ x : Int, _ y : Int) -> Int {
return x + y
}
}
@BananaActor func bananaAdd(_ x : Int) -> ((Int) -> Int) {
return { (_ y : Int) in x + y }
}
@OrangeActor func doSomething() async {
let _ = (await bananaAdd(1))(2)
let _ = await (await bananaAdd(1))(2) // expected-warning{{no calls to 'async' functions occur within 'await' expression}}
let calc = Calculator()
let _ = (await calc.addCurried(1))(2)
let _ = await (await calc.addCurried(1))(2) // expected-warning{{no calls to 'async' functions occur within 'await' expression}}
let plusOne = await calc.addCurried(await calc.add(0, 1))
let _ = plusOne(2)
}
|
apache-2.0
|
869c450e2ad8e098656c59e473a3e34c
| 34.032258 | 180 | 0.678332 | 4.071237 | false | false | false | false |
jmgc/swift
|
test/IDE/complete_constrained.swift
|
1
|
8648
|
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=MYSTRUCT_INT_DOT | %FileCheck %s -check-prefix=MYSTRUCT_INT_DOT
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=META_MYSTRUCT_INT_DOT | %FileCheck %s -check-prefix=META_MYSTRUCT_INT_DOT
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=CONDITIONAL_OVERLOAD_ARG | %FileCheck %s -check-prefix=CONDITIONAL_OVERLOAD_ARG
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=CONDITIONAL_OVERLOAD_INIT_ARG | %FileCheck %s -check-prefix=CONDITIONAL_OVERLOAD_ARG
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=CONDITIONAL_INAPPLICABLE_ARG | %FileCheck %s -check-prefix=CONDITIONAL_INAPPLICABLE_ARG
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=CONDITIONAL_DEPENDENT_TYPEALIAS | %FileCheck %s -check-prefix=CONDITIONAL_DEPENDENT_TYPEALIAS
protocol SomeProto {
associatedtype Assoc
}
extension SomeProto where Assoc == String {
func protoExt_AssocEqString_None() -> Int { return 1 }
}
extension SomeProto where Assoc == Int {
func protoExt_AssocEqInt_None() -> Int { return 1 }
}
extension SomeProto where Assoc: SomeProto {
func protoExt_AssocConformsToSomeProto_None() -> Int { return 1 }
}
extension SomeProto {
func protoExt_None_AssocEqString<U>(_ x: U) -> Int where Assoc == String { return 1 }
func protoExt_None_AssocEqInt<U>(_ x: U) -> Int where Assoc == Int { return 1 }
func protoExt_None_AssocConformsToSomeProto<U>(_ x: U) -> Int where Assoc: SomeProto { return 1 }
}
struct MyStruct<T> : SomeProto {
typealias Assoc = T
init<U>(int: U) where T == Int {}
init<U>(str: U) where T == String {}
init<U: SomeProto>(withConstrainedGenericParam: U) {}
func methodWithConstrainedGenericParam<U: SomeProto>(x: U) -> Int { return 1 }
}
extension MyStruct where T == String {
func concreteExt_TEqString_None() -> Int { return 1 }
}
extension MyStruct where T == Int {
func concreteExt_TEqInt_None() -> Int { return 1 }
}
extension MyStruct where T: SomeProto {
func concreteExt_TConformsToSomeProto_None() -> Int { return 1 }
}
extension MyStruct {
func concreteExt_None_TEqString<U>(_ x: U) -> Int where T == String { return 1 }
func concreteExt_None_TEqInt<U>(_ x: U) -> Int where T == Int { return 1 }
func concreteExt_None_TConformsToSomeProto<U>(_ x: U) -> Int where T: SomeProto { return 1 }
}
protocol Proto_Int {}
extension Proto_Int {
func conditional_Int() -> Int { return 1 }
}
protocol Proto_String {}
extension Proto_String {
func conditional_String() -> Int { return 1 }
}
extension MyStruct: Proto_Int where T == Int{}
extension MyStruct: Proto_String where T == String {}
func foo(s: MyStruct<Int>) {
let _ = s.#^MYSTRUCT_INT_DOT^#
// MYSTRUCT_INT_DOT: Begin completions, 7 items
// MYSTRUCT_INT_DOT-DAG: Keyword[self]/CurrNominal: self[#MyStruct<Int>#]; name=self
// MYSTRUCT_INT_DOT-DAG: Decl[InstanceMethod]/CurrNominal: methodWithConstrainedGenericParam({#x: SomeProto#})[#Int#]; name=methodWithConstrainedGenericParam(x: SomeProto)
// MYSTRUCT_INT_DOT-DAG: Decl[InstanceMethod]/CurrNominal: concreteExt_TEqInt_None()[#Int#]; name=concreteExt_TEqInt_None()
// MYSTRUCT_INT_DOT-DAG: Decl[InstanceMethod]/CurrNominal: concreteExt_None_TEqInt({#(x): U#})[#Int#]; name=concreteExt_None_TEqInt(x: U)
// MYSTRUCT_INT_DOT-DAG: Decl[InstanceMethod]/Super: protoExt_AssocEqInt_None()[#Int#]; name=protoExt_AssocEqInt_None()
// MYSTRUCT_INT_DOT-DAG: Decl[InstanceMethod]/Super: protoExt_None_AssocEqInt({#(x): U#})[#Int#]; name=protoExt_None_AssocEqInt(x: U)
// MYSTRUCT_INT_DOT-DAG: Decl[InstanceMethod]/Super: conditional_Int()[#Int#]; name=conditional_Int()
// MYSTRUCT_INT_DOT: End completions
let _ = MyStruct<Int>.#^META_MYSTRUCT_INT_DOT^#
// META_MYSTRUCT_INT_DOT: Begin completions, 11 items
// META_MYSTRUCT_INT_DOT-DAG: Keyword[self]/CurrNominal: self[#MyStruct<Int>.Type#]; name=self
// META_MYSTRUCT_INT_DOT-DAG: Keyword/CurrNominal: Type[#MyStruct<Int>.Type#]; name=Type
// META_MYSTRUCT_INT_DOT-DAG: Decl[TypeAlias]/CurrNominal: Assoc[#T#]; name=Assoc
// META_MYSTRUCT_INT_DOT-DAG: Decl[Constructor]/CurrNominal: init({#int: U#})[#MyStruct<Int>#]; name=init(int: U)
// META_MYSTRUCT_INT_DOT-DAG: Decl[Constructor]/CurrNominal: init({#withConstrainedGenericParam: SomeProto#})[#MyStruct<Int>#]; name=init(withConstrainedGenericParam: SomeProto)
// META_MYSTRUCT_INT_DOT-DAG: Decl[InstanceMethod]/CurrNominal: methodWithConstrainedGenericParam({#(self): MyStruct<Int>#})[#(x: SomeProto) -> Int#]; name=methodWithConstrainedGenericParam(self: MyStruct<Int>)
// META_MYSTRUCT_INT_DOT-DAG: Decl[InstanceMethod]/CurrNominal: concreteExt_TEqInt_None({#(self): MyStruct<Int>#})[#() -> Int#]; name=concreteExt_TEqInt_None(self: MyStruct<Int>)
// META_MYSTRUCT_INT_DOT-DAG: Decl[InstanceMethod]/CurrNominal: concreteExt_None_TEqInt({#(self): MyStruct<Int>#})[#(U) -> Int#]; name=concreteExt_None_TEqInt(self: MyStruct<Int>)
// META_MYSTRUCT_INT_DOT-DAG: Decl[InstanceMethod]/Super: protoExt_AssocEqInt_None({#(self): MyStruct<Int>#})[#() -> Int#]; name=protoExt_AssocEqInt_None(self: MyStruct<Int>)
// META_MYSTRUCT_INT_DOT-DAG: Decl[InstanceMethod]/Super: protoExt_None_AssocEqInt({#(self): MyStruct<Int>#})[#(U) -> Int#]; name=protoExt_None_AssocEqInt(self: MyStruct<Int>)
// META_MYSTRUCT_INT_DOT-DAG: Decl[InstanceMethod]/Super: conditional_Int({#(self): MyStruct<Int>#})[#() -> Int#]; name=conditional_Int(self: MyStruct<Int>)
// META_MYSTRUCT_INT_DOT: End completions
}
//https://bugs.swift.org/browse/SR-9938
enum Fruit { case apple }
enum Vegetable { case broccoli }
enum Meat { case chicken }
protocol EatsFruit { }
protocol EatsVegetables { }
protocol EatsMeat { }
struct Chef <Client> { }
extension Chef where Client: EatsFruit {
init(_ favorite: Fruit) {}
func cook(_ food: Fruit) { }
}
extension Chef where Client: EatsVegetables {
init(_ favorite: Vegetable) {}
func cook(_ food: Vegetable) { }
}
extension Chef where Client: EatsMeat {
init(favorite: Meat) {}
func cook(_ food: Meat) { }
func eat(_ food: Meat) {}
}
struct Vegetarian: EatsFruit, EatsVegetables { }
func testVegetarian(chef: Chef<Vegetarian>) {
chef.cook(.#^CONDITIONAL_OVERLOAD_ARG^#)
// CONDITIONAL_OVERLOAD_ARG: Begin completions, 4 items
// CONDITIONAL_OVERLOAD_ARG-DAG: Decl[EnumElement]/ExprSpecific/TypeRelation[Identical]: apple[#Fruit#]; name=apple
// CONDITIONAL_OVERLOAD_ARG-DAG: Decl[InstanceMethod]/CurrNominal/TypeRelation[Invalid]: hash({#(self): Fruit#})[#(into: inout Hasher) -> Void#]; name=hash(self: Fruit)
// CONDITIONAL_OVERLOAD_ARG-DAG: Decl[EnumElement]/ExprSpecific/TypeRelation[Identical]: broccoli[#Vegetable#]; name=broccoli
// CONDITIONAL_OVERLOAD_ARG-DAG: Decl[InstanceMethod]/CurrNominal/TypeRelation[Invalid]: hash({#(self): Vegetable#})[#(into: inout Hasher) -> Void#]; name=hash(self: Vegetable)
// CONDITIONAL_OVERLOAD_ARG: End completions
var chefMeta: Chef<Vegetarian>.Type = Chef<Vegetarian>.self
let _ = chefMeta.init(.#^CONDITIONAL_OVERLOAD_INIT_ARG^#)
chef.eat(.#^CONDITIONAL_INAPPLICABLE_ARG^#)
// Note: 'eat' is from an inapplicable constrained extension. We complete as if the user intends to addess that later
// (e.g. by adding the missing 'Meat' conformance to 'Vegetarian' - clearly not the intention here - but replace 'Meat' with 'Equatable').
// CONDITIONAL_INAPPLICABLE_ARG: Begin completions, 2 items
// CONDITIONAL_INAPPLICABLE_ARG-DAG: Decl[EnumElement]/ExprSpecific/TypeRelation[Identical]: chicken[#Meat#]; name=chicken
// CONDITIONAL_INAPPLICABLE_ARG-DAG: Decl[InstanceMethod]/CurrNominal/TypeRelation[Invalid]: hash({#(self): Meat#})[#(into: inout Hasher) -> Void#]; name=hash(self: Meat)
// CONDITIONAL_INAPPLICABLE_ARG: End completions
}
// rdar://problem/53401609
protocol MyProto {
associatedtype Index
}
extension MyProto where Index: Strideable, Index.Stride == Int {
func indices() {}
}
struct MyConcrete {}
extension MyConcrete: MyProto {
typealias Index = Int
}
func testHasIndex(value: MyConcrete) {
value.#^CONDITIONAL_DEPENDENT_TYPEALIAS^#
// CONDITIONAL_DEPENDENT_TYPEALIAS: Begin completions, 2 items
// CONDITIONAL_DEPENDENT_TYPEALIAS-DAG: Keyword[self]/CurrNominal: self[#MyConcrete#];
// CONDITIONAL_DEPENDENT_TYPEALIAS-DAG: Decl[InstanceMethod]/Super: indices()[#Void#];
// CONDITIONAL_DEPENDENT_TYPEALIAS: End completions
}
|
apache-2.0
|
75e334357abfdc781f02791944407f3f
| 54.435897 | 212 | 0.718663 | 3.487097 | false | true | false | false |
lotpb/iosSQLswift
|
mySQLswift/SettingCell.swift
|
1
|
1933
|
//
// SettingCell.swift
// youtube
//
// Created by Brian Voong on 6/18/16.
// Copyright © 2016 letsbuildthatapp. All rights reserved.
//
import UIKit
class SettingCell: CollectionViewCell {
override var highlighted: Bool {
didSet {
backgroundColor = highlighted ? UIColor.darkGrayColor() : UIColor.whiteColor()
nameLabel.textColor = highlighted ? UIColor.whiteColor() : UIColor.blackColor()
iconImageView.tintColor = highlighted ? UIColor.whiteColor() : UIColor.darkGrayColor()
}
}
var setting: Setting? {
didSet {
nameLabel.text = setting?.name.rawValue
if let imageName = setting?.imageName {
iconImageView.image = UIImage(named: imageName)?.imageWithRenderingMode(.AlwaysTemplate)
iconImageView.tintColor = UIColor.darkGrayColor()
}
}
}
let nameLabel: UILabel = {
let label = UILabel()
label.text = "Setting"
label.font = UIFont.systemFontOfSize(13)
return label
}()
let iconImageView: UIImageView = {
let imageView = UIImageView()
imageView.image = UIImage(named: "settings")
imageView.contentMode = .ScaleAspectFill
return imageView
}()
override func setupViews() {
super.setupViews()
addSubview(nameLabel)
addSubview(iconImageView)
addConstraintsWithFormat("H:|-8-[v0(30)]-8-[v1]|", views: iconImageView, nameLabel)
addConstraintsWithFormat("V:|[v0]|", views: nameLabel)
addConstraintsWithFormat("V:[v0(30)]", views: iconImageView)
addConstraint(NSLayoutConstraint(item: iconImageView, attribute: .CenterY, relatedBy: .Equal, toItem: self, attribute: .CenterY, multiplier: 1, constant: 0))
}
}
|
gpl-2.0
|
b4623021477b67d06b2d30ef964e138d
| 27 | 165 | 0.59472 | 5.337017 | false | false | false | false |
younata/RSSClient
|
TethysAppSpecs/UI/Feeds/FeedListControllerSpec.swift
|
1
|
42678
|
import Quick
import Nimble
import Tethys
import TethysKit
import Result
import CBGPromise
final class FeedListControllerSpec: QuickSpec {
override func spec() {
var subject: FeedListController!
var feedCoordinator: FakeFeedCoordinator!
var navigationController: UINavigationController!
var settingsRepository: SettingsRepository!
var mainQueue: FakeOperationQueue!
var notificationCenter: NotificationCenter!
var messenger: FakeMessenger!
let feeds: [Feed] = [
feedFactory(title: "a"),
feedFactory(title: "b"),
feedFactory(title: "c")
]
var recorder: NotificationRecorder!
beforeEach {
feedCoordinator = FakeFeedCoordinator()
mainQueue = FakeOperationQueue()
settingsRepository = SettingsRepository(userDefaults: nil)
settingsRepository.refreshControl = .spinner
notificationCenter = NotificationCenter()
messenger = FakeMessenger()
subject = FeedListController(
feedCoordinator: feedCoordinator,
settingsRepository: settingsRepository,
messenger: messenger,
mainQueue: mainQueue,
notificationCenter: notificationCenter,
findFeedViewController: {
return FindFeedViewController(
importUseCase: FakeImportUseCase(),
analytics: FakeAnalytics(),
notificationCenter: notificationCenter
)
},
feedViewController: { feed in
return feedViewControllerFactory(feed: feed)
},
settingsViewController: { settingsViewControllerFactory() },
articleListController: { feed in articleListControllerFactory(feed: feed) }
)
navigationController = UINavigationController(rootViewController: subject)
recorder = NotificationRecorder()
notificationCenter.addObserver(recorder!, selector: #selector(NotificationRecorder.received(notification:)),
name: Notifications.reloadUI, object: subject)
}
describe("when the view loads") {
beforeEach {
expect(subject.view).toNot(beNil())
// Make sure the refresh control has set the refresh control style.
// Which requires running an operation on the main queue.
expect(subject.refreshControl).toNot(beNil())
expect(mainQueue.operationCount).to(equal(3))
mainQueue.runNextOperation()
expect(mainQueue.operationCount).to(equal(2))
mainQueue.runNextOperation()
expect(mainQueue.operationCount).to(equal(1))
mainQueue.runNextOperation()
expect(mainQueue.operationCount).to(equal(0))
subject.viewWillAppear(false)
}
it("dismisses the keyboard upon drag") {
expect(subject.view).toNot(beNil())
expect(subject.tableView.keyboardDismissMode).to(equal(UIScrollView.KeyboardDismissMode.onDrag))
}
describe("theming") {
it("updates the tableView") {
expect(subject.tableView.backgroundColor).to(equal(Theme.backgroundColor))
expect(subject.tableView.separatorColor).to(equal(Theme.separatorColor))
}
}
describe("Key Commands") {
it("can become first responder") {
expect(subject.canBecomeFirstResponder) == true
}
it("have a list of key commands") {
let keyCommands = subject.keyCommands
expect(keyCommands).toNot(beNil())
guard let commands = keyCommands else {
return
}
// cmd+i, cmd+shift+i, cmd+opt+i
let expectedCommands = [
(input: "i", modifierFlags: UIKeyModifierFlags.command),
(input: ",", modifierFlags: UIKeyModifierFlags.command),
(input: "r", modifierFlags: UIKeyModifierFlags.command),
]
let expectedDiscoverabilityTitles = [
"Add from Web",
"Open settings",
"Reload Feeds",
]
expect(commands.count).to(equal(expectedCommands.count))
for (idx, cmd) in commands.enumerated() {
let expectedCmd = expectedCommands[idx]
expect(cmd.input).to(equal(expectedCmd.input))
expect(cmd.modifierFlags).to(equal(expectedCmd.modifierFlags))
let expectedTitle = expectedDiscoverabilityTitles[idx]
expect(cmd.discoverabilityTitle).to(equal(expectedTitle))
}
}
}
describe("the navigation bar items") {
describe("the left bar button items") {
it("has one item on the left side") {
expect(subject.navigationItem.leftBarButtonItems ?? []).to(haveCount(1))
}
describe("the settings button") {
it("is enabled for accessibility") {
expect(subject.navigationItem.leftBarButtonItem?.isAccessibilityElement).to(beTrue())
expect(subject.navigationItem.leftBarButtonItem?.accessibilityLabel).to(equal("Settings"))
expect(subject.navigationItem.leftBarButtonItem?.accessibilityTraits).to(equal([.button]))
}
describe("tapping it") {
beforeEach {
subject.navigationItem.leftBarButtonItem?.tap()
}
it("presents a settings page") {
expect(subject.presentedViewController).to(beAnInstanceOf(UINavigationController.self))
expect((subject.presentedViewController as? UINavigationController)?.visibleViewController).to(beAnInstanceOf(SettingsViewController.self))
}
it("stops refreshing the control") {
expect(subject.refreshControl.isRefreshing).to(beFalse())
}
}
}
}
describe("the right bar button items") {
it("has two items on the right side") {
expect(subject.navigationItem.rightBarButtonItems ?? []).to(haveCount(2))
}
describe("the add feed button") {
var addFeedButton: UIBarButtonItem?
beforeEach {
addFeedButton = subject.navigationItem.rightBarButtonItems?.first
}
it("is enabled for accessibility") {
expect(addFeedButton?.isAccessibilityElement).to(beTrue())
expect(addFeedButton?.accessibilityLabel).to(equal("Lookup feed to subscribe to"))
expect(addFeedButton?.accessibilityTraits).to(equal([.button]))
}
describe("tapping it") {
beforeEach {
addFeedButton?.tap()
}
afterEach {
navigationController.popToRootViewController(animated: false)
}
it("presents a FindFeedViewController") {
expect(subject.presentedViewController).to(beAnInstanceOf(UINavigationController.self))
expect((subject.presentedViewController as? UINavigationController)?.visibleViewController).to(beAnInstanceOf(FindFeedViewController.self))
}
it("stops refreshing the control") {
expect(subject.refreshControl.isRefreshing).to(beFalse())
}
}
}
it("has the edit button as the second one") {
expect(subject.navigationItem.rightBarButtonItems?.last?.title).to(equal("Edit"))
}
}
}
it("asks the feed coordinator to fetch the feeds") {
expect(feedCoordinator.feedsPublishers).to(haveCount(1))
}
it("starts refreshing") {
expect(subject.refreshControl.isRefreshing).to(beTrue())
}
describe("when the feed coordinator updates successfully") {
context("with a set of feeds") {
beforeEach {
feedCoordinator.feedsPublishers.last?.update(with: .success(AnyCollection(feeds)))
mainQueue.runNextOperation()
}
it("shows a row for each returned feed") {
expect(subject.tableView.numberOfSections).to(equal(1))
expect(subject.tableView.numberOfRows(inSection: 0)).to(equal(3))
}
it("does not stop refreshing") {
expect(subject.refreshControl.isRefreshing).to(beTrue())
}
it("removes the onboarding view") {
expect(subject.onboardingView.superview).to(beNil())
}
describe("the table") {
it("has a row for each feed") {
expect(subject.tableView.numberOfSections).to(equal(1))
expect(subject.tableView.numberOfRows(inSection: 0)).to(equal(3))
}
describe("a cell") {
var cell: FeedTableCell? = nil
var feed: Feed! = nil
let indexPath = IndexPath(row: 0, section: 0)
beforeEach {
cell = subject.tableView.cellForRow(at: indexPath) as? FeedTableCell
feed = feeds[0]
expect(cell).to(beAnInstanceOf(FeedTableCell.self))
}
it("is configured with the feed") {
expect(cell?.feed).to(equal(feed))
}
describe("tapping on it") {
beforeEach {
let indexPath = IndexPath(row: 0, section: 0)
if let _ = cell {
subject.tableView.delegate?.tableView?(
subject.tableView, didSelectRowAt: indexPath
)
}
}
it("should navigate to an ArticleListViewController for that feed") {
expect(navigationController.topViewController).to(beAnInstanceOf(ArticleListController.self))
if let articleList = navigationController.topViewController as? ArticleListController {
expect(articleList.feed).to(equal(feed))
}
}
}
describe("contextual menus") {
var menuConfiguration: UIContextMenuConfiguration?
beforeEach {
menuConfiguration = subject.tableView.delegate?.tableView?(subject.tableView, contextMenuConfigurationForRowAt: indexPath, point: .zero)
}
it("shows a menu configured to show a set of articles") {
expect(menuConfiguration).toNot(beNil())
let viewController = menuConfiguration?.previewProvider?()
expect(viewController).to(beAKindOf(ArticleListController.self))
if let articleVC = viewController as? ArticleListController {
expect(articleVC.feed) == feed
}
}
describe("the menu items") {
var menu: UIMenu?
var action: UIAction?
beforeEach {
menu = menuConfiguration?.actionProvider?([])
}
it("has 4 children actions") {
expect(menu?.children).to(haveCount(4))
expect(menu?.children.compactMap { $0 as? UIAction }).to(haveCount(4))
}
describe("the first action") {
beforeEach {
action = menu?.children.first as? UIAction
}
it("states it marks all items in the feed as read") {
expect(action?.title).to(equal("Mark Read"))
}
it("uses the mark read image") {
expect(action?.image).to(equal(UIImage(named: "MarkRead")))
}
describe("tapping it") {
beforeEach {
action?.handler(action!)
}
it("marks all articles of that feed as read") {
expect(feedCoordinator.readAllOfFeedCalls).to(equal([feeds[0]]))
}
describe("when the feed coordinator succeeds") {
beforeEach {
feedCoordinator.readAllOfFeedPromises.last?.resolve(.success(()))
mainQueue.runNextOperation()
}
it("marks the cell as unread") {
expect(cell?.unreadCounter.unread).to(equal(0))
}
it("posts a notification telling other things to reload") {
expect(recorder.notifications).to(haveCount(1))
expect(recorder.notifications.last?.object as? NSObject).to(be(subject))
}
it("does not tell the feed coordinator to fetch new feeds") {
expect(feedCoordinator.feedsPublishers).to(haveCount(1))
}
}
describe("when the feed coordinator fails") {
beforeEach {
feedCoordinator.readAllOfFeedPromises.last?.resolve(.failure(.database(.unknown)))
mainQueue.runNextOperation()
}
it("brings up an alert notifying the user") {
expect(messenger.errorCalls).to(haveCount(1))
expect(messenger.errorCalls.last).to(equal(
MessageCall(
title: "Unable to update feed",
message: "Unknown Database Error"
)
))
}
it("doesn't post a notification telling other things to reload") {
expect(recorder.notifications).to(beEmpty())
}
}
}
}
describe("the second action") {
beforeEach {
guard let menu = menu, menu.children.count > 1 else { return }
action = menu.children[1] as? UIAction
}
it("states it edits the feed") {
expect(action?.title).to(equal("Edit"))
}
describe("tapping it") {
beforeEach {
action?.handler(action!)
}
it("brings up a feed edit screen") {
expect(navigationController.visibleViewController).to(beAnInstanceOf(FeedViewController.self))
}
}
}
describe("the third action") {
beforeEach {
guard let menu = menu, menu.children.count > 2 else { return }
action = menu.children[2] as? UIAction
}
it("states it opens a share sheet") {
expect(action?.title).to(equal("Share"))
}
it("uses the share icon") {
expect(action?.image).to(equal(UIImage(systemName: "square.and.arrow.up")))
}
describe("tapping it") {
beforeEach {
action?.handler(action!)
}
it("brings up a share sheet") {
expect(navigationController.visibleViewController).to(beAnInstanceOf(UIActivityViewController.self))
if let shareSheet = navigationController.visibleViewController as? UIActivityViewController {
expect(shareSheet.activityItems as? [URL]).to(equal([feeds[0].url]))
}
}
}
}
describe("the fourth action") {
beforeEach {
guard let menu = menu, menu.children.count > 3 else { return }
action = menu.children[3] as? UIAction
}
it("states it deletes the feed") {
expect(action?.title).to(equal("Unsubscribe"))
}
it("uses a trash can icon") {
expect(action?.image).to(equal(UIImage(systemName: "trash")))
}
describe("tapping it") {
beforeEach {
action?.handler(action!)
}
it("unsubcribes from the feed") {
expect(feedCoordinator.unsubscribeCalls).to(equal([feeds[0]]))
}
describe("if the unsubscribe succeeds") {
beforeEach {
feedCoordinator.unsubscribePromises.last?.resolve(.success(()))
mainQueue.runNextOperation()
}
it("removes the feed from the list of cells") {
expect(subject.tableView.numberOfSections).to(equal(1))
expect(subject.tableView.numberOfRows(inSection: 0)).to(equal(2))
}
}
describe("if the unsubscribe fails") {
beforeEach {
feedCoordinator.unsubscribePromises.last?.resolve(.failure(.database(.unknown)))
mainQueue.runNextOperation()
}
it("brings up an alert notifying the user") {
expect(messenger.errorCalls).to(haveCount(1))
expect(messenger.errorCalls.last).to(equal(
MessageCall(
title: "Unable to delete feed",
message: "Unknown Database Error"
)
))
}
it("does not remove the feed from the list of cells") {
expect(subject.tableView.numberOfSections).to(equal(1))
expect(subject.tableView.numberOfRows(inSection: 0)).to(equal(3))
}
}
}
}
}
describe("committing the view controller (tapping on it again)") {
beforeEach {
guard let config = menuConfiguration else { return }
let animator = FakeContextMenuAnimator(commitStyle: .pop, viewController: menuConfiguration?.previewProvider?())
subject.tableView.delegate?.tableView?(subject.tableView, willPerformPreviewActionForMenuWith: config, animator: animator)
expect(animator.addAnimationsCalls).to(beEmpty())
expect(animator.addCompletionCalls).to(haveCount(1))
animator.addCompletionCalls.last?()
}
it("navigates to the view controller") {
expect(navigationController.topViewController).to(beAnInstanceOf(ArticleListController.self))
if let articleVC = navigationController.topViewController as? ArticleListController {
expect(articleVC.feed) == feed
}
}
}
}
describe("contextual actions") {
var contextualActions: [UIContextualAction] = []
var action: UIContextualAction?
beforeEach {
let swipeActions = subject.tableView.delegate?.tableView?(subject.tableView, trailingSwipeActionsConfigurationForRowAt: indexPath)
expect(swipeActions?.performsFirstActionWithFullSwipe).to(beTrue())
contextualActions = swipeActions?.actions ?? []
}
it("has 4 edit actions") {
expect(subject.tableView.dataSource?.tableView?(subject.tableView, canEditRowAt: indexPath)).to(beTrue())
expect(contextualActions).to(haveCount(4))
}
describe("the first one") {
beforeEach {
guard contextualActions.count > 0 else { return }
action = contextualActions[0]
}
it("states it marks all items in the feed as read") {
expect(action?.title).to(equal("Mark\nRead"))
}
describe("tapping it") {
var completionHandlerCalls: [Bool] = []
beforeEach {
completionHandlerCalls = []
action?.handler(action!, subject.tableView.cellForRow(at: indexPath)!) { completionHandlerCalls.append($0) }
}
it("marks all articles of that feed as read") {
expect(feedCoordinator.readAllOfFeedCalls).to(equal([feeds[0]]))
}
describe("when the feed coordinator succeeds") {
beforeEach {
feedCoordinator.readAllOfFeedPromises.last?.resolve(.success(()))
mainQueue.runNextOperation()
}
it("marks the cell as unread") {
expect(cell?.unreadCounter.unread).to(equal(0))
}
it("posts a notification telling other things to reload") {
expect(recorder.notifications).to(haveCount(1))
expect(recorder.notifications.last?.object as? NSObject).to(be(subject))
}
it("does not tell the feed coordinator to fetch new feeds") {
expect(feedCoordinator.feedsPublishers).to(haveCount(1))
}
it("calls the completion handler") {
expect(completionHandlerCalls).to(equal([true]))
}
}
describe("when the feed coordinator fails") {
beforeEach {
feedCoordinator.readAllOfFeedPromises.last?.resolve(.failure(.database(.unknown)))
mainQueue.runNextOperation()
}
it("brings up an alert notifying the user") {
expect(messenger.errorCalls).to(haveCount(1))
expect(messenger.errorCalls.last).to(equal(
MessageCall(
title: "Unable to update feed",
message: "Unknown Database Error"
)
))
}
it("doesn't post a notification") {
expect(recorder.notifications).to(beEmpty())
}
it("calls the completion handler") {
expect(completionHandlerCalls).to(equal([false]))
}
}
}
}
describe("the second one") {
beforeEach {
guard contextualActions.count > 1 else { return }
action = contextualActions[1]
}
it("states it deletes the feed") {
expect(action?.title).to(equal("Unsubscribe"))
}
describe("tapping it") {
var completionHandlerCalls: [Bool] = []
beforeEach {
completionHandlerCalls = []
action?.handler(action!, subject.tableView.cellForRow(at: indexPath)!) { completionHandlerCalls.append($0) }
}
it("unsubscribes from the feed") {
expect(feedCoordinator.unsubscribeCalls).to(equal([feeds[0]]))
}
describe("if the unsubscribe succeeds") {
beforeEach {
feedCoordinator.unsubscribePromises.last?.resolve(.success(()))
mainQueue.runNextOperation()
}
it("removes the feed from the list of cells") {
expect(subject.tableView.numberOfSections).to(equal(1))
expect(subject.tableView.numberOfRows(inSection: 0)).to(equal(2))
}
it("calls the completion handler") {
expect(completionHandlerCalls).to(equal([true]))
}
}
describe("if the unsubscribe fails") {
beforeEach {
feedCoordinator.unsubscribePromises.last?.resolve(.failure(.database(.unknown)))
mainQueue.runNextOperation()
}
it("brings up an alert notifying the user") {
expect(messenger.errorCalls).to(haveCount(1))
expect(messenger.errorCalls.last).to(equal(
MessageCall(
title: "Unable to delete feed",
message: "Unknown Database Error"
)
))
}
it("does not remove the feed from the list of cells") {
expect(subject.tableView.numberOfSections).to(equal(1))
expect(subject.tableView.numberOfRows(inSection: 0)).to(equal(3))
}
it("calls the completion handler") {
expect(completionHandlerCalls).to(equal([false]))
}
}
}
}
describe("the third one") {
beforeEach {
guard contextualActions.count > 2 else { return }
action = contextualActions[2]
}
it("states it edits the feed") {
expect(action?.title).to(equal("Edit"))
}
describe("tapping it") {
var completionHandlerCalls: [Bool] = []
beforeEach {
completionHandlerCalls = []
action?.handler(action!, subject.tableView.cellForRow(at: indexPath)!) { completionHandlerCalls.append($0) }
}
it("brings up a feed edit screen") {
expect(navigationController.visibleViewController).to(beAnInstanceOf(FeedViewController.self))
}
it("calls the completion handler") {
expect(completionHandlerCalls).to(equal([true]))
}
}
}
describe("the fourth one") {
beforeEach {
guard contextualActions.count > 3 else { return }
action = contextualActions[3]
}
it("states it opens a share sheet") {
expect(action?.title).to(equal("Share"))
}
it("colors itself based on the theme's highlight color") {
expect(action?.backgroundColor).to(equal(Theme.highlightColor))
}
describe("tapping it") {
var completionHandlerCalls: [Bool] = []
beforeEach {
completionHandlerCalls = []
action?.handler(action!, subject.tableView.cellForRow(at: indexPath)!) { completionHandlerCalls.append($0) }
}
it("brings up a share sheet") {
expect(navigationController.visibleViewController).to(beAnInstanceOf(UIActivityViewController.self))
if let shareSheet = navigationController.visibleViewController as? UIActivityViewController {
expect(shareSheet.activityItems as? [URL]).to(equal([feeds[0].url]))
}
}
it("calls the completion handler") {
expect(completionHandlerCalls).to(equal([true]))
}
}
}
}
}
}
describe("when the reloadUI notification is posted") {
beforeEach {
notificationCenter.post(name: Notifications.reloadUI, object: self)
}
it("tells the feedService to fetch new feeds") {
expect(feedCoordinator.feedsPublishers).to(haveCount(2))
}
}
}
context("but no feeds were found") {
beforeEach {
feedCoordinator.feedsPublishers.last?.update(with: .success(AnyCollection([])))
mainQueue.runNextOperation()
}
it("shows the onboarding view") {
expect(subject.onboardingView.superview).toNot(beNil())
}
it("does not stop refreshing") {
expect(subject.refreshControl.isRefreshing).to(beTrue())
}
it("gives the onboarding view accessibility information") {
expect(subject.onboardingView.accessibilityLabel).to(equal("Usage"))
expect(subject.onboardingView.accessibilityValue).to(equal("Welcome to Tethys! Use the add button to search for feeds to follow"))
}
}
}
describe("when the feed coordinator updates with an error") {
beforeEach {
feedCoordinator.feedsPublishers.last?.update(with: .failure(.database(.unknown)))
mainQueue.runNextOperation()
}
it("does not stop refreshing") {
expect(subject.refreshControl.isRefreshing).to(beTrue())
}
it("brings up an alert notifying the user") {
expect(messenger.errorCalls).to(haveCount(1))
expect(messenger.errorCalls.last).to(equal(
MessageCall(
title: "Unable to fetch feeds",
message: "Unknown Database Error"
)
))
}
}
describe("when the feed coordinator finishes") {
beforeEach {
feedCoordinator.feedsPublishers.last?.finish()
mainQueue.runNextOperation()
}
it("stops refreshing") {
expect(subject.refreshControl.isRefreshing).to(beFalse())
}
describe("pull to refresh") {
beforeEach {
subject.refreshControl.beginRefreshing()
subject.refreshControl.spinner.sendActions(for: .valueChanged)
}
it("tells the feed coordinator to fetch new feeds") {
expect(feedCoordinator.feedsPublishers).to(haveCount(2))
}
it("refreshes") {
expect(subject.refreshControl.isRefreshing).to(beTrue())
}
}
}
}
}
}
// Helper function inserted by Swift 4.2 migrator.
fileprivate func convertFromOptionalNSAttributedStringKeyDictionary(_ input: [NSAttributedString.Key: Any]?) -> [String: Any]? {
guard let input = input else { return nil }
return Dictionary(uniqueKeysWithValues: input.map {key, value in (key.rawValue, value)})
}
// Helper function inserted by Swift 4.2 migrator.
fileprivate func convertFromNSAttributedStringKey(_ input: NSAttributedString.Key) -> String {
return input.rawValue
}
class NotificationRecorder: NSObject {
var notifications: [Notification] = []
@objc func received(notification: Notification) {
self.notifications.append(notification)
}
}
|
mit
|
c3de9e3bb46c179d66f2951613c378bc
| 51.623921 | 172 | 0.386218 | 7.789378 | false | false | false | false |
jonathanhogan/receptionkit
|
ReceptionKit/AppDelegate.swift
|
3
|
2875
|
//
// AppDelegate.swift
// ReceptionKit
//
// Created by Andy Cho on 2015-04-23.
// Copyright (c) 2015 Andy Cho. All rights reserved.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
let conversationDelegate = ConversationDelegate()
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
// SupportKit Settings
let skSettings = SKTSettings(appToken: Config.SupportKit.AppToken)
skSettings.enableGestureHintOnFirstLaunch = false
skSettings.enableAppWideGesture = false
SupportKit.initWithSettings(skSettings)
// Setup SupportKit
SupportKit.conversation().delegate = conversationDelegate
SupportKit.setUserFirstName(Config.Slack.Name, lastName: "")
SKTUser.currentUser().email = Config.Slack.Email
// App-wide styles
UIApplication.sharedApplication().setStatusBarHidden(true, withAnimation: UIStatusBarAnimation.Slide)
UINavigationBar.appearance().barTintColor = UIColor(hex: Config.Colour.NavigationBar)
return true
}
func applicationWillResignActive(application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}
func applicationDidEnterBackground(application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(application: UIApplication) {
// Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}
}
|
mit
|
2aa212a203918f42e15f881779f21337
| 46.131148 | 285 | 0.739478 | 5.507663 | false | true | false | false |
ingresse/ios-sdk
|
IngresseSDK/Parser/URLBuilder.swift
|
1
|
4805
|
//
// Copyright © 2017 Gondek. All rights reserved.
//
public enum Environment: String {
case prod = ""
case hml = "hml-"
case hmlA = "hmla-"
case hmlB = "hmlb-"
case hmlC = "hmlc-"
case test = "test-"
case stg = "stg-"
case integration = "integration2-"
case undefined = "undefined-"
static func hmlEnvs() -> [Environment] { [.hml, .hmlA, .hmlB, .hmlC] }
public init(envType: String) {
switch envType {
case "prod":
self = .prod
case "hml":
self = .hml
case "hmla":
self = .hmlA
case "hmlb":
self = .hmlB
case "hmlc":
self = .hmlC
case "test":
self = .test
case "stg":
self = .stg
case "integration2-":
self = .integration
default:
self = .undefined
}
}
}
public enum Host: String {
case events = "event.ingresse.com/"
case api = "api.ingresse.com/"
case cep = "cep.ingresse.com/"
case search = "event-search.ingresse.com/"
case searchHml = "event.ingresse.com/search/company/"
case userTransactions = "my-transactions.ingresse.com/"
case ingresseLive = "live.ingresse.com/"
case ingresseLiveHml = "live-homolog.ingresse.com/"
case cashless = "cashless.ingresse.com"
}
public class URLBuilder: NSObject {
private var url: String = ""
private var host: Host = .api
private var environment: Environment = .prod
private var path: String = ""
private var apiKey: String = ""
private var parameters: [String: String] = [:]
public init(client: IngresseClient) {
self.environment = client.environment
self.apiKey = client.apiKey
}
public func setHost(_ endpoint: Host) -> URLBuilder {
self.host = endpoint
return self
}
public func setEnvironment(_ env: Environment) -> URLBuilder {
self.environment = env
return self
}
public func setPath(_ path: String) -> URLBuilder {
self.path = path
return self
}
public func setKeys(apiKey: String) -> URLBuilder {
self.apiKey = apiKey
return self
}
public func addParameter(key: String, value: Any) -> URLBuilder {
self.parameters[key] = "\(value)"
return self
}
func addEncodableParameter( _ param: Encodable) -> URLBuilder {
var builder = self
param.encoded?.forEach { builder = builder.addParameter(key: $0, value: $1) }
return builder
}
public func build() throws -> URLRequest {
var urlString = getHostUrl()
urlString += path
let params = parameters.merging(authorizationAPIParam()) { _, key in key }
if !params.isEmpty {
urlString += "?"
urlString += params.stringFromHttpParameters()
}
guard let url = URL(string: urlString) else {
throw URLRequestError.requestInvalid
}
let request = URLRequest(url: url,
cachePolicy: .useProtocolCachePolicy,
timeoutInterval: 60)
return requestWithHeaders(request)
}
public func getHostUrl() -> String {
if !Environment.hmlEnvs().contains(environment) {
return "https://\(environment.rawValue)\(host.rawValue)"
}
switch host {
case .search:
return "https://\(environment.rawValue)\(Host.searchHml.rawValue)"
case .ingresseLive:
return "https://\(Host.ingresseLiveHml.rawValue)"
default:
return "https://\(environment.rawValue)\(host.rawValue)"
}
}
}
// MARK: - Private Methods
extension URLBuilder {
private func requestWithHeaders(_ request: URLRequest) -> URLRequest {
var request = request
if let header = UserAgent.header {
request.addValue(header, forHTTPHeaderField: "User-Agent")
}
if let auth = UserAgent.authorization {
request.addValue("Bearer \(auth)", forHTTPHeaderField: "Authorization")
}
authorizationAPIParam().forEach {
request.addValue($0.value,
forHTTPHeaderField: $0.key)
}
return request
}
private func authorizationAPIParam() -> [String: String] {
switch host {
case .api, .ingresseLive:
return ["apikey": apiKey]
case .userTransactions:
return ["X-Api-Key": "fcEpWMJGBp4oXfA1qEQ6maSepdyrZd2v4yk7q4xv"]
default:
return [:]
}
}
}
// MARK: - URLRequestError
enum URLRequestError: Error {
case requestInvalid
}
|
mit
|
3e3ca85b26bbb9fa50b2959477cb7f38
| 25.395604 | 85 | 0.563697 | 4.270222 | false | false | false | false |
UpBra/SwiftLog
|
SwiftLog/Log.swift
|
1
|
2402
|
//
// Log.swift
// Copyright © 2017 gleesh. All rights reserved.
//
import Foundation
public struct Log: OptionSet {
public let rawValue: UInt8
public init(rawValue: UInt8) { self.rawValue = rawValue }
static public var enabledTypes: Log = [.general, .network, .operations]
static public var prefix: PrefixMode = [.date, .methodName, .line]
public static let none: Log = []
// MARK: - Types
public static let general = Log(rawValue: 1 << 0)
public static let network = Log(rawValue: 1 << 1)
public static let operations = Log(rawValue: 1 << 2)
public func print(_ items: Any?..., separator: String = " ", terminator: String = "\n", _ file: String = #file, _ function: String = #function, _ line: Int = #line) {
#if DEBUG
guard Log.enabledTypes.contains(self) else { return }
let prefix = Log.prefix.generatePrefix(file: file, function: function, line: line)
let validItems = items.flatMap { $0 }
let validItemsArray = validItems.map { "\($0)" }
let statement = validItemsArray.joined(separator: separator)
let output = [prefix, statement].flatMap { $0 }.joined(separator: separator)
Swift.print(output, terminator: terminator)
#endif
}
}
public struct PrefixMode: OptionSet {
public let rawValue: UInt8
public init(rawValue: UInt8) { self.rawValue = rawValue }
public static let none = PrefixMode(rawValue: 0)
public static let date = PrefixMode(rawValue: 1 << 0)
public static let fileName = PrefixMode(rawValue: 1 << 1)
public static let methodName = PrefixMode(rawValue: 1 << 2)
public static let line = PrefixMode(rawValue: 1 << 3)
public func generatePrefix(file: String, function: String, line: Int, separator: String = " | ") -> String? {
guard self != .none else { return nil }
var components = [String]()
if self.contains(.date) {
let date = PrefixMode.formatter.string(from: Date())
components.append(date)
}
if contains(.fileName) {
components.append(file)
}
if contains(.methodName) {
components.append(function)
}
if contains(.line) {
components.append("\(line)")
}
let prefix = components.joined(separator: separator)
return prefix.isEmpty ? nil : "[\(prefix)]"
}
}
extension PrefixMode {
static private let formatter: DateFormatter = {
let value = DateFormatter()
value.dateFormat = "yyyy.MM.dd HH:mm"
return value
}()
}
|
mit
|
e10e6674aa9709a4d60a99543ac3cdeb
| 25.977528 | 167 | 0.67222 | 3.489826 | false | false | false | false |
qiuncheng/study-for-swift
|
learn-rx-swift/Chocotastic-starter/Pods/RxSwift/RxSwift/Observables/Implementations/TakeWhile.swift
|
6
|
3504
|
//
// TakeWhile.swift
// RxSwift
//
// Created by Krunoslav Zaher on 6/7/15.
// Copyright © 2015 Krunoslav Zaher. All rights reserved.
//
import Foundation
class TakeWhileSink<ElementType, O: ObserverType>
: Sink<O>
, ObserverType where O.E == ElementType {
typealias Parent = TakeWhile<ElementType>
typealias Element = ElementType
fileprivate let _parent: Parent
fileprivate var _running = true
init(parent: Parent, observer: O) {
_parent = parent
super.init(observer: observer)
}
func on(_ event: Event<Element>) {
switch event {
case .next(let value):
if !_running {
return
}
do {
_running = try _parent._predicate(value)
} catch let e {
forwardOn(.error(e))
dispose()
return
}
if _running {
forwardOn(.next(value))
} else {
forwardOn(.completed)
dispose()
}
case .error, .completed:
forwardOn(event)
dispose()
}
}
}
class TakeWhileSinkWithIndex<ElementType, O: ObserverType>
: Sink<O>
, ObserverType where O.E == ElementType {
typealias Parent = TakeWhile<ElementType>
typealias Element = ElementType
fileprivate let _parent: Parent
fileprivate var _running = true
fileprivate var _index = 0
init(parent: Parent, observer: O) {
_parent = parent
super.init(observer: observer)
}
func on(_ event: Event<Element>) {
switch event {
case .next(let value):
if !_running {
return
}
do {
_running = try _parent._predicateWithIndex(value, _index)
let _ = try incrementChecked(&_index)
} catch let e {
forwardOn(.error(e))
dispose()
return
}
if _running {
forwardOn(.next(value))
} else {
forwardOn(.completed)
dispose()
}
case .error, .completed:
forwardOn(event)
dispose()
}
}
}
class TakeWhile<Element>: Producer<Element> {
typealias Predicate = (Element) throws -> Bool
typealias PredicateWithIndex = (Element, Int) throws -> Bool
fileprivate let _source: Observable<Element>
fileprivate let _predicate: Predicate!
fileprivate let _predicateWithIndex: PredicateWithIndex!
init(source: Observable<Element>, predicate: @escaping Predicate) {
_source = source
_predicate = predicate
_predicateWithIndex = nil
}
init(source: Observable<Element>, predicate: @escaping PredicateWithIndex) {
_source = source
_predicate = nil
_predicateWithIndex = predicate
}
override func run<O : ObserverType>(_ observer: O) -> Disposable where O.E == Element {
if let _ = _predicate {
let sink = TakeWhileSink(parent: self, observer: observer)
sink.disposable = _source.subscribe(sink)
return sink
} else {
let sink = TakeWhileSinkWithIndex(parent: self, observer: observer)
sink.disposable = _source.subscribe(sink)
return sink
}
}
}
|
mit
|
ff3ebab4484200539b1d8129cc2453e4
| 25.537879 | 91 | 0.531544 | 5.033046 | false | false | false | false |
itsaboutcode/WordPress-iOS
|
WordPress/Classes/ViewRelated/Jetpack/Jetpack Settings/JetpackSpeedUpSiteSettingsViewController.swift
|
1
|
6514
|
import Foundation
import CocoaLumberjack
import WordPressShared
/// This class will display the Blog's "Speed you site" settings, and will allow the user to modify them.
/// Upon selection, WordPress.com backend will get hit, and the new value will be persisted.
///
open class JetpackSpeedUpSiteSettingsViewController: UITableViewController {
// MARK: - Private Properties
fileprivate var blog: Blog!
fileprivate var service: BlogJetpackSettingsService!
fileprivate lazy var handler: ImmuTableViewHandler = {
return ImmuTableViewHandler(takeOver: self)
}()
// MARK: - Computed Properties
fileprivate var settings: BlogSettings {
return blog.settings!
}
// MARK: - Initializer
@objc public convenience init(blog: Blog) {
self.init(style: .grouped)
self.blog = blog
self.service = BlogJetpackSettingsService(managedObjectContext: settings.managedObjectContext!)
}
// MARK: - View Lifecycle
open override func viewDidLoad() {
super.viewDidLoad()
title = NSLocalizedString("Speed up your site", comment: "Title for the Speed up your site Settings Screen")
ImmuTable.registerRows([SwitchRow.self], tableView: tableView)
WPStyleGuide.configureColors(view: view, tableView: tableView)
reloadViewModel()
}
open override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
reloadViewModel()
refreshSettings()
}
// MARK: - Model
fileprivate func reloadViewModel() {
handler.viewModel = tableViewModel()
}
func tableViewModel() -> ImmuTable {
let serveImagesFromOurServers = SwitchRow(title: NSLocalizedString("Serve images from our servers",
comment: "Title for the Serve images from our servers setting"),
value: self.settings.jetpackServeImagesFromOurServers,
onChange: self.serveImagesFromOurServersValueChanged())
let lazyLoadImages = SwitchRow(title: NSLocalizedString("\"Lazy-load\" images",
comment: "Title for the lazy load images setting"),
value: self.settings.jetpackLazyLoadImages,
onChange: self.lazyLoadImagesValueChanged())
return ImmuTable(sections: [
ImmuTableSection(
headerText: "",
rows: [serveImagesFromOurServers],
footerText: NSLocalizedString("Jetpack will optimize your images and serve them from the server " +
"location nearest to your visitors. Using our global content delivery " +
"network will boost the loading speed of your site.",
comment: "Footer for the Serve images from our servers setting")),
ImmuTableSection(
headerText: "",
rows: [lazyLoadImages],
footerText: NSLocalizedString("Improve your site's speed by only loading images visible on the screen. " +
"New images will load just before they scroll into view. This prevents " +
"viewers from having to download all the images on a page all at once, " +
"even ones they can't see.",
comment: "Footer for the Serve images from our servers setting")),
])
}
// MARK: - Row Handlers
fileprivate func serveImagesFromOurServersValueChanged() -> (_ newValue: Bool) -> Void {
return { [unowned self] newValue in
self.settings.jetpackServeImagesFromOurServers = newValue
self.reloadViewModel()
self.service.updateJetpackServeImagesFromOurServersModuleSettingForBlog(self.blog,
success: {},
failure: { [weak self] (_) in
self?.refreshSettingsAfterSavingError()
})
}
}
fileprivate func lazyLoadImagesValueChanged() -> (_ newValue: Bool) -> Void {
return { [unowned self] newValue in
self.settings.jetpackLazyLoadImages = newValue
self.reloadViewModel()
self.service.updateJetpackLazyImagesModuleSettingForBlog(self.blog,
success: {},
failure: { [weak self] (_) in
self?.refreshSettingsAfterSavingError()
})
}
}
// MARK: - Persistance
fileprivate func refreshSettings() {
service.syncJetpackModulesForBlog(blog,
success: { [weak self] in
self?.reloadViewModel()
DDLogInfo("Reloaded Speed up site settings")
},
failure: { (error: Error?) in
DDLogError("Error while syncing blog Speed up site settings: \(String(describing: error))")
})
}
fileprivate func refreshSettingsAfterSavingError() {
let errorTitle = NSLocalizedString("Error updating speed up site settings",
comment: "Title of error dialog when updating speed up site settings fail.")
let errorMessage = NSLocalizedString("Please contact support for assistance.",
comment: "Message displayed on an error alert to prompt the user to contact support")
WPError.showAlert(withTitle: errorTitle, message: errorMessage, withSupportButton: true)
refreshSettings()
}
}
|
gpl-2.0
|
2769c6bf6b5cf5fdcfa05866dfd21bd5
| 47.251852 | 139 | 0.521032 | 6.527054 | false | false | false | false |
migchaves/SwiftCoreData
|
Swift CoreData Example/DataBase/DBManager.swift
|
1
|
5370
|
//
// DBManager.swift
// Swift CoreData Example
//
// Created by Miguel Chaves on 19/01/16.
// Copyright © 2016 Miguel Chaves. All rights reserved.
//
import UIKit
import CoreData
class DBManager: NSObject {
// MARK: - Class Properties
var managedObjectContext: NSManagedObjectContext
var managedObjectModel: NSManagedObjectModel
var persistentStoreCoordinator: NSPersistentStoreCoordinator
// MARK: - Init class
override init() {
self.managedObjectModel = NSManagedObjectModel.init(contentsOfURL: DBManager.getModelUrl())!
self.persistentStoreCoordinator = NSPersistentStoreCoordinator.init(managedObjectModel: self.managedObjectModel)
do {
try self.persistentStoreCoordinator.addPersistentStoreWithType(NSSQLiteStoreType, configuration: nil,
URL: DBManager.storeURL(), options: nil)
} catch let error as NSError {
print(error)
abort()
}
self.managedObjectContext = NSManagedObjectContext.init(concurrencyType: .MainQueueConcurrencyType)
self.managedObjectContext.persistentStoreCoordinator = self.persistentStoreCoordinator
self.managedObjectContext.mergePolicy = NSOverwriteMergePolicy
}
// MARK: - Shared Instance
class var sharedInstance: DBManager {
struct Singleton {
static let instance = DBManager()
}
return Singleton.instance
}
// MARK: - Create and Save objects
func managedObjectOfType(objectType: String) -> NSManagedObject {
let newObject = NSEntityDescription.insertNewObjectForEntityForName(objectType,
inManagedObjectContext: self.managedObjectContext)
return newObject
}
func temporaryManagedObjectOfType(objectType: String) -> NSManagedObject {
let description = NSEntityDescription.entityForName(objectType,
inManagedObjectContext: self.managedObjectContext)
let temporaryObject = NSManagedObject.init(entity: description!,
insertIntoManagedObjectContext: nil)
return temporaryObject
}
func insertManagedObject(object: NSManagedObject) {
self.managedObjectContext.insertObject(object)
saveContext()
}
func saveContext() {
if (!self.managedObjectContext.hasChanges) {
return
} else {
do {
try self.managedObjectContext.save()
} catch let exception as NSException {
print("Error while saving \(exception.userInfo) : \(exception.reason)")
} catch {
print("Error while saving data!")
}
}
}
// MARK: - Retrieve data
func allEntriesOfType(objectType: String) -> [AnyObject] {
let entety = NSEntityDescription.entityForName(objectType,
inManagedObjectContext: self.managedObjectContext)
let request = NSFetchRequest.init()
request.entity = entety
request.includesPendingChanges = true
do {
let result = try self.managedObjectContext.executeFetchRequest(request)
return result
} catch {
print("Error executing request in the Data Base.")
}
return []
}
func getEntryOfType(objectType: String, propertyName: String, propertyValue: AnyObject) -> [AnyObject] {
let entety = NSEntityDescription.entityForName(objectType,
inManagedObjectContext: self.managedObjectContext)
let request = NSFetchRequest.init()
request.entity = entety
request.includesPendingChanges = true
let predicate = NSPredicate(format: "\(propertyName) == \(propertyValue)")
request.predicate = predicate
do {
let result = try self.managedObjectContext.executeFetchRequest(request)
var returnArray: [AnyObject] = [AnyObject]()
for element in result {
returnArray.append(element)
}
return returnArray
} catch {
print("Error executing request in the Data Base")
}
return []
}
func deleteAllEntriesOfType(objectType: String) {
let elements = allEntriesOfType(objectType)
if (elements.count > 0) {
for element in elements {
self.managedObjectContext.deleteObject(element as! NSManagedObject)
}
saveContext()
}
}
func deleteObject(object: NSManagedObject) {
self.managedObjectContext.deleteObject(object)
saveContext()
}
// MARK: - Private functions
static private func getModelUrl() -> NSURL {
return NSBundle.mainBundle().URLForResource("Model", withExtension: "momd")!
}
static private func storeURL () -> NSURL? {
let applicationDocumentsDirectory = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask).last
let storeUrl = applicationDocumentsDirectory?.URLByAppendingPathComponent("Model.sqlite")
return storeUrl
}
}
|
mit
|
c5d82919842c61aea567d350494be5ae
| 31.149701 | 144 | 0.623207 | 6.286885 | false | false | false | false |
cocoascientist/Jetstream
|
JetstreamCore/Controllers/WeatherStore.swift
|
1
|
1974
|
//
// WeatherStore.swift
// Jetstream
//
// Created by Andrew Shepard on 1/21/15.
// Copyright (c) 2015 Andrew Shepard. All rights reserved.
//
import Foundation
import CoreLocation
import CoreData
import Combine
public final class WeatherStore {
public lazy var initializedDataStoreEvent: Future<Void, Error> = {
return Future<Void, Error>.init { [weak self] (observer) in
self?.dataController.persistentStoreContainer
.loadPersistentStores { (description, error) in
if let error = error {
observer(.failure(error))
} else {
observer(.success(()))
}
}
}
}()
public var weatherDidChange: AnyPublisher<Void, Never> {
return _weatherDidChange.eraseToAnyPublisher()
}
private let _weatherDidChange = PassthroughSubject<Void, Never>()
private let dataController: CoreDataController
private var cancelables: [AnyCancellable] = []
public init(dataController: CoreDataController = CoreDataController()) {
self.dataController = dataController
}
deinit {
cancelables.forEach { $0.cancel() }
}
public var managedObjectContext: NSManagedObjectContext {
return dataController.persistentStoreContainer.viewContext
}
public var backgroundManagedObjectContext: NSManagedObjectContext {
return dataController.persistentStoreContainer.newBackgroundContext()
}
}
public enum WeatherStoreUpdateType {
case noData
case newData
}
public enum WeatherStoreError: Error {
case noData
case other(NSError)
}
extension WeatherStoreError: CustomDebugStringConvertible {
public var debugDescription: String {
switch self {
case .noData:
return "No response data"
case .other(let error):
return "\(error)"
}
}
}
|
mit
|
68dbd48e8e1f21bd3c8b6bb219c3b0ac
| 26.041096 | 77 | 0.634752 | 5.408219 | false | false | false | false |
syncloud/ios
|
Syncloud/DiscoveryController.swift
|
1
|
5909
|
import Foundation
import UIKit
class DiscoveryController: UIViewController, UITableViewDelegate, UITableViewDataSource, EndpointListener {
@IBOutlet weak var tableEndpoints: UITableView!
@IBOutlet weak var viewNoDevices: UIView!
var discovery: Discovery
var endpoints = [IdentifiedEndpoint]()
var refreshEndpoints: UIRefreshControl?
func mainController() -> MainController {
return self.navigationController as! MainController
}
init() {
discovery = Discovery()
super.init(nibName: "Discovery", bundle: nil)
}
required init(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func viewDidLoad() {
super.viewDidLoad()
let cellNib = UINib(nibName: "DeviceCell", bundle: nil)
self.tableEndpoints.register(cellNib, forCellReuseIdentifier: "deviceCell")
self.title = "Discovery"
let btnRefresh = UIBarButtonItem(title: "Refresh", style: UIBarButtonItem.Style.plain, target: self, action: #selector(DiscoveryController.btnDiscoveryClick(_:)))
let flexibleSpace = UIBarButtonItem(barButtonSystemItem: UIBarButtonItem.SystemItem.flexibleSpace, target: self, action: nil)
self.toolbarItems = [flexibleSpace, btnRefresh, flexibleSpace]
let refreshControl = UIRefreshControl()
refreshControl.addTarget(self, action: #selector(DiscoveryController.btnDiscoveryClick(_:)), for: .valueChanged)
refreshControl.attributedTitle = NSAttributedString(string: "Discovering devices...")
self.tableEndpoints.addSubview(refreshControl)
self.refreshEndpoints = refreshControl
(self.navigationController as! MainController).addSettings()
}
override var shouldAutorotate : Bool {
return false
}
override func viewWillAppear(_ animated: Bool) {
self.navigationController!.setNavigationBarHidden(false, animated: animated)
self.navigationController!.setToolbarHidden(false, animated: animated)
super.viewWillAppear(animated)
checkWiFi()
}
@IBAction func btnLearnMoreClicked(_ sender: AnyObject) {
self.mainController().openUrl("http://syncloud.org")
}
func checkWiFi() {
let ssid = getSSID()
if ssid == nil {
let alertMessage = "You are not connected to Wi-Fi network. Discovery is possible only in the same Wi-Fi network where you have Syncloud device connected."
let alert = UIAlertController(title: "Wi-Fi Connection", message: alertMessage, preferredStyle: UIAlertController.Style.alert)
alert.addAction(UIAlertAction(title: "Try Again", style: .default, handler: { action in
self.checkWiFi()
}))
alert.addAction(UIAlertAction(title: "Cancel", style: .cancel, handler: { action in
self.navigationController!.popViewController(animated: true)
}))
self.present(alert, animated: true, completion: nil)
} else {
discoveryStart()
}
}
@IBAction func btnDiscoveryClick(_ sender: AnyObject) {
discoveryStart()
}
func discoveryStart() {
self.tableEndpoints.isHidden = false
self.viewNoDevices.isHidden = true
if self.refreshEndpoints!.isRefreshing == false {
self.refreshEndpoints!.beginRefreshing()
}
self.endpoints.removeAll(keepingCapacity: true)
self.tableEndpoints.reloadData()
let queue = DispatchQueue(label: "org.syncloud.Syncloud", attributes: []);
queue.async { () -> Void in
NSLog("Starting discovery")
self.discovery.stop()
self.discovery.start("syncloud", listener: self)
sleep(10)
NSLog("Stopping discovery")
self.discovery.stop()
DispatchQueue.main.async { () -> Void in
self.refreshEndpoints!.endRefreshing()
if self.endpoints.isEmpty {
self.tableEndpoints.isHidden = true
self.viewNoDevices.isHidden = false
}
}
}
}
func found(_ endpoint: Endpoint) {
let queue = DispatchQueue(label: "org.syncloud.Syncloud", attributes: []);
queue.async { () -> Void in
let device = DeviceInternal(host: endpoint.host)
let (id, error) = device.id()
if error != nil {
return
}
let identifiedEndpoint = IdentifiedEndpoint(endpoint: endpoint, id: id!)
DispatchQueue.main.async {
() -> Void in
if self.endpoints.filter({ e in e.endpoint.host == identifiedEndpoint.endpoint.host }).count == 0 {
self.endpoints.append(identifiedEndpoint)
self.tableEndpoints.reloadData()
}
}
}
}
func error(_ error: Error) {
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return endpoints.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let endpoint = self.endpoints[indexPath.row]
let cell = self.tableEndpoints.dequeueReusableCell(withIdentifier: "deviceCell") as! DeviceCell
cell.load(endpoint)
return cell
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
self.tableEndpoints.deselectRow(at: indexPath, animated: true)
let endpoint = self.endpoints[indexPath.row]
self.mainController().openUrl(endpoint.endpoint.activationUrl())
}
}
|
gpl-3.0
|
52a178b424d8c8d719ea9cc417817e62
| 35.030488 | 170 | 0.618886 | 5.323423 | false | false | false | false |
ArthurKK/Kingfisher
|
KingfisherTests/UIImageViewExtensionTests.swift
|
6
|
11533
|
//
// UIImageViewExtensionTests.swift
// Kingfisher
//
// Created by Wei Wang on 15/4/17.
//
// Copyright (c) 2015 Wei Wang <[email protected]>
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import UIKit
import XCTest
import Kingfisher
class UIImageViewExtensionTests: XCTestCase {
var imageView: UIImageView!
override class func setUp() {
super.setUp()
LSNocilla.sharedInstance().start()
}
override class func tearDown() {
super.tearDown()
LSNocilla.sharedInstance().stop()
}
override func setUp() {
super.setUp()
// Put setup code here. This method is called before the invocation of each test method in the class.
imageView = UIImageView()
KingfisherManager.sharedManager.downloader = ImageDownloader(name: "testDownloader")
}
override func tearDown() {
// Put teardown code here. This method is called after the invocation of each test method in the class.
LSNocilla.sharedInstance().clearStubs()
imageView = nil
cleanDefaultCache()
super.tearDown()
}
func testImageDownloadForImageView() {
let expectation = expectationWithDescription("wait for downloading image")
let URLString = testKeys[0]
stubRequest("GET", URLString).andReturn(200).withBody(testImageData)
let URL = NSURL(string: URLString)!
var progressBlockIsCalled = false
imageView.kf_setImageWithURL(URL, placeholderImage: nil, optionsInfo: nil, progressBlock: { (receivedSize, totalSize) -> () in
progressBlockIsCalled = true
}) { (image, error, cacheType, imageURL) -> () in
expectation.fulfill()
XCTAssert(progressBlockIsCalled, "progressBlock should be called at least once.")
XCTAssert(image != nil, "Downloaded image should exist.")
XCTAssert(image! == testImage, "Downloaded image should be the same as test image.")
XCTAssert(self.imageView.image! == testImage, "Downloaded image should be already set to the image property.")
XCTAssert(self.imageView.kf_webURL == imageURL, "Web URL should equal to the downloaded url.")
XCTAssert(cacheType == .None, "The cache type should be none here. This image was just downloaded.")
}
waitForExpectationsWithTimeout(5, handler: nil)
}
func testImageDownloadWithResourceForImageView() {
let expectation = expectationWithDescription("wait for downloading image")
let URLString = testKeys[0]
stubRequest("GET", URLString).andReturn(200).withBody(testImageData)
let URL = NSURL(string: URLString)!
let resource = Resource(downloadURL: URL)
var progressBlockIsCalled = false
imageView.kf_setImageWithResource(resource, placeholderImage: nil, optionsInfo: nil, progressBlock: { (receivedSize, totalSize) -> () in
progressBlockIsCalled = true
}) { (image, error, cacheType, imageURL) -> () in
expectation.fulfill()
XCTAssert(progressBlockIsCalled, "progressBlock should be called at least once.")
XCTAssert(image != nil, "Downloaded image should exist.")
XCTAssert(image! == testImage, "Downloaded image should be the same as test image.")
XCTAssert(self.imageView.image! == testImage, "Downloaded image should be already set to the image property.")
XCTAssert(self.imageView.kf_webURL == imageURL, "Web URL should equal to the downloaded url.")
XCTAssert(cacheType == .None, "The cache type should be none here. This image was just downloaded.")
}
waitForExpectationsWithTimeout(5, handler: nil)
}
func testImageDownloadCancelForImageView() {
let expectation = expectationWithDescription("wait for downloading image")
let URLString = testKeys[0]
stubRequest("GET", URLString).andReturn(200).withBody(testImageData)
let URL = NSURL(string: URLString)!
var progressBlockIsCalled = false
var completionBlockIsCalled = false
let task = imageView.kf_setImageWithURL(URL, placeholderImage: nil, optionsInfo: nil, progressBlock: { (receivedSize, totalSize) -> () in
progressBlockIsCalled = true
}) { (image, error, cacheType, imageURL) -> () in
completionBlockIsCalled = true
}
task.cancel()
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, Int64(Double(NSEC_PER_SEC) * 0.09)), dispatch_get_main_queue()) { () -> Void in
expectation.fulfill()
XCTAssert(progressBlockIsCalled == false, "ProgressBlock should not be called since it is canceled.")
XCTAssert(completionBlockIsCalled == false, "CompletionBlock should not be called since it is canceled.")
}
waitForExpectationsWithTimeout(5, handler: nil)
}
func testImageDownloadCacelPartialTask() {
let expectation = expectationWithDescription("wait for downloading image")
let URLString = testKeys[0]
stubRequest("GET", URLString).andReturn(200).withBody(testImageData)
let URL = NSURL(string: URLString)!
var task1Completion = false
var task2Completion = false
var task3Completion = false
let task1 = imageView.kf_setImageWithURL(URL, placeholderImage: nil, optionsInfo: nil, progressBlock: { (receivedSize, totalSize) -> () in
}) { (image, error, cacheType, imageURL) -> () in
task1Completion = true
}
let task2 = imageView.kf_setImageWithURL(URL, placeholderImage: nil, optionsInfo: nil, progressBlock: { (receivedSize, totalSize) -> () in
}) { (image, error, cacheType, imageURL) -> () in
task2Completion = true
}
let task3 = imageView.kf_setImageWithURL(URL, placeholderImage: nil, optionsInfo: nil, progressBlock: { (receivedSize, totalSize) -> () in
}) { (image, error, cacheType, imageURL) -> () in
task3Completion = true
}
task1.cancel()
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, Int64(Double(NSEC_PER_SEC) * 0.09)), dispatch_get_main_queue()) { () -> Void in
expectation.fulfill()
XCTAssert(task1Completion == false, "Task 1 is canceled. The completion flag should be fasle.")
XCTAssert(task2Completion == true, "Task 2 should be completed.")
XCTAssert(task3Completion == true, "Task 3 should be completed.")
}
waitForExpectationsWithTimeout(5, handler: nil)
}
func testImageDownalodMultipleCaches() {
let cache1 = ImageCache(name: "cache1")
let cache2 = ImageCache(name: "cache2")
let expectation = expectationWithDescription("wait for downloading image")
let URLString = testKeys[0]
stubRequest("GET", URLString).andReturn(200).withBody(testImageData)
let URL = NSURL(string: URLString)!
imageView.kf_setImageWithURL(URL, placeholderImage: nil, optionsInfo: [.TargetCache: cache1], progressBlock: { (receivedSize, totalSize) -> () in
}) { (image, error, cacheType, imageURL) -> () in
XCTAssertTrue(cache1.isImageCachedForKey(URLString).cached, "This image should be cached in cache1.")
XCTAssertFalse(cache2.isImageCachedForKey(URLString).cached, "This image should not be cached in cache2.")
XCTAssertFalse(KingfisherManager.sharedManager.cache.isImageCachedForKey(URLString).cached, "This image should not be cached in default cache.")
self.imageView.kf_setImageWithURL(URL, placeholderImage: nil, optionsInfo: [.TargetCache: cache2], progressBlock: { (receivedSize, totalSize) -> () in
}, completionHandler: { (image, error, cacheType, imageURL) -> () in
XCTAssertTrue(cache1.isImageCachedForKey(URLString).cached, "This image should be cached in cache1.")
XCTAssertTrue(cache2.isImageCachedForKey(URLString).cached, "This image should be cached in cache2.")
XCTAssertFalse(KingfisherManager.sharedManager.cache.isImageCachedForKey(URLString).cached, "This image should not be cached in default cache.")
clearCaches([cache1, cache2])
expectation.fulfill()
})
}
waitForExpectationsWithTimeout(5, handler: { (error) -> Void in
clearCaches([cache1, cache2])
})
}
func testIndicatorViewExisting() {
imageView.kf_showIndicatorWhenLoading = true
XCTAssertNotNil(imageView.kf_indicator, "The indicator view should exist when showIndicatorWhenLoading is true")
imageView.kf_showIndicatorWhenLoading = false
XCTAssertNil(imageView.kf_indicator, "The indicator view should be removed when showIndicatorWhenLoading set to false")
}
func testIndicatorViewAnimating() {
imageView.kf_showIndicatorWhenLoading = true
let expectation = expectationWithDescription("wait for downloading image")
let URLString = testKeys[0]
stubRequest("GET", URLString).andReturn(200).withBody(testImageData)
let URL = NSURL(string: URLString)!
imageView.kf_setImageWithURL(URL, placeholderImage: nil, optionsInfo: nil, progressBlock: { (receivedSize, totalSize) -> () in
let indicator = self.imageView.kf_indicator
XCTAssertNotNil(indicator, "The indicator view should exist when showIndicatorWhenLoading is true")
XCTAssertTrue(indicator!.isAnimating(), "The indicator should be animating when loading")
}) { (image, error, cacheType, imageURL) -> () in
let indicator = self.imageView.kf_indicator
XCTAssertFalse(indicator!.isAnimating(), "The indicator should stop after loading")
expectation.fulfill()
}
waitForExpectationsWithTimeout(5, handler: nil)
}
}
|
mit
|
904bf710dc8acd68d81ebc1171022064
| 44.765873 | 162 | 0.642764 | 5.273434 | false | true | false | false |
warren-gavin/OBehave
|
OBehave/Classes/ViewController/Lifecycle/OBCloseViewControllerBehavior.swift
|
1
|
4106
|
//
// OBCloseViewControllerBehavior.swift
// OBehave
//
// Created by Warren Gavin on 24/10/15.
// Copyright © 2015 Apokrupto. All rights reserved.
//
import UIKit
public protocol OBCloseViewControllerBehaviorDelegate: OBBehaviorDelegate {
func viewControllerWillClose(for behavior: OBCloseViewControllerBehavior)
func viewControllerDidClose(for behavior: OBCloseViewControllerBehavior)
func viewControllerCompletion()
}
public extension OBCloseViewControllerBehaviorDelegate {
func viewControllerWillClose(for behavior: OBCloseViewControllerBehavior) {
}
func viewControllerDidClose(for behavior: OBCloseViewControllerBehavior) {
}
func viewControllerCompletion() {
}
}
public protocol OBNavigationModalPresentationSegueDelegate {
func dismissModalPresentation(controller: UIViewController, animated: Bool, completion: (() -> Void)?)
}
public final class OBCloseViewControllerBehavior: OBBehavior {
@IBInspectable public var shouldPop: Bool = false
/**
Close a view controller
Note: iOS 8
This will not work if you are attempting to close a modal view embedded in a navigation view controller. Use
closeEnclosingViewController: instead
- parameter sender: UI element that instantated the close
*/
@IBAction public func closeViewController(sender: AnyObject?) {
let closeDelegate: OBCloseViewControllerBehaviorDelegate? = getDelegate()
closeDelegate?.viewControllerWillClose(for: self)
if let navigationController = owner?.navigationController, shouldPop {
navigationController.popViewController(animated: true)
closeDelegate?.viewControllerCompletion()
}
else {
owner?.dismiss(animated: true, completion: closeDelegate?.viewControllerCompletion)
}
closeDelegate?.viewControllerDidClose(for: self)
}
/**
Close a navigation stack that has been presented modally over another window
- parameter sender: UI element that instantated the close
*/
@IBAction public func closeEnclosingViewController(sender: AnyObject?) {
if let navigationController = owner?.navigationController {
let closeDelegate: OBCloseViewControllerBehaviorDelegate? = getDelegate()
let enclosingWindowDelegate = navigationController.enclosingWindowDelegate
closeDelegate?.viewControllerWillClose(for: self)
enclosingWindowDelegate?.dismissModalPresentation(controller: navigationController,
animated: true,
completion: closeDelegate?.viewControllerCompletion)
closeDelegate?.viewControllerDidClose(for: self)
}
}
}
// MARK: - OBNavigationModalPresentationSegueDelegate
/**
Extend UIViewController to have a delegate to allow dismissing of presented modals that contain embedding navigation
view controllers
*/
extension UIViewController: OBNavigationModalPresentationSegueDelegate {
private struct Constants {
static var associatedKey = "com.apokrupto.OBBehaviorModalDelegateBinding"
}
@nonobjc
public var enclosingWindowDelegate: OBNavigationModalPresentationSegueDelegate? {
get {
return objc_getAssociatedObject(self, &Constants.associatedKey) as? OBNavigationModalPresentationSegueDelegate
}
set {
if let enclosingWindowDelegate = newValue {
objc_setAssociatedObject(self,
&Constants.associatedKey,
enclosingWindowDelegate as AnyObject,
.OBJC_ASSOCIATION_RETAIN_NONATOMIC)
}
}
}
@nonobjc
public func dismissModalPresentation(controller: UIViewController, animated: Bool, completion: (() -> Void)?) {
dismiss(animated: animated, completion: completion)
}
}
|
mit
|
e97814d8cc61cb8c203274ce71d63089
| 35.651786 | 122 | 0.676005 | 5.889527 | false | false | false | false |
roambotics/swift
|
test/SILGen/unreachable_code.swift
|
2
|
3651
|
// RUN: %target-swift-emit-sil %s -verify | %FileCheck %s
func testUnreachableAfterReturn() -> Int {
var x: Int = 3
return x
x += 1 //expected-warning {{code after 'return' will never be executed}}
}
func testUnreachableAfterIfReturn(a: Bool) -> Int {
if a {
return 1
} else {
return 0
}
var _: Int = testUnreachableAfterReturn() // expected-warning {{will never be executed}}
}
func testUnreachableForAfterContinue(b: Bool) {
for _ in 0..<10 {
var y: Int = 300
y += 1
if b {
break
y += 1 // expected-warning {{code after 'break' will never be executed}}
}
continue
y -= 1 // expected-warning {{code after 'continue' will never be executed}}
}
}
func testUnreachableWhileAfterContinue(b: Bool) {
var i:Int = 0
while (i<10) {
var y: Int = 300
y += 1
if b {
break
y += 1 // expected-warning {{code after 'break' will never be executed}}
}
continue
i += 1 // expected-warning {{code after 'continue' will never be executed}}
}
}
func testBreakAndContinue() {
var m = 0
for _ in 0 ..< 10 {
m += 1
if m == 15 {
break
} else {
continue
}
m += 1 // expected-warning {{will never be executed}}
}
}
// <rdar://problem/20253447> `case let Case` without bindings incorrectly matches other cases
enum Tree {
case Leaf(Int)
case Branch(Int)
}
func testUnreachableCase1(a : Tree) {
switch a {
case let Leaf:
_ = Leaf
return
case .Branch(_): // expected-warning {{case is already handled by previous patterns; consider removing it}}
return
}
}
func testUnreachableCase2(a : Tree) {
switch a {
case let Leaf:
_ = Leaf
fallthrough
case .Branch(_): // expected-warning {{case is already handled by previous patterns; consider removing it}}
return
}
}
func testUnreachableCase3(a : Tree) {
switch a {
case _:
break
case .Branch(_): // expected-warning {{case is already handled by previous patterns; consider removing it}}
return
}
}
func testUnreachableCase4(a : Tree) {
switch a {
case .Leaf(_):
return
case .Branch(_):
return
}
}
func testUnreachableCase5(a : Tree) {
switch a {
case _:
break
default: // expected-warning {{default will never be executed}}
return
}
}
// https://github.com/apple/swift/issues/48333
func testOptionalEvaluationBreak(a : Tree) {
class C { func foo() {} }
func createOptional() -> C? { return C() }
switch a {
case _:
break
createOptional()?.foo() // expected-warning {{code after 'break' will never be executed}}
}
}
func testUnreachableAfterThrow(e: Error) throws {
throw e
return // expected-warning {{code after 'throw' will never be executed}}
}
class TestThrowInInit {
required init(e: Error) throws {
throw e // no unreachable code diagnostic for the implicit return.
}
}
// https://github.com/apple/swift/issues/48696
func f_48696() {
var bar: String? = ""
return;
bar?.append("x") // expected-warning{{code after 'return' will never be executed}}
}
func testUnreachableCatchClause() {
enum ErrorEnum: Error { case someError }
do {
throw ErrorEnum.someError
} catch let error {
print(error)
} catch ErrorEnum.someError { // expected-warning {{case will never be executed}}
print("some error")
}
}
// https://github.com/apple/swift/issues/56075
func f_56075() -> Int {
return Foo.bar
struct Foo { // no-warning
static var bar = 0
// CHECK: sil private @$s16unreachable_code7f_56075SiyF3FooL_V7fooFuncyyF : $@convention(method) (Foo) -> ()
func fooFunc() {}
}
func appendix() {} // no-warning
}
|
apache-2.0
|
b6e17e6f005567564fc7ce9076525e4d
| 21.677019 | 112 | 0.63599 | 3.661986 | false | true | false | false |
xedin/swift
|
stdlib/public/core/CTypes.swift
|
1
|
9211
|
//===----------------------------------------------------------------------===//
//
// 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
//
//===----------------------------------------------------------------------===//
// C Primitive Types
//===----------------------------------------------------------------------===//
/// The C 'char' type.
///
/// This will be the same as either `CSignedChar` (in the common
/// case) or `CUnsignedChar`, depending on the platform.
public typealias CChar = Int8
/// The C 'unsigned char' type.
public typealias CUnsignedChar = UInt8
/// The C 'unsigned short' type.
public typealias CUnsignedShort = UInt16
/// The C 'unsigned int' type.
public typealias CUnsignedInt = UInt32
/// The C 'unsigned long' type.
#if os(Windows) && arch(x86_64)
public typealias CUnsignedLong = UInt32
#else
public typealias CUnsignedLong = UInt
#endif
/// The C 'unsigned long long' type.
public typealias CUnsignedLongLong = UInt64
/// The C 'signed char' type.
public typealias CSignedChar = Int8
/// The C 'short' type.
public typealias CShort = Int16
/// The C 'int' type.
public typealias CInt = Int32
/// The C 'long' type.
#if os(Windows) && arch(x86_64)
public typealias CLong = Int32
#else
public typealias CLong = Int
#endif
/// The C 'long long' type.
public typealias CLongLong = Int64
/// The C 'float' type.
public typealias CFloat = Float
/// The C 'double' type.
public typealias CDouble = Double
/// The C 'long double' type.
#if os(macOS) || os(iOS) || os(watchOS) || os(tvOS)
// On Darwin, long double is Float80 on x86, and Double otherwise.
#if arch(x86_64) || arch(i386)
public typealias CLongDouble = Float80
#else
public typealias CLongDouble = Double
#endif
#elseif os(Windows)
// On Windows, long double is always Double.
public typealias CLongDouble = Double
#elseif os(Linux)
// On Linux/x86, long double is Float80.
// TODO: Fill in definitions for additional architectures as needed. IIRC
// armv7 should map to Double, but arm64 and ppc64le should map to Float128,
// which we don't yet have in Swift.
#if arch(x86_64) || arch(i386)
public typealias CLongDouble = Float80
#endif
// TODO: Fill in definitions for other OSes.
#if arch(s390x)
// On s390x '-mlong-double-64' option with size of 64-bits makes the
// Long Double type equivalent to Double type.
public typealias CLongDouble = Double
#endif
#elseif os(Android)
// On Android, long double is Float128 for AAPCS64, which we don't have yet in
// Swift (SR-9072); and Double for ARMv7.
#if arch(arm)
public typealias CLongDouble = Double
#endif
#endif
// FIXME: Is it actually UTF-32 on Darwin?
//
/// The C++ 'wchar_t' type.
public typealias CWideChar = Unicode.Scalar
// FIXME: Swift should probably have a UTF-16 type other than UInt16.
//
/// The C++11 'char16_t' type, which has UTF-16 encoding.
public typealias CChar16 = UInt16
/// The C++11 'char32_t' type, which has UTF-32 encoding.
public typealias CChar32 = Unicode.Scalar
/// The C '_Bool' and C++ 'bool' type.
public typealias CBool = Bool
/// A wrapper around an opaque C pointer.
///
/// Opaque pointers are used to represent C pointers to types that
/// cannot be represented in Swift, such as incomplete struct types.
@frozen
public struct OpaquePointer {
@usableFromInline
internal var _rawValue: Builtin.RawPointer
@usableFromInline @_transparent
internal init(_ v: Builtin.RawPointer) {
self._rawValue = v
}
/// Creates an `OpaquePointer` from a given address in memory.
@_transparent
public init?(bitPattern: Int) {
if bitPattern == 0 { return nil }
self._rawValue = Builtin.inttoptr_Word(bitPattern._builtinWordValue)
}
/// Creates an `OpaquePointer` from a given address in memory.
@_transparent
public init?(bitPattern: UInt) {
if bitPattern == 0 { return nil }
self._rawValue = Builtin.inttoptr_Word(bitPattern._builtinWordValue)
}
/// Converts a typed `UnsafePointer` to an opaque C pointer.
@_transparent
public init<T>(_ from: UnsafePointer<T>) {
self._rawValue = from._rawValue
}
/// Converts a typed `UnsafePointer` to an opaque C pointer.
///
/// The result is `nil` if `from` is `nil`.
@_transparent
public init?<T>(_ from: UnsafePointer<T>?) {
guard let unwrapped = from else { return nil }
self.init(unwrapped)
}
/// Converts a typed `UnsafeMutablePointer` to an opaque C pointer.
@_transparent
public init<T>(_ from: UnsafeMutablePointer<T>) {
self._rawValue = from._rawValue
}
/// Converts a typed `UnsafeMutablePointer` to an opaque C pointer.
///
/// The result is `nil` if `from` is `nil`.
@_transparent
public init?<T>(_ from: UnsafeMutablePointer<T>?) {
guard let unwrapped = from else { return nil }
self.init(unwrapped)
}
}
extension OpaquePointer: Equatable {
@inlinable // unsafe-performance
public static func == (lhs: OpaquePointer, rhs: OpaquePointer) -> Bool {
return Bool(Builtin.cmp_eq_RawPointer(lhs._rawValue, rhs._rawValue))
}
}
extension OpaquePointer: Hashable {
/// Hashes the essential components of this value by feeding them into the
/// given hasher.
///
/// - Parameter hasher: The hasher to use when combining the components
/// of this instance.
@inlinable
public func hash(into hasher: inout Hasher) {
hasher.combine(Int(Builtin.ptrtoint_Word(_rawValue)))
}
}
extension OpaquePointer : CustomDebugStringConvertible {
/// A textual representation of the pointer, suitable for debugging.
public var debugDescription: String {
return _rawPointerToString(_rawValue)
}
}
extension Int {
/// Creates a new value with the bit pattern of the given pointer.
///
/// The new value represents the address of the pointer passed as `pointer`.
/// If `pointer` is `nil`, the result is `0`.
///
/// - Parameter pointer: The pointer to use as the source for the new
/// integer.
@inlinable // unsafe-performance
public init(bitPattern pointer: OpaquePointer?) {
self.init(bitPattern: UnsafeRawPointer(pointer))
}
}
extension UInt {
/// Creates a new value with the bit pattern of the given pointer.
///
/// The new value represents the address of the pointer passed as `pointer`.
/// If `pointer` is `nil`, the result is `0`.
///
/// - Parameter pointer: The pointer to use as the source for the new
/// integer.
@inlinable // unsafe-performance
public init(bitPattern pointer: OpaquePointer?) {
self.init(bitPattern: UnsafeRawPointer(pointer))
}
}
/// A wrapper around a C `va_list` pointer.
#if arch(arm64) && !(os(macOS) || os(iOS) || os(tvOS) || os(watchOS) || os(Windows))
@frozen
public struct CVaListPointer {
@usableFromInline // unsafe-performance
internal var _value: (__stack: UnsafeMutablePointer<Int>?,
__gr_top: UnsafeMutablePointer<Int>?,
__vr_top: UnsafeMutablePointer<Int>?,
__gr_off: Int32,
__vr_off: Int32)
@inlinable // unsafe-performance
public // @testable
init(__stack: UnsafeMutablePointer<Int>?,
__gr_top: UnsafeMutablePointer<Int>?,
__vr_top: UnsafeMutablePointer<Int>?,
__gr_off: Int32,
__vr_off: Int32) {
_value = (__stack, __gr_top, __vr_top, __gr_off, __vr_off)
}
}
extension CVaListPointer : CustomDebugStringConvertible {
public var debugDescription: String {
return "(\(_value.__stack.debugDescription), " +
"\(_value.__gr_top.debugDescription), " +
"\(_value.__vr_top.debugDescription), " +
"\(_value.__gr_off), " +
"\(_value.__vr_off))"
}
}
#else
@frozen
public struct CVaListPointer {
@usableFromInline // unsafe-performance
internal var _value: UnsafeMutableRawPointer
@inlinable // unsafe-performance
public // @testable
init(_fromUnsafeMutablePointer from: UnsafeMutableRawPointer) {
_value = from
}
}
extension CVaListPointer : CustomDebugStringConvertible {
/// A textual representation of the pointer, suitable for debugging.
public var debugDescription: String {
return _value.debugDescription
}
}
#endif
@inlinable
internal func _memcpy(
dest destination: UnsafeMutableRawPointer,
src: UnsafeRawPointer,
size: UInt
) {
let dest = destination._rawValue
let src = src._rawValue
let size = UInt64(size)._value
Builtin.int_memcpy_RawPointer_RawPointer_Int64(
dest, src, size,
/*volatile:*/ false._value)
}
/// Copy `count` bytes of memory from `src` into `dest`.
///
/// The memory regions `source..<source + count` and
/// `dest..<dest + count` may overlap.
@inlinable
internal func _memmove(
dest destination: UnsafeMutableRawPointer,
src: UnsafeRawPointer,
size: UInt
) {
let dest = destination._rawValue
let src = src._rawValue
let size = UInt64(size)._value
Builtin.int_memmove_RawPointer_RawPointer_Int64(
dest, src, size,
/*volatile:*/ false._value)
}
|
apache-2.0
|
9193ee63e4362a425a1c10f8a9f85b3e
| 28.522436 | 84 | 0.670068 | 4.038141 | false | false | false | false |
SoufianeLasri/Sisley
|
Sisley/SharingView.swift
|
1
|
4105
|
//
// SharingView.swift
// Sisley
//
// Created by Soufiane Lasri on 25/12/2015.
// Copyright © 2015 Soufiane Lasri. All rights reserved.
//
import UIKit
class SharingView: UIView {
var label: UILabel!
var sharingCloseButton: SharingCloseButton!
var openingState: Bool = false
var buttons: [ SharingButton ] = []
var items: [ String ] = []
override init( frame: CGRect ) {
super.init( frame: frame )
self.items = [ "facebook", "twitter", "pinterest" ]
self.backgroundColor = UIColor( red: 0.06, green: 0.08, blue: 0.32, alpha: 0.0 )
self.label = UILabel( frame: CGRect( x: 0, y: self.frame.height / 2 - 200, width: self.frame.width, height: 80 ) )
self.label.text = "Je souhaite partager\nmon orchidée"
self.label.numberOfLines = 2
self.label.font = UIFont( name: "Santana-Bold", size: 26.0 )
self.label.textColor = UIColor.whiteColor()
self.label.textAlignment = .Center
self.label.alpha = 0
self.label.frame.origin.y += 5
self.addSubview( self.label )
self.sharingCloseButton = SharingCloseButton( frame: CGRect( x: self.frame.width / 2 - 30, y: self.frame.height - 70, width: 50, height: 50 ) )
self.sharingCloseButton.alpha = 0
self.sharingCloseButton.frame.origin.y += 5
let closingTap = UITapGestureRecognizer( target: self, action: "closeMenu:" )
self.sharingCloseButton.addGestureRecognizer( closingTap )
self.addSubview( self.sharingCloseButton )
for var i = 0; i < self.items.count; i++ {
let button = SharingButton( frame: CGRect( x: self.frame.width / 2 - 30 + CGFloat( 80 * ( i - 1 ) ), y: self.frame.height / 2 - 80, width: 50, height: 50 ), imageName: self.items[ i ] )
self.buttons.append( button )
self.addSubview( button )
}
self.hidden = true
}
func openMenu() {
self.hidden = false
self.openingState = true
var delay = 0.0
UIView.animateWithDuration( 0.3, delay: delay, options: UIViewAnimationOptions.TransitionNone, animations: {
self.backgroundColor = UIColor( red: 0.06, green: 0.08, blue: 0.32, alpha: 0.7 )
self.label.alpha = 1
self.label.frame.origin.y -= 5
self.sharingCloseButton.alpha = 1
self.sharingCloseButton.frame.origin.y -= 5
}, completion: { finished in
self.sharingCloseButton.enabled = true
} )
for item in self.buttons {
UIView.animateWithDuration( 0.3, delay: delay, options: UIViewAnimationOptions.TransitionNone, animations: {
item.toggleButton( self.openingState )
}, completion: nil )
delay += 0.1
}
}
func closeMenu( recognizer: UITapGestureRecognizer ) {
if recognizer.state == .Ended {
self.openingState = false
var delay = 0.3
UIView.animateWithDuration( 0.3, delay: delay, options: UIViewAnimationOptions.TransitionNone, animations: {
self.backgroundColor = UIColor( red: 0.06, green: 0.08, blue: 0.32, alpha: 0.0 )
self.label.alpha = 0
self.label.frame.origin.y += 5
self.sharingCloseButton.alpha = 0
self.sharingCloseButton.frame.origin.y += 5
}, completion: { finished in
self.sharingCloseButton.enabled = false
self.hidden = true
} )
for item in self.buttons {
UIView.animateWithDuration( 0.3, delay: delay, options: UIViewAnimationOptions.TransitionNone, animations: {
item.toggleButton( self.openingState )
}, completion: nil )
delay -= 0.1
}
}
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
|
mit
|
3c9f05e41ae071648cb148249004b2c2
| 37.35514 | 198 | 0.572508 | 4.269511 | false | false | false | false |
benjaminsnorris/AvatarView
|
AvatarView/AvatarLineView.swift
|
1
|
5845
|
/*
| _ ____ ____ _
| | |‾| ⚈ |-| ⚈ |‾| |
| | | ‾‾‾‾| |‾‾‾‾ | |
| ‾ ‾ ‾
*/
import UIKit
@IBDesignable open class AvatarLineView: UIView {
// MARK: - Inspectable properties
@IBInspectable open var avatarBorderColor: UIColor = UIColor(red: 29 / 255.0, green: 30 / 255.0, blue: 29 / 255.0, alpha: 1.0) {
didSet {
updateColors()
}
}
@IBInspectable open var innerColor: UIColor = UIColor(red: 232 / 255.0, green: 236 / 255.0, blue: 237 / 255.0, alpha: 1.0) {
didSet {
updateColors()
}
}
@IBInspectable open var textColor: UIColor = UIColor(red: 29 / 255.0, green: 30 / 255.0, blue: 29 / 255.0, alpha: 1.0) {
didSet {
updateColors()
}
}
@IBInspectable open var spacingColor: UIColor = UIColor.white {
didSet {
updateColors()
}
}
@IBInspectable open var avatarBorderWidth: CGFloat = 0.0 {
didSet {
updateBorders()
}
}
@IBInspectable open var fontName: String? = nil {
didSet {
setNeedsLayout()
}
}
@IBInspectable open var fontSize: CGFloat = 17.0 {
didSet {
setNeedsLayout()
}
}
@IBInspectable open var overlap: CGFloat = 10 {
didSet {
stackView.spacing = -overlap
}
}
@IBInspectable open var spacing: CGFloat = 2.0 {
didSet {
updateMargins()
}
}
@IBInspectable open var maxCircles: Int = 3 {
didSet {
layoutIfNeeded()
}
}
/// If `true` avatars with initials instead of images will be filtered out if possible
@IBInspectable open var preferImageAvatars = false {
didSet {
layoutIfNeeded()
}
}
fileprivate var avatars = [AvatarPresentable]()
fileprivate var avatarViews = [AvatarView]()
fileprivate var plusAvatar = AvatarView()
fileprivate let stackView = UIStackView()
// MARK: - Initialization
override public init(frame: CGRect) {
super.init(frame: frame)
setUpViews()
}
required public init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
setUpViews()
}
}
//MARK: - Public
extension AvatarLineView {
open func update(with avatars: [AvatarPresentable]) {
if self.avatars.count == avatars.count {
let combined = zip(self.avatars, avatars)
let identical = combined.reduce(true) { result, pair in result && pair.0.isIdentical(to: pair.1) }
if identical {
return
}
}
self.avatars = avatars
updateAvatars()
}
}
private extension AvatarLineView {
func setUpViews() {
backgroundColor = .clear
clipsToBounds = true
translatesAutoresizingMaskIntoConstraints = false
stackView.translatesAutoresizingMaskIntoConstraints = false
stackView.axis = .horizontal
stackView.distribution = .fillEqually
stackView.alignment = .fill
stackView.spacing = -overlap
addSubview(stackView)
updateAllConstraints()
updateMargins()
updateAvatars()
}
func updateAvatars() {
if !avatarViews.isEmpty {
avatarViews.forEach { $0.removeFromSuperview() }
avatarViews.removeAll()
}
if avatars.isEmpty {
addAvatar(for: nil)
} else {
for (index, avatar) in avatars.enumerated() {
if avatars.count > maxCircles && index >= maxCircles - 1 {
let remaining = avatars.count - index
addAvatar(for: nil, text: "+\(remaining)")
break
} else {
addAvatar(for: avatar)
}
}
}
}
func addAvatar(for person: AvatarPresentable?, text: String? = nil) {
let avatarView = AvatarView()
setUpAvatarView(avatarView)
if let person = person {
avatarView.update(with: person)
} else {
avatarView.reset()
avatarView.initials = text
}
stackView.addArrangedSubview(avatarView)
self.avatarViews.append(avatarView)
}
func updateAllConstraints() {
addConstraint(leadingAnchor.constraint(equalTo: stackView.leadingAnchor))
addConstraint(topAnchor.constraint(equalTo: stackView.topAnchor))
addConstraint(bottomAnchor.constraint(equalTo: stackView.bottomAnchor))
addConstraint(trailingAnchor.constraint(equalTo: stackView.trailingAnchor))
}
func setUpAvatarView(_ avatarView: AvatarView) {
avatarView.addConstraint(avatarView.widthAnchor.constraint(equalTo: avatarView.heightAnchor))
avatarView.borderColor = avatarBorderColor
avatarView.innerColor = innerColor
avatarView.textColor = textColor
avatarView.spacingColor = spacingColor
avatarView.borderWidth = avatarBorderWidth
avatarView.fontName = fontName
avatarView.fontSize = fontSize
avatarView.outerMargin = spacing
}
func updateBorders() {
avatarViews.forEach { $0.layer.borderWidth = avatarBorderWidth }
}
func updateColors() {
avatarViews.forEach { avatarView in
avatarView.borderColor = avatarBorderColor
avatarView.innerColor = innerColor
avatarView.textColor = textColor
avatarView.spacingColor = spacingColor
}
}
func updateMargins() {
avatarViews.forEach { $0.outerMargin = spacing }
}
}
|
mit
|
0dd6fe7e9b7cb547e4ef749e2a91dbff
| 26.690476 | 132 | 0.569218 | 5.060923 | false | false | false | false |
AckeeCZ/ACKategories
|
ACKategoriesExample/Screens/UIControl blocks/UIControlBlocksViewController.swift
|
1
|
1398
|
//
// UIControlBlocksViewController.swift
// ACKategories
//
// Created by Jakub Olejník on 12/09/2018.
// Copyright © 2018 Ackee, s.r.o. All rights reserved.
//
import UIKit
import ACKategories
final class UIControlBlocksViewController: BaseViewControllerNoVM {
private weak var button: UIButton!
// MARK: View life cycle
override func loadView() {
super.loadView()
view.backgroundColor = .white
let button = UIButton(type: .system)
button.setTitle("Tap here!", for: .normal)
if #available(iOS 13.0, *) {
button.setBackgroundImage(UIColor.systemGray6.image(), for: .normal)
}
view.addSubview(button)
button.translatesAutoresizingMaskIntoConstraints = false
NSLayoutConstraint.activate([
button.centerXAnchor.constraint(equalTo: view.centerXAnchor),
button.centerYAnchor.constraint(equalTo: view.centerYAnchor)
])
self.button = button
}
override func viewDidLoad() {
super.viewDidLoad()
button.on(.touchUpInside) { [unowned self] _ in
let alertVC = UIAlertController(title: "Button", message: "Tapped!", preferredStyle: .alert)
let okAction = UIAlertAction(title: "OK", style: .default)
alertVC.addAction(okAction)
self.present(alertVC, animated: true)
}
}
}
|
mit
|
24a7234209a351870461e56638951bdf
| 26.372549 | 104 | 0.64255 | 4.607261 | false | false | false | false |
takeshineshiro/Eureka
|
Source/Controllers.swift
|
4
|
6194
|
// Controllers.swift
// Eureka ( https://github.com/xmartlabs/Eureka )
//
// Copyright (c) 2015 Xmartlabs ( http://xmartlabs.com )
//
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import Foundation
import UIKit
public class SelectorViewController<T:Equatable> : FormViewController, TypedRowControllerType {
public var row: RowOf<T>!
public var completionCallback : ((UIViewController) -> ())?
override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: NSBundle?) {
super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil)
}
required public init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
convenience public init(_ callback: (UIViewController) -> ()){
self.init()
completionCallback = callback
}
public override func viewDidLoad() {
super.viewDidLoad()
guard let options = row.dataProvider?.arrayData else { return }
form +++= Section()
for o in options {
form.first! <<< CheckRow(){ [weak self] in
$0.title = self?.row.displayValueFor?(o)
$0.value = self?.row.value == o
}
.onCellSelection { [weak self] _, _ in
self?.row.value = o
self?.completionCallback?(self!)
}
}
form.first?.header = HeaderFooterView<UITableViewHeaderFooterView>(title: row.title)
}
}
public class MultipleSelectorViewController<T:Hashable> : FormViewController, TypedRowControllerType {
public var row: RowOf<Set<T>>!
public var completionCallback : ((UIViewController) -> ())?
override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: NSBundle?) {
super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil)
}
required public init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
convenience public init(_ callback: (UIViewController) -> ()){
self.init()
completionCallback = callback
}
public override func viewDidLoad() {
super.viewDidLoad()
guard let options = row.dataProvider?.arrayData else { return }
form +++= Section()
for o in options {
form.first! <<< CheckRow() { [weak self] in
$0.title = String(o.first!)
$0.value = self?.row.value?.contains(o.first!) ?? false
}
.onCellSelection { [weak self] _, _ in
guard let set = self?.row.value else {
self?.row.value = [o.first!]
return
}
if set.contains(o.first!) {
self?.row.value!.remove(o.first!)
}
else{
self?.row.value!.insert(o.first!)
}
}
}
form.first?.header = HeaderFooterView<UITableViewHeaderFooterView>(title: row.title)
}
}
public class SelectorAlertController<T: Equatable> : UIAlertController, TypedRowControllerType {
public var row: RowOf<T>!
public var completionCallback : ((UIViewController) -> ())?
override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: NSBundle?) {
super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil)
}
required public init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
convenience public init(_ callback: (UIViewController) -> ()){
self.init()
completionCallback = callback
}
public override func viewDidLoad() {
super.viewDidLoad()
guard let options = row.dataProvider?.arrayData else { return }
addAction(UIAlertAction(title: "Cancel", style: .Cancel, handler: nil))
for option in options {
addAction(UIAlertAction(title: row.displayValueFor?(option), style: .Default, handler: { [weak self] _ in
self?.row.value = option
self?.completionCallback?(self!)
}))
}
}
}
public class ImagePickerController : UIImagePickerController, TypedRowControllerType, UIImagePickerControllerDelegate, UINavigationControllerDelegate {
public var row: RowOf<UIImage>!
public var completionCallback : ((UIViewController) -> ())?
public override func viewDidLoad() {
super.viewDidLoad()
delegate = self
}
public func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : AnyObject]){
row.value = info[UIImagePickerControllerOriginalImage] as? UIImage
completionCallback?(self)
}
public func imagePickerControllerDidCancel(picker: UIImagePickerController){
completionCallback?(self)
}
}
|
mit
|
4dc7971f090b4cc13fc5370c0ab7338f
| 37.234568 | 151 | 0.600097 | 5.404887 | false | false | false | false |
MukeshKumarS/Swift
|
test/SILGen/if_expr.swift
|
1
|
1515
|
// RUN: %target-swift-frontend -emit-silgen %s | FileCheck %s
func fizzbuzz(i: Int) -> String {
return i % 3 == 0
? "fizz"
: i % 5 == 0
? "buzz"
: "\(i)"
// CHECK: cond_br {{%.*}}, [[OUTER_TRUE:bb[0-9]+]], [[OUTER_FALSE:bb[0-9]+]]
// CHECK: [[OUTER_TRUE]]:
// CHECK: br [[OUTER_CONT:bb[0-9]+]]
// CHECK: [[OUTER_FALSE]]:
// CHECK: cond_br {{%.*}}, [[INNER_TRUE:bb[0-9]+]], [[INNER_FALSE:bb[0-9]+]]
// CHECK: [[INNER_TRUE]]:
// CHECK: br [[INNER_CONT:bb[0-9]+]]
// CHECK: [[INNER_FALSE]]:
// CHECK: function_ref {{.*}}stringInterpolation
// CHECK: br [[INNER_CONT]]
// CHECK: [[INNER_CONT]]({{.*}}):
// CHECK: br [[OUTER_CONT]]
// CHECK: [[OUTER_CONT]]({{.*}}):
// CHECK: return
}
protocol AddressOnly {}
struct A : AddressOnly {}
struct B : AddressOnly {}
func consumeAddressOnly(_: AddressOnly) {}
// CHECK: sil hidden @_TF7if_expr19addr_only_ternary_1
func addr_only_ternary_1(x: Bool) -> AddressOnly {
// CHECK: bb0([[RET:%.*]] : $*AddressOnly, {{.*}}):
// CHECK: [[a:%[0-9]+]] = alloc_box $AddressOnly, var, name "a"
var a : AddressOnly = A()
// CHECK: [[b:%[0-9]+]] = alloc_box $AddressOnly, var, name "b"
var b : AddressOnly = B()
// CHECK: cond_br {{%.*}}, [[TRUE:bb[0-9]+]], [[FALSE:bb[0-9]+]]
// CHECK: [[TRUE]]:
// CHECK: copy_addr [[a]]#1 to [initialization] [[RET]]
// CHECK: br [[CONT:bb[0-9]+]]
// CHECK: [[FALSE]]:
// CHECK: copy_addr [[b]]#1 to [initialization] [[RET]]
// CHECK: br [[CONT]]
return x ? a : b
}
|
apache-2.0
|
3b22fa2965066319f0fa456950f8bbdb
| 30.5625 | 78 | 0.531353 | 3.03 | false | false | false | false |
wireapp/wire-ios
|
Wire-iOS Tests/NetworkStatusView/NetworkStatusViewTests.swift
|
1
|
2982
|
//
// Wire
// Copyright (C) 2017 Wire Swiss GmbH
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see http://www.gnu.org/licenses/.
//
import Foundation
import XCTest
@testable import Wire
class MockContainer: NetworkStatusViewDelegate {
var shouldAnimateNetworkStatusView: Bool = true
var bottomMargin: CGFloat = 0
func didChangeHeight(_ networkStatusView: NetworkStatusView, animated: Bool, state: NetworkStatusViewState) {
}
}
final class NetworkStatusViewTests: XCTestCase {
var sut: NetworkStatusView!
var mockApplication: MockApplication!
var mockContainer: MockContainer!
override func setUp() {
super.setUp()
mockApplication = MockApplication()
mockContainer = MockContainer()
sut = NetworkStatusView(application: mockApplication)
sut.delegate = mockContainer
}
override func tearDown() {
sut = nil
mockApplication = nil
mockContainer = nil
super.tearDown()
}
func testThatSyncBarChangesToHiddenWhenTheAppGoesToBackground() {
// GIVEN
mockApplication.applicationState = .active
sut.state = .onlineSynchronizing
XCTAssertEqual(sut.connectingView.heightConstraint.constant, CGFloat.SyncBar.height, "NetworkStatusView should not be zero height")
// WHEN
mockApplication.applicationState = .background
sut.state = .onlineSynchronizing
// THEN
XCTAssertEqual(sut.connectingView.heightConstraint.constant, 0, "NetworkStatusView should be zero height")
}
}
final class NetworkStatusViewSnapShotTests: ZMSnapshotTestCase {
var sut: NetworkStatusView!
var mockContainer: MockContainer!
override func setUp() {
super.setUp()
accentColor = .violet
mockContainer = MockContainer()
sut = NetworkStatusView()
sut.delegate = mockContainer
}
override func tearDown() {
sut = nil
mockContainer = nil
super.tearDown()
}
func testOfflineExpandedState() {
// GIVEN
sut.state = .offlineExpanded
// WHEN && THEN
verifyInAllPhoneWidths(view: sut)
}
func testOnlineSynchronizing() {
// GIVEN
sut.state = .onlineSynchronizing
sut.layer.speed = 0 // freeze animations for deterministic tests
// WHEN && THEN
verifyInAllPhoneWidths(view: sut)
}
}
|
gpl-3.0
|
ce13edaf03e5024b9e277e6349fbd523
| 27.673077 | 139 | 0.685111 | 4.786517 | false | true | false | false |
LYM-mg/MGDYZB
|
MGDYZB/MGDYZB/Class/Main/Controller/BaseViewController.swift
|
1
|
1714
|
//
// BaseViewController.swift
// MGDYZB
//
// Created by ming on 16/10/26.
// Copyright © 2016年 ming. All rights reserved.
//
import UIKit
class BaseViewController: UIViewController {
// MARK: 定义属性
var contentView : UIView?
// MARK: 懒加载属性
fileprivate lazy var animImageView : UIImageView = { [unowned self] in
let imageView = UIImageView(image: UIImage(named: "img_loading_1"))
imageView.contentMode = UIViewContentMode.scaleAspectFill
imageView.center = self.view.center
imageView.animationImages = [UIImage(named : "img_loading_1")!, UIImage(named : "img_loading_2")!]
imageView.animationDuration = 0.5
imageView.animationRepeatCount = LONG_MAX
imageView.autoresizingMask = [.flexibleTopMargin, .flexibleBottomMargin]
return imageView
}()
// MARK: 系统回调
override func viewDidLoad() {
super.viewDidLoad()
setUpMainView()
}
}
// MARK: - 设置UI
extension BaseViewController {
func setUpMainView() {
// 1.隐藏内容的View
contentView?.isHidden = true
// 2.添加执行动画的UIImageView
view.addSubview(animImageView)
// 3.给animImageView执行动画
animImageView.startAnimating()
// 4.设置view的背景颜色
view.backgroundColor = UIColor(r: 250, g: 250, b: 250)
}
func loadDataFinished() {
// 1.停止动画
animImageView.stopAnimating()
// 2.隐藏animImageView
animImageView.isHidden = true
// 3.显示内容的View
contentView?.isHidden = false
}
}
|
mit
|
5293e46acd2ad0240534643efa3356bc
| 24.983871 | 106 | 0.61018 | 4.72434 | false | false | false | false |
minimoog/MetalToy
|
MetalToy/ShaderDocument.swift
|
1
|
1640
|
//
// ShaderDocument.swift
// MetalToy
//
// Created by minimoog on 1/22/18.
// Copyright © 2018 Toni Jovanoski. All rights reserved.
//
import UIKit
class ShaderDocument: UIDocument {
var shaderInfo: ShaderInfo?
override init(fileURL url: URL) {
super.init(fileURL: url)
}
init() {
let tempDir = FileManager.default.temporaryDirectory
let url = tempDir.appendingPathComponent("MyShader.shader")
shaderInfo = ShaderInfo()
super.init(fileURL: url)
}
func getTextures() -> [String] {
if let shaderInfo = shaderInfo {
let path = Bundle.main.resourcePath!
let textures: [String] = shaderInfo.textures.map {
if $0 == "NULL" {
return "NULL"
} else {
return path + "/" + $0
}
}
return textures
}
return [String](repeating: "NULL", count: 4)
}
override func contents(forType typeName: String) throws -> Any {
if let shaderInfo = shaderInfo {
guard let jsonData = encodeToJsonData(shaderInfo: shaderInfo) else { return Data() }
return jsonData as Any
}
return Data()
}
override func load(fromContents contents: Any, ofType typeName: String?) throws {
guard let data = contents as? Data else {
fatalError("\(contents) is not an instance of Data")
}
shaderInfo = decodeFromJsonData(data: data)
}
}
|
mit
|
6fe5eaa465f080d158edb7d515216fef
| 25.015873 | 96 | 0.530201 | 4.778426 | false | false | false | false |
halo/biosphere
|
Biosphere/Support/Log.swift
|
1
|
1103
|
import os.log
import Foundation
public struct Log {
private static let log = OSLog(subsystem: BundleIdentifier.string, category: "logger")
public static func debug(_ message: String, callerPath: String = #file) {
write(message, level: .debug, callerPath: callerPath)
}
public static func info(_ message: String, callerPath: String = #file) {
write(message, level: .info, callerPath: callerPath)
}
public static func error(_ message: String, callerPath: String = #file) {
write(message, level: .error, callerPath: callerPath)
}
private static func write(_ message: String, level: OSLogType, callerPath: String) {
guard let filename = callerPath.components(separatedBy: "/").last else {
return write(message, level: level)
}
guard let classname = filename.components(separatedBy: ".").first else {
return write(message, level: level)
}
write("\(classname) - \(message)", level: level)
}
private static func write(_ message: String, level: OSLogType) {
os_log("%{public}@", log: log, type: level, message)
}
}
|
mit
|
f75341cf015a5e6294f072e5fcd51698
| 31.441176 | 88 | 0.671804 | 4.226054 | false | false | false | false |
SwiftGen/StencilSwiftKit
|
Tests/StencilSwiftKitTests/CallNodeTests.swift
|
1
|
4330
|
//
// StencilSwiftKit UnitTests
// Copyright © 2022 SwiftGen
// MIT Licence
//
@testable import Stencil
@testable import StencilSwiftKit
import XCTest
final class CallNodeTests: XCTestCase {
func testParser() {
let tokens: [Token] = [
.block(value: "call myFunc", at: .unknown)
]
let parser = TokenParser(tokens: tokens, environment: stencilSwiftEnvironment())
guard let nodes = try? parser.parse(),
let node = nodes.first as? CallNode else {
XCTFail("Unable to parse tokens")
return
}
XCTAssertEqual(node.variable.variable, "myFunc")
XCTAssertEqual(node.arguments.count, 0)
}
func testParserWithArgumentsVariable() {
let tokens: [Token] = [
.block(value: "call myFunc a b c", at: .unknown)
]
let parser = TokenParser(tokens: tokens, environment: stencilSwiftEnvironment())
guard let nodes = try? parser.parse(),
let node = nodes.first as? CallNode else {
XCTFail("Unable to parse tokens")
return
}
XCTAssertEqual(node.variable.variable, "myFunc")
let variables = node.arguments.compactMap { $0 as? FilterExpression }.compactMap { $0.variable }
XCTAssertEqual(variables, [Variable("a"), Variable("b"), Variable("c")])
}
func testParserWithArgumentsRange() throws {
let token: Token = .block(value: "call myFunc 1...3 5...7 9...a", at: .unknown)
let tokens = [token]
let parser = TokenParser(tokens: tokens, environment: stencilSwiftEnvironment())
guard let nodes = try? parser.parse(),
let node = nodes.first as? CallNode else {
XCTFail("Unable to parse tokens")
return
}
XCTAssertEqual(node.variable.variable, "myFunc")
let variables = node.arguments.compactMap { $0 as? RangeVariable }
XCTAssertEqual(variables.count, 3) // RangeVariable isn't equatable
}
func testParserFail() {
do {
let tokens: [Token] = [
.block(value: "call", at: .unknown)
]
let parser = TokenParser(tokens: tokens, environment: stencilSwiftEnvironment())
XCTAssertThrowsError(try parser.parse())
}
}
func testRender() throws {
let block = CallableBlock(parameters: [], nodes: [TextNode(text: "hello")])
let context = Context(dictionary: ["myFunc": block])
let node = CallNode(variable: Variable("myFunc"), arguments: [])
let output = try node.render(context)
XCTAssertEqual(output, "hello")
}
func testRenderFail() {
let context = Context(dictionary: [:])
let node = CallNode(variable: Variable("myFunc"), arguments: [])
XCTAssertThrowsError(try node.render(context))
}
func testRenderWithParameters() throws {
let block = CallableBlock(
parameters: ["a", "b", "c"],
nodes: [
TextNode(text: "variables: "),
VariableNode(variable: "a"),
VariableNode(variable: "b"),
VariableNode(variable: "c")
]
)
let context = Context(dictionary: ["myFunc": block])
let node = CallNode(
variable: Variable("myFunc"),
arguments: [
Variable("\"hello\""),
Variable("\"world\""),
Variable("\"test\"")
]
)
let output = try node.render(context)
XCTAssertEqual(output, "variables: helloworldtest")
}
func testRenderWithParametersFail() {
let block = CallableBlock(
parameters: ["a", "b", "c"],
nodes: [
TextNode(text: "variables: "),
VariableNode(variable: "a"),
VariableNode(variable: "b"),
VariableNode(variable: "c")
]
)
let context = Context(dictionary: ["myFunc": block])
// must pass arguments
do {
let node = CallNode(variable: Variable("myFunc"), arguments: [])
XCTAssertThrowsError(try node.render(context))
}
// not enough arguments
do {
let node = CallNode(
variable: Variable("myFunc"),
arguments: [
Variable("\"hello\"")
]
)
XCTAssertThrowsError(try node.render(context))
}
// too many arguments
do {
let node = CallNode(
variable: Variable("myFunc"),
arguments: [
Variable("\"hello\""),
Variable("\"world\""),
Variable("\"test\""),
Variable("\"test\"")
]
)
XCTAssertThrowsError(try node.render(context))
}
}
}
|
mit
|
5a15f7a8725bb5a34bac719e0246a0f8
| 26.929032 | 100 | 0.61423 | 4.307463 | false | true | false | false |
wireapp/wire-ios
|
Wire-iOS/Sources/UserInterface/UserProfile/Devices/UserClientListViewController.swift
|
1
|
6375
|
//
// 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 UIKit
import WireSyncEngine
final class UserClientListViewController: UIViewController, UICollectionViewDelegateFlowLayout, UICollectionViewDataSource {
fileprivate let headerView: ParticipantDeviceHeaderView
fileprivate let collectionView = UICollectionView(forGroupedSections: ())
fileprivate var clients: [UserClientType]
fileprivate var tokens: [Any?] = []
fileprivate var user: UserType
override var supportedInterfaceOrientations: UIInterfaceOrientationMask {
return wr_supportedInterfaceOrientations
}
override var preferredStatusBarStyle: UIStatusBarStyle {
return ColorScheme.default.statusBarStyle
}
init(user: UserType) {
self.user = user
self.clients = UserClientListViewController.clientsSortedByRelevance(for: user)
self.headerView = ParticipantDeviceHeaderView(userName: user.name ?? "")
super.init(nibName: nil, bundle: nil)
if let userSession = ZMUserSession.shared() {
tokens.append(UserChangeInfo.add(observer: self, for: user, in: userSession))
}
self.headerView.delegate = self
title = "profile.devices.title".localized
}
@available(*, unavailable)
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func viewDidLoad() {
super.viewDidLoad()
setupViews()
createConstraints()
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
(user as? ZMUser)?.fetchUserClients()
}
private func setupViews() {
headerView.translatesAutoresizingMaskIntoConstraints = false
headerView.showUnencryptedLabel = (user as? ZMUser)?.clients.count == 0
collectionView.translatesAutoresizingMaskIntoConstraints = false
collectionView.delegate = self
collectionView.dataSource = self
UserClientCell.register(in: collectionView)
collectionView.register(CollectionViewCellAdapter.self, forSupplementaryViewOfKind: UICollectionView.elementKindSectionHeader, withReuseIdentifier: CollectionViewCellAdapter.zm_reuseIdentifier)
view.addSubview(collectionView)
view.backgroundColor = SemanticColors.View.backgroundDefault
}
private func createConstraints() {
NSLayoutConstraint.activate([
collectionView.topAnchor.constraint(equalTo: view.topAnchor),
collectionView.leadingAnchor.constraint(equalTo: view.leadingAnchor),
collectionView.trailingAnchor.constraint(equalTo: view.trailingAnchor),
collectionView.bottomAnchor.constraint(equalTo: view.bottomAnchor)
])
}
fileprivate static func clientsSortedByRelevance(for user: UserType) -> [UserClientType] {
return user.allClients.sortedByRelevance().filter({ !$0.isSelfClient() })
}
// MARK: - UICollectionViewDelegateFlowLayout & UICollectionViewDataSource
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForHeaderInSection section: Int) -> CGSize {
headerView.size(fittingWidth: collectionView.bounds.size.width)
return headerView.bounds.size
}
func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView {
let headerViewCell = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: CollectionViewCellAdapter.zm_reuseIdentifier, for: indexPath) as! CollectionViewCellAdapter
headerViewCell.wrappedView = headerView
return headerViewCell
}
func numberOfSections(in collectionView: UICollectionView) -> Int {
return 1
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return clients.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(ofType: UserClientCell.self, for: indexPath)
let client = clients[indexPath.row]
cell.configure(with: client)
return cell
}
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
let client = clients[indexPath.row]
let profileClientViewController = ProfileClientViewController(client: client as! UserClient, fromConversation: true) // TODO jacob don't force unwrap
profileClientViewController.showBackButton = false
show(profileClientViewController, sender: nil)
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
return .init(width: view.bounds.size.width, height: 64)
}
}
extension UserClientListViewController: ZMUserObserver {
func userDidChange(_ changeInfo: UserChangeInfo) {
guard changeInfo.clientsChanged || changeInfo.trustLevelChanged else { return }
// TODO: add clients to userType
headerView.showUnencryptedLabel = (user as? ZMUser)?.clients.isEmpty == true
clients = UserClientListViewController.clientsSortedByRelevance(for: user)
collectionView.reloadData()
}
}
extension UserClientListViewController: ParticipantDeviceHeaderViewDelegate {
func participantsDeviceHeaderViewDidTapLearnMore(_ headerView: ParticipantDeviceHeaderView) {
URL.wr_fingerprintLearnMore.openInApp(above: self)
}
}
|
gpl-3.0
|
014716d2f5f78d5d7622fd2d23488a53
| 38.110429 | 203 | 0.736784 | 5.557977 | false | false | false | false |
wireapp/wire-ios
|
Wire-iOS/Sources/UserInterface/Components/KeyboardAvoidingViewController.swift
|
1
|
5612
|
//
// Wire
// Copyright (C) 2020 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 UIKit
class KeyboardAvoidingViewController: UIViewController, SpinnerCapable {
// MARK: SpinnerCapable
var dismissSpinner: SpinnerCompletion?
let viewController: UIViewController
var disabledWhenInsidePopover: Bool = false
private var animator: UIViewPropertyAnimator?
private var bottomEdgeConstraint: NSLayoutConstraint?
private var topEdgeConstraint: NSLayoutConstraint?
required init(viewController: UIViewController) {
self.viewController = viewController
super.init(nibName: nil, bundle: nil)
NotificationCenter.default.addObserver(self,
selector: #selector(keyboardFrameWillChange),
name: UIWindow.keyboardWillChangeFrameNotification,
object: nil)
}
@available(*, unavailable)
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override var shouldAutorotate: Bool {
return viewController.shouldAutorotate
}
override var supportedInterfaceOrientations: UIInterfaceOrientationMask {
return viewController.supportedInterfaceOrientations
}
override var navigationItem: UINavigationItem {
return viewController.navigationItem
}
override var childForStatusBarStyle: UIViewController? {
return viewController
}
override var childForStatusBarHidden: UIViewController? {
return viewController
}
override var title: String? {
get {
return viewController.title
}
set {
viewController.title = newValue
}
}
override func viewDidLoad() {
super.viewDidLoad()
view.isOpaque = false
addChild(viewController)
view.addSubview(viewController.view)
view.backgroundColor = viewController.view.backgroundColor
viewController.view.translatesAutoresizingMaskIntoConstraints = false
viewController.didMove(toParent: self)
createInitialConstraints()
}
private func createInitialConstraints() {
NSLayoutConstraint.activate([
viewController.view.leadingAnchor.constraint(equalTo: view.leadingAnchor),
viewController.view.trailingAnchor.constraint(equalTo: view.trailingAnchor),
viewController.view.topAnchor.constraint(equalTo: view.topAnchor)
])
topEdgeConstraint = viewController.view.topAnchor.constraint(equalTo: view.topAnchor)
topEdgeConstraint?.isActive = true
bottomEdgeConstraint = viewController.view.safeAreaLayoutGuide.bottomAnchor.constraint(equalTo: view.safeAreaLayoutGuide.bottomAnchor, constant: 0)
bottomEdgeConstraint?.isActive = true
}
@objc
private func keyboardFrameWillChange(_ notification: Notification?) {
guard let bottomEdgeConstraint = bottomEdgeConstraint else { return }
guard !disabledWhenInsidePopover || !isInsidePopover else {
bottomEdgeConstraint.constant = 0
view.layoutIfNeeded()
return
}
guard let userInfo = notification?.userInfo,
let duration = userInfo[UIResponder.keyboardAnimationDurationUserInfoKey] as? TimeInterval
else { return }
let keyboardFrameInView = UIView.keyboardFrame(in: self.view, forKeyboardNotification: notification)
var bottomOffset: CGFloat
// The keyboard frame includes the safe area so we need to substract it since the bottomEdgeConstraint is attached to the safe area.
bottomOffset = -keyboardFrameInView.intersection(view.safeAreaLayoutGuide.layoutFrame).height
// When the keyboard is visible &
// this controller's view is presented at a form sheet style on iPad, the view is has a top offset and the bottomOffset should be reduced.
if !keyboardFrameInView.origin.y.isInfinite,
modalPresentationStyle == .formSheet,
let frame = presentationController?.frameOfPresentedViewInContainerView {
// TODO: no need to add when no keyboard
bottomOffset += frame.minY
}
guard bottomEdgeConstraint.constant != bottomOffset else { return }
// When the keyboard is dismissed and then quickly revealed again, then
// the dismiss animation will be cancelled.
animator?.stopAnimation(true)
view.layoutIfNeeded()
animator = UIViewPropertyAnimator(duration: duration, timingParameters: UISpringTimingParameters())
animator?.addAnimations {
bottomEdgeConstraint.constant = bottomOffset
self.view.layoutIfNeeded()
}
animator?.addCompletion { [weak self] _ in
self?.animator = nil
}
animator?.startAnimation()
}
}
|
gpl-3.0
|
69beb2f1bda1d14ff640f24102323118
| 34.974359 | 155 | 0.687277 | 5.894958 | false | false | false | false |
TriforkKRK/TFFoundation
|
TFFoundation/Concurrency/AsynchronousOperation.swift
|
1
|
2639
|
//
// MIT License
//
// Copyright (c) 2017 Trifork Kraków Office
//
// 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
/// Base class for asynchronous `NSOperation`s. Handles thread-safe execution state management.
open class AsynchronousOperation: Operation {
private enum State {
case idle
case executing
case finished
}
private var state: State = .idle {
willSet {
willChangeValue(forKey: "isExecuting")
willChangeValue(forKey: "isFinished")
}
didSet {
didChangeValue(forKey: "isFinished")
didChangeValue(forKey: "isExecuting")
}
}
private var stateSynchronized: State {
get { return synchronized { self.state } }
set { synchronized { self.state = newValue } }
}
override public final var isExecuting: Bool { return stateSynchronized == .executing }
override public final var isFinished: Bool { return stateSynchronized == .finished }
override public final var isAsynchronous: Bool { return true }
override public final func start() {
guard isCancelled == false else {
markFinished()
return
}
stateSynchronized = .executing
didStart()
}
/// To be overridden in subclasses, invoked after operation is successfully started.
open func didStart() {
fatalError("Template method. Must be overriden")
}
/// Called to mark execution as finished.
public final func markFinished() { stateSynchronized = .finished }
}
|
mit
|
be2b221c45aa2032a58bc4bc5ec382e3
| 35.136986 | 95 | 0.683093 | 5.024762 | false | false | false | false |
cuba/NetworkKit
|
Example/NetworkKitTests/EncodingTests.swift
|
1
|
2139
|
//
// TestEncoding.swift
// NetworkKitTests
//
// Created by Jacob Sikorski on 2019-04-13.
// Copyright © 2019 Jacob Sikorski. All rights reserved.
//
import XCTest
@testable import Example
@testable import NetworkKit
class EncodingTests: XCTestCase {
func testAddDataToRequest() {
// Given
let myData = Data(count: 0)
var request = BasicRequest(method: .post, path: "/users")
request.httpBody = myData
XCTAssertNotNil(request.httpBody)
}
func testEncodeJsonString() {
// Given
let jsonString = """
{
"name": "Jim Halpert"
}
"""
// Example
var request = BasicRequest(method: .post, path: "/users")
request.setHTTPBody(string: jsonString, encoding: .utf8)
XCTAssertNotNil(request.httpBody)
}
func testEncodeJsonObject() {
do {
let jsonObject: [String: Any?] = [
"id": "123",
"name": "Kevin Malone"
]
var request = BasicRequest(method: .post, path: "/users")
try request.setHTTPBody(jsonObject: jsonObject)
XCTAssertNotNil(request.httpBody)
} catch {
XCTFail("Should not throw")
}
}
func testEncodeEncodable() {
let myCodable = Post(id: 123, userId: 123, title: "Some post", body: "Lorem ipsum ...")
do {
var request = BasicRequest(method: .post, path: "/posts")
try request.setJSONBody(encodable: myCodable)
XCTAssertNotNil(request.httpBody)
} catch {
XCTFail("Should not throw")
}
}
func testEncodeMapEncodable() {
let mappable = MapCodablePost(id: 123, userId: 123, title: "Some post", body: "Lorem ipsum ...")
var request = BasicRequest(method: .post, path: "/posts")
do {
try request.setJSONBody(mapEncodable: mappable)
XCTAssertNotNil(request.httpBody)
} catch {
XCTFail("Should not throw")
}
}
}
|
mit
|
b54e093283adc68af3753e1810fe945a
| 26.766234 | 104 | 0.546305 | 4.647826 | false | true | false | false |
Tombio/Trafalert
|
iOS Client/Trafalert/WeatherStationAnnotation.swift
|
1
|
679
|
//
// WeatherStationOverlay.swift
// Trafalert
//
// Created by Tomi Lahtinen on 29/01/16.
// Copyright © 2016 Tomi Lahtinen. All rights reserved.
//
import Foundation
import MapKit
class WeatherStationAnnotation: NSObject, MKAnnotation {
var title: String?
var subtitle: String?
var stationName: String
var active: Bool
var coordinate: CLLocationCoordinate2D
init(title: String, subtitle: String, stationName: String, active: Bool, coord: CLLocationCoordinate2D) {
self.title = title
self.subtitle = subtitle
self.stationName = stationName
self.active = active
self.coordinate = coord
}
}
|
mit
|
acffe2b2b1f7b36b304d504f0852a666
| 23.25 | 109 | 0.678466 | 4.374194 | false | false | false | false |
ffittschen/hackaTUM
|
MachtSpass/AppCoordinator.swift
|
1
|
1620
|
//
// AppCoordinator.swift
// MachtSpass
//
// Created by Florian Fittschen on 11/11/2016.
// Copyright © 2016 BaconLove. All rights reserved.
//
import Foundation
import UIKit
import RxSwift
import Hue
import RxMoya
import Moya
import Freddy
/**
Object that bosses one or more view controllers around by taking all of the driving logic
out of the view controllers, and moving that stuff one layer up.
- note:
Adapted from: [Coordinators Redux](http://khanlou.com/2015/10/coordinators-redux/)
*/
protocol Coordinator {
/// Start the work of the `Coordinator`.
func start()
}
// Coordinates Main Tab Navigation
class AppCoordinator: NSObject, Coordinator {
fileprivate let disposeBag: DisposeBag
fileprivate let homeTabCoordinator: HomeTabCoordinator
fileprivate let scannerTabCoordinator: QRScannerTabViewCoordinator
private var tabBarController: UITabBarController
private var tabs: [TabCoordinator]
required init(tabBarController: UITabBarController) {
self.tabBarController = tabBarController
self.tabBarController.tabBar.tintColor = UIColor(hex: "df0000")
disposeBag = DisposeBag()
homeTabCoordinator = HomeTabCoordinator()
scannerTabCoordinator = QRScannerTabViewCoordinator()
tabs = [scannerTabCoordinator, homeTabCoordinator]
super.init()
}
func start() {
tabBarController.viewControllers = tabs.map() { coordinator -> UIViewController in
return coordinator.navigationController
}
tabs.forEach() { $0.start() }
}
}
|
mit
|
6bde636a78abec722794bf3e86459794
| 26.440678 | 90 | 0.703521 | 4.804154 | false | false | false | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.