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 |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
wireapp/wire-ios-data-model | Tests/Source/Model/Conversation/ConversationCreationOptionsTests.swift | 1 | 1520 | //
// Wire
// Copyright (C) 2018 Wire Swiss GmbH
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see http://www.gnu.org/licenses/.
//
import Foundation
import XCTest
@testable import WireDataModel
class ConversationCreationOptionsTests: ZMConversationTestsBase {
func testThatItCreatesTheConversationWithOptions() {
// given
let user = self.createUser()
let name = "Test Conversation In Swift"
let team = Team.insertNewObject(in: self.uiMOC)
let options = ConversationCreationOptions(participants: [user], name: name, team: team, allowGuests: true)
// when
let conversation = self.coreDataStack.insertGroup(with: options)
// then
XCTAssertEqual(conversation.displayName, name)
XCTAssertEqual(conversation.localParticipants, Set([user, .selfUser(in: uiMOC)]))
XCTAssertEqual(conversation.team, team)
XCTAssertEqual(conversation.allowGuests, true)
}
}
| gpl-3.0 | 3462fd5f6626dae1a63a2c00a7435874 | 37.974359 | 114 | 0.723026 | 4.676923 | false | true | false | false |
wireapp/wire-ios-data-model | Source/Model/Conversation/ZMConversation+Timestamps.swift | 1 | 15094 | //
// Wire
// Copyright (C) 2018 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
fileprivate extension ZMConversationMessage {
var serverTimestampIncludingChildMessages: Date? {
if let systemMessage = self as? ZMSystemMessage {
return systemMessage.lastChildMessageDate
}
return serverTimestamp
}
}
fileprivate extension ZMMessage {
static func isVisible(_ message: ZMMessage) -> Bool {
if let systemMessage = message as? ZMSystemMessage, let parentMessage = systemMessage.parentMessage as? ZMMessage {
return parentMessage.visibleInConversation != nil
} else {
return message.visibleInConversation != nil
}
}
}
extension ZMConversation {
// MARK: - Timestamps
func updatePendingLastRead(_ timestamp: Date) {
if timestamp > pendingLastReadServerTimestamp {
pendingLastReadServerTimestamp = timestamp
}
if previousLastReadServerTimestamp == nil {
previousLastReadServerTimestamp = lastReadServerTimeStamp
}
}
@objc
func updateLastRead(_ timestamp: Date, synchronize: Bool = false) {
guard let managedObjectContext = managedObjectContext else { return }
if timestamp > lastReadServerTimeStamp {
lastReadServerTimeStamp = timestamp
// modified keys are set "automatically" on the uiMOC
if synchronize && managedObjectContext.zm_isSyncContext {
setLocallyModifiedKeys(Set([ZMConversationLastReadServerTimeStampKey]))
}
NotificationInContext(name: ZMConversation.lastReadDidChangeNotificationName, context: managedObjectContext.notificationContext, object: self, userInfo: nil).post()
}
}
@objc
public func updateLastModified(_ timestamp: Date) {
if timestamp > lastModifiedDate {
lastModifiedDate = timestamp
}
}
@objc
public func updateServerModified(_ timestamp: Date) {
if timestamp > lastServerTimeStamp {
lastServerTimeStamp = timestamp
}
}
@objc
public func updateCleared(_ timestamp: Date, synchronize: Bool = false) {
guard let managedObjectContext = managedObjectContext else { return }
if timestamp > clearedTimeStamp {
clearedTimeStamp = timestamp
if synchronize && managedObjectContext.zm_isSyncContext {
setLocallyModifiedKeys(Set([ZMConversationClearedTimeStampKey]))
}
}
}
@objc @discardableResult
func updateArchived(_ timestamp: Date, synchronize: Bool = false) -> Bool {
guard let managedObjectContext = managedObjectContext else { return false }
if timestamp > archivedChangedTimestamp {
archivedChangedTimestamp = timestamp
if synchronize && managedObjectContext.zm_isSyncContext {
setLocallyModifiedKeys([ZMConversationArchivedChangedTimeStampKey])
}
return true
} else if timestamp == archivedChangedTimestamp {
if synchronize {
setLocallyModifiedKeys([ZMConversationArchivedChangedTimeStampKey])
}
return true
}
return false
}
@objc @discardableResult
func updateMuted(_ timestamp: Date, synchronize: Bool = false) -> Bool {
guard let managedObjectContext = managedObjectContext else { return false }
if timestamp > silencedChangedTimestamp {
silencedChangedTimestamp = timestamp
if synchronize && managedObjectContext.zm_isSyncContext {
setLocallyModifiedKeys([ZMConversationSilencedChangedTimeStampKey])
}
return true
} else if timestamp == silencedChangedTimestamp {
if synchronize {
setLocallyModifiedKeys([ZMConversationSilencedChangedTimeStampKey])
}
return true
}
return false
}
fileprivate func updateLastUnreadKnock(_ timestamp: Date?) {
guard let timestamp = timestamp else { return lastUnreadKnockDate = nil }
if timestamp > lastUnreadKnockDate {
lastUnreadKnockDate = timestamp
}
}
fileprivate func updateLastUnreadMissedCall(_ timestamp: Date?) {
guard let timestamp = timestamp else { return lastUnreadMissedCallDate = nil }
if timestamp > lastUnreadMissedCallDate {
lastUnreadMissedCallDate = timestamp
}
}
// MARK: - Update timestamps on messages events
/// Update timetamps after an message has been updated or created from an update event
@objc
func updateTimestampsAfterUpdatingMessage(_ message: ZMMessage) {
guard let timestamp = message.serverTimestamp else { return }
updateServerModified(timestamp)
if message.shouldGenerateUnreadCount() {
updateLastModified(timestamp)
}
if let sender = message.sender, sender.isSelfUser {
// if the message was sent by the self user we don't want to send a lastRead event, since we consider this message to be already read
updateLastRead(timestamp, synchronize: false)
}
self.needsToCalculateUnreadMessages = true
}
/// Update timetamps after an message has been inserted locally by the self user
@objc
func updateTimestampsAfterInsertingMessage(_ message: ZMMessage) {
guard let timestamp = message.serverTimestamp else { return }
if message.shouldGenerateUnreadCount() {
updateLastModified(timestamp)
}
calculateLastUnreadMessages()
}
/// Update timetamps after an message has been deleted
@objc
func updateTimestampsAfterDeletingMessage() {
// If an unread message is deleted we must re-calculate the unread messages.
calculateLastUnreadMessages()
}
// MARK: - Mark as read
/// Mark all messages in the conversation as read
@objc
public func markAsRead() {
guard let timestamp = lastServerTimeStamp else { return }
enqueueMarkAsReadUpdate(timestamp)
savePendingLastRead()
}
/// Mark messages up until the given message as read
@objc(markMessagesAsReadUntil:)
public func markMessagesAsRead(until message: ZMConversationMessage) {
guard let messageTimestamp = message.serverTimestampIncludingChildMessages else { return }
if let currentTimestamp = lastReadServerTimeStamp,
currentTimestamp.compare(messageTimestamp) == .orderedDescending {
// Current last read timestamp is newer than message we are marking as read
return
}
// Any unsent unread message is cleared when entering a conversation
if hasUnreadUnsentMessage {
hasUnreadUnsentMessage = false
}
guard let unreadTimestamp = message.isSent ? messageTimestamp : unreadMessagesIncludingInvisible(until: messageTimestamp).last?.serverTimestamp else { return }
enqueueMarkAsReadUpdate(unreadTimestamp)
}
/// Enqueue an mark-as-read update.
///
/// - parameter timestamp: Point in time from which all older messages should be considered read.
///
/// This method only has an effect when called from the UI context and it's throttled so it's fine to call it repeatedly.
fileprivate func enqueueMarkAsReadUpdate(_ timestamp: Date) {
guard let managedObjectContext = managedObjectContext, managedObjectContext.zm_isUserInterfaceContext else { return }
updatePendingLastRead(timestamp)
lastReadTimestampUpdateCounter += 1
let currentCount: Int64 = lastReadTimestampUpdateCounter
let groups = managedObjectContext.enterAllGroups()
DispatchQueue.main.asyncAfter(deadline: .now() + lastReadTimestampSaveDelay) { [weak self] in
guard currentCount == self?.lastReadTimestampUpdateCounter else { return managedObjectContext.leaveAllGroups(groups) }
self?.savePendingLastRead()
managedObjectContext.leaveAllGroups(groups)
}
}
/// Perform the an mark-as-read update by updating the last-read timestamp and
/// create read confirmations for the newly read messages.
///
/// - Parameters:
/// - range: The range of time in which all messages should be considered read.
///
/// This method can only be run from the UI context but the actual work will happen
/// on the sync context since that's the context where we update timestamps.
fileprivate func performMarkAsReadUpdate(in range: ClosedRange<Date>) {
guard
managedObjectContext?.zm_isUserInterfaceContext == true,
let syncMOC = managedObjectContext?.zm_sync
else {
return
}
let objectID = self.objectID
syncMOC.performGroupedBlock {
let conversation = syncMOC.object(with: objectID) as? ZMConversation
conversation?.confirmUnreadMessagesAsRead(in: range)
conversation?.updateLastRead(range.upperBound, synchronize: true)
syncMOC.saveOrRollback()
}
}
/// Triggers the mark-as-read update.
@objc
public func savePendingLastRead() {
guard let upperBound = pendingLastReadServerTimestamp else { return }
let lowerBound = previousLastReadServerTimestamp ?? lastReadServerTimeStamp ?? .distantPast
performMarkAsReadUpdate(in: lowerBound...upperBound)
pendingLastReadServerTimestamp = nil
previousLastReadServerTimestamp = nil
lastReadTimestampUpdateCounter = 0
}
/// Calculates the the last unread knock, missed call and total unread unread count. This should be re-calculated
/// when the last read timetamp changes or a message is inserted / deleted.
@objc
func calculateLastUnreadMessages() {
// We only calculate unread message on the sync MOC
guard let managedObjectContext = managedObjectContext, managedObjectContext.zm_isSyncContext else { return }
let messages = unreadMessages()
var lastKnockDate: Date?
var lastMissedCallDate: Date?
var unreadCount: Int64 = 0
var unreadSelfMentionCount: Int64 = 0
var unreadSelfReplyCount: Int64 = 0
for message in messages {
if message.isKnock {
lastKnockDate = message.serverTimestamp
}
if message.isSystem, let systemMessage = message as? ZMSystemMessage, systemMessage.systemMessageType == .missedCall {
lastMissedCallDate = message.serverTimestamp
}
if let textMessageData = message.textMessageData {
if textMessageData.isMentioningSelf {
unreadSelfMentionCount += 1
}
if textMessageData.isQuotingSelf {
unreadSelfReplyCount += 1
}
}
if message.shouldGenerateUnreadCount() {
unreadCount += 1
}
}
updateLastUnreadKnock(lastKnockDate)
updateLastUnreadMissedCall(lastMissedCallDate)
internalEstimatedUnreadCount = unreadCount
internalEstimatedUnreadSelfMentionCount = unreadSelfMentionCount
internalEstimatedUnreadSelfReplyCount = unreadSelfReplyCount
needsToCalculateUnreadMessages = false
}
/// Returns the first unread message in a converation. If the first unread message is child message
/// of system message the parent message will be returned.
@objc
public var firstUnreadMessage: ZMConversationMessage? {
let replaceChildWithParent: (ZMMessage) -> ZMMessage = { message in
if let systemMessage = message as? ZMSystemMessage, let parentMessage = systemMessage.parentMessage as? ZMMessage {
return parentMessage
} else {
return message
}
}
return unreadMessagesIncludingInvisible().lazy
.map(replaceChildWithParent)
.filter { $0.visibleInConversation != nil }
.first { $0.shouldGenerateUnreadCount() }
}
/// Returns first unread message mentioning the self user.
public var firstUnreadMessageMentioningSelf: ZMConversationMessage? {
return unreadMessages.first(where: { $0.textMessageData?.isMentioningSelf ?? false })
}
/// Returns all unread messages. This may contain unread child messages of a system message
/// which aren't directly visible in the conversation.
@objc
public var unreadMessages: [ZMConversationMessage] {
return unreadMessages()
}
internal func unreadMessages(until timestamp: Date = .distantFuture) -> [ZMMessage] {
return unreadMessagesIncludingInvisible(until: timestamp).filter(ZMMessage.isVisible)
}
internal func unreadMessagesIncludingInvisible(until timestamp: Date = .distantFuture) -> [ZMMessage] {
let range = (lastReadServerTimeStamp ?? .distantPast)...timestamp
return unreadMessagesIncludingInvisible(in: range)
}
internal func unreadMessages(in range: ClosedRange<Date>) -> [ZMMessage] {
return unreadMessagesIncludingInvisible(in: range).filter(ZMMessage.isVisible)
}
internal func unreadMessagesIncludingInvisible(in range: ClosedRange<Date>) -> [ZMMessage] {
guard let managedObjectContext = managedObjectContext else { return [] }
let selfUser = ZMUser.selfUser(in: managedObjectContext)
let fetchRequest = NSFetchRequest<ZMMessage>(entityName: ZMMessage.entityName())
fetchRequest.predicate = NSPredicate(format: "(%K == %@ OR %K == %@) AND %K != %@ AND %K > %@ AND %K <= %@",
ZMMessageConversationKey, self,
ZMMessageHiddenInConversationKey, self,
ZMMessageSenderKey, selfUser,
ZMMessageServerTimestampKey, range.lowerBound as NSDate,
ZMMessageServerTimestampKey, range.upperBound as NSDate)
fetchRequest.sortDescriptors = ZMMessage.defaultSortDescriptors()
return managedObjectContext.fetchOrAssert(request: fetchRequest).filter { $0.shouldGenerateUnreadCount() }
}
}
| gpl-3.0 | bc25aaffa3198c6507f3cd860b0616a7 | 36.17734 | 176 | 0.666291 | 5.836814 | false | false | false | false |
congncif/SiFUtilities | Example/Pods/Boardy/Boardy/Core/Board/BoardContainer.swift | 1 | 1307 | //
// BoardContainer.swift
// Boardy
//
// Created by NGUYEN CHI CONG on 12/23/20.
//
import Foundation
public final class BoardContainer: BoardDynamicProducer {
private var externalProducer: ActivableBoardProducer?
private var container: [BoardID: BoardConstructor] = [:]
public init(externalProducer: ActivableBoardProducer? = nil) {
self.externalProducer = externalProducer
}
public func registerBoard(_ identifier: BoardID, factory: @escaping BoardConstructor) {
container[identifier] = factory
}
public func produceBoard(identifier: BoardID) -> ActivatableBoard? {
if let boardFactory = container[identifier] {
return boardFactory(identifier)
} else if let board = externalProducer?.produceBoard(identifier: identifier) {
return board
} else {
return nil
}
}
public func matchBoard(withIdentifier identifier: BoardID, to anotherIdentifier: BoardID) -> ActivatableBoard? {
if let boardFactory = container[identifier] {
return boardFactory(anotherIdentifier)
} else if let board = externalProducer?.matchBoard(withIdentifier: identifier, to: anotherIdentifier) {
return board
} else {
return nil
}
}
}
| mit | ad267b139b83285f5afe3e210e4437be | 30.119048 | 116 | 0.666412 | 4.684588 | false | false | false | false |
ripitrust/Fitapp | iOSClient/SIOSwift2/SwiftIO/SocketAckHandler.swift | 1 | 2394 | //
// SocketAckHandler.swift
// Socket.IO-Swift
//
// Created by Erik Little on 2/14/15.
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import Foundation
public typealias AckCallback = (NSArray?) -> Void
@objc public class SocketAckHandler {
let ackNum:Int!
let event:String!
var acked = false
var callback:AckCallback?
weak var socket:SocketIOClient?
init(event:String, ackNum:Int = 0, socket:SocketIOClient) {
self.ackNum = ackNum
self.event = event
self.socket = socket
}
public func onAck(timeout:UInt64, withCallback callback:AckCallback) {
self.callback = callback
if timeout != 0 {
let time = dispatch_time(DISPATCH_TIME_NOW, Int64(timeout * NSEC_PER_SEC))
dispatch_after(time, dispatch_get_main_queue()) {[weak self] in
if self == nil {
return
}
if !self!.acked {
self?.executeAck(["No ACK"])
self?.socket?.removeAck(self!)
}
}
}
}
func executeAck(data:NSArray?) {
dispatch_async(dispatch_get_main_queue()) {[weak self, cb = self.callback] in
self?.acked = true
cb?(data)
return
}
}
} | mit | ae1989bce2d5cf2a1f7fb50d1ee08c28 | 33.710145 | 86 | 0.63325 | 4.384615 | false | false | false | false |
finngaida/wwdc | 2016/Finn Gaida/CustomKeyboard/KeyboardViewController.swift | 1 | 33203 | //
// KeyboardViewController.swift
// Keyboard
//
// Created by Alexei Baboulevitch on 6/9/14.
// Copyright (c) 2014 Alexei Baboulevitch ("Archagon"). All rights reserved.
//
import UIKit
import AudioToolbox
let metrics: [String:Double] = [
"topBanner": 30
]
func metric(name: String) -> CGFloat { return CGFloat(metrics[name]!) }
// TODO: move this somewhere else and localize
let kAutoCapitalization = "kAutoCapitalization"
let kPeriodShortcut = "kPeriodShortcut"
let kKeyboardClicks = "kKeyboardClicks"
let kSmallLowercase = "kSmallLowercase"
let kReloadKeys = "kReloadKeys"
class KeyboardViewController: UIInputViewController {
let backspaceDelay: NSTimeInterval = 0.5
let backspaceRepeat: NSTimeInterval = 0.07
var keyboard: Keyboard!
var forwardingView: ForwardingView!
var layout: KeyboardLayout?
var heightConstraint: NSLayoutConstraint?
var bannerView: ExtraView?
var settingsView: ExtraView?
var textField:UITextField!
var currentMode: Int {
didSet {
if oldValue != currentMode {
setMode(currentMode)
}
}
}
var backspaceActive: Bool {
get {
return (backspaceDelayTimer != nil) || (backspaceRepeatTimer != nil)
}
}
var backspaceDelayTimer: NSTimer?
var backspaceRepeatTimer: NSTimer?
enum AutoPeriodState {
case NoSpace
case FirstSpace
}
var autoPeriodState: AutoPeriodState = .NoSpace
var lastCharCountInBeforeContext: Int = 0
var shiftState: ShiftState {
didSet {
switch shiftState {
case .Disabled:
self.updateKeyCaps(false)
case .Enabled:
self.updateKeyCaps(true)
case .Locked:
self.updateKeyCaps(true)
}
}
}
// state tracking during shift tap
var shiftWasMultitapped: Bool = false
var shiftStartingState: ShiftState?
var keyboardHeight: CGFloat {
get {
if let constraint = self.heightConstraint {
return constraint.constant
}
else {
return 0
}
}
set {
self.setHeight(newValue)
}
}
// TODO: why does the app crash if this isn't here?
convenience init() {
self.init(nibName: nil, bundle: nil, emoji: false)
}
init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: NSBundle?, emoji: Bool) {
NSUserDefaults.standardUserDefaults().registerDefaults([
kAutoCapitalization: true,
kPeriodShortcut: true,
kKeyboardClicks: false,
kSmallLowercase: true
])
self.keyboard = defaultKeyboard(!emoji, functionKeys: true)
self.shiftState = .Disabled
self.currentMode = 0
super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil)
self.forwardingView = ForwardingView(frame: CGRectZero)
self.view.addSubview(self.forwardingView)
NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(KeyboardViewController.defaultsChanged(_:)), name: NSUserDefaultsDidChangeNotification, object: nil)
}
required init?(coder: NSCoder) {
fatalError("NSCoding not supported")
}
deinit {
backspaceDelayTimer?.invalidate()
backspaceRepeatTimer?.invalidate()
NSNotificationCenter.defaultCenter().removeObserver(self)
}
func defaultsChanged(bool:Bool) {
//let defaults = notification.object as? NSUserDefaults
self.keyboard = defaultKeyboard(bool, functionKeys: true)
self.updateKeyCaps(self.shiftState.uppercase())
}
// without this here kludge, the height constraint for the keyboard does not work for some reason
var kludge: UIView?
func setupKludge() {
if self.kludge == nil {
let kludge = UIView()
self.view.addSubview(kludge)
kludge.translatesAutoresizingMaskIntoConstraints = false
kludge.hidden = true
let a = NSLayoutConstraint(item: kludge, attribute: NSLayoutAttribute.Left, relatedBy: NSLayoutRelation.Equal, toItem: self.view, attribute: NSLayoutAttribute.Left, multiplier: 1, constant: 0)
let b = NSLayoutConstraint(item: kludge, attribute: NSLayoutAttribute.Right, relatedBy: NSLayoutRelation.Equal, toItem: self.view, attribute: NSLayoutAttribute.Left, multiplier: 1, constant: 0)
let c = NSLayoutConstraint(item: kludge, attribute: NSLayoutAttribute.Top, relatedBy: NSLayoutRelation.Equal, toItem: self.view, attribute: NSLayoutAttribute.Top, multiplier: 1, constant: 0)
let d = NSLayoutConstraint(item: kludge, attribute: NSLayoutAttribute.Bottom, relatedBy: NSLayoutRelation.Equal, toItem: self.view, attribute: NSLayoutAttribute.Top, multiplier: 1, constant: 0)
self.view.addConstraints([a, b, c, d])
self.kludge = kludge
}
}
/*
BUG NOTE
For some strange reason, a layout pass of the entire keyboard is triggered
whenever a popup shows up, if one of the following is done:
a) The forwarding view uses an autoresizing mask.
b) The forwarding view has constraints set anywhere other than init.
On the other hand, setting (non-autoresizing) constraints or just setting the
frame in layoutSubviews works perfectly fine.
I don't really know what to make of this. Am I doing Autolayout wrong, is it
a bug, or is it expected behavior? Perhaps this has to do with the fact that
the view's frame is only ever explicitly modified when set directly in layoutSubviews,
and not implicitly modified by various Autolayout constraints
(even though it should really not be changing).
*/
var constraintsAdded: Bool = false
func setupLayout() {
if !constraintsAdded {
self.layout = self.dynamicType.layoutClass.init(model: self.keyboard, superview: self.forwardingView, layoutConstants: self.dynamicType.layoutConstants, globalColors: self.dynamicType.globalColors, darkMode: self.darkMode(), solidColorMode: self.solidColorMode())
self.layout?.initialize()
self.setMode(0)
self.setupKludge()
self.updateKeyCaps(self.shiftState.uppercase())
self.setCapsIfNeeded()
self.updateAppearances(self.darkMode())
self.addInputTraitsObservers()
self.constraintsAdded = true
}
}
// only available after frame becomes non-zero
func darkMode() -> Bool {
let darkMode = { () -> Bool in
let proxy = self.textDocumentProxy
return proxy.keyboardAppearance == UIKeyboardAppearance.Dark
}()
return darkMode
}
func solidColorMode() -> Bool {
return UIAccessibilityIsReduceTransparencyEnabled()
}
var lastLayoutBounds: CGRect?
override func viewDidLayoutSubviews() {
if view.bounds == CGRectZero {
return
}
self.setupLayout()
let orientationSavvyBounds = CGRectMake(0, 0, self.view.bounds.width, self.heightForOrientation(self.interfaceOrientation, withTopBanner: false))
if (lastLayoutBounds != nil && lastLayoutBounds == orientationSavvyBounds) {
// do nothing
}
else {
let uppercase = self.shiftState.uppercase()
let characterUppercase = (NSUserDefaults.standardUserDefaults().boolForKey(kSmallLowercase) ? uppercase : true)
self.forwardingView.frame = orientationSavvyBounds
self.layout?.layoutKeys(self.currentMode, uppercase: uppercase, characterUppercase: characterUppercase, shiftState: self.shiftState)
self.lastLayoutBounds = orientationSavvyBounds
self.setupKeys()
}
self.bannerView?.frame = CGRectMake(0, 0, self.view.bounds.width, metric("topBanner"))
let newOrigin = CGPointMake(0, self.view.bounds.height - self.forwardingView.bounds.height)
self.forwardingView.frame.origin = newOrigin
}
override func loadView() {
super.loadView()
if let aBanner = self.createBanner() {
aBanner.hidden = true
self.view.insertSubview(aBanner, belowSubview: self.forwardingView)
self.bannerView = aBanner
}
}
override func viewWillAppear(animated: Bool) {
self.bannerView?.hidden = false
self.keyboardHeight = self.heightForOrientation(self.interfaceOrientation, withTopBanner: true)
}
override func willRotateToInterfaceOrientation(toInterfaceOrientation: UIInterfaceOrientation, duration: NSTimeInterval) {
self.forwardingView.resetTrackedViews()
self.shiftStartingState = nil
self.shiftWasMultitapped = false
// optimization: ensures smooth animation
if let keyPool = self.layout?.keyPool {
for view in keyPool {
view.shouldRasterize = true
}
}
self.keyboardHeight = self.heightForOrientation(toInterfaceOrientation, withTopBanner: true)
}
override func didRotateFromInterfaceOrientation(fromInterfaceOrientation: UIInterfaceOrientation) {
// optimization: ensures quick mode and shift transitions
if let keyPool = self.layout?.keyPool {
for view in keyPool {
view.shouldRasterize = false
}
}
}
func heightForOrientation(orientation: UIInterfaceOrientation, withTopBanner: Bool) -> CGFloat {
let isPad = UIDevice.currentDevice().userInterfaceIdiom == UIUserInterfaceIdiom.Pad
//TODO: hardcoded stuff
let actualScreenWidth = (UIScreen.mainScreen().nativeBounds.size.width / UIScreen.mainScreen().nativeScale)
let canonicalPortraitHeight = (isPad ? CGFloat(264) : CGFloat(orientation.isPortrait && actualScreenWidth >= 400 ? 226 : 216))
let canonicalLandscapeHeight = (isPad ? CGFloat(352) : CGFloat(162))
let topBannerHeight = (withTopBanner ? metric("topBanner") : 0)
return CGFloat(orientation.isPortrait ? canonicalPortraitHeight + topBannerHeight : canonicalLandscapeHeight + topBannerHeight)
}
/*
BUG NOTE
None of the UIContentContainer methods are called for this controller.
*/
//override func viewWillTransitionToSize(size: CGSize, withTransitionCoordinator coordinator: UIViewControllerTransitionCoordinator) {
// super.viewWillTransitionToSize(size, withTransitionCoordinator: coordinator)
//}
func setupKeys() {
if self.layout == nil {
return
}
for page in keyboard.pages {
for rowKeys in page.rows { // TODO: quick hack
for key in rowKeys {
if let keyView = self.layout?.viewForKey(key) {
keyView.removeTarget(nil, action: nil, forControlEvents: UIControlEvents.AllEvents)
switch key.type {
case Key.KeyType.KeyboardChange:
keyView.addTarget(self, action: #selector(KeyboardViewController.advanceTapped(_:)), forControlEvents: .TouchUpInside)
case Key.KeyType.Backspace:
let cancelEvents: UIControlEvents = [UIControlEvents.TouchUpInside, UIControlEvents.TouchUpInside, UIControlEvents.TouchDragExit, UIControlEvents.TouchUpOutside, UIControlEvents.TouchCancel, UIControlEvents.TouchDragOutside]
keyView.addTarget(self, action: #selector(KeyboardViewController.backspaceDown(_:)), forControlEvents: .TouchDown)
keyView.addTarget(self, action: #selector(KeyboardViewController.backspaceUp(_:)), forControlEvents: cancelEvents)
case Key.KeyType.Shift:
keyView.addTarget(self, action: #selector(KeyboardViewController.shiftDown(_:)), forControlEvents: .TouchDown)
keyView.addTarget(self, action: #selector(KeyboardViewController.shiftUp(_:)), forControlEvents: .TouchUpInside)
keyView.addTarget(self, action: #selector(KeyboardViewController.shiftDoubleTapped(_:)), forControlEvents: .TouchDownRepeat)
case Key.KeyType.ModeChange:
keyView.addTarget(self, action: #selector(KeyboardViewController.modeChangeTapped(_:)), forControlEvents: .TouchDown)
case Key.KeyType.Settings:
keyView.addTarget(self, action: #selector(KeyboardViewController.toggleSettings), forControlEvents: .TouchUpInside)
case Key.KeyType.Hide:
keyView.addTarget(self, action: #selector(KeyboardViewController.hideKeyboard), forControlEvents: .TouchUpInside)
default:
break
}
if key.isCharacter {
if UIDevice.currentDevice().userInterfaceIdiom != UIUserInterfaceIdiom.Pad {
keyView.addTarget(self, action: #selector(KeyboardViewController.showPopup(_:)), forControlEvents: [.TouchDown, .TouchDragInside, .TouchDragEnter])
keyView.addTarget(keyView, action: #selector(KeyboardKey.hidePopup), forControlEvents: [.TouchDragExit, .TouchCancel])
keyView.addTarget(self, action: #selector(KeyboardViewController.hidePopupDelay(_:)), forControlEvents: [.TouchUpInside, .TouchUpOutside, .TouchDragOutside])
}
}
if key.hasOutput {
keyView.addTarget(self, action: #selector(KeyboardViewController.keyPressedHelper(_:)), forControlEvents: .TouchUpInside)
}
if key.type != Key.KeyType.Shift && key.type != Key.KeyType.ModeChange {
keyView.addTarget(self, action: #selector(KeyboardViewController.highlightKey(_:)), forControlEvents: [.TouchDown, .TouchDragInside, .TouchDragEnter])
keyView.addTarget(self, action: #selector(KeyboardViewController.unHighlightKey(_:)), forControlEvents: [.TouchUpInside, .TouchUpOutside, .TouchDragOutside, .TouchDragExit, .TouchCancel])
}
keyView.addTarget(self, action: #selector(KeyboardViewController.playKeySound), forControlEvents: .TouchDown)
}
}
}
}
}
/////////////////
// POPUP DELAY //
/////////////////
var keyWithDelayedPopup: KeyboardKey?
var popupDelayTimer: NSTimer?
func showPopup(sender: KeyboardKey) {
if sender == self.keyWithDelayedPopup {
self.popupDelayTimer?.invalidate()
}
sender.showPopup()
}
func hidePopupDelay(sender: KeyboardKey) {
self.popupDelayTimer?.invalidate()
if sender != self.keyWithDelayedPopup {
self.keyWithDelayedPopup?.hidePopup()
self.keyWithDelayedPopup = sender
}
if sender.popup != nil {
self.popupDelayTimer = NSTimer.scheduledTimerWithTimeInterval(0.05, target: self, selector: #selector(KeyboardViewController.hidePopupCallback), userInfo: nil, repeats: false)
}
}
func hidePopupCallback() {
self.keyWithDelayedPopup?.hidePopup()
self.keyWithDelayedPopup = nil
self.popupDelayTimer = nil
}
/////////////////////
// POPUP DELAY END //
/////////////////////
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated
}
// TODO: this is currently not working as intended; only called when selection changed -- iOS bug
override func textDidChange(textInput: UITextInput?) {
self.contextChanged()
}
func contextChanged() {
self.setCapsIfNeeded()
self.autoPeriodState = .NoSpace
}
func setHeight(height: CGFloat) {
if self.heightConstraint == nil {
self.heightConstraint = NSLayoutConstraint(
item:self.view,
attribute:NSLayoutAttribute.Height,
relatedBy:NSLayoutRelation.Equal,
toItem:nil,
attribute:NSLayoutAttribute.NotAnAttribute,
multiplier:0,
constant:height)
self.heightConstraint!.priority = 1000
self.view.addConstraint(self.heightConstraint!) // TODO: what if view already has constraint added?
}
else {
self.heightConstraint?.constant = height
}
}
func updateAppearances(appearanceIsDark: Bool) {
self.layout?.solidColorMode = self.solidColorMode()
self.layout?.darkMode = appearanceIsDark
self.layout?.updateKeyAppearance()
self.bannerView?.darkMode = appearanceIsDark
self.settingsView?.darkMode = appearanceIsDark
}
func highlightKey(sender: KeyboardKey) {
sender.highlighted = true
}
func unHighlightKey(sender: KeyboardKey) {
sender.highlighted = false
}
func keyPressedHelper(sender: KeyboardKey) {
if let model = self.layout?.keyForView(sender) {
self.keyPressed(model)
// auto exit from special char subkeyboard
if model.type == Key.KeyType.Space || model.type == Key.KeyType.Return {
self.currentMode = 0
} else if model.lowercaseOutput == "'" {
self.currentMode = 0
}
// TODO: This is dumb and will be deleted
/*
else if model.type == Key.KeyType.Character {
self.currentMode = 0
}*/
// auto period on double space
// TODO: timeout
self.handleAutoPeriod(model)
// TODO: reset context
}
self.setCapsIfNeeded()
}
func handleAutoPeriod(key: Key) {
if !NSUserDefaults.standardUserDefaults().boolForKey(kPeriodShortcut) {
return
}
if self.autoPeriodState == .FirstSpace {
if key.type != Key.KeyType.Space {
self.autoPeriodState = .NoSpace
return
}
let charactersAreInCorrectState = { () -> Bool in
let previousContext = self.textDocumentProxy.documentContextBeforeInput
if previousContext == nil || (previousContext!).characters.count < 3 {
return false
}
var index = previousContext!.endIndex
index = index.predecessor()
if previousContext![index] != " " {
return false
}
index = index.predecessor()
if previousContext![index] != " " {
return false
}
index = index.predecessor()
let char = previousContext![index]
if self.characterIsWhitespace(char) || self.characterIsPunctuation(char) || char == "," {
return false
}
return true
}()
if charactersAreInCorrectState {
self.textDocumentProxy.deleteBackward()
self.textDocumentProxy.deleteBackward()
self.textDocumentProxy.insertText(".")
self.textDocumentProxy.insertText(" ")
}
self.autoPeriodState = .NoSpace
}
else {
if key.type == Key.KeyType.Space {
self.autoPeriodState = .FirstSpace
}
}
}
func cancelBackspaceTimers() {
self.backspaceDelayTimer?.invalidate()
self.backspaceRepeatTimer?.invalidate()
self.backspaceDelayTimer = nil
self.backspaceRepeatTimer = nil
}
func backspaceDown(sender: KeyboardKey) {
self.cancelBackspaceTimers()
self.textDocumentProxy.deleteBackward()
if self.textField.text?.characters.count > 0 {
self.textField.text = self.textField.text?.substringToIndex((self.textField.text?.endIndex.predecessor())!)
}
self.setCapsIfNeeded()
// trigger for subsequent deletes
self.backspaceDelayTimer = NSTimer.scheduledTimerWithTimeInterval(backspaceDelay - backspaceRepeat, target: self, selector: #selector(KeyboardViewController.backspaceDelayCallback), userInfo: nil, repeats: false)
}
func backspaceUp(sender: KeyboardKey) {
self.cancelBackspaceTimers()
}
func backspaceDelayCallback() {
self.backspaceDelayTimer = nil
self.backspaceRepeatTimer = NSTimer.scheduledTimerWithTimeInterval(backspaceRepeat, target: self, selector: #selector(KeyboardViewController.backspaceRepeatCallback), userInfo: nil, repeats: true)
}
func backspaceRepeatCallback() {
self.playKeySound()
self.textDocumentProxy.deleteBackward()
self.setCapsIfNeeded()
}
func shiftDown(sender: KeyboardKey) {
self.shiftStartingState = self.shiftState
if let shiftStartingState = self.shiftStartingState {
if shiftStartingState.uppercase() {
// handled by shiftUp
return
}
else {
switch self.shiftState {
case .Disabled:
self.shiftState = .Enabled
case .Enabled:
self.shiftState = .Disabled
case .Locked:
self.shiftState = .Disabled
}
(sender.shape as? ShiftShape)?.withLock = false
}
}
}
func shiftUp(sender: KeyboardKey) {
if self.shiftWasMultitapped {
// do nothing
}
else {
if let shiftStartingState = self.shiftStartingState {
if !shiftStartingState.uppercase() {
// handled by shiftDown
}
else {
switch self.shiftState {
case .Disabled:
self.shiftState = .Enabled
case .Enabled:
self.shiftState = .Disabled
case .Locked:
self.shiftState = .Disabled
}
(sender.shape as? ShiftShape)?.withLock = false
}
}
}
self.shiftStartingState = nil
self.shiftWasMultitapped = false
}
func shiftDoubleTapped(sender: KeyboardKey) {
self.shiftWasMultitapped = true
switch self.shiftState {
case .Disabled:
self.shiftState = .Locked
case .Enabled:
self.shiftState = .Locked
case .Locked:
self.shiftState = .Disabled
}
}
func updateKeyCaps(uppercase: Bool) {
let characterUppercase = (NSUserDefaults.standardUserDefaults().boolForKey(kSmallLowercase) ? uppercase : true)
self.layout?.updateKeyCaps(true, uppercase: uppercase, characterUppercase: characterUppercase, shiftState: self.shiftState)
}
func modeChangeTapped(sender: KeyboardKey) {
if let toMode = self.layout?.viewToModel[sender]?.toMode {
self.currentMode = toMode
}
}
func setMode(mode: Int) {
self.forwardingView.resetTrackedViews()
self.shiftStartingState = nil
self.shiftWasMultitapped = false
let uppercase = self.shiftState.uppercase()
let characterUppercase = (NSUserDefaults.standardUserDefaults().boolForKey(kSmallLowercase) ? uppercase : true)
self.layout?.layoutKeys(mode, uppercase: uppercase, characterUppercase: characterUppercase, shiftState: self.shiftState)
self.setupKeys()
}
func advanceTapped(sender: KeyboardKey) {
self.forwardingView.resetTrackedViews()
self.shiftStartingState = nil
self.shiftWasMultitapped = false
self.advanceToNextInputMode()
}
@IBAction func toggleSettings() {
// lazy load settings
if self.settingsView == nil {
if let aSettings = self.createSettings() {
aSettings.darkMode = self.darkMode()
aSettings.hidden = true
self.view.addSubview(aSettings)
self.settingsView = aSettings
aSettings.translatesAutoresizingMaskIntoConstraints = false
let widthConstraint = NSLayoutConstraint(item: aSettings, attribute: NSLayoutAttribute.Width, relatedBy: NSLayoutRelation.Equal, toItem: self.view, attribute: NSLayoutAttribute.Width, multiplier: 1, constant: 0)
let heightConstraint = NSLayoutConstraint(item: aSettings, attribute: NSLayoutAttribute.Height, relatedBy: NSLayoutRelation.Equal, toItem: self.view, attribute: NSLayoutAttribute.Height, multiplier: 1, constant: 0)
let centerXConstraint = NSLayoutConstraint(item: aSettings, attribute: NSLayoutAttribute.CenterX, relatedBy: NSLayoutRelation.Equal, toItem: self.view, attribute: NSLayoutAttribute.CenterX, multiplier: 1, constant: 0)
let centerYConstraint = NSLayoutConstraint(item: aSettings, attribute: NSLayoutAttribute.CenterY, relatedBy: NSLayoutRelation.Equal, toItem: self.view, attribute: NSLayoutAttribute.CenterY, multiplier: 1, constant: 0)
self.view.addConstraint(widthConstraint)
self.view.addConstraint(heightConstraint)
self.view.addConstraint(centerXConstraint)
self.view.addConstraint(centerYConstraint)
}
}
if let settings = self.settingsView {
let hidden = settings.hidden
settings.hidden = !hidden
self.forwardingView.hidden = hidden
self.forwardingView.userInteractionEnabled = !hidden
self.bannerView?.hidden = hidden
}
}
func hideKeyboard() {
self.dismissKeyboard()
}
func setCapsIfNeeded() -> Bool {
if self.shouldAutoCapitalize() {
switch self.shiftState {
case .Disabled:
self.shiftState = .Enabled
case .Enabled:
self.shiftState = .Enabled
case .Locked:
self.shiftState = .Locked
}
return true
}
else {
switch self.shiftState {
case .Disabled:
self.shiftState = .Disabled
case .Enabled:
self.shiftState = .Disabled
case .Locked:
self.shiftState = .Locked
}
return false
}
}
func characterIsPunctuation(character: Character) -> Bool {
return (character == ".") || (character == "!") || (character == "?")
}
func characterIsNewline(character: Character) -> Bool {
return (character == "\n") || (character == "\r")
}
func characterIsWhitespace(character: Character) -> Bool {
// there are others, but who cares
return (character == " ") || (character == "\n") || (character == "\r") || (character == "\t")
}
func stringIsWhitespace(string: String?) -> Bool {
if string != nil {
for char in (string!).characters {
if !characterIsWhitespace(char) {
return false
}
}
}
return true
}
func shouldAutoCapitalize() -> Bool {
if !NSUserDefaults.standardUserDefaults().boolForKey(kAutoCapitalization) {
return false
}
let traits = self.textDocumentProxy
if let autocapitalization = traits.autocapitalizationType {
let documentProxy = self.textDocumentProxy
//var beforeContext = documentProxy.documentContextBeforeInput
switch autocapitalization {
case .None:
return false
case .Words:
if let beforeContext = documentProxy.documentContextBeforeInput {
let previousCharacter = beforeContext[beforeContext.endIndex.predecessor()]
return self.characterIsWhitespace(previousCharacter)
}
else {
return true
}
case .Sentences:
if let beforeContext = documentProxy.documentContextBeforeInput {
let offset:Int = min(3, beforeContext.characters.count)
var index = beforeContext.endIndex
for i in 0..<offset {
index = index.predecessor()
let char = beforeContext[index]
if characterIsPunctuation(char) {
if i == 0 {
return false //not enough spaces after punctuation
}
else {
return true //punctuation with at least one space after it
}
}
else {
if !characterIsWhitespace(char) {
return false //hit a foreign character before getting to 3 spaces
}
else if characterIsNewline(char) {
return true //hit start of line
}
}
}
return true //either got 3 spaces or hit start of line
}
else {
return true
}
case .AllCharacters:
return true
}
}
else {
return false
}
}
// this only works if full access is enabled
func playKeySound() {
if !NSUserDefaults.standardUserDefaults().boolForKey(kKeyboardClicks) {
return
}
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), {
AudioServicesPlaySystemSound(1104)
})
}
//////////////////////////////////////
// MOST COMMONLY EXTENDABLE METHODS //
//////////////////////////////////////
class var layoutClass: KeyboardLayout.Type { get { return KeyboardLayout.self }}
class var layoutConstants: LayoutConstants.Type { get { return LayoutConstants.self }}
class var globalColors: GlobalColors.Type { get { return GlobalColors.self }}
func keyPressed(key: Key) {
self.textDocumentProxy.insertText(key.outputForCase(self.shiftState.uppercase()))
self.textField.text = self.textField.text! + key.outputForCase(self.shiftState.uppercase())
}
// a banner that sits in the empty space on top of the keyboard
func createBanner() -> ExtraView? {
// note that dark mode is not yet valid here, so we just put false for clarity
//return ExtraView(globalColors: self.dynamicType.globalColors, darkMode: false, solidColorMode: self.solidColorMode())
return nil
}
// a settings view that replaces the keyboard when the settings button is pressed
func createSettings() -> ExtraView? {
// note that dark mode is not yet valid here, so we just put false for clarity
let settingsView = DefaultSettings(globalColors: self.dynamicType.globalColors, darkMode: false, solidColorMode: self.solidColorMode())
settingsView.backButton?.addTarget(self, action: #selector(KeyboardViewController.toggleSettings), forControlEvents: UIControlEvents.TouchUpInside)
return settingsView
}
}
| gpl-2.0 | 798722e8e7aa3b7694d426a1cb0c46ab | 38.200708 | 275 | 0.584194 | 6.133937 | false | false | false | false |
ethanneff/organize | Organize/Util.swift | 1 | 6372 | import UIKit
import AVFoundation // sounds
import Firebase
import SystemConfiguration // network connection
class Util {
// multiple story board navigation
class func navToStoryboard(currentController currentController:UIViewController, storyboard:String) {
let storyboard = UIStoryboard(name: storyboard, bundle: nil)
let controller = storyboard.instantiateInitialViewController()! as UIViewController
currentController.presentViewController(controller, animated: true, completion: nil)
}
// changing the status bar color
class func setStatusBarBackgroundColor(color: UIColor) {
guard let statusBar = UIApplication.sharedApplication().valueForKey("statusBarWindow")?.valueForKey("statusBar") as? UIView else {
return
}
statusBar.backgroundColor = color
}
// removing the text from the back button in the navigation bar
class func removeNavBackButtonText(controller controller: UIViewController) {
controller.navigationItem.backBarButtonItem = UIBarButtonItem(title: "", style: .Plain, target: nil, action: nil)
}
// background thread delay
class func delay(delay: Double, closure: ()->()) {
dispatch_after(
dispatch_time(
DISPATCH_TIME_NOW,
Int64(delay * Double(NSEC_PER_SEC))
),
dispatch_get_main_queue(), closure)
}
// random
class func randomString(length length: Int) -> String {
let letters : NSString = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
let randomString : NSMutableString = NSMutableString(capacity: length)
for _ in 0..<length {
let len = UInt32(letters.length)
let rand = arc4random_uniform(len)
randomString.appendFormat("%C", letters.characterAtIndex(Int(rand)))
}
return String(randomString)
}
class func randomNumber(upperLimit upperLimit: UInt32) -> Int {
return Int(arc4random_uniform(upperLimit))
}
// threading
class func threadBackground(completion: () -> ()) {
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)) {
completion()
}
}
class func threadMain(completion: () -> ()) {
dispatch_async(dispatch_get_main_queue()) {
completion()
}
}
// animation
class func animateButtonPress(button button: UIView, completion: (() -> ())? = nil) {
UIView.animateWithDuration(0.05, animations: {
button.alpha = 0.4
}, completion: { success in
UIView.animateWithDuration(0.20, animations: {
button.alpha = 1
}, completion: { success in
if let completion = completion {
completion()
}
})
})
Util.playSound(systemSound: .Tap)
}
// sounds
enum SystemSounds: UInt32 {
case Type = 1104
case Tap = 1103 // tick
case Positive = 1054 // vibrate
case Negative = 1053 // vibrate
case MailReceived = 1000 // vibrate
case MailSent = 1001 // woosh
case SMSReceived = 1003 // vibrate
case SMSSent = 1004 // woop
case CalendarAlert = 1005 // beep bo beep bop beep bo beep bop
case LowPower = 1006 // dum dum dum
case Voicemail = 1015 // boo bo beep
case BeepBeepSuccess = 1111
case BeepBeepFailure = 1112
case BeepBoBoopSuccess = 1115
case BeepBoBoopFailure = 1116
}
class func playSound(systemSound systemSound: SystemSounds) {
Util.threadMain {
// play sound
let systemSoundID: SystemSoundID = systemSound.rawValue
AudioServicesPlaySystemSound(systemSoundID)
}
}
// vibrate
class func vibrate() {
Util.threadMain {
AudioServicesPlayAlertSound(SystemSoundID(kSystemSoundID_Vibrate))
}
}
// image
class func imageViewWithColor(image image: UIImage, color: UIColor) -> UIImageView {
let imageView = UIImageView(image: image)
imageView.image = imageView.image!.imageWithRenderingMode(.AlwaysTemplate)
imageView.tintColor = color
return imageView
}
// network indicator
class func toggleNetworkIndicator(on on: Bool) {
UIApplication.sharedApplication().networkActivityIndicatorVisible = on
}
static var hasNetworkConnection: Bool {
var zeroAddress = sockaddr_in()
zeroAddress.sin_len = UInt8(sizeofValue(zeroAddress))
zeroAddress.sin_family = sa_family_t(AF_INET)
guard let defaultRouteReachability = withUnsafePointer(&zeroAddress, {
SCNetworkReachabilityCreateWithAddress(nil, UnsafePointer($0))
}) else {
return false
}
var flags : SCNetworkReachabilityFlags = []
if !SCNetworkReachabilityGetFlags(defaultRouteReachability, &flags) {
return false
}
let isReachable = flags.contains(.Reachable)
let needsConnection = flags.contains(.ConnectionRequired)
return (isReachable && !needsConnection)
}
// keyboard
class func handleKeyboardScrollView(keyboardNotification keyboardNotification: NSNotification, scrollViewBottomConstraint: NSLayoutConstraint, view: UIView, constant: CGFloat? = nil) {
if let userInfo = keyboardNotification.userInfo {
let endFrame = (userInfo[UIKeyboardFrameEndUserInfoKey] as? NSValue)?.CGRectValue()
let endFrameHeight: CGFloat = endFrame?.size.height ?? 0.0
let duration: NSTimeInterval = (userInfo[UIKeyboardAnimationDurationUserInfoKey] as? NSNumber)?.doubleValue ?? 0
let animationCurveRawNSN = userInfo[UIKeyboardAnimationCurveUserInfoKey] as? NSNumber
let animationCurveRaw = animationCurveRawNSN?.unsignedLongValue ?? UIViewAnimationOptions.CurveEaseInOut.rawValue
let animationCurve: UIViewAnimationOptions = UIViewAnimationOptions(rawValue: animationCurveRaw)
if endFrame?.origin.y >= UIScreen.mainScreen().bounds.size.height {
scrollViewBottomConstraint.constant = 0.0
} else {
scrollViewBottomConstraint.constant = -endFrameHeight + (constant ?? 0)
}
UIView.animateWithDuration(duration, delay: NSTimeInterval(0), options: animationCurve, animations: {
view.layoutIfNeeded()
}, completion: nil)
}
}
class func keyboardHeight(notification notification: NSNotification) -> CGFloat {
if let userInfo = notification.userInfo, let keyboardHeight = userInfo[UIKeyboardFrameEndUserInfoKey]?.CGRectValue().size.height {
return keyboardHeight
}
return 0
}
} | mit | 0a0f4cd98dbe3b42719275f0696312ce | 33.63587 | 186 | 0.699466 | 5.077291 | false | false | false | false |
mrk21/study_mobile | swift_variable/swift_variable.playground/Contents.swift | 1 | 499 | //: Playground - noun: a place where people can play
import UIKit
// variable
var variable = "value1"
print(variable)
variable = "value2"
print(variable)
// constant
let constant = "const1"
print(constant)
//constant = "const2" // error
// multibyte identifier names
var 日本語 = "🆖"
print(日本語)
var 😰 = "🆖"
print(😰)
// typing
var value1: String
// var value2: String = 10 // error
// expand variables in string
var name = "hoge"
var age = 45
print("\(name) => \(age)")
| mit | 3e384c5387fcabae3b70e065425d96d6 | 13.84375 | 52 | 0.661053 | 3.006329 | false | false | false | false |
royhsu/RHAnimatedTitleView | Example/RHAnimatedTitleView/ViewController.swift | 1 | 1009 | //
// ViewController.swift
// UILabel
//
// Created by Roy Hsu on 2015/3/30.
// Copyright (c) 2015年 tinyWorld. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var slider: UISlider!
var titleView: RHAnimatedTitleView?
override func viewDidLoad() {
super.viewDidLoad()
titleView = RHAnimatedTitleView(oldTitle: "AAAA", newTitle: "BBBB")
titleView?.titleColor = UIColor.redColor()
titleView?.transition = true
navigationItem.titleView = titleView
if let height = titleView?.frame.height {
slider.maximumValue = Float(height)
slider.minimumValue = 0.0
}
}
@IBAction func didMoveSlider(sender: AnyObject) {
if let slider = sender as? UISlider {
if titleView != nil {
let y = CGFloat(slider.value)
titleView!.contentOffset = CGPointMake(0.0, y)
}
}
}
}
| mit | 3817cee15cd883d0c53b5dbbfe715194 | 22.97619 | 75 | 0.591857 | 4.662037 | false | false | false | false |
satorun/designPattern | Builder/Builder/TextBuilder.swift | 1 | 674 | //
// TextBuilder.swift
// Builder
//
// Created by satorun on 2016/02/03.
// Copyright © 2016年 satorun. All rights reserved.
//
class TextBuilder: Builder {
private var buffer = ""
func makeTitle(title: String) {
buffer += "=======================\n"
buffer += "『\(title)』\n\n"
}
func makeString(str: String) {
buffer += "■\(str)\n\n"
}
func makeItems(items: [String]) {
for item in items {
buffer += " ・\(item)\n"
}
buffer += "\n"
}
func close() {
buffer += "=======================\n"
}
func getResult() -> String {
return buffer
}
} | mit | d1701f4c19744bf9f5f04682323aee3b | 21.066667 | 51 | 0.464448 | 3.651934 | false | false | false | false |
Bunn/firefox-ios | Client/Frontend/Browser/TabManagerStore.swift | 9 | 6681 | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
import Foundation
import WebKit
import Storage
import Shared
import XCGLogger
private let log = Logger.browserLogger
class TabManagerStore {
fileprivate var lockedForReading = false
fileprivate let imageStore: DiskImageStore?
fileprivate var fileManager = FileManager.default
fileprivate let serialQueue = DispatchQueue(label: "tab-manager-write-queue")
fileprivate var writeOperation = DispatchWorkItem {}
// Init this at startup with the tabs on disk, and then on each save, update the in-memory tab state.
fileprivate lazy var archivedStartupTabs = { return tabsToRestore() }()
init(imageStore: DiskImageStore?, _ fileManager: FileManager = FileManager.default) {
self.fileManager = fileManager
self.imageStore = imageStore
}
var isRestoringTabs: Bool {
return lockedForReading
}
var hasTabsToRestoreAtStartup: Bool {
return archivedStartupTabs.count > 0
}
fileprivate func tabsStateArchivePath() -> String? {
let profilePath: String?
if AppConstants.IsRunningTest {
profilePath = (UIApplication.shared.delegate as? TestAppDelegate)?.dirForTestProfile
} else {
profilePath = fileManager.containerURL( forSecurityApplicationGroupIdentifier: AppInfo.sharedContainerIdentifier)?.appendingPathComponent("profile.profile").path
}
guard let path = profilePath else { return nil }
return URL(fileURLWithPath: path).appendingPathComponent("tabsState.archive").path
}
fileprivate func tabsToRestore() -> [SavedTab] {
guard let tabStateArchivePath = tabsStateArchivePath(),
fileManager.fileExists(atPath: tabStateArchivePath),
let tabData = try? Data(contentsOf: URL(fileURLWithPath: tabStateArchivePath)) else {
return [SavedTab]()
}
let unarchiver = NSKeyedUnarchiver(forReadingWith: tabData)
unarchiver.decodingFailurePolicy = .setErrorAndReturn
guard let tabs = unarchiver.decodeObject(forKey: "tabs") as? [SavedTab] else {
Sentry.shared.send(
message: "Failed to restore tabs",
tag: SentryTag.tabManager,
severity: .error,
description: "\(unarchiver.error ??? "nil")")
return [SavedTab]()
}
return tabs
}
fileprivate func prepareSavedTabs(fromTabs tabs: [Tab], selectedTab: Tab?) -> [SavedTab]? {
var savedTabs = [SavedTab]()
var savedUUIDs = Set<String>()
for tab in tabs {
if let savedTab = SavedTab(tab: tab, isSelected: tab === selectedTab) {
savedTabs.append(savedTab)
if let screenshot = tab.screenshot,
let screenshotUUID = tab.screenshotUUID {
savedUUIDs.insert(screenshotUUID.uuidString)
imageStore?.put(screenshotUUID.uuidString, image: screenshot)
}
}
}
// Clean up any screenshots that are no longer associated with a tab.
_ = imageStore?.clearExcluding(savedUUIDs)
return savedTabs.isEmpty ? nil : savedTabs
}
// Async write of the tab state. In most cases, code doesn't care about performing an operation
// after this completes. Deferred completion is called always, regardless of Data.write return value.
// Write failures (i.e. due to read locks) are considered inconsequential, as preserveTabs will be called frequently.
@discardableResult func preserveTabs(_ tabs: [Tab], selectedTab: Tab?) -> Success {
assert(Thread.isMainThread)
guard let savedTabs = prepareSavedTabs(fromTabs: tabs, selectedTab: selectedTab),
let path = tabsStateArchivePath() else {
clearArchive()
return succeed()
}
writeOperation.cancel()
let tabStateData = NSMutableData()
let archiver = NSKeyedArchiver(forWritingWith: tabStateData)
archiver.encode(savedTabs, forKey: "tabs")
archiver.finishEncoding()
let result = Success()
writeOperation = DispatchWorkItem {
let written = tabStateData.write(toFile: path, atomically: true)
log.debug("PreserveTabs write ok: \(written)") // Ignore write failure (could be restoring).
result.fill(Maybe(success: ()))
}
// Delay by 100ms to debounce repeated calls to preserveTabs in quick succession.
// Notice above that a repeated 'preserveTabs' call will 'cancel()' a pending write operation.
serialQueue.asyncAfter(deadline: .now() + 0.100, execute: writeOperation)
return result
}
func restoreStartupTabs(clearPrivateTabs: Bool, tabManager: TabManager) -> Tab? {
let selectedTab = restoreTabs(savedTabs: archivedStartupTabs, clearPrivateTabs: clearPrivateTabs, tabManager: tabManager)
archivedStartupTabs.removeAll()
return selectedTab
}
func restoreTabs(savedTabs: [SavedTab], clearPrivateTabs: Bool, tabManager: TabManager) -> Tab? {
assertIsMainThread("Restoration is a main-only operation")
guard !lockedForReading, savedTabs.count > 0 else { return nil }
lockedForReading = true
defer {
lockedForReading = false
}
var savedTabs = savedTabs
// Make sure to wipe the private tabs if the user has the pref turned on
if clearPrivateTabs {
savedTabs = savedTabs.filter { !$0.isPrivate }
}
var tabToSelect: Tab?
for savedTab in savedTabs {
// Provide an empty request to prevent a new tab from loading the home screen
var tab = tabManager.addTab(flushToDisk: false, zombie: true, isPrivate: savedTab.isPrivate)
tab = savedTab.configureSavedTabUsing(tab, imageStore: imageStore)
if savedTab.isSelected {
tabToSelect = tab
}
}
if tabToSelect == nil {
tabToSelect = tabManager.tabs.first(where: { $0.isPrivate == false })
}
return tabToSelect
}
func clearArchive() {
if let path = tabsStateArchivePath() {
try? FileManager.default.removeItem(atPath: path)
}
}
}
// Functions for testing
extension TabManagerStore {
func testTabCountOnDisk() -> Int {
assert(AppConstants.IsRunningTest)
return tabsToRestore().count
}
}
| mpl-2.0 | 6976fcac7cde97de2b729144b8c2a7bd | 39.005988 | 173 | 0.651399 | 5.374899 | false | false | false | false |
xedin/swift | test/Generics/superclass_constraint.swift | 3 | 6373 | // RUN: %target-typecheck-verify-swift
// RUN: %target-typecheck-verify-swift -typecheck -debug-generic-signatures %s > %t.dump 2>&1
// RUN: %FileCheck %s < %t.dump
class A {
func foo() { }
}
class B : A {
func bar() { }
}
class Other { }
func f1<T : A>(_: T) where T : Other {} // expected-error{{generic parameter 'T' cannot be a subclass of both 'Other' and 'A'}}
// expected-note@-1{{superclass constraint 'T' : 'A' written here}}
func f2<T : A>(_: T) where T : B {}
// expected-warning@-1{{redundant superclass constraint 'T' : 'A'}}
// expected-note@-2{{superclass constraint 'T' : 'B' written here}}
class GA<T> {}
class GB<T> : GA<T> {}
protocol P {}
func f3<T, U>(_: T, _: U) where U : GA<T> {}
func f4<T, U>(_: T, _: U) where U : GA<T> {}
func f5<T, U : GA<T>>(_: T, _: U) {}
func f6<U : GA<T>, T : P>(_: T, _: U) {}
func f7<U, T>(_: T, _: U) where U : GA<T>, T : P {}
func f8<T : GA<A>>(_: T) where T : GA<B> {} // expected-error{{generic parameter 'T' cannot be a subclass of both 'GA<B>' and 'GA<A>'}}
// expected-note@-1{{superclass constraint 'T' : 'GA<A>' written here}}
func f9<T : GA<A>>(_: T) where T : GB<A> {}
// expected-warning@-1{{redundant superclass constraint 'T' : 'GA<A>'}}
// expected-note@-2{{superclass constraint 'T' : 'GB<A>' written here}}
func f10<T : GB<A>>(_: T) where T : GA<A> {}
// expected-warning@-1{{redundant superclass constraint 'T' : 'GA<A>'}}
// expected-note@-2{{superclass constraint 'T' : 'GB<A>' written here}}
func f11<T : GA<T>>(_: T) { } // expected-error{{superclass constraint 'T' : 'GA<T>' is recursive}}
func f12<T : GA<U>, U : GB<T>>(_: T, _: U) { } // expected-error{{superclass constraint 'U' : 'GB<T>' is recursive}} // expected-error{{superclass constraint 'T' : 'GA<U>' is recursive}}
func f13<T : U, U : GA<T>>(_: T, _: U) { } // expected-error{{type 'T' constrained to non-protocol, non-class type 'U'}}
// rdar://problem/24730536
// Superclass constraints can be used to resolve nested types to concrete types.
protocol P3 {
associatedtype T
}
protocol P2 {
associatedtype T : P3
}
class C : P3 {
typealias T = Int
}
class S : P2 {
typealias T = C
}
// CHECK: superclassConformance1
// CHECK: Canonical generic signature: <τ_0_0 where τ_0_0 : C>
func superclassConformance1<T>(t: T)
where T : C, // expected-note{{conformance constraint 'T': 'P3' implied here}}
T : P3 {} // expected-warning{{redundant conformance constraint 'T': 'P3'}}
// CHECK: superclassConformance2
// CHECK: Canonical generic signature: <τ_0_0 where τ_0_0 : C>
func superclassConformance2<T>(t: T)
where T : C, // expected-note{{conformance constraint 'T': 'P3' implied here}}
T : P3 {} // expected-warning{{redundant conformance constraint 'T': 'P3'}}
protocol P4 { }
class C2 : C, P4 { }
// CHECK: superclassConformance3
// CHECK: Canonical generic signature: <τ_0_0 where τ_0_0 : C2>
func superclassConformance3<T>(t: T) where T : C, T : P4, T : C2 {}
// expected-warning@-1{{redundant superclass constraint 'T' : 'C'}}
// expected-note@-2{{superclass constraint 'T' : 'C2' written here}}
// expected-warning@-3{{redundant conformance constraint 'T': 'P4'}}
// expected-note@-4{{conformance constraint 'T': 'P4' implied here}}
protocol P5: A { }
protocol P6: A, Other { } // expected-error {{protocol 'P6' cannot require 'Self' to be a subclass of both 'Other' and 'A'}}
// expected-error@-1{{multiple inheritance from classes 'A' and 'Other'}}
// expected-note@-2 {{superclass constraint 'Self' : 'A' written here}}
func takeA(_: A) { }
func takeP5<T: P5>(_ t: T) {
takeA(t) // okay
}
protocol P7 {
associatedtype Assoc: A, Other
// expected-note@-1{{superclass constraint 'Self.Assoc' : 'A' written here}}
// expected-error@-2{{'Self.Assoc' cannot be a subclass of both 'Other' and 'A'}}
}
// CHECK: superclassConformance4
// CHECK: Generic signature: <T, U where T : P3, U : P3, T.T : C, T.T == U.T>
func superclassConformance4<T: P3, U: P3>(_: T, _: U)
where T.T: C, // expected-note{{superclass constraint 'T.T' : 'C' written here}}
U.T: C, // expected-warning{{redundant superclass constraint 'U.T' : 'C'}}
T.T == U.T { }
// Lookup of superclass associated types from inheritance clause
protocol Elementary {
associatedtype Element
func get() -> Element
}
class Classical : Elementary {
func get() -> Int {
return 0
}
}
func genericFunc<T : Elementary, U : Classical>(_: T, _: U) where T.Element == U.Element {}
// Lookup within superclass constraints.
protocol P8 {
associatedtype B
}
class C8 {
struct A { }
}
func superclassLookup1<T: C8 & P8>(_: T) where T.A == T.B { }
func superclassLookup2<T: P8>(_: T) where T.A == T.B, T: C8 { }
func superclassLookup3<T>(_: T) where T.A == T.B, T: C8, T: P8 { }
// SR-5165
class C9 {}
protocol P9 {}
class C10 : C9, P9 { }
protocol P10 {
associatedtype A: C9
}
// CHECK: superclass_constraint.(file).testP10
// CHECK: Generic signature: <T where T : P10, T.A : C10>
// CHECK: Canonical generic signature: <τ_0_0 where τ_0_0 : P10, τ_0_0.A : C10>
func testP10<T>(_: T) where T: P10, T.A: C10 { }
// Nested types of generic class-constrained type parameters.
protocol Tail {
associatedtype E
}
protocol Rump : Tail {
associatedtype E = Self
}
class Horse<T>: Rump { }
func hasRedundantConformanceConstraint<X : Horse<T>, T>(_: X) where X : Rump {}
// expected-warning@-1 {{redundant conformance constraint 'X': 'Rump'}}
// expected-note@-2 {{conformance constraint 'X': 'Rump' implied here}}
// SR-5862
protocol X {
associatedtype Y : A
}
// CHECK-DAG: .noRedundancyWarning@
// CHECK: Generic signature: <C where C : X, C.Y == B>
func noRedundancyWarning<C : X>(_ wrapper: C) where C.Y == B {}
// Qualified lookup bug -- <https://bugs.swift.org/browse/SR-2190>
protocol Init {
init(x: ())
}
class Base {
required init(y: ()) {}
}
class Derived : Base {}
func g<T : Init & Derived>(_: T.Type) {
_ = T(x: ())
_ = T(y: ())
}
// Binding a class-constrained generic parameter to a subclass existential is
// not sound.
struct G<T : Base> {}
// expected-note@-1 2 {{requirement specified as 'T' : 'Base' [with T = Base & P]}}
_ = G<Base & P>() // expected-error {{'G' requires that 'Base & P' inherit from 'Base'}}
func badClassConstrainedType(_: G<Base & P>) {}
// expected-error@-1 {{'G' requires that 'Base & P' inherit from 'Base'}}
| apache-2.0 | 456fa463e0993e2a60200cbfc9d98795 | 28.6 | 186 | 0.630893 | 2.999057 | false | false | false | false |
shajrawi/swift | test/ParseableInterface/stored-properties.swift | 1 | 4083 | // RUN: %empty-directory(%t)
// RUN: %target-swift-frontend -typecheck -emit-parseable-module-interface-path %t.swiftinterface %s
// RUN: %FileCheck %s < %t.swiftinterface --check-prefix CHECK --check-prefix COMMON
// RUN: %target-swift-frontend -typecheck -emit-parseable-module-interface-path %t-resilient.swiftinterface -enable-library-evolution %s
// RUN: %FileCheck %s < %t-resilient.swiftinterface --check-prefix RESILIENT --check-prefix COMMON
// RUN: %target-swift-frontend -emit-module -o %t/Test.swiftmodule %t.swiftinterface -disable-objc-attr-requires-foundation-module
// RUN: %target-swift-frontend -emit-module -o /dev/null -merge-modules %t/Test.swiftmodule -module-name Test -emit-parseable-module-interface-path - | %FileCheck %s --check-prefix CHECK --check-prefix COMMON
// RUN: %target-swift-frontend -emit-module -o %t/TestResilient.swiftmodule -enable-library-evolution %t-resilient.swiftinterface -disable-objc-attr-requires-foundation-module
// RUN: %target-swift-frontend -emit-module -o /dev/null -merge-modules %t/TestResilient.swiftmodule -module-name TestResilient -enable-library-evolution -emit-parseable-module-interface-path - | %FileCheck %s --check-prefix RESILIENT --check-prefix COMMON
// COMMON: public struct HasStoredProperties {
public struct HasStoredProperties {
// COMMON: public var computedGetter: [[INT:.*Int]] {
// COMMON-NEXT: get
// COMMON-NEXT: }
public var computedGetter: Int { return 3 }
// COMMON: public var computedGetSet: [[INT]] {
// COMMON-NEXT: get
// COMMON-NEXT: set
// COMMON-NEXT: }
public var computedGetSet: Int {
get { return 3 }
set {}
}
// COMMON: public let simpleStoredImmutable: [[INT]]{{$}}
public let simpleStoredImmutable: Int
// COMMON: public var simpleStoredMutable: [[INT]]{{$}}
public var simpleStoredMutable: Int
// CHECK: @_hasStorage public var storedWithObservers: [[BOOL:.*Bool]] {
// RESILIENT: {{^}} public var storedWithObservers: [[BOOL:.*Bool]] {
// COMMON-NEXT: get
// COMMON-NEXT: set
// COMMON-NEXT: }
public var storedWithObservers: Bool {
willSet {}
}
// CHECK: @_hasStorage public var storedPrivateSet: [[INT]] {
// RESILIENT: {{^}} public var storedPrivateSet: [[INT]] {
// COMMON-NEXT: get
// COMMON-NEXT: }
public private(set) var storedPrivateSet: Int
// CHECK: private var privateVar: [[BOOL]]
// RESILIENT-NOT: private var privateVar: [[BOOL]]
private var privateVar: Bool
// CHECK: @_hasStorage @_hasInitialValue public var storedWithObserversInitialValue: [[INT]] {
// RESILIENT: {{^}} public var storedWithObserversInitialValue: [[INT]] {
// COMMON-NEXT: get
// COMMON-NEXT: set
// COMMON-NEXT: }
public var storedWithObserversInitialValue: Int = 0 {
didSet {}
}
// COMMON: public init(){{$}}
public init() {
self.simpleStoredImmutable = 0
self.simpleStoredMutable = 0
self.storedPrivateSet = 0
self.storedWithObservers = false
self.privateVar = false
}
// COMMON: }
}
// COMMON: @_fixed_layout public struct BagOfVariables {
@_fixed_layout
public struct BagOfVariables {
// COMMON: private let hidden: [[INT]] = 0
private let hidden: Int = 0
// COMMON: public let a: [[INT]] = 0
public let a: Int = 0
// COMMON: public var b: [[BOOL]] = false
public var b: Bool = false
// COMMON: public var c: [[INT]] = 0
public var c: Int = 0
// COMMON: public init()
public init() {}
// COMMON: }
}
// COMMON: @_fixed_layout public struct HasStoredPropertiesFixedLayout {
@_fixed_layout
public struct HasStoredPropertiesFixedLayout {
// COMMON: public var simpleStoredMutable: [[BAGOFVARIABLES:.*BagOfVariables]]
public var simpleStoredMutable: BagOfVariables
// COMMON: @_hasStorage public var storedWithObservers: [[BAGOFVARIABLES]] {
// COMMON-NEXT: get
// COMMON-NEXT: set
// COMMON-NEXT: }
public var storedWithObservers: BagOfVariables {
didSet {}
}
// COMMON: public init(){{$}}
public init() {
self.simpleStoredMutable = BagOfVariables()
self.storedWithObservers = BagOfVariables()
}
}
| apache-2.0 | e9950396d959aeed00aa426cfa68fd39 | 33.897436 | 256 | 0.696057 | 4.030602 | false | true | false | false |
ZeeQL/ZeeQL3 | Sources/ZeeQL/Access/AdaptorQueryColumnRepresentable.swift | 1 | 2416 | //
// AdaptorQueryColumnRepresentable.swift
// ZeeQL3
//
// Created by Helge Hess on 08.05.17.
// Copyright © 2017 ZeeZide GmbH. All rights reserved.
//
public protocol AdaptorQueryColumnRepresentable {
static func fromAdaptorQueryValue(_ value: Any?) throws -> Self
}
enum AdaptorQueryTypeError : Swift.Error {
case NullInNonOptionalType(Any.Type)
case CannotConvertValue(Any.Type, Any)
}
extension String : AdaptorQueryColumnRepresentable {
public static func fromAdaptorQueryValue(_ value: Any?) throws -> String {
guard let value = value
else {
throw AdaptorQueryTypeError.NullInNonOptionalType(String.self)
}
if let value = value as? String { return value }
return "\(value)"
}
}
extension Int : AdaptorQueryColumnRepresentable {
public static func fromAdaptorQueryValue(_ value: Any?) throws -> Int {
guard let value = value
else {
throw AdaptorQueryTypeError.NullInNonOptionalType(Int.self)
}
switch value {
case let typedValue as Int: return typedValue
case let typedValue as Int64: return Int(typedValue)
case let typedValue as Int32: return Int(typedValue)
case let typedValue as String:
guard let i = Int(typedValue)
else {
throw AdaptorQueryTypeError.CannotConvertValue(Int.self, value)
}
return i
default:
// ERROR: VALUE: 9999 Int32
globalZeeQLLogger.error("VALUE: \(value) \(type(of: value))")
throw AdaptorQueryTypeError.CannotConvertValue(Int.self, value)
}
}
}
extension Optional where Wrapped : AdaptorQueryColumnRepresentable {
// this is not picked
// For this: you’ll need conditional conformance. Swift 4, hopefully
public static func fromAdaptorQueryValue(_ value: Any?) throws
-> Optional<Wrapped>
{
guard let value = value else { return .none }
return try Wrapped.fromAdaptorQueryValue(value)
}
}
extension Optional : AdaptorQueryColumnRepresentable {
public static func fromAdaptorQueryValue(_ value: Any?) throws
-> Optional<Wrapped>
{
guard let value = value else { return .none }
guard let c = Wrapped.self as? AdaptorQueryColumnRepresentable.Type
else {
throw AdaptorQueryTypeError.CannotConvertValue(Int.self, value)
}
return try c.fromAdaptorQueryValue(value) as? Wrapped
}
}
| apache-2.0 | ddf49a6009b128aafdfe7146c1558a2a | 27.05814 | 76 | 0.684625 | 4.731373 | false | false | false | false |
PiHanHsu/myscorebaord_lite | myscoreboard_lite/Controller/TeamTableViewController.swift | 1 | 4354 | //
// TeamTableViewController.swift
// myscoreboard_lite
//
// Created by PiHan on 2017/9/18.
// Copyright © 2017年 PiHan. All rights reserved.
//
import UIKit
import Alamofire
//import SDWebImage
import Kingfisher
class TeamTableViewController: UITableViewController {
override func viewDidLoad() {
super.viewDidLoad()
navigationController?.setNavigationBarHidden(false, animated: false)
tableView.tableFooterView = UIView(frame: CGRect.zero)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: - Table view data source
override func numberOfSections(in tableView: UITableView) -> Int {
// #warning Incomplete implementation, return the number of sections
return 1
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// #warning Incomplete implementation, return the number of rows
return DataSource.sharedInstance.teams.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "TeamTableViewCell", for: indexPath) as! TeamTableViewCell
let teams = DataSource.sharedInstance.teams
let imageURL = URL(string: teams[indexPath.row].teamImageUrl)
cell.nameLabel.text = teams[indexPath.row].name
cell.memberCountLabel.text = "球隊人數: \(teams[indexPath.row].players.count)"
cell.teamImageView.kf.indicatorType = .activity
let processor = ResizingImageProcessor(referenceSize: CGSize(width: cell.teamImageView.frame.size.width, height: cell.teamImageView.frame.size.height))
DispatchQueue.main.async {
cell.teamImageView.kf.setImage(with: imageURL, placeholder: UIImage(named: "user_placeholder"), options: [.processor(processor)], progressBlock: nil, completionHandler: nil)
}
//cell.teamImageView.sd_setShowActivityIndicatorView(true)
//cell.teamImageView.sd_setIndicatorStyle(.gray)
//cell.teamImageView.sd_setImage(with: imageURL, placeholderImage: UIImage(named: "user_placeholder"), options: .retryFailed, completed: nil)
return cell
}
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
DataSource.sharedInstance.currentPlayingTeamIndex = indexPath.row
performSegue(withIdentifier: "SelectPlayers", sender: self)
}
override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return 120
}
@IBAction func logout(_ sender: Any) {
let params = ["auth_token" : DataSource.sharedInstance.auth_token]
Alamofire.request("https://product.myscoreboardapp.com/api/v1/logout", method: .post, parameters: params, encoding: JSONEncoding.default, headers: nil).validate().responseJSON{response in
if response.result.isSuccess{
DataSource.sharedInstance = DataSource()
self.navigationController?.popViewController(animated: true)
}else{
print("can't logout")
}
}
}
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "SelectPlayers" {
let vc = segue.destination as! SelectPlayersCollectionViewController
let index = DataSource.sharedInstance.currentPlayingTeamIndex
vc.team = DataSource.sharedInstance.teams[index]
}
if segue.identifier == "GoToTeamViewController" {
let nav = segue.destination as! UINavigationController
let vc = nav.topViewController as! TeamViewController
if let cell = sender as? UITableViewCell {
if let indexPath = tableView.indexPath(for: cell){
print(indexPath.row)
vc.team = DataSource.sharedInstance.teams[indexPath.row]
}
}
}
}
}
| mit | 36b713b3c8177285a9198aad861f6231 | 38.463636 | 195 | 0.666897 | 5.161712 | false | false | false | false |
tappytaps/TTLiveAgentWidget | Pod/Classes/Controllers/TTLiveAgentWidgetQuestionsController.swift | 1 | 8823 | //
// TTLiveAgentWidgetQuestionsViewController.swift
// liveagent-ioswidget
//
// Created by Lukas Boura on 02/02/15.
// Copyright (c) 2015 TappyTaps s.r.o. All rights reserved.
//
import UIKit
import MessageUI
class TTLiveAgentWidgetQuestionsController: UITableViewController {
var topic: TTLiveAgentWidgetSupportTopic!
private var onceReload: dispatch_once_t = 0
private let kLAArticleCellIdentifier = "TTLiveAgentWidgetArticleCell"
private let kLAIconCellIdentifier = "TTLiveAgentWidgetIconCell"
private var supportWidget = TTLiveAgentWidget.getInstance()
var contentOffset: CGFloat!
var articles: [TTLiveAgentWidgetSupportArticle]!
var tintColor: UIColor!
var barColor: UIColor!
var titleColor: UIColor!
var barStyle: UIBarStyle!
override func viewDidLoad() {
super.viewDidLoad()
self.navigationItem.title = topic.title
let backButton = UIBarButtonItem(title: NSLocalizedString("Back", comment: "Back button."), style: .Plain, target: self, action: nil)
self.navigationController?.navigationBar.topItem?.backBarButtonItem = backButton
if tintColor != nil {
self.navigationController?.navigationBar.tintColor = tintColor
}
if barColor != nil {
self.navigationController?.navigationBar.barTintColor = barColor
self.navigationController?.navigationBar.translucent = false
}
if titleColor != nil {
self.navigationController?.navigationBar.titleTextAttributes = [
NSForegroundColorAttributeName: titleColor
]
}
if barStyle != nil {
self.navigationController?.navigationBar.barStyle = barStyle
}
articles = supportWidget.dataManager.getArticlesByKeyword(topic.key)
articles.sort({$0.order < $1.order})
setupViews()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
if let tableView = tableView {
if contentOffset != nil {
dispatch_async(dispatch_get_main_queue(), {
self.tableView.setContentOffset(CGPoint(x: 0, y: self.contentOffset), animated: false)
})
}
dispatch_once(&onceReload, {
dispatch_async(dispatch_get_main_queue(), {
self.tableView.reloadData()
})
})
}
}
override func loadView() {
if !isViewLoaded() {
let appFrame = UIScreen.mainScreen().applicationFrame
let contentView = UIView(frame: appFrame)
contentView.backgroundColor = UIColor.whiteColor()
self.view = contentView
self.view.autoresizesSubviews = true
}
}
func setupViews() {
self.tableView = UITableView(frame: self.view.frame, style: UITableViewStyle.Grouped)
self.tableView.delaysContentTouches = false
self.tableView.estimatedRowHeight = 100;
self.tableView.rowHeight = UITableViewAutomaticDimension;
self.tableView.registerClass(UITableViewCell.self, forCellReuseIdentifier: kLAArticleCellIdentifier)
self.tableView.registerClass(IconTableViewCell.self, forCellReuseIdentifier: kLAIconCellIdentifier)
}
override func willAnimateRotationToInterfaceOrientation(toInterfaceOrientation: UIInterfaceOrientation, duration: NSTimeInterval) {
if let tableView = self.tableView {
tableView.reloadData()
}
}
}
//
// UITableView DataSource
//
extension TTLiveAgentWidgetQuestionsController {
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 2
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if section == 0 {
if let articles = articles {
return articles.count > supportWidget.maxArticlesCount ? supportWidget.maxArticlesCount : articles.count
}
return 0
} else {
return 1
}
}
override func tableView(tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
switch (section) {
case 0:
if articles.count == 0 {
return nil
} else {
return NSLocalizedString("Popular questions", comment: "Popular questions table view section header title.")
}
case 1:
return NSLocalizedString("Contact us", comment: "Contact us table view section header title.")
default:
return ""
}
}
override func tableView(tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
if section == 0 {
if articles == nil || articles.count == 0 {
return 0.01
}
}
return UITableViewAutomaticDimension
}
override func tableView(tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
return UITableViewAutomaticDimension
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
if indexPath.section == 0 {
var cell = tableView.dequeueReusableCellWithIdentifier(kLAArticleCellIdentifier) as! UITableViewCell
var topic = articles[indexPath.row]
cell.accessoryType = .DisclosureIndicator
cell.textLabel?.text = topic.title
cell.textLabel?.font = UIFont.systemFontOfSize(16)
cell.textLabel?.numberOfLines = 0
cell.textLabel?.lineBreakMode = .ByWordWrapping
cell.autoresizesSubviews = true
cell.autoresizingMask = UIViewAutoresizing.FlexibleHeight
return cell
} else {
var cell = tableView.dequeueReusableCellWithIdentifier(kLAIconCellIdentifier) as! IconTableViewCell
cell.accessoryType = .DisclosureIndicator
let bundle = NSBundle(forClass: TTLiveAgentWidgetQuestionsController.self)
let imagePath = bundle.pathForResource("Envelope", ofType: "png")
if imagePath != nil {
var image = UIImage(contentsOfFile: imagePath!)
image = image?.imageWithRenderingMode(.AlwaysTemplate)
cell.iconView.image = image
}
if tintColor != nil {
cell.iconView.tintColor = tintColor
}
cell.titleLabel.text = NSLocalizedString("Send email to support", comment: "Send support email table view row.")
return cell
}
}
override func tableView(tableView: UITableView, estimatedHeightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
return 100
}
}
//
// UITableView Delegate
//
extension TTLiveAgentWidgetQuestionsController {
override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
tableView.deselectRowAtIndexPath(indexPath, animated: true)
if indexPath.section == 0 {
let contentOffset = tableView.contentOffset.y
let lawa = TTLiveAgentWidgetArticleController()
lawa.article = articles[indexPath.row]
self.navigationController?.pushViewController(lawa, animated: true)
} else if indexPath.section == 1 {
supportWidget.emailComposer.show(fromController: self, topic: topic)
}
}
}
private class IconTableViewCell: UITableViewCell {
var iconView: UIImageView!
var titleLabel: UILabel!
override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
setupViews()
}
required init(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
setupViews()
}
func setupViews() {
iconView = UIImageView()
iconView.frame = CGRect(x: 12, y: 14, width: self.contentView.frame.height - 10, height: self.contentView.frame.height - 28)
iconView.contentMode = UIViewContentMode.ScaleAspectFit
contentView.addSubview(iconView)
titleLabel = UILabel()
titleLabel.frame = CGRect(x: iconView.frame.maxX + 6, y: 0, width: self.contentView.frame.width - (iconView.frame.maxX + 6), height: self.contentView.frame.height)
titleLabel.font = UIFont.systemFontOfSize(16)
contentView.addSubview(titleLabel)
self.accessoryType = .DisclosureIndicator
}
}
| mit | 8ea29412936a15477efd1fa3b5468a37 | 35.609959 | 171 | 0.640145 | 5.6341 | false | false | false | false |
SwiftGen/SwiftGen | SwiftGen.playground/Pages/XCAssets-Demo.xcplaygroundpage/Contents.swift | 1 | 5408 | //: #### Other pages
//:
//: * [Demo for `colors` parser](Colors-Demo)
//: * [Demo for `coredata` parser](CoreData-Demo)
//: * [Demo for `files` parser](Files-Demo)
//: * [Demo for `fonts` parser](Fonts-Demo)
//: * [Demo for `ib` parser](InterfaceBuilder-Demo)
//: * [Demo for `json` parser](JSON-Demo)
//: * [Demo for `plist` parser](Plist-Demo)
//: * [Demo for `strings` parser](Strings-Demo)
//: * Demo for `xcassets` parser
//: * [Demo for `yaml` parser](YAML-Demo)
// setup code to make this work in playground
// swiftlint:disable convenience_type
private final class BundleToken {
static let bundle: Bundle = {
#if SWIFT_PACKAGE
return Bundle.module
#else
return Bundle(for: BundleToken.self)
#endif
}()
}
// swiftlint:enable convenience_type
bundle = BundleToken.bundle
//: #### Example of code generated by `xcassets` parser with "swift5" template
#if os(macOS)
import AppKit
#elseif os(iOS)
import ARKit
import UIKit
#elseif os(tvOS) || os(watchOS)
import UIKit
#endif
import PlaygroundSupport
// swiftlint:disable superfluous_disable_command
// swiftlint:disable file_length
// MARK: - Asset Catalogs
// swiftlint:disable identifier_name line_length nesting type_body_length type_name
internal enum Asset {
internal enum Files {
internal static let data = DataAsset(name: "Data")
internal enum Json {
internal static let data = DataAsset(name: "Json/Data")
}
internal static let readme = DataAsset(name: "README")
}
internal enum Food {
internal enum Exotic {
internal static let banana = ImageAsset(name: "Exotic/Banana")
internal static let mango = ImageAsset(name: "Exotic/Mango")
}
internal enum Round {
internal static let apricot = ImageAsset(name: "Round/Apricot")
internal static let apple = ImageAsset(name: "Round/Apple")
internal enum Double {
internal static let cherry = ImageAsset(name: "Round/Double/Cherry")
}
internal static let tomato = ImageAsset(name: "Round/Tomato")
}
internal static let `private` = ImageAsset(name: "private")
}
internal enum Styles {
internal enum _24Vision {
internal static let background = ColorAsset(name: "24Vision/Background")
internal static let primary = ColorAsset(name: "24Vision/Primary")
}
internal static let orange = ImageAsset(name: "Orange")
internal enum Vengo {
internal static let primary = ColorAsset(name: "Vengo/Primary")
internal static let tint = ColorAsset(name: "Vengo/Tint")
}
}
internal enum Symbols {
internal static let exclamationMark = SymbolAsset(name: "Exclamation Mark")
internal static let plus = SymbolAsset(name: "Plus")
}
internal enum Targets {
internal static let bottles = ARResourceGroupAsset(name: "Bottles")
internal static let paintings = ARResourceGroupAsset(name: "Paintings")
internal static let posters = ARResourceGroupAsset(name: "Posters")
}
}
// swiftlint:enable identifier_name line_length nesting type_body_length type_name
//: #### Usage Example
// images
// Tip: Use "Show Result" box on the right to display the images inline in playground
let image1 = UIImage(asset: Asset.Food.Exotic.banana)
let image2 = Asset.Food.Round.tomato.image
// Show fruits animated in the playground's liveView
PlaygroundPage.current.liveView = {
let assets = [
Asset.Food.Exotic.banana,
Asset.Food.Exotic.mango,
Asset.Food.Round.apricot,
Asset.Food.Round.apple,
Asset.Food.Round.tomato,
Asset.Food.Round.Double.cherry
]
let iv = UIImageView(frame: CGRect(x: 0, y: 0, width: 200, height: 200))
iv.animationImages = assets.map(\.image)
iv.animationDuration = TimeInterval(assets.count)/2 // 0.5s per image
iv.startAnimating()
return iv
}()
// colors
let color1 = UIColor(asset: Asset.Styles.Vengo.primary)
let color2 = Asset.Styles.Vengo.tint.color
/* Colors support variations for different interface styles (light/dark mode) */ _ = {
let vc = UIViewController()
vc.overrideUserInterfaceStyle = .dark
vc.view.backgroundColor = Asset.Styles.Vengo.primary.color
vc.view // Use "Show Result" box on the right to display contextualized color inline in playground
vc.overrideUserInterfaceStyle = .light
vc.view // Use "Show Result" box on the right to display contextualized color inline in playground
}()
// data
let dataAsset1 = NSDataAsset(asset: Asset.Files.data)
let dataAsset2 = Asset.Files.readme.data
let readmeText = String(data: dataAsset2.data, encoding: .utf8) ?? "-"
print(readmeText)
// AR resources
let paintingReferenceImages = Asset.Targets.paintings.referenceImages
let bottleReferenceObjects = Asset.Targets.bottles.referenceObjects
// symbols
let plus = Asset.Symbols.plus.image
let style = UIImage.SymbolConfiguration(textStyle: .headline)
let styled = Asset.Symbols.exclamationMark.image(with: style)
// SwiftUI
import SwiftUI
import PlaygroundSupport
struct ContentView: View {
var body: some View {
VStack {
Image(decorative: Asset.Food.Exotic.mango)
Button(action: {}) {
HStack {
Asset.Symbols.plus.swiftUIImage
Text("Add")
}
}
.padding()
.foregroundColor(Asset.Styles.Vengo.tint.swiftUIColor)
.background(Asset.Styles.Vengo.primary.swiftUIColor)
.cornerRadius(.infinity)
}
}
}
PlaygroundPage.current.setLiveView(ContentView())
| mit | bca65f5ab3ce108376a89094ebb908c9 | 30.625731 | 100 | 0.706731 | 3.935953 | false | false | false | false |
outware/Scenarios | Scenarios/Scenario.swift | 1 | 3359 | // Copyright © 2015 Outware Mobile. All rights reserved.
/// Define a scenario by giving it a name and then adding steps, like so:
///
/// Scenario("Greeting on first load")
/// .Given("the app has launched")
/// .Then("the text 'Hello, world!' is displayed")
///
/// After the last step is defined, the scenario is compiled into a Quick example
/// block by looking up the step definitions based on the step names. The test
/// fails if any of the steps are undefined.
public final class Scenario: Preparable, Actionable, ScenarioBuilder {
private let name: String
private let file: StaticString
private let line: UInt
private let commitFunc: CommitFunc
private var stepDescriptions: [StepMetadata] = []
public init(_ name: String, file: StaticString = #file, line: UInt = #line, commit: @escaping CommitFunc) {
self.name = name
self.file = file
self.line = line
self.commitFunc = commit
}
public convenience init(_ name: String, file: StaticString = #file, line: UInt = #line) {
self.init(
name,
file: file,
line: line,
commit: quick_it
)
}
public func Given(_ description: String, file: StaticString = #file, line: UInt = #line) -> Prepared {
add(stepWithDescription: description, file: file, line: line)
return Prepared(self)
}
public func When(_ description: String, file: StaticString = #file, line: UInt = #line) -> Actioned {
add(stepWithDescription: description, file: file, line: line)
return Actioned(self)
}
deinit {
let unresolvedSteps = stepDescriptions.map { metadata in
{ (metadata, StepDefinition.lookup(metadata.description, forStepInFile: metadata.file, atLine: metadata.line)) }
}
commit(name, file: file, line: line) {
let result: ResolvedSteps = unresolvedSteps.reduce(.matchedActions([])) { result, lookup in
switch result {
case .missingStep:
return result
case var .matchedActions(actions):
let (metadata, query) = lookup()
if let action = query() {
actions.append(action)
return .matchedActions(actions)
} else {
return .missingStep(metadata)
}
}
}
switch result {
case let .missingStep(metadata):
XCTFail("couldn't match step description: '\(metadata.description)'", file: metadata.file, line: metadata.line)
case let .matchedActions(actions):
for action in actions {
action()
}
}
}
}
private func commit(_ description: String, file: StaticString, line: UInt, closure: @escaping () -> Void) {
commitFunc(description, file, line, closure)
}
internal func add(stepWithDescription description: String, file: StaticString, line: UInt) {
stepDescriptions.append((description: description, file: file, line: line))
}
}
public typealias CommitFunc = (String, StaticString, UInt, @escaping () -> Void) -> Void
private let quick_it: CommitFunc = { description, file, line, closure in
it(description, file: String(describing: file), line: line, closure: closure)
}
private typealias StepMetadata = (description: String, file: StaticString, line: UInt)
private enum ResolvedSteps {
case missingStep(StepMetadata)
case matchedActions([StepActionFunc])
}
import Quick
import XCTest
| apache-2.0 | 151cd3febf801854071a84bb578e27c3 | 31.288462 | 119 | 0.664681 | 4.181818 | false | false | false | false |
CaptainTeemo/MetroIndicatorView | MetroIndicatorView/MetroIndicatorView.swift | 1 | 3554 | //
// MetroIndicatorView.swift
// Teegramo
//
// Created by Captain Teemo on 9/16/15.
// Copyright © 2015 Captain Teemo. All rights reserved.
//
import UIKit
import QuartzCore
class Circle: UIView {
var color = UIColor.whiteColor()
override init(frame: CGRect) {
super.init(frame: frame)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func drawRect(rect: CGRect) {
let context = UIGraphicsGetCurrentContext()
self.color.set()
CGContextFillEllipseInRect(context, self.frame)
CGContextAddArc(context, self.frame.width / 3, self.frame.height / 3, self.frame.height / 3 - 1, 0, 2 * CGFloat(M_PI), 1)
CGContextDrawPath(context, .Fill)
}
}
class MetroIndicatorView: UIView {
var isAnimating = false
var circleCount = 0
var maxCircleCount = 4
var circleSize: CGFloat = 0
var radius: CGFloat = 0
var color = UIColor.whiteColor()
var circleDelay: NSTimer!
override var frame: CGRect {
didSet {
if self.isAnimating {
self.stopAnimating()
self.startAnimating()
}
}
}
override init(frame: CGRect) {
super.init(frame: frame)
}
init(frame: CGRect, color: UIColor) {
super.init(frame: frame)
self.color = color
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
func startAnimating() {
if !self.isAnimating {
self.isAnimating = true
self.circleCount = 0
self.radius = self.frame.width / 2
if self.frame.width > self.frame.height {
self.radius = self.frame.height / 2
}
self.circleSize = 10 * self.radius / 55
self.circleDelay = NSTimer.scheduledTimerWithTimeInterval(0.2, target: self, selector: "nextCircle", userInfo: nil, repeats: true)
}
}
func nextCircle() {
if self.circleCount < self.maxCircleCount {
self.circleCount += 1
let circle = Circle(frame: CGRect(x: (self.frame.width - self.circleSize) / 2 - 1, y: self.frame.height - self.circleSize - 1, width: self.circleSize + 2, height: self.circleSize + 2))
circle.color = self.color
circle.backgroundColor = UIColor.clearColor()
self.addSubview(circle)
let circlePath = CGPathCreateMutable()
var transform = CGAffineTransformIdentity
CGPathMoveToPoint(circlePath, nil, 0, 0)
CGPathAddLineToPoint(circlePath, &transform, 350, 0)
let circleAnimation = CAKeyframeAnimation(keyPath: "position")
circleAnimation.duration = 2.5
circleAnimation.timingFunction = CAMediaTimingFunction(controlPoints: 0.15, 0.6, 0.85, 0.4)
circleAnimation.calculationMode = kCAAnimationPaced
circleAnimation.path = circlePath
circleAnimation.repeatCount = Float.infinity
circle.layer.addAnimation(circleAnimation, forKey: "circleAnimation")
} else {
self.circleDelay.invalidate()
}
}
func stopAnimating() {
self.layer.removeAllAnimations()
self.circleDelay.invalidate()
for view in self.subviews {
view.removeFromSuperview()
}
self.isAnimating = false
}
}
| mit | 9a66a9e185cda955d627c02b13ea6c58 | 29.895652 | 196 | 0.592176 | 4.75 | false | false | false | false |
stripysock/SwiftGen | swiftgen-cli/colors.swift | 1 | 934 | //
// SwiftGen
// Copyright (c) 2015 Olivier Halligon
// MIT Licence
//
import Commander
import PathKit
import GenumKit
let colorsCommand = command(
outputOption,
templateOption("colors"), templatePathOption,
Option<String>("enumName", "Name", flag: "e", description: "The name of the enum to generate"),
Argument<Path>("FILE", description: "Colors.txt file to parse.", validator: fileExists)
) { output, templateName, templatePath, enumName, path in
let parser = ColorsFileParser()
do {
try parser.parseTextFile(String(path))
let templateRealPath = try findTemplate("colors", templateShortName: templateName, templateFullPath: templatePath)
let template = try GenumTemplate(path: templateRealPath)
let context = parser.stencilContext(enumName: enumName)
let rendered = try template.render(context)
output.write(rendered)
} catch {
print("Failed to render template \(error)")
}
}
| mit | fc147441fb431b32701ec877f90792ac | 30.133333 | 118 | 0.72591 | 4.344186 | false | false | false | false |
AcelLuxembourg/LidderbuchApp | Lidderbuch/LBLyricsView.swift | 1 | 11257 | //
// LBLyricsView.swift
// Lidderbuch
//
// Copyright (c) 2015 Fränz Friederes <[email protected]>
// Licensed under the MIT license.
//
import UIKit
class LBLyricsView: UIScrollView
{
fileprivate var lineOrigins: [CGPoint]!
fileprivate var lineViews: [[UIView]]!
weak var lyricsViewDelegate: LBLyricsViewDelegate?
@IBOutlet var headerView: UIView? {
didSet {
if headerView != nil {
addSubview(headerView!)
} else if oldValue != nil {
oldValue!.removeFromSuperview()
}
invalidateLyricsLayout()
}
}
var tapGestureRecognizer: UITapGestureRecognizer!
var paragraphs = [LBParagraph]() {
didSet {
invalidateLyricsLayout()
}
}
var font = UIFont(name: "Georgia", size: 17.0)! {
didSet {
invalidateLyricsLayout()
}
}
var textColor = UIColor(white: 0.15, alpha: 1.0) {
didSet {
setNeedsDisplay()
}
}
var lyricsInset = UIEdgeInsets(top: 20.0, left: 20.0, bottom: 20.0, right: 20.0) {
didSet {
invalidateLyricsLayout()
}
}
var lineHeight: CGFloat = 27 {
didSet {
invalidateLyricsLayout()
}
}
var paragraphPadding: CGFloat = 27 {
didSet {
invalidateLyricsLayout()
}
}
fileprivate let lineWrapInset: CGFloat = 24
var refrainParagraphInset: CGFloat = 0 {
didSet {
invalidateLyricsLayout()
}
}
var refrainFont: UIFont = UIFont(name: "Georgia-Italic", size: 17.0)! {
didSet {
invalidateLyricsLayout()
}
}
var highlightedLine: Int? = nil {
didSet {
if highlightedLine != oldValue && lineViews != nil
{
// go through all anchor views
for i in 0..<lineViews!.count
{
var anchorAlpha: CGFloat = 1.0
if highlightedLine != nil && i != highlightedLine! {
anchorAlpha = 0.4
}
// change alpha of views
let views = lineViews![i]
for view in views {
view.alpha = anchorAlpha
}
}
if highlightedLine != nil {
scrollToLine(highlightedLine!)
}
// inform delegate
if let delegate = lyricsViewDelegate {
delegate.lyricsView(self, didHighlightLine: highlightedLine)
}
}
}
}
required init?(coder aDecoder: NSCoder)
{
super.init(coder: aDecoder)
// redraw content if bounds change
contentMode = .redraw
backgroundColor = UIColor.white
// configure tab gesture recognizer
tapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(LBLyricsView.handleTapGesture(_:)))
addGestureRecognizer(tapGestureRecognizer)
}
override func layoutSubviews()
{
super.layoutSubviews()
layoutLyrics()
}
fileprivate func invalidateLyricsLayout()
{
// reset layout
lineOrigins = nil
lineViews = nil
}
fileprivate func layoutLyrics()
{
let width = bounds.size.width
// only layout if width changed
if contentSize.width == width {
return
}
// remove all views
if lineViews != nil {
for fragmentViews in lineViews {
for fragmentView in fragmentViews {
fragmentView.removeFromSuperview()
}
}
}
// reset layout
lineOrigins = [CGPoint]()
lineViews = [[UIView]]()
// load images
let lineBreakImage = UIImage(named: "LineBreakIcon")!
// layout each paragraph
var y: CGFloat = lyricsInset.top
// let the cursor jump below header view
if headerView != nil {
y += headerView!.bounds.size.height
}
for paragraph: LBParagraph in paragraphs
{
let paragraphFont: UIFont = (paragraph.refrain ? refrainFont : font)
let lines = paragraph.content.components(separatedBy: "\n")
for line: String in lines
{
// determin line alpha according to highlighted line
var lineAlpha: CGFloat = 1.0
if highlightedLine != nil && lineViews.count + 1 != highlightedLine! {
lineAlpha = 0.4
}
// wrap line in multiple fragments
// and consume remainder
var fragmentViews = [UIView]()
var remainder: String? = line
while (remainder != nil)
{
// calculate line offset
let x: CGFloat = 0
+ lyricsInset.left
+ (paragraph.refrain ? refrainParagraphInset : 0)
+ (fragmentViews.count > 0 ? lineWrapInset : 0)
if fragmentViews.count == 0
{
// at first iteration store line origin
lineOrigins.append(CGPoint(x: x, y: y))
}
else if fragmentViews.count == 1
{
// create line break view
let lineBreakView = UIImageView()
lineBreakView.image = lineBreakImage
lineBreakView.alpha = lineAlpha
lineBreakView.frame = CGRect(x: x - 22.0, y: y, width: 0.0, height: 0.0)
lineBreakView.sizeToFit()
fragmentViews.append(lineBreakView)
addSubview(lineBreakView)
}
// wrap line in container width
let result = wrapText(remainder!, font: font, containerWidth: width - x - lyricsInset.right)
remainder = result.remainder
// create line fragment view
let fragmentView = UILabel()
fragmentView.text = result.fragment
fragmentView.textColor = textColor
fragmentView.font = paragraphFont
fragmentView.alpha = lineAlpha
fragmentView.frame = CGRect(x: x, y: y, width: 0.0, height: 0.0)
fragmentView.sizeToFit()
fragmentViews.append(fragmentView)
addSubview(fragmentView)
y += lineHeight
}
// add fragment views to line
lineViews.append(fragmentViews)
}
y += paragraphPadding
}
y += lyricsInset.bottom - paragraphPadding
// set the intrinsic layout size
contentSize = CGSize(width: width, height: y)
}
fileprivate func wrapText(_ text: String, font: UIFont, containerWidth: CGFloat)
-> (fragment: String, remainder: String?)
{
// compose attributed string with given font
let attributedString = NSMutableAttributedString(string: text)
attributedString.addAttribute(NSFontAttributeName, value: font,
range: NSMakeRange(0, attributedString.length))
// compose layout manager
let layoutManager = NSLayoutManager()
let textContainer = NSTextContainer(size: CGSize(width: containerWidth, height: CGFloat.greatestFiniteMagnitude));
layoutManager.addTextContainer(textContainer)
let textStorage = NSTextStorage(attributedString: attributedString)
textStorage.addLayoutManager(layoutManager)
var result: (fragment: String, remainder: String?)?
// go through each line fragment
layoutManager.enumerateLineFragments(forGlyphRange: NSMakeRange(0, layoutManager.numberOfGlyphs), using: {
(rect, usedRect, textContainer, glyphRange, stop) in
// we are only interested in the first fragment
if (result == nil)
{
let range = layoutManager.characterRange(forGlyphRange: glyphRange, actualGlyphRange: nil)
// substring wrapped line and remainder
let fragment = NSString(string: text).substring(with: range)
let remainder: String = NSString(string: text).substring(from: range.length)
result = (fragment: fragment, remainder: (remainder.count > 0 ? remainder : nil))
}
})
return result!
}
func lineNextToTopOffset(_ topOffset: CGFloat) -> Int
{
layoutLyrics()
if lineOrigins.count < 2 {
return 0
}
var line = 1
while line < lineOrigins.count - 1 && lineOrigins[line].y <= topOffset + contentInset.top + bounds.size.height * 0.15 {
line += 1
}
let middleBetweenLinesTopOffset = (lineOrigins[line].y - lineOrigins[line - 1].y) * 0.5 + lineOrigins[line - 1].y
// choose nearest neighbour line
return (topOffset < middleBetweenLinesTopOffset ? line - 1 : line)
}
func scrollToLine(_ line: Int)
{
let offsetTop = max(lineOrigins[line].y - contentInset.top - bounds.size.height * 0.15, 0.0)
self.contentOffset = CGPoint(x: self.contentOffset.x, y: offsetTop)
}
@IBAction func handleTapGesture(_ gestureRecognizer: UITapGestureRecognizer)
{
var line: Int?
// choose line
if highlightedLine == nil {
if contentOffset.y <= 0 {
line = 0
} else {
line = lineNextToTopOffset(contentOffset.y)
}
} else {
line = highlightedLine! + 1
}
if line! >= lineOrigins.count
{
// reached end of lyrics
line = nil
// scroll to top
UIView.animate(withDuration: 0.3, animations: {
self.contentOffset = CGPoint(x: self.contentOffset.x, y: -self.contentInset.top)
})
}
// highlight line
UIView.animate(withDuration: 0.2, animations: {
self.highlightedLine = line
})
}
}
protocol LBLyricsViewDelegate: class
{
func lyricsView(_ lyricsView: LBLyricsView, didHighlightLine line: Int?)
}
| mit | c24fcc4e38ecdb8278c639556fa0d4a3 | 31.16 | 127 | 0.505775 | 5.772308 | false | false | false | false |
Tea-and-Coffee/CollectionView-Sample-Swift | CollectionView-Sample/Model/WEWeather.swift | 1 | 1630 | //
// WEWeather.swift
//
// Create by masato arai on 1/9/2016
// Copyright © 2016. All rights reserved.
// Model file generated using JSONExport: https://github.com/Ahmed-Ali/JSONExport
import Foundation
struct WEWeather{
var copyright : WECopyright?
var descriptionField : WEDescription?
var forecasts : [WEForecast]!
var link : String?
var location : WELocation?
var pinpointLocations : [WEProvider]
var publicTime : String?
var title : String?
/**
* Instantiate the instance using the passed dictionary values to set the properties values
*/
init(fromDictionary dictionary: NSDictionary){
if let copyrightData = dictionary["copyright"] as? NSDictionary{
copyright = WECopyright(fromDictionary: copyrightData)
}
if let descriptionFieldData = dictionary["description"] as? NSDictionary{
descriptionField = WEDescription(fromDictionary: descriptionFieldData)
}
forecasts = [WEForecast]()
if let forecastsArray = dictionary["forecasts"] as? [NSDictionary]{
for dic in forecastsArray{
let value = WEForecast(fromDictionary: dic)
forecasts.append(value)
}
}
link = dictionary["link"] as? String
if let locationData = dictionary["location"] as? NSDictionary{
location = WELocation(fromDictionary: locationData)
}
pinpointLocations = [WEProvider]()
if let pinpointLocationsArray = dictionary["pinpointLocations"] as? [NSDictionary]{
for dic in pinpointLocationsArray{
let value = WEProvider(fromDictionary: dic)
pinpointLocations.append(value)
}
}
publicTime = dictionary["publicTime"] as? String
title = dictionary["title"] as? String
}
}
| mit | 9940ba6e9344d3144360883713e8cf9e | 29.166667 | 92 | 0.735421 | 3.94431 | false | false | false | false |
Jnosh/swift | test/SILGen/global_resilience.swift | 6 | 3484 | // RUN: rm -rf %t && mkdir %t
// RUN: %target-swift-frontend -emit-module -enable-resilience -emit-module-path=%t/resilient_global.swiftmodule -module-name=resilient_global %S/../Inputs/resilient_global.swift
// RUN: %target-swift-frontend -I %t -emit-silgen -enable-resilience -parse-as-library %s | %FileCheck %s
// RUN: %target-swift-frontend -I %t -emit-sil -O -enable-resilience -parse-as-library %s | %FileCheck --check-prefix=CHECK-OPT %s
import resilient_global
public struct MyEmptyStruct {}
// CHECK-LABEL: sil_global @_T017global_resilience13myEmptyGlobalAA02MyD6StructVv : $MyEmptyStruct
public var myEmptyGlobal = MyEmptyStruct()
// CHECK-LABEL: sil_global @_T017global_resilience19myFixedLayoutGlobalAA13MyEmptyStructVv : $MyEmptyStruct
@_fixed_layout public var myFixedLayoutGlobal = MyEmptyStruct()
// Mutable addressor for resilient global (should not be public?)
// CHECK-LABEL: sil [global_init] @_T017global_resilience13myEmptyGlobalAA02MyD6StructVfau : $@convention(thin) () -> Builtin.RawPointer
// CHECK: global_addr @_T017global_resilience13myEmptyGlobalAA02MyD6StructVv
// CHECK: return
// Synthesized getter and setter for our resilient global variable
// CHECK-LABEL: sil @_T017global_resilience13myEmptyGlobalAA02MyD6StructVfg
// CHECK: function_ref @_T017global_resilience13myEmptyGlobalAA02MyD6StructVfau
// CHECK: return
// CHECK-LABEL: sil @_T017global_resilience13myEmptyGlobalAA02MyD6StructVfs
// CHECK: function_ref @_T017global_resilience13myEmptyGlobalAA02MyD6StructVfau
// CHECK: return
// Mutable addressor for fixed-layout global
// CHECK-LABEL: sil [global_init] @_T017global_resilience19myFixedLayoutGlobalAA13MyEmptyStructVfau
// CHECK: global_addr @_T017global_resilience19myFixedLayoutGlobalAA13MyEmptyStructVv
// CHECK: return
// CHECK-OPT-LABEL: sil private @globalinit_{{.*}}_func0
// CHECK-OPT: alloc_global @_T017global_resilience19myFixedLayoutGlobalAA13MyEmptyStructVv
// CHECK-OPT: return
// CHECK-OPT-LABEL: sil [global_init] @_T017global_resilience19myFixedLayoutGlobalAA13MyEmptyStructVfau
// CHECK-OPT: global_addr @_T017global_resilience19myFixedLayoutGlobalAA13MyEmptyStructVv
// CHECK-OPT: function_ref @globalinit_{{.*}}_func0
// CHECK-OPT: return
// Accessing resilient global from our resilience domain --
// call the addressor directly
// CHECK-LABEL: sil @_T017global_resilience16getMyEmptyGlobalAA0dE6StructVyF
// CHECK: function_ref @_T017global_resilience13myEmptyGlobalAA02MyD6StructVfau
// CHECK: return
public func getMyEmptyGlobal() -> MyEmptyStruct {
return myEmptyGlobal
}
// Accessing resilient global from a different resilience domain --
// access it with accessors
// CHECK-LABEL: sil @_T017global_resilience14getEmptyGlobal010resilient_A00D15ResilientStructVyF
// CHECK: function_ref @_T016resilient_global11emptyGlobalAA20EmptyResilientStructVfg
// CHECK: return
public func getEmptyGlobal() -> EmptyResilientStruct {
return emptyGlobal
}
// Accessing fixed-layout global from a different resilience domain --
// call the addressor directly
// CHECK-LABEL: sil @_T017global_resilience20getFixedLayoutGlobal010resilient_A020EmptyResilientStructVyF
// CHECK: function_ref @_T016resilient_global17fixedLayoutGlobalAA20EmptyResilientStructVfau
// CHECK: return
public func getFixedLayoutGlobal() -> EmptyResilientStruct {
return fixedLayoutGlobal
}
| apache-2.0 | 5f2072cbe14cc771b763d13ae37b0d03 | 44.246753 | 178 | 0.770379 | 4.192539 | false | false | false | false |
Tj3n/TVNExtensions | UIKit/UIButton.swift | 1 | 3993 | //
// UIButtonExtension.swift
// MerchantDashboard
//
// Created by Tien Nhat Vu on 3/17/16.
// Copyright © 2016 Tien Nhat Vu. All rights reserved.
//
import Foundation
import UIKit
import ObjectiveC
public extension UIButton {
/// To add padding to UIButton
///
/// Example
/// ```
/// button.setInsets(forContentPadding: UIEdgeInsets(top: 0, left: 16, bottom: 0, right: 16), imageTitlePadding: 8)
/// ```
/// - Parameters:
/// - contentPadding: Padding for content edge
/// - imageTitlePadding: Padding between image and title
func setInsets(forContentPadding contentPadding: UIEdgeInsets, imageTitlePadding: CGFloat) {
self.contentEdgeInsets = UIEdgeInsets(
top: contentPadding.top,
left: contentPadding.left,
bottom: contentPadding.bottom,
right: contentPadding.right + imageTitlePadding
)
self.titleEdgeInsets = UIEdgeInsets(
top: 0,
left: imageTitlePadding,
bottom: 0,
right: -imageTitlePadding
)
}
var isEnabledWithBG: Bool {
get {
return self.isEnabled
}
set {
if newValue == true {
self.alpha = 1
} else {
self.alpha = 0.5
}
self.isEnabled = newValue
}
}
@IBInspectable var autoShrinkFont: Bool {
get {
if let label = titleLabel {
return label.adjustsFontSizeToFitWidth
}
return false
}
set {
self.titleLabel?.frame.size.width = self.frame.size.width - (self.imageView?.frame.size.width ?? 0)
self.titleLabel?.adjustsFontSizeToFitWidth = newValue
}
}
@IBInspectable var minimumScaleFactor: CGFloat {
get {
if let label = titleLabel {
return label.minimumScaleFactor
}
return 1.0
}
set {
self.titleLabel?.minimumScaleFactor = newValue > 1.0 ? 1.0 : newValue
}
}
@IBInspectable var flipContent: Bool {
get {
return !self.transform.isIdentity
}
set {
if newValue {
self.transform = CGAffineTransform.identity.scaledBy(x: -1.0, y: 1.0)
self.titleLabel?.transform = CGAffineTransform.identity.scaledBy(x: -1.0, y: 1.0)
self.imageView?.transform = CGAffineTransform.identity.scaledBy(x: -1.0, y: 1.0)
} else {
self.transform = CGAffineTransform.identity
}
}
}
}
// MARK: - .touchUpInside with closure
extension UIButton {
public typealias ButtonAction = (_ button: UIButton)->()
private class ActionStore: NSObject {
let action: ButtonAction
init(_ action: @escaping ButtonAction) {
self.action = action
}
}
private struct AssociatedKeys {
static var btnActionKey = "btnActionKey"
}
/// MUST USE [unowned self] to prevent retain cycle
///
/// - Parameter action: closure for .touchUpInside action
public func addTouchUpInsideAction(_ action: @escaping ButtonAction) {
touchUpInsideAction = action
self.addTarget(self, action: #selector(UIButton.doAction), for: .touchUpInside)
}
@objc func doAction() {
touchUpInsideAction?(self)
}
private var touchUpInsideAction: ButtonAction? {
get {
guard let store = objc_getAssociatedObject(self, &AssociatedKeys.btnActionKey) as? ActionStore else { return nil }
return store.action
}
set(newValue) {
guard let newValue = newValue else { return }
objc_setAssociatedObject(self, &AssociatedKeys.btnActionKey, ActionStore(newValue), .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
}
}
}
| mit | ffe4ea27f1acd5710277802184e7b70e | 28.57037 | 131 | 0.570391 | 4.977556 | false | false | false | false |
SwiftAndroid/swift | test/1_stdlib/Runtime.swift | 1 | 42802 | // RUN: rm -rf %t && mkdir %t
//
// RUN: %target-build-swift -parse-stdlib -module-name a %s -o %t.out
// RUN: %target-run %t.out
// REQUIRES: executable_test
import Swift
import StdlibUnittest
import SwiftShims
var swiftObjectCanaryCount = 0
class SwiftObjectCanary {
init() {
swiftObjectCanaryCount += 1
}
deinit {
swiftObjectCanaryCount -= 1
}
}
struct SwiftObjectCanaryStruct {
var ref = SwiftObjectCanary()
}
var Runtime = TestSuite("Runtime")
Runtime.test("_canBeClass") {
expectEqual(1, _canBeClass(SwiftObjectCanary.self))
expectEqual(0, _canBeClass(SwiftObjectCanaryStruct.self))
typealias SwiftClosure = () -> ()
expectEqual(0, _canBeClass(SwiftClosure.self))
}
//===----------------------------------------------------------------------===//
// The protocol should be defined in the standard library, otherwise the cast
// does not work.
typealias P1 = Boolean
typealias P2 = CustomStringConvertible
protocol Q1 {}
// A small struct that can be stored inline in an opaque buffer.
struct StructConformsToP1 : Boolean, Q1 {
var boolValue: Bool {
return true
}
}
// A small struct that can be stored inline in an opaque buffer.
struct Struct2ConformsToP1<T : Boolean> : Boolean, Q1 {
init(_ value: T) {
self.value = value
}
var boolValue: Bool {
return value.boolValue
}
var value: T
}
// A large struct that cannot be stored inline in an opaque buffer.
struct Struct3ConformsToP2 : CustomStringConvertible, Q1 {
var a: UInt64 = 10
var b: UInt64 = 20
var c: UInt64 = 30
var d: UInt64 = 40
var description: String {
// Don't rely on string interpolation, it uses the casts that we are trying
// to test.
var result = ""
result += _uint64ToString(a) + " "
result += _uint64ToString(b) + " "
result += _uint64ToString(c) + " "
result += _uint64ToString(d)
return result
}
}
// A large struct that cannot be stored inline in an opaque buffer.
struct Struct4ConformsToP2<T : CustomStringConvertible> : CustomStringConvertible, Q1 {
var value: T
var e: UInt64 = 50
var f: UInt64 = 60
var g: UInt64 = 70
var h: UInt64 = 80
init(_ value: T) {
self.value = value
}
var description: String {
// Don't rely on string interpolation, it uses the casts that we are trying
// to test.
var result = value.description + " "
result += _uint64ToString(e) + " "
result += _uint64ToString(f) + " "
result += _uint64ToString(g) + " "
result += _uint64ToString(h)
return result
}
}
struct StructDoesNotConformToP1 : Q1 {}
class ClassConformsToP1 : Boolean, Q1 {
var boolValue: Bool {
return true
}
}
class Class2ConformsToP1<T : Boolean> : Boolean, Q1 {
init(_ value: T) {
self.value = [ value ]
}
var boolValue: Bool {
return value[0].boolValue
}
// FIXME: should be "var value: T", but we don't support it now.
var value: Array<T>
}
class ClassDoesNotConformToP1 : Q1 {}
Runtime.test("dynamicCasting with as") {
var someP1Value = StructConformsToP1()
var someP1Value2 = Struct2ConformsToP1(true)
var someNotP1Value = StructDoesNotConformToP1()
var someP2Value = Struct3ConformsToP2()
var someP2Value2 = Struct4ConformsToP2(Struct3ConformsToP2())
var someP1Ref = ClassConformsToP1()
var someP1Ref2 = Class2ConformsToP1(true)
var someNotP1Ref = ClassDoesNotConformToP1()
expectTrue(someP1Value is P1)
expectTrue(someP1Value2 is P1)
expectFalse(someNotP1Value is P1)
expectTrue(someP2Value is P2)
expectTrue(someP2Value2 is P2)
expectTrue(someP1Ref is P1)
expectTrue(someP1Ref2 is P1)
expectFalse(someNotP1Ref is P1)
expectTrue(someP1Value as P1 is P1)
expectTrue(someP1Value2 as P1 is P1)
expectTrue(someP2Value as P2 is P2)
expectTrue(someP2Value2 as P2 is P2)
expectTrue(someP1Ref as P1 is P1)
expectTrue(someP1Value as Q1 is P1)
expectTrue(someP1Value2 as Q1 is P1)
expectFalse(someNotP1Value as Q1 is P1)
expectTrue(someP2Value as Q1 is P2)
expectTrue(someP2Value2 as Q1 is P2)
expectTrue(someP1Ref as Q1 is P1)
expectTrue(someP1Ref2 as Q1 is P1)
expectFalse(someNotP1Ref as Q1 is P1)
expectTrue(someP1Value as Any is P1)
expectTrue(someP1Value2 as Any is P1)
expectFalse(someNotP1Value as Any is P1)
expectTrue(someP2Value as Any is P2)
expectTrue(someP2Value2 as Any is P2)
expectTrue(someP1Ref as Any is P1)
expectTrue(someP1Ref2 as Any is P1)
expectFalse(someNotP1Ref as Any is P1)
expectTrue(someP1Ref as AnyObject is P1)
expectTrue(someP1Ref2 as AnyObject is P1)
expectFalse(someNotP1Ref as AnyObject is P1)
expectTrue((someP1Value as P1).boolValue)
expectTrue((someP1Value2 as P1).boolValue)
expectEqual("10 20 30 40", (someP2Value as P2).description)
expectEqual("10 20 30 40 50 60 70 80", (someP2Value2 as P2).description)
expectTrue((someP1Ref as P1).boolValue)
expectTrue((someP1Ref2 as P1).boolValue)
expectTrue(((someP1Value as Q1) as! P1).boolValue)
expectTrue(((someP1Value2 as Q1) as! P1).boolValue)
expectEqual("10 20 30 40", ((someP2Value as Q1) as! P2).description)
expectEqual("10 20 30 40 50 60 70 80",
((someP2Value2 as Q1) as! P2).description)
expectTrue(((someP1Ref as Q1) as! P1).boolValue)
expectTrue(((someP1Ref2 as Q1) as! P1).boolValue)
expectTrue(((someP1Value as Any) as! P1).boolValue)
expectTrue(((someP1Value2 as Any) as! P1).boolValue)
expectEqual("10 20 30 40", ((someP2Value as Any) as! P2).description)
expectEqual("10 20 30 40 50 60 70 80",
((someP2Value2 as Any) as! P2).description)
expectTrue(((someP1Ref as Any) as! P1).boolValue)
expectTrue(((someP1Ref2 as Any) as! P1).boolValue)
expectTrue(((someP1Ref as AnyObject) as! P1).boolValue)
expectEmpty((someNotP1Value as? P1))
expectEmpty((someNotP1Ref as? P1))
expectTrue(((someP1Value as Q1) as? P1)!.boolValue)
expectTrue(((someP1Value2 as Q1) as? P1)!.boolValue)
expectEmpty(((someNotP1Value as Q1) as? P1))
expectEqual("10 20 30 40", ((someP2Value as Q1) as? P2)!.description)
expectEqual("10 20 30 40 50 60 70 80",
((someP2Value2 as Q1) as? P2)!.description)
expectTrue(((someP1Ref as Q1) as? P1)!.boolValue)
expectTrue(((someP1Ref2 as Q1) as? P1)!.boolValue)
expectEmpty(((someNotP1Ref as Q1) as? P1))
expectTrue(((someP1Value as Any) as? P1)!.boolValue)
expectTrue(((someP1Value2 as Any) as? P1)!.boolValue)
expectEmpty(((someNotP1Value as Any) as? P1))
expectEqual("10 20 30 40", ((someP2Value as Any) as? P2)!.description)
expectEqual("10 20 30 40 50 60 70 80",
((someP2Value2 as Any) as? P2)!.description)
expectTrue(((someP1Ref as Any) as? P1)!.boolValue)
expectTrue(((someP1Ref2 as Any) as? P1)!.boolValue)
expectEmpty(((someNotP1Ref as Any) as? P1))
expectTrue(((someP1Ref as AnyObject) as? P1)!.boolValue)
expectTrue(((someP1Ref2 as AnyObject) as? P1)!.boolValue)
expectEmpty(((someNotP1Ref as AnyObject) as? P1))
let doesThrow: Int throws -> Int = { $0 }
let doesNotThrow: String -> String = { $0 }
var any: Any = doesThrow
expectTrue(doesThrow as Any is Int throws -> Int)
expectFalse(doesThrow as Any is String throws -> Int)
expectFalse(doesThrow as Any is String throws -> String)
expectFalse(doesThrow as Any is Int throws -> String)
expectFalse(doesThrow as Any is Int -> Int)
expectFalse(doesThrow as Any is String throws -> String)
expectFalse(doesThrow as Any is String -> String)
expectTrue(doesNotThrow as Any is String throws -> String)
expectTrue(doesNotThrow as Any is String -> String)
expectFalse(doesNotThrow as Any is Int -> String)
expectFalse(doesNotThrow as Any is Int -> Int)
expectFalse(doesNotThrow as Any is String -> Int)
expectFalse(doesNotThrow as Any is Int throws -> Int)
expectFalse(doesNotThrow as Any is Int -> Int)
}
extension Int {
class ExtensionClassConformsToP2 : P2 {
var description: String { return "abc" }
}
private class PrivateExtensionClassConformsToP2 : P2 {
var description: String { return "def" }
}
}
Runtime.test("dynamic cast to existential with cross-module extensions") {
let internalObj = Int.ExtensionClassConformsToP2()
let privateObj = Int.PrivateExtensionClassConformsToP2()
expectTrue(internalObj is P2)
expectTrue(privateObj is P2)
}
class SomeClass {}
struct SomeStruct {}
enum SomeEnum {
case A
init() { self = .A }
}
Runtime.test("typeName") {
expectEqual("a.SomeClass", _typeName(SomeClass.self))
expectEqual("a.SomeStruct", _typeName(SomeStruct.self))
expectEqual("a.SomeEnum", _typeName(SomeEnum.self))
expectEqual("protocol<>.Protocol", _typeName(Any.Protocol.self))
expectEqual("Swift.AnyObject.Protocol", _typeName(AnyObject.Protocol.self))
expectEqual("Swift.AnyObject.Type.Protocol", _typeName(AnyClass.Protocol.self))
expectEqual("Swift.Optional<Swift.AnyObject>.Type", _typeName((AnyObject?).Type.self))
var a: Any = SomeClass()
expectEqual("a.SomeClass", _typeName(a.dynamicType))
a = SomeStruct()
expectEqual("a.SomeStruct", _typeName(a.dynamicType))
a = SomeEnum()
expectEqual("a.SomeEnum", _typeName(a.dynamicType))
a = AnyObject.self
expectEqual("Swift.AnyObject.Protocol", _typeName(a.dynamicType))
a = AnyClass.self
expectEqual("Swift.AnyObject.Type.Protocol", _typeName(a.dynamicType))
a = (AnyObject?).self
expectEqual("Swift.Optional<Swift.AnyObject>.Type",
_typeName(a.dynamicType))
a = Any.self
expectEqual("protocol<>.Protocol", _typeName(a.dynamicType))
}
class SomeSubclass : SomeClass {}
protocol SomeProtocol {}
class SomeConformingClass : SomeProtocol {}
Runtime.test("typeByName") {
expectTrue(_typeByName("a.SomeClass") == SomeClass.self)
expectTrue(_typeByName("a.SomeSubclass") == SomeSubclass.self)
// name lookup will be via protocol conformance table
expectTrue(_typeByName("a.SomeConformingClass") == SomeConformingClass.self)
// FIXME: NonObjectiveCBase is slated to die, but I can't think of another
// nongeneric public class in the stdlib...
expectTrue(_typeByName("Swift.NonObjectiveCBase") == NonObjectiveCBase.self)
}
Runtime.test("demangleName") {
expectEqual("", _stdlib_demangleName(""))
expectEqual("abc", _stdlib_demangleName("abc"))
expectEqual("\0", _stdlib_demangleName("\0"))
expectEqual("Swift.Double", _stdlib_demangleName("_TtSd"))
expectEqual("x.a : x.Foo<x.Foo<x.Foo<Swift.Int, Swift.Int>, x.Foo<Swift.Int, Swift.Int>>, x.Foo<x.Foo<Swift.Int, Swift.Int>, x.Foo<Swift.Int, Swift.Int>>>",
_stdlib_demangleName("_Tv1x1aGCS_3FooGS0_GS0_SiSi_GS0_SiSi__GS0_GS0_SiSi_GS0_SiSi___"))
expectEqual("Foobar", _stdlib_demangleName("_TtC13__lldb_expr_46Foobar"))
}
Runtime.test("_stdlib_atomicCompareExchangeStrongPtr") {
typealias IntPtr = UnsafeMutablePointer<Int>
var origP1 = IntPtr(bitPattern: 0x10101010)!
var origP2 = IntPtr(bitPattern: 0x20202020)!
var origP3 = IntPtr(bitPattern: 0x30303030)!
do {
var object = origP1
var expected = origP1
let r = _stdlib_atomicCompareExchangeStrongPtr(
object: &object, expected: &expected, desired: origP2)
expectTrue(r)
expectEqual(origP2, object)
expectEqual(origP1, expected)
}
do {
var object = origP1
var expected = origP2
let r = _stdlib_atomicCompareExchangeStrongPtr(
object: &object, expected: &expected, desired: origP3)
expectFalse(r)
expectEqual(origP1, object)
expectEqual(origP1, expected)
}
struct FooStruct {
var i: Int
var object: IntPtr
var expected: IntPtr
init(_ object: IntPtr, _ expected: IntPtr) {
self.i = 0
self.object = object
self.expected = expected
}
}
do {
var foo = FooStruct(origP1, origP1)
let r = _stdlib_atomicCompareExchangeStrongPtr(
object: &foo.object, expected: &foo.expected, desired: origP2)
expectTrue(r)
expectEqual(origP2, foo.object)
expectEqual(origP1, foo.expected)
}
do {
var foo = FooStruct(origP1, origP2)
let r = _stdlib_atomicCompareExchangeStrongPtr(
object: &foo.object, expected: &foo.expected, desired: origP3)
expectFalse(r)
expectEqual(origP1, foo.object)
expectEqual(origP1, foo.expected)
}
}
Runtime.test("casting AnyObject to class metatypes") {
do {
var ao: AnyObject = SomeClass()
expectTrue(ao as? Any.Type == nil)
expectTrue(ao as? AnyClass == nil)
}
do {
var a: Any = SomeClass()
expectTrue(a as? Any.Type == nil)
expectTrue(a as? AnyClass == nil)
a = SomeClass.self
expectTrue(a as? Any.Type == SomeClass.self)
expectTrue(a as? AnyClass == SomeClass.self)
expectTrue(a as? SomeClass.Type == SomeClass.self)
}
}
class Malkovich: Malkovichable {
var malkovich: String { return "malkovich" }
}
protocol Malkovichable: class {
var malkovich: String { get }
}
struct GenericStructWithReferenceStorage<T> {
var a: T
unowned(safe) var unownedConcrete: Malkovich
unowned(unsafe) var unmanagedConcrete: Malkovich
weak var weakConcrete: Malkovich?
unowned(safe) var unownedProto: Malkovichable
unowned(unsafe) var unmanagedProto: Malkovichable
weak var weakProto: Malkovichable?
}
func exerciseReferenceStorageInGenericContext<T>(
_ x: GenericStructWithReferenceStorage<T>,
forceCopy y: GenericStructWithReferenceStorage<T>
) {
expectEqual(x.unownedConcrete.malkovich, "malkovich")
expectEqual(x.unmanagedConcrete.malkovich, "malkovich")
expectEqual(x.weakConcrete!.malkovich, "malkovich")
expectEqual(x.unownedProto.malkovich, "malkovich")
expectEqual(x.unmanagedProto.malkovich, "malkovich")
expectEqual(x.weakProto!.malkovich, "malkovich")
expectEqual(y.unownedConcrete.malkovich, "malkovich")
expectEqual(y.unmanagedConcrete.malkovich, "malkovich")
expectEqual(y.weakConcrete!.malkovich, "malkovich")
expectEqual(y.unownedProto.malkovich, "malkovich")
expectEqual(y.unmanagedProto.malkovich, "malkovich")
expectEqual(y.weakProto!.malkovich, "malkovich")
}
Runtime.test("Struct layout with reference storage types") {
let malkovich = Malkovich()
let x = GenericStructWithReferenceStorage(a: malkovich,
unownedConcrete: malkovich,
unmanagedConcrete: malkovich,
weakConcrete: malkovich,
unownedProto: malkovich,
unmanagedProto: malkovich,
weakProto: malkovich)
exerciseReferenceStorageInGenericContext(x, forceCopy: x)
expectEqual(x.unownedConcrete.malkovich, "malkovich")
expectEqual(x.unmanagedConcrete.malkovich, "malkovich")
expectEqual(x.weakConcrete!.malkovich, "malkovich")
expectEqual(x.unownedProto.malkovich, "malkovich")
expectEqual(x.unmanagedProto.malkovich, "malkovich")
expectEqual(x.weakProto!.malkovich, "malkovich")
// Make sure malkovich lives long enough.
print(malkovich)
}
var Reflection = TestSuite("Reflection")
func wrap1 (_ x: Any) -> Any { return x }
func wrap2<T>(_ x: T) -> Any { return wrap1(x) }
func wrap3 (_ x: Any) -> Any { return wrap2(x) }
func wrap4<T>(_ x: T) -> Any { return wrap3(x) }
func wrap5 (_ x: Any) -> Any { return wrap4(x) }
class JustNeedAMetatype {}
Reflection.test("nested existential containers") {
let wrapped = wrap5(JustNeedAMetatype.self)
expectEqual("\(wrapped)", "JustNeedAMetatype")
}
Reflection.test("dumpToAStream") {
var output = ""
dump([ 42, 4242 ], to: &output)
expectEqual("▿ 2 elements\n - 42\n - 4242\n", output)
}
struct StructWithDefaultMirror {
let s: String
init (_ s: String) {
self.s = s
}
}
Reflection.test("Struct/NonGeneric/DefaultMirror") {
do {
var output = ""
dump(StructWithDefaultMirror("123"), to: &output)
expectEqual("▿ a.StructWithDefaultMirror\n - s: \"123\"\n", output)
}
do {
// Build a String around an interpolation as a way of smoke-testing that
// the internal _Mirror implementation gets memory management right.
var output = ""
dump(StructWithDefaultMirror("\(456)"), to: &output)
expectEqual("▿ a.StructWithDefaultMirror\n - s: \"456\"\n", output)
}
expectEqual(
.`struct`,
Mirror(reflecting: StructWithDefaultMirror("")).displayStyle)
}
struct GenericStructWithDefaultMirror<T, U> {
let first: T
let second: U
}
Reflection.test("Struct/Generic/DefaultMirror") {
do {
var value = GenericStructWithDefaultMirror<Int, [Any?]>(
first: 123,
second: [ "abc", 456, 789.25 ])
var output = ""
dump(value, to: &output)
let expected =
"▿ a.GenericStructWithDefaultMirror<Swift.Int, Swift.Array<Swift.Optional<protocol<>>>>\n" +
" - first: 123\n" +
" ▿ second: 3 elements\n" +
" ▿ Optional(\"abc\")\n" +
" - some: \"abc\"\n" +
" ▿ Optional(456)\n" +
" - some: 456\n" +
" ▿ Optional(789.25)\n" +
" - some: 789.25\n"
expectEqual(expected, output)
}
}
enum NoPayloadEnumWithDefaultMirror {
case A, ß
}
Reflection.test("Enum/NoPayload/DefaultMirror") {
do {
let value: [NoPayloadEnumWithDefaultMirror] =
[.A, .ß]
var output = ""
dump(value, to: &output)
let expected =
"▿ 2 elements\n" +
" - a.NoPayloadEnumWithDefaultMirror.A\n" +
" - a.NoPayloadEnumWithDefaultMirror.ß\n"
expectEqual(expected, output)
}
}
enum SingletonNonGenericEnumWithDefaultMirror {
case OnlyOne(Int)
}
Reflection.test("Enum/SingletonNonGeneric/DefaultMirror") {
do {
let value = SingletonNonGenericEnumWithDefaultMirror.OnlyOne(5)
var output = ""
dump(value, to: &output)
let expected =
"▿ a.SingletonNonGenericEnumWithDefaultMirror.OnlyOne\n" +
" - OnlyOne: 5\n"
expectEqual(expected, output)
}
}
enum SingletonGenericEnumWithDefaultMirror<T> {
case OnlyOne(T)
}
Reflection.test("Enum/SingletonGeneric/DefaultMirror") {
do {
let value = SingletonGenericEnumWithDefaultMirror.OnlyOne("IIfx")
var output = ""
dump(value, to: &output)
let expected =
"▿ a.SingletonGenericEnumWithDefaultMirror<Swift.String>.OnlyOne\n" +
" - OnlyOne: \"IIfx\"\n"
expectEqual(expected, output)
}
expectEqual(0, LifetimeTracked.instances)
do {
let value = SingletonGenericEnumWithDefaultMirror.OnlyOne(
LifetimeTracked(0))
expectEqual(1, LifetimeTracked.instances)
var output = ""
dump(value, to: &output)
}
expectEqual(0, LifetimeTracked.instances)
}
enum SinglePayloadNonGenericEnumWithDefaultMirror {
case Cat
case Dog
case Volleyball(String, Int)
}
Reflection.test("Enum/SinglePayloadNonGeneric/DefaultMirror") {
do {
let value: [SinglePayloadNonGenericEnumWithDefaultMirror] =
[.Cat,
.Dog,
.Volleyball("Wilson", 2000)]
var output = ""
dump(value, to: &output)
let expected =
"▿ 3 elements\n" +
" - a.SinglePayloadNonGenericEnumWithDefaultMirror.Cat\n" +
" - a.SinglePayloadNonGenericEnumWithDefaultMirror.Dog\n" +
" ▿ a.SinglePayloadNonGenericEnumWithDefaultMirror.Volleyball\n" +
" ▿ Volleyball: (2 elements)\n" +
" - .0: \"Wilson\"\n" +
" - .1: 2000\n"
expectEqual(expected, output)
}
}
enum SinglePayloadGenericEnumWithDefaultMirror<T, U> {
case Well
case Faucet
case Pipe(T, U)
}
Reflection.test("Enum/SinglePayloadGeneric/DefaultMirror") {
do {
let value: [SinglePayloadGenericEnumWithDefaultMirror<Int, [Int]>] =
[.Well,
.Faucet,
.Pipe(408, [415])]
var output = ""
dump(value, to: &output)
let expected =
"▿ 3 elements\n" +
" - a.SinglePayloadGenericEnumWithDefaultMirror<Swift.Int, Swift.Array<Swift.Int>>.Well\n" +
" - a.SinglePayloadGenericEnumWithDefaultMirror<Swift.Int, Swift.Array<Swift.Int>>.Faucet\n" +
" ▿ a.SinglePayloadGenericEnumWithDefaultMirror<Swift.Int, Swift.Array<Swift.Int>>.Pipe\n" +
" ▿ Pipe: (2 elements)\n" +
" - .0: 408\n" +
" ▿ .1: 1 element\n" +
" - 415\n"
expectEqual(expected, output)
}
}
enum MultiPayloadTagBitsNonGenericEnumWithDefaultMirror {
case Plus
case SE30
case Classic(mhz: Int)
case Performa(model: Int)
}
Reflection.test("Enum/MultiPayloadTagBitsNonGeneric/DefaultMirror") {
do {
let value: [MultiPayloadTagBitsNonGenericEnumWithDefaultMirror] =
[.Plus,
.SE30,
.Classic(mhz: 16),
.Performa(model: 220)]
var output = ""
dump(value, to: &output)
let expected =
"▿ 4 elements\n" +
" - a.MultiPayloadTagBitsNonGenericEnumWithDefaultMirror.Plus\n" +
" - a.MultiPayloadTagBitsNonGenericEnumWithDefaultMirror.SE30\n" +
" ▿ a.MultiPayloadTagBitsNonGenericEnumWithDefaultMirror.Classic\n" +
" - Classic: 16\n" +
" ▿ a.MultiPayloadTagBitsNonGenericEnumWithDefaultMirror.Performa\n" +
" - Performa: 220\n"
expectEqual(expected, output)
}
}
class Floppy {
let capacity: Int
init(capacity: Int) { self.capacity = capacity }
}
class CDROM {
let capacity: Int
init(capacity: Int) { self.capacity = capacity }
}
enum MultiPayloadSpareBitsNonGenericEnumWithDefaultMirror {
case MacWrite
case MacPaint
case FileMaker
case ClarisWorks(floppy: Floppy)
case HyperCard(cdrom: CDROM)
}
Reflection.test("Enum/MultiPayloadSpareBitsNonGeneric/DefaultMirror") {
do {
let value: [MultiPayloadSpareBitsNonGenericEnumWithDefaultMirror] =
[.MacWrite,
.MacPaint,
.FileMaker,
.ClarisWorks(floppy: Floppy(capacity: 800)),
.HyperCard(cdrom: CDROM(capacity: 600))]
var output = ""
dump(value, to: &output)
let expected =
"▿ 5 elements\n" +
" - a.MultiPayloadSpareBitsNonGenericEnumWithDefaultMirror.MacWrite\n" +
" - a.MultiPayloadSpareBitsNonGenericEnumWithDefaultMirror.MacPaint\n" +
" - a.MultiPayloadSpareBitsNonGenericEnumWithDefaultMirror.FileMaker\n" +
" ▿ a.MultiPayloadSpareBitsNonGenericEnumWithDefaultMirror.ClarisWorks\n" +
" ▿ ClarisWorks: a.Floppy #0\n" +
" - capacity: 800\n" +
" ▿ a.MultiPayloadSpareBitsNonGenericEnumWithDefaultMirror.HyperCard\n" +
" ▿ HyperCard: a.CDROM #1\n" +
" - capacity: 600\n"
expectEqual(expected, output)
}
}
enum MultiPayloadTagBitsSmallNonGenericEnumWithDefaultMirror {
case MacWrite
case MacPaint
case FileMaker
case ClarisWorks(floppy: Bool)
case HyperCard(cdrom: Bool)
}
Reflection.test("Enum/MultiPayloadTagBitsSmallNonGeneric/DefaultMirror") {
do {
let value: [MultiPayloadTagBitsSmallNonGenericEnumWithDefaultMirror] =
[.MacWrite,
.MacPaint,
.FileMaker,
.ClarisWorks(floppy: true),
.HyperCard(cdrom: false)]
var output = ""
dump(value, to: &output)
let expected =
"▿ 5 elements\n" +
" - a.MultiPayloadTagBitsSmallNonGenericEnumWithDefaultMirror.MacWrite\n" +
" - a.MultiPayloadTagBitsSmallNonGenericEnumWithDefaultMirror.MacPaint\n" +
" - a.MultiPayloadTagBitsSmallNonGenericEnumWithDefaultMirror.FileMaker\n" +
" ▿ a.MultiPayloadTagBitsSmallNonGenericEnumWithDefaultMirror.ClarisWorks\n" +
" - ClarisWorks: true\n" +
" ▿ a.MultiPayloadTagBitsSmallNonGenericEnumWithDefaultMirror.HyperCard\n" +
" - HyperCard: false\n"
expectEqual(expected, output)
}
}
enum MultiPayloadGenericEnumWithDefaultMirror<T, U> {
case IIe
case IIgs
case Centris(ram: T)
case Quadra(hdd: U)
case PowerBook170
case PowerBookDuo220
}
Reflection.test("Enum/MultiPayloadGeneric/DefaultMirror") {
do {
let value: [MultiPayloadGenericEnumWithDefaultMirror<Int, String>] =
[.IIe,
.IIgs,
.Centris(ram: 4096),
.Quadra(hdd: "160MB"),
.PowerBook170,
.PowerBookDuo220]
var output = ""
dump(value, to: &output)
let expected =
"▿ 6 elements\n" +
" - a.MultiPayloadGenericEnumWithDefaultMirror<Swift.Int, Swift.String>.IIe\n" +
" - a.MultiPayloadGenericEnumWithDefaultMirror<Swift.Int, Swift.String>.IIgs\n" +
" ▿ a.MultiPayloadGenericEnumWithDefaultMirror<Swift.Int, Swift.String>.Centris\n" +
" - Centris: 4096\n" +
" ▿ a.MultiPayloadGenericEnumWithDefaultMirror<Swift.Int, Swift.String>.Quadra\n" +
" - Quadra: \"160MB\"\n" +
" - a.MultiPayloadGenericEnumWithDefaultMirror<Swift.Int, Swift.String>.PowerBook170\n" +
" - a.MultiPayloadGenericEnumWithDefaultMirror<Swift.Int, Swift.String>.PowerBookDuo220\n"
expectEqual(expected, output)
}
expectEqual(0, LifetimeTracked.instances)
do {
let value = MultiPayloadGenericEnumWithDefaultMirror<LifetimeTracked,
LifetimeTracked>
.Quadra(hdd: LifetimeTracked(0))
expectEqual(1, LifetimeTracked.instances)
var output = ""
dump(value, to: &output)
}
expectEqual(0, LifetimeTracked.instances)
}
enum Foo<T> {
indirect case Foo(Int)
case Bar(T)
}
enum List<T> {
case Nil
indirect case Cons(first: T, rest: List<T>)
}
Reflection.test("Enum/IndirectGeneric/DefaultMirror") {
let x = Foo<String>.Foo(22)
let y = Foo<String>.Bar("twenty-two")
expectEqual("\(x)", "Foo(22)")
expectEqual("\(y)", "Bar(\"twenty-two\")")
let list = List.Cons(first: 0, rest: .Cons(first: 1, rest: .Nil))
expectEqual("\(list)",
"Cons(0, a.List<Swift.Int>.Cons(1, a.List<Swift.Int>.Nil))")
}
class Brilliant : CustomReflectable {
let first: Int
let second: String
init(_ fst: Int, _ snd: String) {
self.first = fst
self.second = snd
}
var customMirror: Mirror {
return Mirror(self, children: ["first": first, "second": second, "self": self])
}
}
/// Subclasses inherit their parents' custom mirrors.
class Irradiant : Brilliant {
init() {
super.init(400, "")
}
}
Reflection.test("CustomMirror") {
do {
var output = ""
dump(Brilliant(123, "four five six"), to: &output)
let expected =
"▿ a.Brilliant #0\n" +
" - first: 123\n" +
" - second: \"four five six\"\n" +
" ▿ self: a.Brilliant #0\n"
expectEqual(expected, output)
}
do {
var output = ""
dump(Brilliant(123, "four five six"), to: &output, maxDepth: 0)
expectEqual("▹ a.Brilliant #0\n", output)
}
do {
var output = ""
dump(Brilliant(123, "four five six"), to: &output, maxItems: 3)
let expected =
"▿ a.Brilliant #0\n" +
" - first: 123\n" +
" - second: \"four five six\"\n" +
" (1 more child)\n"
expectEqual(expected, output)
}
do {
var output = ""
dump(Brilliant(123, "four five six"), to: &output, maxItems: 2)
let expected =
"▿ a.Brilliant #0\n" +
" - first: 123\n" +
" (2 more children)\n"
expectEqual(expected, output)
}
do {
var output = ""
dump(Brilliant(123, "four five six"), to: &output, maxItems: 1)
let expected =
"▿ a.Brilliant #0\n" +
" (3 children)\n"
expectEqual(expected, output)
}
do {
// Check that object identifiers are unique to class instances.
let a = Brilliant(1, "")
let b = Brilliant(2, "")
let c = Brilliant(3, "")
// Equatable
checkEquatable(true, ObjectIdentifier(a), ObjectIdentifier(a))
checkEquatable(false, ObjectIdentifier(a), ObjectIdentifier(b))
// Comparable
func isComparable<X : Comparable>(_ x: X) {}
isComparable(ObjectIdentifier(a))
// Check the ObjectIdentifier created is stable
expectTrue(
(ObjectIdentifier(a) < ObjectIdentifier(b))
!= (ObjectIdentifier(a) > ObjectIdentifier(b)))
expectFalse(
ObjectIdentifier(a) >= ObjectIdentifier(b)
&& ObjectIdentifier(a) <= ObjectIdentifier(b))
// Check that ordering is transitive.
expectEqual(
[ ObjectIdentifier(a), ObjectIdentifier(b), ObjectIdentifier(c) ].sorted(),
[ ObjectIdentifier(c), ObjectIdentifier(b), ObjectIdentifier(a) ].sorted())
}
}
Reflection.test("CustomMirrorIsInherited") {
do {
var output = ""
dump(Irradiant(), to: &output)
let expected =
"▿ a.Brilliant #0\n" +
" - first: 400\n" +
" - second: \"\"\n" +
" ▿ self: a.Brilliant #0\n"
expectEqual(expected, output)
}
}
protocol SomeNativeProto {}
extension Int: SomeNativeProto {}
Reflection.test("MetatypeMirror") {
do {
var output = ""
let concreteMetatype = Int.self
dump(concreteMetatype, to: &output)
let expectedInt = "- Swift.Int #0\n"
expectEqual(expectedInt, output)
let anyMetatype: Any.Type = Int.self
output = ""
dump(anyMetatype, to: &output)
expectEqual(expectedInt, output)
let nativeProtocolMetatype: SomeNativeProto.Type = Int.self
output = ""
dump(nativeProtocolMetatype, to: &output)
expectEqual(expectedInt, output)
let concreteClassMetatype = SomeClass.self
let expectedSomeClass = "- a.SomeClass #0\n"
output = ""
dump(concreteClassMetatype, to: &output)
expectEqual(expectedSomeClass, output)
let nativeProtocolConcreteMetatype = SomeNativeProto.self
let expectedNativeProtocolConcrete = "- a.SomeNativeProto #0\n"
output = ""
dump(nativeProtocolConcreteMetatype, to: &output)
expectEqual(expectedNativeProtocolConcrete, output)
}
}
Reflection.test("TupleMirror") {
do {
var output = ""
let tuple =
(Brilliant(384, "seven six eight"), StructWithDefaultMirror("nine"))
dump(tuple, to: &output)
let expected =
"▿ (2 elements)\n" +
" ▿ .0: a.Brilliant #0\n" +
" - first: 384\n" +
" - second: \"seven six eight\"\n" +
" ▿ self: a.Brilliant #0\n" +
" ▿ .1: a.StructWithDefaultMirror\n" +
" - s: \"nine\"\n"
expectEqual(expected, output)
expectEqual(.tuple, Mirror(reflecting: tuple).displayStyle)
}
do {
// A tuple of stdlib types with mirrors.
var output = ""
let tuple = (1, 2.5, false, "three")
dump(tuple, to: &output)
let expected =
"▿ (4 elements)\n" +
" - .0: 1\n" +
" - .1: 2.5\n" +
" - .2: false\n" +
" - .3: \"three\"\n"
expectEqual(expected, output)
}
do {
// A nested tuple.
var output = ""
let tuple = (1, ("Hello", "World"))
dump(tuple, to: &output)
let expected =
"▿ (2 elements)\n" +
" - .0: 1\n" +
" ▿ .1: (2 elements)\n" +
" - .0: \"Hello\"\n" +
" - .1: \"World\"\n"
expectEqual(expected, output)
}
}
class DullClass {}
Reflection.test("ClassReflection") {
expectEqual(.`class`, Mirror(reflecting: DullClass()).displayStyle)
}
Reflection.test("String/Mirror") {
do {
var output = ""
dump("", to: &output)
let expected =
"- \"\"\n"
expectEqual(expected, output)
}
do {
// U+0061 LATIN SMALL LETTER A
// U+304B HIRAGANA LETTER KA
// U+3099 COMBINING KATAKANA-HIRAGANA VOICED SOUND MARK
// U+1F425 FRONT-FACING BABY CHICK
var output = ""
dump("\u{61}\u{304b}\u{3099}\u{1f425}", to: &output)
let expected =
"- \"\u{61}\u{304b}\u{3099}\u{1f425}\"\n"
expectEqual(expected, output)
}
}
Reflection.test("String.UTF8View/Mirror") {
// U+0061 LATIN SMALL LETTER A
// U+304B HIRAGANA LETTER KA
// U+3099 COMBINING KATAKANA-HIRAGANA VOICED SOUND MARK
var output = ""
dump("\u{61}\u{304b}\u{3099}".utf8, to: &output)
let expected =
"▿ UTF8View(\"\u{61}\u{304b}\u{3099}\")\n" +
" - 97\n" +
" - 227\n" +
" - 129\n" +
" - 139\n" +
" - 227\n" +
" - 130\n" +
" - 153\n"
expectEqual(expected, output)
}
Reflection.test("String.UTF16View/Mirror") {
// U+0061 LATIN SMALL LETTER A
// U+304B HIRAGANA LETTER KA
// U+3099 COMBINING KATAKANA-HIRAGANA VOICED SOUND MARK
// U+1F425 FRONT-FACING BABY CHICK
var output = ""
dump("\u{61}\u{304b}\u{3099}\u{1f425}".utf16, to: &output)
let expected =
"▿ StringUTF16(\"\u{61}\u{304b}\u{3099}\u{1f425}\")\n" +
" - 97\n" +
" - 12363\n" +
" - 12441\n" +
" - 55357\n" +
" - 56357\n"
expectEqual(expected, output)
}
Reflection.test("String.UnicodeScalarView/Mirror") {
// U+0061 LATIN SMALL LETTER A
// U+304B HIRAGANA LETTER KA
// U+3099 COMBINING KATAKANA-HIRAGANA VOICED SOUND MARK
// U+1F425 FRONT-FACING BABY CHICK
var output = ""
dump("\u{61}\u{304b}\u{3099}\u{1f425}".unicodeScalars, to: &output)
let expected =
"▿ StringUnicodeScalarView(\"\u{61}\u{304b}\u{3099}\u{1f425}\")\n" +
" - \"\u{61}\"\n" +
" - \"\\u{304B}\"\n" +
" - \"\\u{3099}\"\n" +
" - \"\\u{0001F425}\"\n"
expectEqual(expected, output)
}
Reflection.test("Character/Mirror") {
do {
// U+0061 LATIN SMALL LETTER A
let input: Character = "\u{61}"
var output = ""
dump(input, to: &output)
let expected =
"- \"\u{61}\"\n"
expectEqual(expected, output)
}
do {
// U+304B HIRAGANA LETTER KA
// U+3099 COMBINING KATAKANA-HIRAGANA VOICED SOUND MARK
let input: Character = "\u{304b}\u{3099}"
var output = ""
dump(input, to: &output)
let expected =
"- \"\u{304b}\u{3099}\"\n"
expectEqual(expected, output)
}
do {
// U+1F425 FRONT-FACING BABY CHICK
let input: Character = "\u{1f425}"
var output = ""
dump(input, to: &output)
let expected =
"- \"\u{1f425}\"\n"
expectEqual(expected, output)
}
}
Reflection.test("UnicodeScalar") {
do {
// U+0061 LATIN SMALL LETTER A
let input: UnicodeScalar = "\u{61}"
var output = ""
dump(input, to: &output)
let expected =
"- \"\u{61}\"\n"
expectEqual(expected, output)
}
do {
// U+304B HIRAGANA LETTER KA
let input: UnicodeScalar = "\u{304b}"
var output = ""
dump(input, to: &output)
let expected =
"- \"\\u{304B}\"\n"
expectEqual(expected, output)
}
do {
// U+3099 COMBINING KATAKANA-HIRAGANA VOICED SOUND MARK
let input: UnicodeScalar = "\u{3099}"
var output = ""
dump(input, to: &output)
let expected =
"- \"\\u{3099}\"\n"
expectEqual(expected, output)
}
do {
// U+1F425 FRONT-FACING BABY CHICK
let input: UnicodeScalar = "\u{1f425}"
var output = ""
dump(input, to: &output)
let expected =
"- \"\\u{0001F425}\"\n"
expectEqual(expected, output)
}
}
Reflection.test("Bool") {
do {
var output = ""
dump(false, to: &output)
let expected =
"- false\n"
expectEqual(expected, output)
}
do {
var output = ""
dump(true, to: &output)
let expected =
"- true\n"
expectEqual(expected, output)
}
}
// FIXME: these tests should cover Float80.
// FIXME: these tests should be automatically generated from the list of
// available floating point types.
Reflection.test("Float") {
do {
var output = ""
dump(Float.nan, to: &output)
let expected =
"- nan\n"
expectEqual(expected, output)
}
do {
var output = ""
dump(Float.infinity, to: &output)
let expected =
"- inf\n"
expectEqual(expected, output)
}
do {
var input: Float = 42.125
var output = ""
dump(input, to: &output)
let expected =
"- 42.125\n"
expectEqual(expected, output)
}
}
Reflection.test("Double") {
do {
var output = ""
dump(Double.nan, to: &output)
let expected =
"- nan\n"
expectEqual(expected, output)
}
do {
var output = ""
dump(Double.infinity, to: &output)
let expected =
"- inf\n"
expectEqual(expected, output)
}
do {
var input: Double = 42.125
var output = ""
dump(input, to: &output)
let expected =
"- 42.125\n"
expectEqual(expected, output)
}
}
// A struct type and class type whose NominalTypeDescriptor.FieldNames
// data is exactly eight bytes long. FieldNames data of exactly
// 4 or 8 or 16 bytes was once miscompiled on arm64.
struct EightByteFieldNamesStruct {
let abcdef = 42
}
class EightByteFieldNamesClass {
let abcdef = 42
}
Reflection.test("FieldNamesBug") {
do {
let expected =
"▿ a.EightByteFieldNamesStruct\n" +
" - abcdef: 42\n"
var output = ""
dump(EightByteFieldNamesStruct(), to: &output)
expectEqual(expected, output)
}
do {
let expected =
"▿ a.EightByteFieldNamesClass #0\n" +
" - abcdef: 42\n"
var output = ""
dump(EightByteFieldNamesClass(), to: &output)
expectEqual(expected, output)
}
}
Reflection.test("MirrorMirror") {
var object = 1
var mirror = Mirror(reflecting: object)
var mirrorMirror = Mirror(reflecting: mirror)
expectEqual(0, mirrorMirror.children.count)
}
Reflection.test("OpaquePointer/null") {
// Don't crash on null pointers. rdar://problem/19708338
let pointer: OpaquePointer? = nil
let mirror = Mirror(reflecting: pointer)
expectEqual(0, mirror.children.count)
}
Reflection.test("StaticString/Mirror") {
do {
var output = ""
dump("" as StaticString, to: &output)
let expected =
"- \"\"\n"
expectEqual(expected, output)
}
do {
// U+0061 LATIN SMALL LETTER A
// U+304B HIRAGANA LETTER KA
// U+3099 COMBINING KATAKANA-HIRAGANA VOICED SOUND MARK
// U+1F425 FRONT-FACING BABY CHICK
var output = ""
dump("\u{61}\u{304b}\u{3099}\u{1f425}" as StaticString, to: &output)
let expected =
"- \"\u{61}\u{304b}\u{3099}\u{1f425}\"\n"
expectEqual(expected, output)
}
}
Reflection.test("DictionaryIterator/Mirror") {
let d: [MinimalHashableValue : OpaqueValue<Int>] =
[ MinimalHashableValue(0) : OpaqueValue(0) ]
var output = ""
dump(d.makeIterator(), to: &output)
let expected =
"- Swift.DictionaryIterator<StdlibUnittest.MinimalHashableValue, StdlibUnittest.OpaqueValue<Swift.Int>>\n"
expectEqual(expected, output)
}
Reflection.test("SetIterator/Mirror") {
let s: Set<MinimalHashableValue> = [ MinimalHashableValue(0)]
var output = ""
dump(s.makeIterator(), to: &output)
let expected =
"- Swift.SetIterator<StdlibUnittest.MinimalHashableValue>\n"
expectEqual(expected, output)
}
var BitTwiddlingTestSuite = TestSuite("BitTwiddling")
func computeCountLeadingZeroes(_ x: Int64) -> Int64 {
var x = x
var r: Int64 = 64
while x != 0 {
x >>= 1
r -= 1
}
return r
}
BitTwiddlingTestSuite.test("_pointerSize") {
#if arch(i386) || arch(arm)
expectEqual(4, sizeof(Optional<AnyObject>.self))
#elseif arch(x86_64) || arch(arm64) || arch(powerpc64) || arch(powerpc64le)
expectEqual(8, sizeof(Optional<AnyObject>.self))
#else
fatalError("implement")
#endif
}
BitTwiddlingTestSuite.test("_countLeadingZeros") {
for i in Int64(0)..<1000 {
expectEqual(computeCountLeadingZeroes(i), _countLeadingZeros(i))
}
expectEqual(0, _countLeadingZeros(Int64.min))
}
BitTwiddlingTestSuite.test("_isPowerOf2/Int") {
func asInt(_ a: Int) -> Int { return a }
expectFalse(_isPowerOf2(asInt(-1025)))
expectFalse(_isPowerOf2(asInt(-1024)))
expectFalse(_isPowerOf2(asInt(-1023)))
expectFalse(_isPowerOf2(asInt(-4)))
expectFalse(_isPowerOf2(asInt(-3)))
expectFalse(_isPowerOf2(asInt(-2)))
expectFalse(_isPowerOf2(asInt(-1)))
expectFalse(_isPowerOf2(asInt(0)))
expectTrue(_isPowerOf2(asInt(1)))
expectTrue(_isPowerOf2(asInt(2)))
expectFalse(_isPowerOf2(asInt(3)))
expectTrue(_isPowerOf2(asInt(1024)))
#if arch(i386) || arch(arm)
// Not applicable to 32-bit architectures.
#elseif arch(x86_64) || arch(arm64) || arch(powerpc64) || arch(powerpc64le)
expectTrue(_isPowerOf2(asInt(0x8000_0000)))
#else
fatalError("implement")
#endif
expectFalse(_isPowerOf2(Int.min))
expectFalse(_isPowerOf2(Int.max))
}
BitTwiddlingTestSuite.test("_isPowerOf2/UInt") {
func asUInt(_ a: UInt) -> UInt { return a }
expectFalse(_isPowerOf2(asUInt(0)))
expectTrue(_isPowerOf2(asUInt(1)))
expectTrue(_isPowerOf2(asUInt(2)))
expectFalse(_isPowerOf2(asUInt(3)))
expectTrue(_isPowerOf2(asUInt(1024)))
expectTrue(_isPowerOf2(asUInt(0x8000_0000)))
expectFalse(_isPowerOf2(UInt.max))
}
BitTwiddlingTestSuite.test("_floorLog2") {
expectEqual(_floorLog2(1), 0)
expectEqual(_floorLog2(8), 3)
expectEqual(_floorLog2(15), 3)
expectEqual(_floorLog2(Int64.max), 62) // 63 minus 1 for sign bit.
}
var AvailabilityVersionsTestSuite = TestSuite("AvailabilityVersions")
AvailabilityVersionsTestSuite.test("lexicographic_compare") {
func version(
_ major: Int,
_ minor: Int,
_ patch: Int
) -> _SwiftNSOperatingSystemVersion {
return _SwiftNSOperatingSystemVersion(
majorVersion: major,
minorVersion: minor,
patchVersion: patch
)
}
checkComparable(.eq, version(0, 0, 0), version(0, 0, 0))
checkComparable(.lt, version(0, 0, 0), version(0, 0, 1))
checkComparable(.lt, version(0, 0, 0), version(0, 1, 0))
checkComparable(.lt, version(0, 0, 0), version(1, 0, 0))
checkComparable(.lt,version(10, 9, 0), version(10, 10, 0))
checkComparable(.lt,version(10, 9, 11), version(10, 10, 0))
checkComparable(.lt,version(10, 10, 3), version(10, 11, 0))
checkComparable(.lt, version(8, 3, 0), version(9, 0, 0))
checkComparable(.lt, version(0, 11, 0), version(10, 10, 4))
checkComparable(.lt, version(0, 10, 0), version(10, 10, 4))
checkComparable(.lt, version(3, 2, 1), version(4, 3, 2))
checkComparable(.lt, version(1, 2, 3), version(2, 3, 1))
checkComparable(.eq, version(10, 11, 12), version(10, 11, 12))
checkEquatable(true, version(1, 2, 3), version(1, 2, 3))
checkEquatable(false, version(1, 2, 3), version(1, 2, 42))
checkEquatable(false, version(1, 2, 3), version(1, 42, 3))
checkEquatable(false, version(1, 2, 3), version(42, 2, 3))
}
AvailabilityVersionsTestSuite.test("_stdlib_isOSVersionAtLeast") {
func isAtLeastOS(_ major: Int, _ minor: Int, _ patch: Int) -> Bool {
return _getBool(_stdlib_isOSVersionAtLeast(major._builtinWordValue,
minor._builtinWordValue,
patch._builtinWordValue))
}
// _stdlib_isOSVersionAtLeast is broken for
// watchOS. rdar://problem/20234735
#if os(OSX) || os(iOS) || os(tvOS) || os(watchOS)
// This test assumes that no version component on an OS we test upon
// will ever be greater than 1066 and that every major version will always
// be greater than 1.
expectFalse(isAtLeastOS(1066, 0, 0))
expectTrue(isAtLeastOS(0, 1066, 0))
expectTrue(isAtLeastOS(0, 0, 1066))
#endif
}
runAllTests()
| apache-2.0 | a2eb3e01337e2d0a68311e2f48a309e3 | 26.491951 | 158 | 0.653753 | 3.740582 | false | false | false | false |
someoneAnyone/Nightscouter | Common/Protocols/ViewModelProtocols.swift | 1 | 2737 | //
// ViewModelProtocols.swift
// Nightscouter
//
// Created by Peter Ina on 3/10/16.
// Copyright © 2016 Nothingonline. All rights reserved.
//
import Foundation
public protocol SiteMetadataDataSource {
var lastReadingDate: Date { get }
var nameLabel: String { get }
var urlLabel: String { get }
}
public protocol SiteMetadataDelegate {
var lastReadingColor: Color { get }
}
public protocol GlucoseValueDataSource {
var sgvLabel: String { get }
var deltaLabel: String { get }
}
public protocol GlucoseValueDelegate {
var sgvColor: Color { get }
var deltaColor: Color { get }
}
public protocol BatteryDataSource {
var batteryHidden: Bool { get }
var batteryLabel: String { get }
}
public protocol BatteryDelegate {
var batteryColor: Color { get }
}
public protocol SiteStaleDataSource {
var lookStale: Bool { get }
}
public protocol RawDataSource {
var rawHidden: Bool { get }
var rawLabel: String { get }
var rawNoise: Noise { get }
var rawFormatedLabel: String { get }
}
public extension RawDataSource {
var rawFormatedLabel: String {
return "\(rawLabel) : \(rawNoise.description)"
}
var rawFormatedLabelShort: String {
return "\(rawLabel) : \(rawNoise.description[rawNoise.description.startIndex])"
}
}
public protocol RawDelegate {
var rawColor: Color { get }
}
public protocol DirectionDisplayable {
var direction: Direction { get }
}
public protocol CompassViewDataSource: SiteMetadataDataSource, GlucoseValueDataSource, SiteStaleDataSource, DirectionDisplayable, RawDataSource {
var text: String { get }
var detailText: String { get }
}
public protocol CompassViewDelegate: SiteMetadataDelegate, GlucoseValueDelegate, RawDelegate {
var desiredColor: DesiredColorState { get }
}
public typealias TableViewRowWithCompassDataSource = SiteMetadataDataSource & GlucoseValueDataSource & BatteryDataSource & CompassViewDataSource
public typealias TableViewRowWithCompassDelegate = SiteMetadataDelegate & GlucoseValueDelegate & CompassViewDelegate & BatteryDelegate
public typealias TableViewRowWithOutCompassDataSource = SiteMetadataDataSource & GlucoseValueDataSource & BatteryDataSource & RawDataSource & DirectionDisplayable
public typealias TableViewRowWithOutCompassDelegate = SiteMetadataDelegate & GlucoseValueDelegate & RawDelegate & BatteryDelegate
public typealias SiteSummaryModelViewModelDataSource = SiteMetadataDataSource & GlucoseValueDataSource & RawDataSource & BatteryDataSource & DirectionDisplayable & CompassViewDataSource
public typealias SiteSummaryModelViewModelDelegate = SiteMetadataDelegate & GlucoseValueDelegate & RawDelegate & CompassViewDelegate & BatteryDelegate
| mit | 25f876a9c8cd9fa30c5adc9931385e46 | 31.571429 | 185 | 0.769006 | 4.894454 | false | false | false | false |
nua-schroers/mvvm-frp | 42_MVVM_FRP-App_WarningDialog/MatchGame/MatchGame/ViewModel/ReactiveModel.swift | 3 | 2881 | //
// ModelWrapper.swift
// MatchGame
//
// Created by Dr. Wolfram Schroers on 5/30/16.
// Copyright © 2016 Wolfram Schroers. All rights reserved.
//
import Foundation
import ReactiveSwift
import ReactiveCocoa
/// This class exports the API of the data model to ReactiveCocoa-style mutable properties.
///
/// - Note: This wrapper looks quite "old style". This may be improved/simplified with advanced use of the
/// ReactiveCocoa-API. Althernatively, the data model could be rewritten from scratch with FRP in mind.
class ReactiveModel {
// MARK: Public API
/// The current move engine being used.
var strategy = MutableProperty(MatchModel.Strategy.dumb)
/// The current match count.
var matchCount = MutableProperty(18)
/// The initial number of matches.
var initialCount = MutableProperty(18)
/// The maximum number of matches to remove.
var removeMax = MutableProperty(3)
/// The maximum number of matches the user can remove.
var userLimit = MutableProperty(3)
/// Indicate whether the game is over or not.
var isGameOver = MutableProperty(false)
/// Designated initializer.
init() {
self.classicMatchModel = MatchModel()
self.updateProperties()
self.strategy.producer.startWithValues { (newStrategy) in
self.classicMatchModel.strategy = newStrategy
}
self.initialCount.producer.startWithValues { (newInitialCount) in
self.classicMatchModel.initialCount = newInitialCount
}
self.removeMax.producer.startWithValues { (newRemoveMax) in
self.classicMatchModel.removeMax = newRemoveMax
self.userLimit.value = self.classicMatchModel.userLimit()
}
}
func restart() {
self.classicMatchModel.restart()
self.updateProperties()
}
func performComputerMove() -> Int {
let computerMove = self.classicMatchModel.performComputerMove()
self.updateProperties()
return computerMove
}
func performUserMove(_ move: Int) {
self.classicMatchModel.performUserMove(move)
self.updateProperties()
}
// MARK: Private
/// The data model with the "old" API.
fileprivate var classicMatchModel: MatchModel
/// Update the properties.
///
/// This could be refactored with KVO, but it will neither make the code easier to read nor to understand.
fileprivate func updateProperties() {
self.strategy.value = self.classicMatchModel.strategy
self.matchCount.value = self.classicMatchModel.matchCount
self.initialCount.value = self.classicMatchModel.initialCount
self.removeMax.value = self.classicMatchModel.removeMax
self.userLimit.value = self.classicMatchModel.userLimit()
self.isGameOver.value = self.classicMatchModel.isGameOver()
}
}
| mit | 37854d07a27cbabfbdeaa9775c4d0b1f | 31.359551 | 110 | 0.687847 | 4.784053 | false | false | false | false |
lachlanhurst/SCNTechniqueTest | SCNTechniqueTest/GeometryBuildTools.swift | 1 | 13730 | //
// GeometryBuildTools.swift
// observeearth
//
// Created by Lachlan Hurst on 24/03/2016.
// Copyright © 2016 Lachlan Hurst. All rights reserved.
//
import Foundation
import SceneKit
class GeometryBuildTools {
static func buildBox() -> SCNGeometry {
let halfSideX:Float = 0.5
let halfSideY:Float = 0.5
let halfSideZ:Float = 2.0
let positions = [
SCNVector3Make(-halfSideX, -halfSideY, halfSideZ),
SCNVector3Make( halfSideX, -halfSideY, halfSideZ),
SCNVector3Make(-halfSideX, -halfSideY, -halfSideZ),
SCNVector3Make( halfSideX, -halfSideY, -halfSideZ),
SCNVector3Make(-halfSideX, halfSideY, halfSideZ),
SCNVector3Make( halfSideX, halfSideY, halfSideZ),
SCNVector3Make(-halfSideX, halfSideY, -halfSideZ),
SCNVector3Make( halfSideX, halfSideY, -halfSideZ),
// repeat exactly the same
SCNVector3Make(-halfSideX, -halfSideY, halfSideZ),
SCNVector3Make( halfSideX, -halfSideY, halfSideZ),
SCNVector3Make(-halfSideX, -halfSideY, -halfSideZ),
SCNVector3Make( halfSideX, -halfSideY, -halfSideZ),
SCNVector3Make(-halfSideX, halfSideY, halfSideZ),
SCNVector3Make( halfSideX, halfSideY, halfSideZ),
SCNVector3Make(-halfSideX, halfSideY, -halfSideZ),
SCNVector3Make( halfSideX, halfSideY, -halfSideZ),
// repeat exactly the same
SCNVector3Make(-halfSideX, -halfSideY, halfSideZ),
SCNVector3Make( halfSideX, -halfSideY, halfSideZ),
SCNVector3Make(-halfSideX, -halfSideY, -halfSideZ),
SCNVector3Make( halfSideX, -halfSideY, -halfSideZ),
SCNVector3Make(-halfSideX, halfSideY, halfSideZ),
SCNVector3Make( halfSideX, halfSideY, halfSideZ),
SCNVector3Make(-halfSideX, halfSideY, -halfSideZ),
SCNVector3Make( halfSideX, halfSideY, -halfSideZ)
]
let normals = [
SCNVector3Make( 0, -1, 0),
SCNVector3Make( 0, -1, 0),
SCNVector3Make( 0, -1, 0),
SCNVector3Make( 0, -1, 0),
SCNVector3Make( 0, 1, 0),
SCNVector3Make( 0, 1, 0),
SCNVector3Make( 0, 1, 0),
SCNVector3Make( 0, 1, 0),
SCNVector3Make( 0, 0, 1),
SCNVector3Make( 0, 0, 1),
SCNVector3Make( 0, 0, -1),
SCNVector3Make( 0, 0, -1),
SCNVector3Make( 0, 0, 1),
SCNVector3Make( 0, 0, 1),
SCNVector3Make( 0, 0, -1),
SCNVector3Make( 0, 0, -1),
SCNVector3Make(-1, 0, 0),
SCNVector3Make( 1, 0, 0),
SCNVector3Make(-1, 0, 0),
SCNVector3Make( 1, 0, 0),
SCNVector3Make(-1, 0, 0),
SCNVector3Make( 1, 0, 0),
SCNVector3Make(-1, 0, 0),
SCNVector3Make( 1, 0, 0),
]
let indices:[CInt] = [
// bottom
0, 2, 1,
1, 2, 3,
// back
10, 14, 11, // 2, 6, 3, + 8
11, 14, 15, // 3, 6, 7, + 8
// left
16, 20, 18, // 0, 4, 2, + 16
18, 20, 22, // 2, 4, 6, + 16
// right
17, 19, 21, // 1, 3, 5, + 16
19, 23, 21, // 3, 7, 5, + 16
// front
8, 9, 12, // 0, 1, 4, + 8
9, 13, 12, // 1, 5, 4, + 8
// top
4, 5, 6,
5, 7, 6
]
let colors = [vector_float4](repeating: vector_float4(1.0,1.0,1.0,0.0), count: positions.count)
let geom = packGeometryTriangles(positions, indexList: indices, colourList: colors, normalsList: normals)
return geom
}
static func buildGeometryWithColor(_ geometry:SCNGeometry, color:vector_float4) -> SCNGeometry {
let indexElement = geometry.geometryElement(at: 0)
let vertexSource = geometry.getGeometrySources(for: SCNGeometrySource.Semantic.vertex).first!
let normalSource = geometry.getGeometrySources(for: SCNGeometrySource.Semantic.normal).first!
let vertexCount = vertexSource.vectorCount
let colourList = [vector_float4](repeating: color, count: vertexCount)
let colourData = Data(bytes: colourList, count: colourList.count * MemoryLayout<vector_float4>.size)
let colourSource = SCNGeometrySource(data: colourData,
semantic: SCNGeometrySource.Semantic.color,
vectorCount: colourList.count,
usesFloatComponents: true,
componentsPerVector: 4,
bytesPerComponent: MemoryLayout<Float>.size,
dataOffset: 0,
dataStride: MemoryLayout<vector_float4>.size)
let geo = SCNGeometry(sources: [vertexSource,normalSource,colourSource], elements: [indexElement])
return geo
}
static func buildSpiral() -> SCNGeometry {
var centerPoints:[SCNVector3] = []
let angleStep:Float = .pi / 30
let zStep:Float = 0.01
let radius:Float = 1
var angle:Float = 0
var z:Float = -2
while z < 2 {
let x = radius * cos(angle)
let y = radius * sin(angle)
let pt = SCNVector3Make(x, y, z)
centerPoints.append(pt)
angle += angleStep
z += zStep
}
let geom = buildTube(centerPoints, center: SCNVector3Zero, radius: 0.05, segmentCount: 10, colour: vector_float4(1.0, 0.0, 0.0, 1.0))
return geom
}
/**
Takes the various arrays and makes a geometry object from it
*/
static func packGeometryTriangles(_ pointsList: [SCNVector3],
indexList: [CInt],
colourList:[vector_float4]?,
normalsList: [SCNVector3]) -> SCNGeometry {
let vertexData = Data(bytes: pointsList, count: pointsList.count * MemoryLayout<vector_float3>.size)
let vertexSourceNew = SCNGeometrySource(data: vertexData,
semantic: SCNGeometrySource.Semantic.vertex,
vectorCount: pointsList.count,
usesFloatComponents: true,
componentsPerVector: 3,
bytesPerComponent: MemoryLayout<Float>.size,
dataOffset: 0,
dataStride: MemoryLayout<SCNVector3>.size)
let normalData = Data(bytes: normalsList, count: normalsList.count * MemoryLayout<vector_float3>.size)
let normalSource = SCNGeometrySource(data: normalData,
semantic: SCNGeometrySource.Semantic.normal,
vectorCount: normalsList.count,
usesFloatComponents: true,
componentsPerVector: 3,
bytesPerComponent: MemoryLayout<Float>.size,
dataOffset: 0,
dataStride: MemoryLayout<SCNVector3>.size)
let indexData = Data(bytes: indexList, count: indexList.count * MemoryLayout<CInt>.size)
let indexElement = SCNGeometryElement(
data: indexData,
primitiveType: SCNGeometryPrimitiveType.triangles,
primitiveCount: indexList.count/3,
bytesPerIndex: MemoryLayout<CInt>.size
)
if let colourList = colourList {
let colourData = Data(bytes: colourList, count: colourList.count * MemoryLayout<vector_float4>.size)
let colourSource = SCNGeometrySource(data: colourData,
semantic: SCNGeometrySource.Semantic.color,
vectorCount: colourList.count,
usesFloatComponents: true,
componentsPerVector: 4,
bytesPerComponent: MemoryLayout<Float>.size,
dataOffset: 0,
dataStride: MemoryLayout<vector_float4>.size)
let geo = SCNGeometry(sources: [vertexSourceNew,normalSource,colourSource], elements: [indexElement])
geo.firstMaterial?.isLitPerPixel = false
return geo
} else {
let geo = SCNGeometry(sources: [vertexSourceNew,normalSource], elements: [indexElement])
geo.firstMaterial?.isLitPerPixel = false
return geo
}
}
static func buildTube(_ points:[SCNVector3], center:SCNVector3, radius:Float, segmentCount:Int, colour:vector_float4?) -> SCNGeometry {
var colour = colour
if colour == nil {
colour = vector_float4(0,0,0,1)
}
let segmentRotationAngle:Float = 2 * .pi / Float(segmentCount)
var pointsList: [SCNVector3] = []
var normalsList: [SCNVector3] = []
var indexList: [CInt] = []
var colourList:[vector_float4] = []
var lastPt:SCNVector3? = nil
var lastPtsOffset:[SCNVector3]? = nil
var lastNormalsOffset:[SCNVector3]? = nil
for (i,pt) in points.enumerated() {
let distanceFromEnd = min(points.count - i, i)
let radiusMultiplicationFactor = min(Float(distanceFromEnd) / 4, 1)
if let lastPt = lastPt {
let along = (pt - lastPt)
let parallel = along.normalized()
let normal = (pt - center).normalized()
let startOffsetVector = normal * (radius * radiusMultiplicationFactor)
let startOffsetVectorGlk = SCNVector3ToGLKVector3(startOffsetVector)
var offsetPoints = [SCNVector3](repeating: SCNVector3Zero, count: segmentCount)
var offsetNormalVectors = [SCNVector3](repeating: SCNVector3Zero, count: segmentCount)
var rotation:Float = 0
for i in 0..<segmentCount {
let quart = GLKQuaternionMakeWithAngleAndAxis(rotation, parallel.x, parallel.y, parallel.z)
let rotatedOffsetVector = GLKQuaternionRotateVector3(quart, startOffsetVectorGlk)
let offsetPoint = pt + SCNVector3FromGLKVector3(rotatedOffsetVector)
offsetPoints[i] = offsetPoint
offsetNormalVectors[i] = SCNVector3FromGLKVector3(rotatedOffsetVector).normalized()
rotation += segmentRotationAngle
}
if let lastPtsOffset = lastPtsOffset, let lastNormalsOffset = lastNormalsOffset {
var prevLastPoint = lastPtsOffset[segmentCount-1]
var prevLastNorma = lastNormalsOffset[segmentCount-1]
var prevPoint = offsetPoints[segmentCount-1]
var prevNorma = offsetNormalVectors[segmentCount-1]
for i in 0..<segmentCount {
let lastPoint = lastPtsOffset[i]
let lastNorma = lastNormalsOffset[i]
let cPoint = offsetPoints[i]
let cNorma = offsetNormalVectors[i]
indexList.append(CInt(pointsList.count))
pointsList.append(prevPoint)
colourList.append(colour!)
normalsList.append(prevNorma * 2)
indexList.append(CInt(pointsList.count))
pointsList.append(prevLastPoint)
colourList.append(colour!)
normalsList.append(prevLastNorma * 2)
indexList.append(CInt(pointsList.count))
pointsList.append(lastPoint)
colourList.append(colour!)
normalsList.append(lastNorma * 2)
indexList.append(CInt(pointsList.count))
pointsList.append(lastPoint)
colourList.append(colour!)
normalsList.append(lastNorma)
indexList.append(CInt(pointsList.count))
pointsList.append(cPoint)
colourList.append(colour!)
normalsList.append(cNorma)
indexList.append(CInt(pointsList.count))
pointsList.append(prevPoint)
colourList.append(colour!)
normalsList.append(prevNorma)
prevLastPoint = lastPoint
prevLastNorma = lastNorma
prevPoint = cPoint
prevNorma = cNorma
}
}
lastPtsOffset = offsetPoints
lastNormalsOffset = offsetNormalVectors
}
lastPt = pt
}
return GeometryBuildTools.packGeometryTriangles(pointsList, indexList: indexList, colourList: colourList, normalsList: normalsList)
}
}
| mit | 77380064264ba6f12c1fd4ceaf4868db | 40.984709 | 141 | 0.525676 | 5.236079 | false | false | false | false |
paulyoung/ReactiveCocoa | ReactiveCocoa/Swift/Property.swift | 1 | 7475 | /// Represents a property that allows observation of its changes.
public protocol PropertyType {
typealias Value
/// The current value of the property.
var value: Value { get }
/// A producer for Signals that will send the property's current value,
/// followed by all changes over time.
var producer: SignalProducer<Value, NoError> { get }
}
/// A read-only property that allows observation of its changes.
public struct AnyProperty<Value>: PropertyType {
private let _value: () -> Value
private let _producer: () -> SignalProducer<Value, NoError>
public var value: Value {
return _value()
}
public var producer: SignalProducer<Value, NoError> {
return _producer()
}
/// Initializes a property as a read-only view of the given property.
public init<P: PropertyType where P.Value == Value>(_ property: P) {
_value = { property.value }
_producer = { property.producer }
}
/// Initializes a property that first takes on `initialValue`, then each value
/// sent on a signal created by `producer`.
public init(initialValue: Value, producer: SignalProducer<Value, NoError>) {
let mutableProperty = MutableProperty(initialValue)
mutableProperty <~ producer
self.init(mutableProperty)
}
/// Initializes a property that first takes on `initialValue`, then each value
/// sent on `signal`.
public init(initialValue: Value, signal: Signal<Value, NoError>) {
let mutableProperty = MutableProperty(initialValue)
mutableProperty <~ signal
self.init(mutableProperty)
}
}
/// A property that never changes.
public struct ConstantProperty<Value>: PropertyType {
public let value: Value
public let producer: SignalProducer<Value, NoError>
/// Initializes the property to have the given value.
public init(_ value: Value) {
self.value = value
self.producer = SignalProducer(value: value)
}
}
/// Represents an observable property that can be mutated directly.
///
/// Only classes can conform to this protocol, because instances must support
/// weak references (and value types currently do not).
public protocol MutablePropertyType: class, PropertyType {
var value: Value { get set }
}
/// A mutable property of type `Value` that allows observation of its changes.
///
/// Instances of this class are thread-safe.
public final class MutableProperty<Value>: MutablePropertyType {
private let observer: Signal<Value, NoError>.Observer
/// Need a recursive lock around `value` to allow recursive access to
/// `value`. Note that recursive sets will still deadlock because the
/// underlying producer prevents sending recursive events.
private let lock = NSRecursiveLock()
private var _value: Value
/// The current value of the property.
///
/// Setting this to a new value will notify all observers of any Signals
/// created from the `values` producer.
public var value: Value {
get {
lock.lock()
let value = _value
lock.unlock()
return value
}
set {
lock.lock()
_value = newValue
observer.sendNext(newValue)
lock.unlock()
}
}
/// A producer for Signals that will send the property's current value,
/// followed by all changes over time, then complete when the property has
/// deinitialized.
public let producer: SignalProducer<Value, NoError>
/// Initializes the property with the given value to start.
public init(_ initialValue: Value) {
lock.name = "org.reactivecocoa.ReactiveCocoa.MutableProperty"
(producer, observer) = SignalProducer<Value, NoError>.buffer(1)
_value = initialValue
observer.sendNext(initialValue)
}
deinit {
observer.sendCompleted()
}
}
/// Wraps a `dynamic` property, or one defined in Objective-C, using Key-Value
/// Coding and Key-Value Observing.
///
/// Use this class only as a last resort! `MutableProperty` is generally better
/// unless KVC/KVO is required by the API you're using (for example,
/// `NSOperation`).
@objc public final class DynamicProperty: RACDynamicPropertySuperclass, MutablePropertyType {
public typealias Value = AnyObject?
private weak var object: NSObject?
private let keyPath: String
/// The current value of the property, as read and written using Key-Value
/// Coding.
public var value: AnyObject? {
@objc(rac_value) get {
return object?.valueForKeyPath(keyPath)
}
@objc(setRac_value:) set(newValue) {
object?.setValue(newValue, forKeyPath: keyPath)
}
}
/// A producer that will create a Key-Value Observer for the given object,
/// send its initial value then all changes over time, and then complete
/// when the observed object has deallocated.
///
/// By definition, this only works if the object given to init() is
/// KVO-compliant. Most UI controls are not!
public var producer: SignalProducer<AnyObject?, NoError> {
if let object = object {
return object.rac_valuesForKeyPath(keyPath, observer: nil).toSignalProducer()
// Errors aren't possible, but the compiler doesn't know that.
.flatMapError { error in
0 // suppresses implicit return error on fatalError
fatalError("Received unexpected error from KVO signal: \(error)")
}
} else {
return .empty
}
}
/// Initializes a property that will observe and set the given key path of
/// the given object. `object` must support weak references!
public init(object: NSObject?, keyPath: String) {
self.object = object
self.keyPath = keyPath
/// DynamicProperty stay alive as long as object is alive.
/// This is made possible by strong reference cycles.
super.init()
object?.rac_willDeallocSignal()?.toSignalProducer().startWithCompleted { self }
}
}
infix operator <~ {
associativity right
// Binds tighter than assignment but looser than everything else
precedence 93
}
/// Binds a signal to a property, updating the property's value to the latest
/// value sent by the signal.
///
/// The binding will automatically terminate when the property is deinitialized,
/// or when the signal sends a `Completed` event.
public func <~ <P: MutablePropertyType>(property: P, signal: Signal<P.Value, NoError>) -> Disposable {
let disposable = CompositeDisposable()
disposable += property.producer.startWithCompleted {
disposable.dispose()
}
disposable += signal.observe { [weak property] event in
switch event {
case let .Next(value):
property?.value = value
case .Completed:
disposable.dispose()
default:
break
}
}
return disposable
}
/// Creates a signal from the given producer, which will be immediately bound to
/// the given property, updating the property's value to the latest value sent
/// by the signal.
///
/// The binding will automatically terminate when the property is deinitialized,
/// or when the created signal sends a `Completed` event.
public func <~ <P: MutablePropertyType>(property: P, producer: SignalProducer<P.Value, NoError>) -> Disposable {
var disposable: Disposable!
producer.startWithSignal { signal, signalDisposable in
property <~ signal
disposable = signalDisposable
property.producer.startWithCompleted {
signalDisposable.dispose()
}
}
return disposable
}
/// Binds `destinationProperty` to the latest values of `sourceProperty`.
///
/// The binding will automatically terminate when either property is
/// deinitialized.
public func <~ <Destination: MutablePropertyType, Source: PropertyType where Source.Value == Destination.Value>(destinationProperty: Destination, sourceProperty: Source) -> Disposable {
return destinationProperty <~ sourceProperty.producer
}
| mit | 26b1b180e3cb8edfe3dd5ab071630913 | 30.016598 | 185 | 0.731237 | 4.157397 | false | false | false | false |
argent-os/argent-ios | app-ios/HistoryDetailViewController.swift | 1 | 4575 | //
// HistoryDetailViewController.swift
// app-ios
//
// Created by Sinan Ulkuatam on 5/14/16.
// Copyright © 2016 Sinan Ulkuatam. All rights reserved.
//
import UIKit
import Foundation
class HistoryDetailViewController: UIViewController, UINavigationBarDelegate {
var amountLabel = UILabel()
var dateLabel = UILabel()
var detailHistory: History? {
didSet {
configureView()
}
}
func configureView() {
self.view.backgroundColor = UIColor.globalBackground()
let screen = UIScreen.mainScreen().bounds
let width = screen.size.width
_ = screen.size.height
// adds a manual credit card entry textfield
// self.view.addSubview(paymentTextField)
if let detailHistory = detailHistory {
amountLabel.text = detailHistory.amount
dateLabel.text = "test"
// Email textfield
amountLabel.frame = CGRectMake(0, 160, width, 110)
amountLabel.textAlignment = .Center
amountLabel.textColor = UIColor.darkGrayColor()
amountLabel.autoresizingMask = [.FlexibleLeftMargin, .FlexibleRightMargin]
self.view.addSubview(amountLabel)
// Email textfield
dateLabel.frame = CGRectMake(0, 240, width, 110)
dateLabel.textAlignment = .Center
dateLabel.textColor = UIColor.darkGrayColor()
dateLabel.autoresizingMask = [.FlexibleWidth, .FlexibleHeight]
self.view.addSubview(dateLabel)
// Title
self.navigationController?.view.backgroundColor = UIColor.slateBlue()
self.navigationController?.navigationBar.setBackgroundImage(UIImage(), forBarMetrics: .Default)
self.navigationController?.navigationBar.backgroundColor = UIColor.clearColor()
self.navigationController?.navigationBar.tintColor = UIColor.whiteColor()
self.navigationController?.navigationBar.barStyle = .BlackTranslucent
let navBar: UINavigationBar = UINavigationBar(frame: CGRect(x: 0, y: 0, width: width, height: 65))
navBar.translucent = true
navBar.tintColor = UIColor.slateBlue()
navBar.backgroundColor = UIColor.slateBlue()
navBar.shadowImage = UIImage()
navBar.setBackgroundImage(UIImage(), forBarMetrics: .Default)
navBar.titleTextAttributes = [
NSForegroundColorAttributeName : UIColor.whiteColor(),
NSFontAttributeName : UIFont.systemFontOfSize(18)
]
self.view.addSubview(navBar)
let navItem = UINavigationItem(title: "")
navItem.leftBarButtonItem?.tintColor = UIColor.whiteColor()
navBar.setItems([navItem], animated: true)
// Navigation Bar
let navigationBar = UINavigationBar(frame: CGRectMake(0, 0, self.view.frame.size.width, 65)) // Offset by 20 pixels vertically to take the status bar into account
navigationBar.backgroundColor = UIColor.slateBlue()
navigationBar.tintColor = UIColor.slateBlue()
navigationBar.delegate = self
// Create a navigation item with a title
let navigationItem = UINavigationItem()
// Create left and right button for navigation item
let leftButton = UIBarButtonItem(image: UIImage(named: "IconClose"), style: UIBarButtonItemStyle.Plain, target: self, action: #selector(HistoryDetailViewController.returnToMenu(_:)))
let font = UIFont.systemFontOfSize(14)
leftButton.setTitleTextAttributes([NSFontAttributeName: font, NSForegroundColorAttributeName:UIColor.mediumBlue()], forState: UIControlState.Normal)
// Create two buttons for the navigation item
navigationItem.leftBarButtonItem = leftButton
// Assign the navigation item to the navigation bar
navigationBar.items = [navigationItem]
// Make the navigation bar a subview of the current view controller
self.view.addSubview(navigationBar)
}
}
override func viewDidLoad() {
super.viewDidLoad()
configureView()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
func returnToMenu(sender: AnyObject) {
self.view.window!.rootViewController!.dismissViewControllerAnimated(true, completion: { _ in })
}
}
| mit | d3e87d7bb12c3700febec455fcfd428f | 41.351852 | 194 | 0.641014 | 5.819338 | false | false | false | false |
NoryCao/zhuishushenqi | zhuishushenqi/RightSide/Topic/Controllers/TopicDetail/QSTopicDetailRouter.swift | 1 | 1247 | //
// QSTopicDetailRouter.swift
// zhuishushenqi
//
// Created yung on 2017/4/20.
// Copyright © 2017年 QS. All rights reserved.
//
// Template generated by Juanpe Catalán @JuanpeCMiOS
//
import UIKit
class QSTopicDetailRouter: QSTopicDetailWireframeProtocol {
weak var viewController: UIViewController?
static func createModule(id:String) -> UIViewController {
// Change to get view from storyboard if not using progammatic UI
let view = QSTopicDetailViewController(nibName: nil, bundle: nil)
let interactor = QSTopicDetailInteractor()
let router = QSTopicDetailRouter()
let presenter = QSTopicDetailPresenter(interface: view, interactor: interactor, router: router)
view.presenter = presenter
interactor.output = presenter
router.viewController = view
interactor.id = id
return view
}
func presentDetail(indexPath:IndexPath,models:[TopicDetailModel]){
if indexPath.section > 0 {
let model = models[indexPath.section - 1]
viewController?.navigationController?.pushViewController(QSBookDetailRouter.createModule(id: model.book._id), animated: true)
}
}
}
| mit | dc27d778d80ce17325e6142befa99680 | 30.871795 | 137 | 0.674175 | 4.952191 | false | false | false | false |
byu-oit-appdev/ios-byuSuite | byuSuite/Apps/LockerRental/model/LockerRentalActionsHelper.swift | 1 | 1861 | //
// LockerRentalActionsHelper.swift
// byuSuite
//
// Created by Erik Brady on 7/19/17.
// Copyright © 2017 Brigham Young University. All rights reserved.
//
class LockerRentalActionsHelper: NSObject {
func rent(locker: LockerRentalLocker, fee: LockerRentalLockerFee, viewController: ByuViewController2, delegate: LockerRentalDelegate, spinner: UIActivityIndicatorView) {
let controller = UIAlertController(title: "Confirm Locker Rental", message: "Are you sure you want to rent this locker starting from today? If it is near the end of the semester or term, you may want to wait until the beginning of the next semester. Your BYU account will be charged \(Double(fee.amount ?? 0).currency()).", preferredStyle: .alert)
controller.addAction(UIAlertAction(title: "Yes", style: .default, handler: { (action) in
spinner.startAnimating()
LockerRentalClient.rent(locker: locker, with: fee, callback: { (rentStatus, error) in
if let rentStatus = rentStatus, let rootVC = delegate as? ByuViewController2 {
//The locker rental service will sometimes return "Error Renting Locker" even when it was a 200. In this case, show that error.
let title = rentStatus == "Rented" ? "Request Successful" : rentStatus
viewController.displayAlert(error: nil, title: title, alertHandler: { (action) in
delegate.loadLockers()
viewController.navigationController?.popToViewController(rootVC, animated: true)
})
} else {
viewController.displayAlert(error: error)
}
})
}))
controller.addAction(UIAlertAction(title: "No", style: .cancel))
viewController.present(controller, animated: true)
}
}
| apache-2.0 | 679a43b07de0ddb62c0af9636289a5ed | 57.125 | 355 | 0.654839 | 4.84375 | false | false | false | false |
cdtschange/SwiftMKit | SwiftMKitDemo/SwiftMKitDemo/UI/Data/Audio/AudioViewController.swift | 1 | 1209 | //
// AudioViewController.swift
// SwiftMKitDemo
//
// Created by wei.mao on 2018/7/13.
// Copyright © 2018年 cdts. All rights reserved.
//
import UIKit
import AudioKit
import AudioKitUI
import SwiftMKit
class AudioViewController: UIViewController, AKKeyboardDelegate {
let bank = AKOscillatorBank()
var keyboardView: AKKeyboardView?
override func viewDidLoad() {
super.viewDidLoad()
AudioKit.output = bank
try? AudioKit.start()
keyboardView = AKKeyboardView(width: 440, height: 100)
keyboardView?.delegate = self
// keyboard.polyphonicMode = true
self.view.addSubview(keyboardView!)
// Do any additional setup after loading the view.
}
override func viewDidLayoutSubviews() {
keyboardView?.frame = CGRect(x: 0, y: 100, w: 440, h: 100)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func noteOn(note: MIDINoteNumber) {
bank.play(noteNumber: note, velocity: 80)
}
func noteOff(note: MIDINoteNumber) {
bank.stop(noteNumber: note)
}
}
| mit | 19369d1ebd8c96fbd47605660943b476 | 24.125 | 66 | 0.646766 | 4.550943 | false | false | false | false |
taotao361/swift | FirstSwiftDemo/src/controller/YTPresentPhotoController.swift | 1 | 4548 | //
// YTPresentPhotoController.swift
// FirstSwiftDemo
//
// Created by yangxutao on 2017/5/23.
// Copyright © 2017年 yangxutao. All rights reserved.
//
import UIKit
private let PhotoBrowserCellReuseIdentifier = "PhotoBrowserCellReuseIdentifier"
class YTPresentPhotoController: YTRootViewController {
var currentIndex : Int?
var photoUrls : [URL]?
override func loadView() {
super.loadView()
view.backgroundColor = UIColor.white
}
override func viewDidLoad() {
super.viewDidLoad()
loadUI()
}
init(index : Int,urls : [URL]) {
currentIndex = index
photoUrls = urls
super.init(nibName: nil, bundle: nil)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
fileprivate func loadUI() {
view.addSubview(collectionView)
view.addSubview(closeBtn)
view.addSubview(saveBtn)
closeBtn.snp.makeConstraints { (make) in
make.right.equalTo(view).offset(-10)
make.bottom.equalTo(view).offset(-10)
make.height.equalTo(35)
make.width.equalTo(100)
}
saveBtn.snp.makeConstraints { (make) in
make.size.equalTo(closeBtn)
make.left.equalTo(view).offset(10)
make.bottom.equalTo(view).offset(-10)
}
collectionView.frame = UIScreen.main.bounds
collectionView.dataSource = self
collectionView.register(YTPhotoBrowserCell.self, forCellWithReuseIdentifier: PhotoBrowserCellReuseIdentifier)
}
func close() {
self.dismiss(animated: true) {
}
}
@objc fileprivate func save () {
let indexPath = collectionView.indexPathsForVisibleItems.last!
let cell = collectionView.cellForItem(at: indexPath) as! YTPhotoBrowserCell
let image = cell.imageView.image!
UIImageWriteToSavedPhotosAlbum(image, self, #selector(image(_:didFinishSavingWithError:contextInfo:)), nil)
}
func image(_ image : UIImage,didFinishSavingWithError error : NSError?,contextInfo : AnyObject) {
if error != nil {
print(error ?? "保存失败")
} else {
print("success")
}
}
//懒加载
fileprivate lazy var closeBtn : UIButton = {
let btn = UIButton.init()
btn.setTitle("关闭", for: UIControlState.normal)
btn.setTitleColor(UIColor.white, for: UIControlState.normal)
btn.backgroundColor = UIColor.darkGray
btn.addTarget(self, action: #selector(close), for: UIControlEvents.touchUpInside)
return btn
}()
fileprivate lazy var saveBtn : UIButton = {
let btn = UIButton.init()
btn.setTitle("保存", for: UIControlState.normal)
btn.setTitleColor(UIColor.red, for: UIControlState.normal)
btn.backgroundColor = UIColor.gray
btn.addTarget(self, action: #selector(save), for: UIControlEvents.touchUpInside)
return btn
}()
fileprivate lazy var collectionView : UICollectionView = UICollectionView.init(frame: CGRect.zero, collectionViewLayout: PhotoBrowserLayout.init())
}
extension YTPresentPhotoController : UICollectionViewDelegate,UICollectionViewDataSource {
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return photoUrls?.count ?? 0
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: PhotoBrowserCellReuseIdentifier, for: indexPath) as! YTPhotoBrowserCell
cell.imageUrl = photoUrls![indexPath.item]
cell.photoBrowserCellDelegate = self as? PhotoBrowserCellDelegate
return cell
}
func photoBrowserCellDIdClose(_ cell : YTPhotoBrowserCell) {
dismiss(animated: true, completion: nil)
}
}
//collectionView layout
class PhotoBrowserLayout: UICollectionViewFlowLayout {
override func prepare() {
itemSize = UIScreen.main.bounds.size
minimumInteritemSpacing = 0
minimumLineSpacing = 0
scrollDirection = UICollectionViewScrollDirection.horizontal
collectionView?.showsHorizontalScrollIndicator = false
collectionView?.isPagingEnabled = true
collectionView?.bounces = false
}
}
| mit | 3f1d5dc9275d3540860a3533a1841afb | 28.180645 | 151 | 0.655538 | 5.314924 | false | false | false | false |
avito-tech/Marshroute | Example/NavigationDemo/VIPER/Recursion/Assembly/RecursionAssemblyImpl.swift | 1 | 1781 | import UIKit
import Marshroute
final class RecursionAssemblyImpl: BaseAssembly, RecursionAssembly {
// MARK: - RecursionAssembly
func module(routerSeed: RouterSeed)
-> UIViewController
{
let router = RecursionRouterIphone(
assemblyFactory: assemblyFactory,
routerSeed: routerSeed
)
let viewControllerPosition = ViewControllerPosition(routerSeed: routerSeed)
return module(
router: router,
viewControllerPosition: viewControllerPosition
)
}
func ipadModule(routerSeed: RouterSeed)
-> UIViewController
{
let router = RecursionRouterIpad(
assemblyFactory: assemblyFactory,
routerSeed: routerSeed
)
let viewControllerPosition = ViewControllerPosition(routerSeed: routerSeed)
return module(
router: router,
viewControllerPosition: viewControllerPosition
)
}
// MARK - Private
private func module(
router: RecursionRouter,
viewControllerPosition: ViewControllerPosition)
-> UIViewController
{
let interactor = RecursionInteractorImpl(
timerService: serviceFactory.timerService()
)
let presenter = RecursionPresenter(
interactor: interactor,
router: router
)
let viewController = RecursionViewController(
viewControllerPosition: viewControllerPosition,
peekAndPopUtility: marshrouteStack.peekAndPopUtility
)
viewController.addDisposable(presenter)
presenter.view = viewController
return viewController
}
}
| mit | 9845b04a9985fc5b95089d9fb0e4cc88 | 26.828125 | 83 | 0.6137 | 7.011811 | false | false | false | false |
Mioke/SwiftArchitectureWithPOP | SwiftyArchitecture/Base/Assistance/Kits/TextInputLimiter/TextInputLimiter.swift | 1 | 2908 | //
// TextInputLimiter.swift
// FileMail
//
// Created by jiangkelan on 20/05/2017.
// Copyright © 2017 KleinMioke. All rights reserved.
//
import UIKit
@objc public protocol Inputer: AnyObject {
}
extension UITextField: Inputer { }
extension UITextView: Inputer { }
public class InputLimiter<T: Inputer>: NSObject {
public var maxCount: Int
public var reachMaxHandler: (() -> Void)?
public var contentDidChanged: ((String?) -> Void)?
weak var inputer: T?
public init(with inputer: T, maxCount: Int) {
self.maxCount = maxCount
self.inputer = inputer
super.init()
}
@objc fileprivate func contentChanged() -> Void {
guard let inputer = inputer else {
return
}
if let textfield = inputer as? UITextField {
self._inputerDidChanged(textfield)
} else if let textView = inputer as? UITextView {
self._inputerDidChanged(textView)
}
}
// text field
fileprivate func _inputerDidChanged<T: UITextField>(_ inputer: T) -> Void {
guard let text = inputer.text else {
return
}
if let selected = inputer.markedTextRange,
let _ = inputer.position(from: selected.start, offset: 0) {
} else {
if text.length > self.maxCount {
inputer.text = text[0..<self.maxCount]
self.reachMaxHandler?()
}
}
self.contentDidChanged?(inputer.text)
}
// text view
fileprivate func _inputerDidChanged<T: UITextView>(_ inputer: T) -> Void {
guard let text = inputer.text else {
return
}
if let selected = inputer.markedTextRange,
let _ = inputer.position(from: selected.start, offset: 0) {
} else {
if text.length > self.maxCount {
// let rangeIndex = (text as NSString).rangeOfComposedCharacterSequence(at: self.maxCount)
// if rangeIndex.length == 1 {
// inputer.text = text[0..<self.maxCount]
// } else {
// let realRange = (text as NSString).rangeOfComposedCharacterSequences(for: NSMakeRange(0, self.maxCount))
// inputer.text = (text as NSString).substring(with: realRange)
// }
inputer.text = text[0..<self.maxCount]
self.reachMaxHandler?()
}
}
self.contentDidChanged?(inputer.text)
}
}
extension InputLimiter where T: UIControl {
public func setup() -> Void {
inputer?.addTarget(self, action: #selector(contentChanged), for: .editingChanged)
}
public func unload() -> Void {
inputer?.removeTarget(self, action: #selector(contentChanged), for: .editingChanged)
}
}
| mit | 495e30df3863ae55bda18eb4d16df591 | 27.5 | 126 | 0.563811 | 4.628981 | false | false | false | false |
mono0926/nlp100-swift | NLP100Swift/Collection.extension.swift | 1 | 649 | //
// Collection.extension.swift
// nlp100-swift
//
// Created by mono on 2016/10/01.
//
//
import Foundation
extension Collection {
public func shuffled() -> [Generator.Element] {
var list = Array(self)
list.shuffle()
return list
}
}
extension MutableCollection where Index == Int {
public mutating func shuffle() {
let c = Int(count.toIntMax())
guard c > 1 else { return }
for i in 0..<(c - 1) {
let j = Int(arc4random_uniform(UInt32(c - i))) + i
guard i != j else { continue }
swap(&self[i], &self[j])
}
}
}
| mit | 0531b5876d46fac5943afcb141a9761e | 18.666667 | 62 | 0.523883 | 3.751445 | false | false | false | false |
zzycami/firefox-ios | Client/Frontend/Tabs/Tabs.swift | 3 | 1576 | // This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at http://mozilla.org/MPL/2.0/
import Foundation
class Tab
{
var title: String
var url: String
init(title: String, url: String) {
self.title = title
self.url = url
}
}
class TabClient
{
var name: String
var tabs: [Tab] = []
init(name: String) {
self.name = name
}
}
class TabsResponse: NSObject
{
var clients: [TabClient] = []
}
func parseTabsResponse(response: AnyObject?) -> TabsResponse {
let tabsResponse = TabsResponse()
if let response: NSArray = response as? NSArray {
for client in response {
let tabClient = TabClient(name: client.valueForKey("clientName") as String)
if let tabs = client.valueForKey("tabs") as? NSArray {
for tab in tabs {
var title = ""
var url = ""
if let t = tab.valueForKey("title") as? String {
title = t
}
if let u = tab.valueForKey("urlHistory") as? NSArray {
if u.count > 0 {
url = u[0] as String
}
}
tabClient.tabs.append(Tab(title: title, url: url))
}
}
tabsResponse.clients.append(tabClient)
}
}
return tabsResponse
}
| mpl-2.0 | 52bb13916b1e3baf50ba25871254b78e | 25.266667 | 87 | 0.506345 | 4.426966 | false | false | false | false |
BoutFitness/Concept2-SDK | Pod/Classes/Subject.swift | 1 | 2139 | //
// Subject.swift
// Pods
//
// Created by Jesse Curry on 11/2/15.
//
// Big thanks to Daniel Tartaglia
// https://gist.github.com/dtartaglia/0a71423c578f2bf3b15c
//
import Foundation
public protocol Disposable {
func dispose()
}
/**
Wraps a variable to allow notifications upon value changes.
*/
public class Subject<T> {
/**
The value that is to be observered.
All current observers will be notified when it is assigned to.
*/
public var value: T {
didSet {
notify()
}
}
/**
Returns true if there are currently observers.
*/
public var isObserved:Bool { get { return observers.count > 0 } }
init(value: T) {
self.value = value
}
deinit {
disposable?.dispose()
}
/**
To observe changes in the subject, attach a block.
When you want observation to end, call `dispose` on the returned Disposable
*/
public func attach(observer: @escaping (T) -> Void) -> Disposable {
let wrapped = ObserverWrapper(subject: self, function: observer)
observers.append(wrapped)
// Notify once on attachment
wrapped.update(value: value)
return wrapped
}
func map<U>(transform: @escaping (T) -> U) -> Subject<U> {
let result: Subject<U> = Subject<U>(value: transform(value))
result.disposable = self.attach { [weak result] value in
result?.value = transform(value)
}
return result
}
fileprivate func detach(wrappedObserver: ObserverWrapper<T>) {
observers = observers.filter { $0 !== wrappedObserver }
}
private func notify() {
for observer in observers {
observer.update(value: value)
}
}
private var disposable: Disposable?
private var observers: [ObserverWrapper<T>] = []
}
// MARK: -
private class ObserverWrapper<T>: Disposable {
init(subject: Subject<T>, function: @escaping (T) -> Void) {
self.subject = subject
self.function = function
}
func update(value: T) {
function(value)
}
func dispose() {
subject.detach(wrappedObserver: self)
}
unowned let subject: Subject<T>
let function: (T) -> Void
}
| mit | 41f2da975d34f203dd8244974ce292ac | 20.39 | 79 | 0.639084 | 3.875 | false | false | false | false |
rdlester/simply-giphy | Pods/Result/Result/Result.swift | 1 | 8002 | // Copyright (c) 2015 Rob Rix. All rights reserved.
/// An enum representing either a failure with an explanatory error, or a success with a result value.
public enum Result<T, Error: Swift.Error>: ResultProtocol, CustomStringConvertible, CustomDebugStringConvertible {
case success(T)
case failure(Error)
// MARK: Constructors
/// Constructs a success wrapping a `value`.
public init(value: T) {
self = .success(value)
}
/// Constructs a failure wrapping an `error`.
public init(error: Error) {
self = .failure(error)
}
/// Constructs a result from an `Optional`, failing with `Error` if `nil`.
public init(_ value: T?, failWith: @autoclosure () -> Error) {
self = value.map(Result.success) ?? .failure(failWith())
}
/// Constructs a result from a function that uses `throw`, failing with `Error` if throws.
public init(_ f: @autoclosure () throws -> T) {
self.init(attempt: f)
}
/// Constructs a result from a function that uses `throw`, failing with `Error` if throws.
public init(attempt f: () throws -> T) {
do {
self = .success(try f())
} catch var error {
if Error.self == AnyError.self {
error = AnyError(error)
}
self = .failure(error as! Error)
}
}
// MARK: Deconstruction
/// Returns the value from `success` Results or `throw`s the error.
public func dematerialize() throws -> T {
switch self {
case let .success(value):
return value
case let .failure(error):
throw error
}
}
/// Case analysis for Result.
///
/// Returns the value produced by applying `ifFailure` to `failure` Results, or `ifSuccess` to `success` Results.
public func analysis<Result>(ifSuccess: (T) -> Result, ifFailure: (Error) -> Result) -> Result {
switch self {
case let .success(value):
return ifSuccess(value)
case let .failure(value):
return ifFailure(value)
}
}
// MARK: Errors
/// The domain for errors constructed by Result.
public static var errorDomain: String { return "com.antitypical.Result" }
/// The userInfo key for source functions in errors constructed by Result.
public static var functionKey: String { return "\(errorDomain).function" }
/// The userInfo key for source file paths in errors constructed by Result.
public static var fileKey: String { return "\(errorDomain).file" }
/// The userInfo key for source file line numbers in errors constructed by Result.
public static var lineKey: String { return "\(errorDomain).line" }
/// Constructs an error.
public static func error(_ message: String? = nil, function: String = #function, file: String = #file, line: Int = #line) -> NSError {
var userInfo: [String: Any] = [
functionKey: function,
fileKey: file,
lineKey: line,
]
if let message = message {
userInfo[NSLocalizedDescriptionKey] = message
}
return NSError(domain: errorDomain, code: 0, userInfo: userInfo)
}
// MARK: CustomStringConvertible
public var description: String {
return analysis(
ifSuccess: { ".success(\($0))" },
ifFailure: { ".failure(\($0))" })
}
// MARK: CustomDebugStringConvertible
public var debugDescription: String {
return description
}
}
// MARK: - Derive result from failable closure
public func materialize<T>(_ f: () throws -> T) -> Result<T, AnyError> {
return materialize(try f())
}
public func materialize<T>(_ f: @autoclosure () throws -> T) -> Result<T, AnyError> {
do {
return .success(try f())
} catch {
return .failure(AnyError(error))
}
}
@available(*, deprecated, message: "Use the overload which returns `Result<T, AnyError>` instead")
public func materialize<T>(_ f: () throws -> T) -> Result<T, NSError> {
return materialize(try f())
}
@available(*, deprecated, message: "Use the overload which returns `Result<T, AnyError>` instead")
public func materialize<T>(_ f: @autoclosure () throws -> T) -> Result<T, NSError> {
do {
return .success(try f())
} catch {
// This isn't great, but it lets us maintain compatibility until this deprecated
// method can be removed.
#if _runtime(_ObjC)
return .failure(error as NSError)
#else
// https://github.com/apple/swift-corelibs-foundation/blob/swift-3.0.2-RELEASE/Foundation/NSError.swift#L314
let userInfo = _swift_Foundation_getErrorDefaultUserInfo(error) as? [String: Any]
let nsError = NSError(domain: error._domain, code: error._code, userInfo: userInfo)
return .failure(nsError)
#endif
}
}
// MARK: - Cocoa API conveniences
#if !os(Linux)
/// Constructs a `Result` with the result of calling `try` with an error pointer.
///
/// This is convenient for wrapping Cocoa API which returns an object or `nil` + an error, by reference. e.g.:
///
/// Result.try { NSData(contentsOfURL: URL, options: .dataReadingMapped, error: $0) }
public func `try`<T>(_ function: String = #function, file: String = #file, line: Int = #line, `try`: (NSErrorPointer) -> T?) -> Result<T, NSError> {
var error: NSError?
return `try`(&error).map(Result.success) ?? .failure(error ?? Result<T, NSError>.error(function: function, file: file, line: line))
}
/// Constructs a `Result` with the result of calling `try` with an error pointer.
///
/// This is convenient for wrapping Cocoa API which returns a `Bool` + an error, by reference. e.g.:
///
/// Result.try { NSFileManager.defaultManager().removeItemAtURL(URL, error: $0) }
public func `try`(_ function: String = #function, file: String = #file, line: Int = #line, `try`: (NSErrorPointer) -> Bool) -> Result<(), NSError> {
var error: NSError?
return `try`(&error) ?
.success(())
: .failure(error ?? Result<(), NSError>.error(function: function, file: file, line: line))
}
#endif
// MARK: - ErrorConvertible conformance
extension NSError: ErrorConvertible {
public static func error(from error: Swift.Error) -> Self {
func cast<T: NSError>(_ error: Swift.Error) -> T {
return error as! T
}
return cast(error)
}
}
// MARK: - Errors
/// An “error” that is impossible to construct.
///
/// This can be used to describe `Result`s where failures will never
/// be generated. For example, `Result<Int, NoError>` describes a result that
/// contains an `Int`eger and is guaranteed never to be a `failure`.
public enum NoError: Swift.Error, Equatable {
public static func ==(lhs: NoError, rhs: NoError) -> Bool {
return true
}
}
/// A type-erased error which wraps an arbitrary error instance. This should be
/// useful for generic contexts.
public struct AnyError: Swift.Error {
/// The underlying error.
public let error: Swift.Error
public init(_ error: Swift.Error) {
if let anyError = error as? AnyError {
self = anyError
} else {
self.error = error
}
}
}
extension AnyError: ErrorConvertible {
public static func error(from error: Error) -> AnyError {
return AnyError(error)
}
}
extension AnyError: CustomStringConvertible {
public var description: String {
return String(describing: error)
}
}
// There appears to be a bug in Foundation on Linux which prevents this from working:
// https://bugs.swift.org/browse/SR-3565
// Don't forget to comment the tests back in when removing this check when it's fixed!
#if !os(Linux)
extension AnyError: LocalizedError {
public var errorDescription: String? {
return error.localizedDescription
}
public var failureReason: String? {
return (error as? LocalizedError)?.failureReason
}
public var helpAnchor: String? {
return (error as? LocalizedError)?.helpAnchor
}
public var recoverySuggestion: String? {
return (error as? LocalizedError)?.recoverySuggestion
}
}
#endif
// MARK: - migration support
extension Result {
@available(*, unavailable, renamed: "success")
public static func Success(_: T) -> Result<T, Error> {
fatalError()
}
@available(*, unavailable, renamed: "failure")
public static func Failure(_: Error) -> Result<T, Error> {
fatalError()
}
}
extension NSError {
@available(*, unavailable, renamed: "error(from:)")
public static func errorFromErrorType(_ error: Swift.Error) -> Self {
fatalError()
}
}
import Foundation
| apache-2.0 | 5413f5235da209ca8be24bdebbcc1e23 | 28.189781 | 148 | 0.691548 | 3.604326 | false | false | false | false |
jum/Charts | Source/Charts/Data/Implementations/Standard/LineRadarChartDataSet.swift | 8 | 2324 | //
// LineRadarChartDataSet.swift
// Charts
//
// Copyright 2015 Daniel Cohen Gindi & Philipp Jahoda
// A port of MPAndroidChart for iOS
// Licensed under Apache License 2.0
//
// https://github.com/danielgindi/Charts
//
import Foundation
import CoreGraphics
open class LineRadarChartDataSet: LineScatterCandleRadarChartDataSet, ILineRadarChartDataSet
{
// MARK: - Data functions and accessors
// MARK: - Styling functions and accessors
/// The color that is used for filling the line surface area.
private var _fillColor = NSUIColor(red: 140.0/255.0, green: 234.0/255.0, blue: 255.0/255.0, alpha: 1.0)
/// The color that is used for filling the line surface area.
open var fillColor: NSUIColor
{
get { return _fillColor }
set
{
_fillColor = newValue
fill = nil
}
}
/// The object that is used for filling the area below the line.
/// **default**: nil
open var fill: Fill?
/// The alpha value that is used for filling the line surface,
/// **default**: 0.33
open var fillAlpha = CGFloat(0.33)
private var _lineWidth = CGFloat(1.0)
/// line width of the chart (min = 0.0, max = 10)
///
/// **default**: 1
open var lineWidth: CGFloat
{
get
{
return _lineWidth
}
set
{
_lineWidth = newValue.clamped(to: 0...10)
}
}
/// Set to `true` if the DataSet should be drawn filled (surface), and not just as a line.
/// Disabling this will give great performance boost.
/// Please note that this method uses the path clipping for drawing the filled area (with images, gradients and layers).
open var drawFilledEnabled = false
/// `true` if filled drawing is enabled, `false` ifnot
open var isDrawFilledEnabled: Bool
{
return drawFilledEnabled
}
// MARK: NSCopying
open override func copy(with zone: NSZone? = nil) -> Any
{
let copy = super.copy(with: zone) as! LineRadarChartDataSet
copy.fill = fill
copy.fillAlpha = fillAlpha
copy._fillColor = _fillColor
copy._lineWidth = _lineWidth
copy.drawFilledEnabled = drawFilledEnabled
return copy
}
}
| apache-2.0 | baab499243d970f0cb2979b98ada9763 | 26.341176 | 124 | 0.608434 | 4.547945 | false | false | false | false |
chaosarts/ChaosMath.swift | ChaosMath/basis3.swift | 1 | 4851 | //
// basis3.swift
// ChaosMath
//
// Created by Fu Lam Diep on 09/10/2016.
// Copyright © 2016 Fu Lam Diep. All rights reserved.
//
import Foundation
public struct tbasis3<T: ArithmeticScalarType>: Equatable {
/*
+--------------------------------------------------------------------------
| Typealiases
+--------------------------------------------------------------------------
*/
/// Describes the data type of the components
public typealias ElementType = T
/// Describes its own type
public typealias SelfType = tbasis3<ElementType>
/// Decribes the VectorType
public typealias VectorType = tvec3<ElementType>
/// Decribes the MatrixType
public typealias MatrixType = tmat3<ElementType>
/*
+--------------------------------------------------------------------------
| Stored properties
+--------------------------------------------------------------------------
*/
/// Provides the first vector of the basis
public let b1: VectorType
/// Provides the second vector of the basis
public let b2: VectorType
/// Provides the third vector of the basis
public let b3: VectorType
/*
+--------------------------------------------------------------------------
| Stored properties
+--------------------------------------------------------------------------
*/
/// Provides the first vector of the basis
public var x: VectorType {
return b1
}
/// Provides the second vector of the basis
public var y: VectorType {
return b2
}
/// Provides the third vector of the basis
public var z: VectorType {
return b3
}
/// Represents the basis as matrix
public var mat: MatrixType {
return MatrixType(x, y, z)
}
/*
+--------------------------------------------------------------------------
| Initialisers
+--------------------------------------------------------------------------
*/
/// Initializes the basis with the standard basis vectors
public init () {
b1 = VectorType.e1
b2 = VectorType.e2
b3 = VectorType.e3
}
/// Initializes the basis with given basis vectors
/// - parameter b1: The first basis vector
/// - parameter b2: The second basis vector
/// - parameter b3: The second basis vector
public init?<ForeignType: ArithmeticScalarType> (_ b1: tvec3<ForeignType>, _ b2: tvec3<ForeignType>, _ b3: tvec3<ForeignType>) {
if determinant(b1, b2, b3) == 0 {
return nil
}
self.b1 = VectorType(b1)
self.b2 = VectorType(b2)
self.b3 = VectorType(b3)
}
/// Initializes the basis with a matrix
/// - parameter mat: The matrix to adopt the
public init?<ForeignType: ArithmeticScalarType> (_ mat: tmat3<ForeignType>) {
if mat.det == 0 {
return nil
}
b1 = VectorType(mat.array[0], mat.array[1], mat.array[2])
b2 = VectorType(mat.array[3], mat.array[4], mat.array[5])
b3 = VectorType(mat.array[6], mat.array[7], mat.array[8])
}
/// Copies a basis
public init<ForeignType: ArithmeticScalarType> (_ basis: tbasis3<ForeignType>) {
b1 = VectorType(basis.b1)
b2 = VectorType(basis.b2)
b3 = VectorType(basis.b3)
}
}
public typealias basis3i = tbasis3<Int>
public typealias basis3f = tbasis3<Float>
public typealias basis3d = tbasis3<Double>
public typealias basis3 = basis3f
/*
+--------------------------------------------------------------------------
| Static function
+--------------------------------------------------------------------------
*/
public func ==<ElementType: ArithmeticScalarType> (left: tbasis3<ElementType>, right: tbasis3<ElementType>) -> Bool {
return left.b1 == right.b1 && left.b2 == right.b2 && left.b3 == right.b3
}
/// Returns the transformation matrix from one basis to another
/// - parameter from: The basis to transform from
/// - parameter to: The basis to transform to
/// - returns: The transformation matrix
public func transformation<T: ArithmeticIntType> (fromBasis from: tbasis3<T>, toBasis to: tbasis3<T>) -> tmat3<Float> {
let inverted : tmat3<Float> = try! invert(from.mat)
return inverted * tmat3<Float>(to.mat)
}
/// Returns the transformation matrix from one basis to another
/// - parameter from: The basis to transform from
/// - parameter to: The basis to transform to
/// - returns: The transformation matrix
public func transformation<T: ArithmeticFloatType> (fromBasis from: tbasis3<T>, toBasis to: tbasis3<T>) -> tmat3<T> {
let inverted : tmat3<T> = try! invert(from.mat)
return inverted * to.mat
}
| gpl-3.0 | 5ede66dcda9ac4bd3605d85241c33312 | 29.89172 | 132 | 0.521649 | 4.754902 | false | false | false | false |
UTBiomedicalInformaticsLab/ProbabilityWheeliOS | Probability Wheel/CustomViews/KnobView.swift | 1 | 4085 | //
// KnobView.swift
// Probability Wheel
//
// Created by Allen Wang on 11/15/15.
// Copyright © 2015 UT Biomedical Informatics Lab. All rights reserved.
//
// The code in this file is largely based on this link:
// http://www.ioscreator.com/tutorials/dragging-views-gestures-tutorial-ios8-swift
import UIKit
class KnobView: UIView {
private var index:Int = 0
private var lastLocation:CGPoint = CGPointMake(0,0)
private var angle:CGFloat = 0.0
let sharedInfo = SharedInfo.sharedInstance
// Overrides the drawing of a rectangle. Makes it look like a circle instead.
override func drawRect(rect: CGRect) {
// Drawing code
super.drawRect(rect)
layer.cornerRadius = frame.size.width / 2
clipsToBounds = true
layer.borderColor = UIColor.clearColor().CGColor
layer.borderWidth = 5.0
}
// Attach a pan gesture recognizer to the view
// This allows us to click and drag it to a new position.
override init(frame: CGRect) {
super.init(frame: frame)
/*
let panRecognizer = UIPanGestureRecognizer(target:self, action:"detectPan:")
self.gestureRecognizers = [panRecognizer]
*/
self.backgroundColor = UIColor.blackColor()
drawRect(frame)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func setAngle(angle: CGFloat) {
self.angle = angle
}
func getAngle() -> CGFloat {
return self.angle
}
/*
func detectPan(recognizer:UIPanGestureRecognizer) {
let translation = recognizer.translationInView(self.superview!)
self.center = CGPointMake(lastLocation.x + translation.x, lastLocation.y + translation.y)
//frame.origin.x = lastLocation.x + translation.x
//frame.origin.y = lastLocation.y + translation.y
}
*/
/*
override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
// promote the touched view
self.superview?.bringSubviewToFront(self)
//print("Knob \(index) being touched")
// Remember the original location
lastLocation = self.center
}
*/
func setPoint(point: CGPoint) {
lastLocation = point
//print("Moving point \(index) to (\(point.x),\(point.y)).")
frame.origin.x = point.x
frame.origin.y = point.y
}
func setIdx(index: Int) {
self.index = index
}
func getIdx() -> Int {
return self.index
}
func closeTo(p : CGPoint) -> Bool {
let x = frame.origin.x
let y = frame.origin.y
let w = frame.width
let h = frame.height
return p.x >= x - w && p.x <= x + w && p.y >= y - h && p.y <= y + h
}
func updateAngle(point: CGPoint) {
let center = sharedInfo.getCenter()
if point.x >= center.x && point.y >= center.y { // Quadrant I
angle = -abs(atan2(center.y - (point.y + 10), (point.x + 10) - center.x) * CGFloat(180.0 / M_PI))
} else if point.x < center.x && point.y > center.y { // Quadrant II
angle = abs(360 + (atan2(-((point.y + 10) - center.y), ((point.x + 10) - center.x)) * CGFloat(180 / M_PI)))
} else if point.x < center.x && point.y < center.y { // Quadrant III
angle = abs(360 + (atan2(-((point.y + 10) - center.y), -(center.x - (point.x + 10))) * CGFloat(180 / M_PI)))
} else { // Quadrant IV
angle = abs(atan2(center.y - (point.y + 10), -(center.x - (point.x + 10))) * (CGFloat(180 / M_PI)))
}
}
func updateCoordinates(p: CGPoint) {
updateAngle(p)
let radius = Float(sharedInfo.getRadius())
let center = sharedInfo.getCenter()
self.frame.origin.x = center.x + CGFloat(radius * cos(Float(angle) / 360 * Float(2*M_PI)))
self.frame.origin.y = center.y - CGFloat(radius * sin(Float(angle) / 360 * Float(2*M_PI)))
}
} | mit | bb13021358505d9035da2315a3186c28 | 33.91453 | 120 | 0.580069 | 3.856468 | false | false | false | false |
emiscience/Prephirences | Prephirences/NSUbiquitousKeyValueStore+Prephirences.swift | 1 | 4351 | //
// NSUbiquitousKeyValueStore+Prephirences.swift
// Prephirences
/*
The MIT License (MIT)
Copyright (c) 2015 Eric Marchand (phimage)
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
/** Prephirences Extends NSUbiquitousKeyValueStore
*/
extension NSUbiquitousKeyValueStore : MutablePreferencesType {
public func dictionary() -> [String : AnyObject] {
return self.dictionaryRepresentation as! [String:AnyObject]
}
public func hasObjectForKey(key: String) -> Bool {
return objectForKey(key) != nil
}
public func clearAll() {
for(key,value) in self.dictionaryRepresentation {
removeObjectForKey(key as! String)
}
}
public func setObjectsForKeysWithDictionary(dictionary: [String:AnyObject]) {
for (key, value) in dictionary {
self.setObject(value, forKey: key)
}
}
public func stringArrayForKey(key: String) -> [AnyObject]? {
return arrayForKey(key) as? [String]
}
// MARK: number
public func integerForKey(key: String) -> Int {
return Int(longLongForKey(key))
}
public func floatForKey(key: String) -> Float {
return Float(doubleForKey(key))
}
public func setInteger(value: Int, forKey key: String){
setLongLong(Int64(value), forKey: key)
}
public func setFloat(value: Float, forKey key: String){
setDouble(Double(value), forKey: key)
}
// MARK: url
public func URLForKey(key: String) -> NSURL? {
if let bookData = self.dataForKey(key) {
var isStale : ObjCBool = false
var error : NSErrorPointer = nil
#if os(OSX)
let options = NSURLBookmarkResolutionOptions.WithSecurityScope
#elseif os(iOS)
let options = NSURLBookmarkResolutionOptions.WithoutUI
#endif
if let url = NSURL(byResolvingBookmarkData: bookData, options: options, relativeToURL: nil, bookmarkDataIsStale: &isStale, error: error) {
if error == nil {
return url
}
}
}
return nil
}
public func setURL(url: NSURL, forKey key: String) {
#if os(OSX)
let options = NSURLBookmarkCreationOptions.WithSecurityScope | NSURLBookmarkCreationOptions.SecurityScopeAllowOnlyReadAccess
#elseif os(iOS)
let options = NSURLBookmarkCreationOptions.allZeros
#endif
let data = url.bookmarkDataWithOptions(options, includingResourceValuesForKeys:nil, relativeToURL:nil, error:nil)
setData(data, forKey: key)
}
// MARK: archive
public func unarchiveObjectForKey(key: String) -> AnyObject? {
return Prephirences.unarchiveObject(self, forKey: key)
}
public func setObjectToArchive(value: AnyObject?, forKey key: String) {
Prephirences.archiveObject(value, preferences: self, forKey: key)
}
}
//MARK: subscript access
extension NSUbiquitousKeyValueStore {
public subscript(key: String) -> AnyObject? {
get {
return self.objectForKey(key)
}
set {
if newValue == nil {
removeObjectForKey(key)
} else {
setObject(newValue, forKey: key)
}
}
}
} | mit | a2c6118a602c0ded60d85cae4e68af9f | 32.736434 | 150 | 0.659618 | 4.933107 | false | false | false | false |
mozilla-mobile/firefox-ios | Tests/UITests/Global.swift | 2 | 26668 | // This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at http://mozilla.org/MPL/2.0
import Foundation
import GCDWebServers
import Storage
import WebKit
import Shared
@testable import Client
let LabelAddressAndSearch = "Address and Search"
extension XCTestCase {
func tester(_ file: String = #file, _ line: Int = #line) -> KIFUITestActor {
return KIFUITestActor(inFile: file, atLine: line, delegate: self)
}
func system(_ file: String = #file, _ line: Int = #line) -> KIFSystemTestActor {
return KIFSystemTestActor(inFile: file, atLine: line, delegate: self)
}
}
extension KIFUITestActor {
/// Looks for a view with the given accessibility hint.
func tryFindingViewWithAccessibilityHint(_ hint: String) -> Bool {
let element = UIApplication.shared.accessibilityElement { element in
return element?.accessibilityHint! == hint
}
return element != nil
}
func waitForViewWithAccessibilityHint(_ hint: String) -> UIView? {
var view: UIView? = nil
autoreleasepool {
wait(for: nil, view: &view, withElementMatching: NSPredicate(format: "accessibilityHint = %@", hint), tappable: false)
}
return view
}
func viewExistsWithLabel(_ label: String) -> Bool {
do {
try self.tryFindingView(withAccessibilityLabel: label)
return true
} catch {
return false
}
}
func viewExistsWithLabelPrefixedBy(_ prefix: String) -> Bool {
let element = UIApplication.shared.accessibilityElement { element in
return element?.accessibilityLabel?.hasPrefix(prefix) ?? false
}
return element != nil
}
/// Waits for and returns a view with the given accessibility value.
func waitForViewWithAccessibilityValue(_ value: String) -> UIView {
var element: UIAccessibilityElement!
run { _ in
element = UIApplication.shared.accessibilityElement { element in
return element?.accessibilityValue == value
}
return (element == nil) ? KIFTestStepResult.wait : KIFTestStepResult.success
}
return UIAccessibilityElement.viewContaining(element)
}
/// Wait for and returns a view with the given accessibility label as an
/// attributed string. See the comment in ReadingListPanel.swift about
/// using attributed strings as labels. (It lets us set the pitch)
func waitForViewWithAttributedAccessibilityLabel(_ label: NSAttributedString) -> UIView {
var element: UIAccessibilityElement!
run { _ in
element = UIApplication.shared.accessibilityElement { element in
if let elementLabel = element?.value(forKey: "accessibilityLabel") as? NSAttributedString {
return elementLabel.isEqual(to: label)
}
return false
}
return (element == nil) ? KIFTestStepResult.wait : KIFTestStepResult.success
}
return UIAccessibilityElement.viewContaining(element)
}
/// There appears to be a KIF bug where waitForViewWithAccessibilityLabel returns the parent
/// UITableView instead of the UITableViewCell with the given label.
/// As a workaround, retry until KIF gives us a cell.
/// Open issue: https://github.com/kif-framework/KIF/issues/336
func waitForCellWithAccessibilityLabel(_ label: String) -> UITableViewCell {
var cell: UITableViewCell!
run { _ in
let view = self.waitForView(withAccessibilityLabel: label)
cell = view as? UITableViewCell
return (cell == nil) ? KIFTestStepResult.wait : KIFTestStepResult.success
}
return cell
}
/**
* Finding views by accessibility label doesn't currently work with WKWebView:
* https://github.com/kif-framework/KIF/issues/460
* As a workaround, inject a KIFHelper class that iterates the document and finds
* elements with the given textContent or title.
*/
func waitForWebViewElementWithAccessibilityLabel(_ text: String) {
run { error in
if self.hasWebViewElementWithAccessibilityLabel(text) {
return KIFTestStepResult.success
}
return KIFTestStepResult.wait
}
}
/**
* Sets the text for a WKWebView input element with the given name.
*/
func enterText(_ text: String, intoWebViewInputWithName inputName: String) {
let webView = getWebViewWithKIFHelper()
var stepResult = KIFTestStepResult.wait
let escaped = text.replacingOccurrences(of: "\"", with: "\\\"")
webView.evaluateJavascriptInDefaultContentWorld("KIFHelper.enterTextIntoInputWithName(\"\(escaped)\", \"\(inputName)\");") { success, _ in
stepResult = ((success as? Bool)!) ? KIFTestStepResult.success : KIFTestStepResult.failure
}
run { error in
if stepResult == KIFTestStepResult.failure {
error?.pointee = NSError(domain: "KIFHelper", code: 0, userInfo: [NSLocalizedDescriptionKey: "Input element not found in webview: \(escaped)"])
}
return stepResult
}
}
/**
* Clicks a WKWebView element with the given label.
*/
func tapWebViewElementWithAccessibilityLabel(_ text: String) {
let webView = getWebViewWithKIFHelper()
var stepResult = KIFTestStepResult.wait
let escaped = text.replacingOccurrences(of: "\"", with: "\\\"")
webView.evaluateJavascriptInDefaultContentWorld("KIFHelper.tapElementWithAccessibilityLabel(\"\(escaped)\")") { success, _ in
stepResult = ((success as? Bool)!) ? KIFTestStepResult.success : KIFTestStepResult.failure
}
run { error in
if stepResult == KIFTestStepResult.failure {
error?.pointee = NSError(domain: "KIFHelper", code: 0, userInfo: [NSLocalizedDescriptionKey: "Accessibility label not found in webview: \(escaped)"])
}
return stepResult
}
}
/**
* Determines whether an element in the page exists.
*/
func hasWebViewElementWithAccessibilityLabel(_ text: String) -> Bool {
let webView = getWebViewWithKIFHelper()
var stepResult = KIFTestStepResult.wait
var found = false
let escaped = text.replacingOccurrences(of: "\"", with: "\\\"")
webView.evaluateJavascriptInDefaultContentWorld("KIFHelper.hasElementWithAccessibilityLabel(\"\(escaped)\")") { success, _ in
found = success as? Bool ?? false
stepResult = KIFTestStepResult.success
}
run { _ in return stepResult }
return found
}
fileprivate func getWebViewWithKIFHelper() -> WKWebView {
let webView = waitForView(withAccessibilityLabel: "Web content") as! WKWebView
// Wait for the web view to stop loading.
run { _ in
return webView.isLoading ? KIFTestStepResult.wait : KIFTestStepResult.success
}
var stepResult = KIFTestStepResult.wait
webView.evaluateJavascriptInDefaultContentWorld("typeof KIFHelper") { result, _ in
if result as! String == "undefined" {
let bundle = Bundle(for: BrowserTests.self)
let path = bundle.path(forResource: "KIFHelper", ofType: "js")!
let source = try! String(contentsOfFile: path, encoding: .utf8)
webView.evaluateJavascriptInDefaultContentWorld(source)
}
stepResult = KIFTestStepResult.success
}
run { _ in return stepResult }
return webView
}
public func deleteCharacterFromFirstResponser() {
self.enterText(intoCurrentFirstResponder: "\u{0008}")
}
}
class BrowserUtils {
// Needs to be in sync with Client Clearables.
enum Clearable: String {
case History = "Browsing History"
case Cache = "Cache"
case OfflineData = "Offline Website Data"
case Cookies = "Cookies"
case TrackingProtection = "Tracking Protection"
}
internal static let AllClearables = Set([Clearable.History, Clearable.Cache, Clearable.OfflineData, Clearable.Cookies, Clearable.TrackingProtection])
class func resetToAboutHomeKIF(_ tester: KIFUITestActor) {
if iPad() {
tester.tapView(withAccessibilityIdentifier: "TopTabsViewController.tabsButton")
} else {
tester.tapView(withAccessibilityIdentifier: "TabToolbar.tabsButton")
}
// if in private mode, close all tabs
tester.tapView(withAccessibilityLabel: "smallPrivateMask")
tester.tapView(withAccessibilityIdentifier: AccessibilityIdentifiers.TabTray.closeAllTabsButton)
tester.tapView(withAccessibilityIdentifier: AccessibilityIdentifiers.TabTray.deleteCloseAllButton)
tester.wait(forTimeInterval: 3)
/* go to Normal mode */
if (tester.viewExistsWithLabel("Show Tabs")) {
tester.tapView(withAccessibilityLabel: "1")
} else {
tester.tapView(withAccessibilityLabel: "1")
}
tester.tapView(withAccessibilityIdentifier: AccessibilityIdentifiers.TabTray.closeAllTabsButton)
tester.tapView(withAccessibilityIdentifier: AccessibilityIdentifiers.TabTray.deleteCloseAllButton)
}
class func dismissFirstRunUI(_ tester: KIFUITestActor) {
tester.waitForAnimationsToFinish(withTimeout: 10)
if (tester.viewExistsWithLabel("Next")) {
tester.tapView(withAccessibilityIdentifier: "nextOnboardingButton")
tester.waitForAnimationsToFinish(withTimeout: 3)
tester.tapView(withAccessibilityIdentifier: "startBrowsingButtonSyncView")
}
}
class func enterUrlAddressBar(_ tester: KIFUITestActor, typeUrl: String) {
tester.tapView(withAccessibilityIdentifier: "url")
tester.enterText(intoCurrentFirstResponder: typeUrl)
tester.enterText(intoCurrentFirstResponder: "\n")
}
class func iPad() -> Bool {
return UIDevice.current.userInterfaceIdiom == .pad
}
/// Injects a URL and title into the browser's history database.
class func addHistoryEntry(_ title: String, url: URL) {
let info: [AnyHashable: Any] = [
"url": url,
"title": title,
"visitType": VisitType.link.rawValue]
NotificationCenter.default.post(name: .OnLocationChange, object: self, userInfo: info)
}
fileprivate class func clearHistoryItemAtIndex(_ index: IndexPath, tester: KIFUITestActor) {
if let row = tester.waitForCell(at: index, inTableViewWithAccessibilityIdentifier: AccessibilityIdentifiers.LibraryPanels.HistoryPanel.tableView) {
tester.swipeView(withAccessibilityLabel: row.accessibilityLabel, value: row.accessibilityValue, in: KIFSwipeDirection.left)
tester.tapView(withAccessibilityLabel: "Remove")
}
}
class func openClearPrivateDataDialogKIF(_ tester: KIFUITestActor) {
tester.tapView(withAccessibilityLabel: "Menu")
tester.tapView(withAccessibilityLabel: "Settings")
tester.accessibilityScroll(.down)
tester.tapView(withAccessibilityIdentifier: "ClearPrivateData")
}
class func closeClearPrivateDataDialog(_ tester: KIFUITestActor) {
tester.tapView(withAccessibilityLabel: "Settings")
tester.tapView(withAccessibilityIdentifier: "AppSettingsTableViewController.navigationItem.leftBarButtonItem")
}
class func acceptClearPrivateData(_ tester: KIFUITestActor) {
tester.tapView(withAccessibilityLabel: "OK")
}
class func clearPrivateData(_ clearables: Set<Clearable>? = AllClearables, _ tester: KIFUITestActor) {
// Disable all items that we don't want to clear.
tester.waitForAnimationsToFinish(withTimeout: 3)
for clearable in AllClearables {
tester.setOn(clearables!.contains(clearable), forSwitchWithAccessibilityLabel: clearable.rawValue)
}
tester.tapView(withAccessibilityIdentifier: "ClearPrivateData")
}
class func clearPrivateDataKIF(_ tester: KIFUITestActor) {
tester.tapView(withAccessibilityIdentifier: "urlBar-cancel")
tester.waitForAnimationsToFinish(withTimeout: 3)
tester.tapView(withAccessibilityLabel: "Menu")
tester.tapView(withAccessibilityLabel: "Settings")
tester.accessibilityScroll(.down)
tester.tapView(withAccessibilityIdentifier: "ClearPrivateData")
tester.tapView(withAccessibilityLabel: "Clear Private Data")
acceptClearPrivateData(tester)
closeClearPrivateDataDialog(tester)
}
class func clearHistoryItems(_ tester: KIFUITestActor, numberOfTests: Int = -1) {
resetToAboutHomeKIF(tester)
tester.tapView(withAccessibilityLabel: "History")
let historyTable = tester.waitForView(withAccessibilityIdentifier: AccessibilityIdentifiers.LibraryPanels.HistoryPanel.tableView) as! UITableView
var index = 0
for _ in 0 ..< historyTable.numberOfSections {
for _ in 0 ..< historyTable.numberOfRows(inSection: 0) {
clearHistoryItemAtIndex(IndexPath(row: 0, section: 0), tester: tester)
if numberOfTests > -1 {
index += 1
if index == numberOfTests {
return
}
}
}
}
tester.tapView(withAccessibilityLabel: "Top sites")
}
class func ensureAutocompletionResult(_ tester: KIFUITestActor, textField: UITextField, prefix: String, completion: String) {
// searches are async (and debounced), so we have to wait for the results to appear.
tester.waitForViewWithAccessibilityValue(prefix + completion)
let autocompleteFieldlabel = textField.subviews.first { $0.accessibilityIdentifier == "autocomplete" } as? UILabel
if completion == "" {
XCTAssertTrue(autocompleteFieldlabel == nil, "The autocomplete was empty but the label still exists.")
return
}
XCTAssertTrue(autocompleteFieldlabel != nil, "The autocomplete was not found")
XCTAssertEqual(completion, autocompleteFieldlabel!.text, "Expected prefix matches actual prefix")
}
class func openLibraryMenu(_ tester: KIFUITestActor) {
tester.waitForAnimationsToFinish()
tester.waitForView(withAccessibilityIdentifier: AccessibilityIdentifiers.Toolbar.settingsMenuButton)
tester.tapView(withAccessibilityIdentifier: AccessibilityIdentifiers.Toolbar.settingsMenuButton)
tester.waitForAnimationsToFinish()
}
class func closeLibraryMenu(_ tester: KIFUITestActor) {
if iPad() {
tester.tapView(withAccessibilityIdentifier: "TabToolbar.libraryButton")
} else {
// Workaround to be able to swipe the view and close the library panel
tester.tapView(withAccessibilityLabel: "Done")
}
tester.waitForAnimationsToFinish()
}
}
class SimplePageServer {
class func getPageData(_ name: String, ext: String = "html") -> String {
let pageDataPath = Bundle(for: self).path(forResource: name, ofType: ext)!
return try! String(contentsOfFile: pageDataPath, encoding: .utf8)
}
static var useLocalhostInsteadOfIP = false
class func start() -> String {
let webServer: GCDWebServer = GCDWebServer()
webServer.addHandler(forMethod: "GET", path: "/image.png", request: GCDWebServerRequest.self) { (request) -> GCDWebServerResponse? in
let img = UIImage(named: "goBack")!.pngData()!
return GCDWebServerDataResponse(data: img, contentType: "image/png")
}
for page in ["findPage", "noTitle", "readablePage", "JSPrompt", "blobURL", "firefoxScheme"] {
webServer.addHandler(forMethod: "GET", path: "/\(page).html", request: GCDWebServerRequest.self) { (request) -> GCDWebServerResponse? in
return GCDWebServerDataResponse(html: self.getPageData(page))
}
}
// we may create more than one of these but we need to give them uniquie accessibility ids in the tab manager so we'll pass in a page number
webServer.addHandler(forMethod: "GET", path: "/scrollablePage.html", request: GCDWebServerRequest.self) { (request) -> GCDWebServerResponse? in
var pageData = self.getPageData("scrollablePage")
let page = Int((request.query?["page"] as! String))!
pageData = pageData.replacingOccurrences(of: "{page}", with: page.description)
return GCDWebServerDataResponse(html: pageData as String)
}
webServer.addHandler(forMethod: "GET", path: "/numberedPage.html", request: GCDWebServerRequest.self) { (request) -> GCDWebServerResponse? in
var pageData = self.getPageData("numberedPage")
let page = Int((request.query?["page"] as! String))!
pageData = pageData.replacingOccurrences(of: "{page}", with: page.description)
return GCDWebServerDataResponse(html: pageData as String)
}
webServer.addHandler(forMethod: "GET", path: "/readerContent.html", request: GCDWebServerRequest.self) { (request) -> GCDWebServerResponse? in
return GCDWebServerDataResponse(html: self.getPageData("readerContent"))
}
webServer.addHandler(forMethod: "GET", path: "/loginForm.html", request: GCDWebServerRequest.self) { _ in
return GCDWebServerDataResponse(html: self.getPageData("loginForm"))
}
webServer.addHandler(forMethod: "GET", path: "/navigationDelegate.html", request: GCDWebServerRequest.self) { _ in
return GCDWebServerDataResponse(html: self.getPageData("navigationDelegate"))
}
webServer.addHandler(forMethod: "GET", path: "/localhostLoad.html", request: GCDWebServerRequest.self) { _ in
return GCDWebServerDataResponse(html: self.getPageData("localhostLoad"))
}
webServer.addHandler(forMethod: "GET", path: "/auth.html", request: GCDWebServerRequest.self) { (request: GCDWebServerRequest?) in
// "user:pass", Base64-encoded.
let expectedAuth = "Basic dXNlcjpwYXNz"
let response: GCDWebServerDataResponse
if request?.headers["Authorization"] == expectedAuth && request?.query?["logout"] == nil {
response = GCDWebServerDataResponse(html: "<html><body>logged in</body></html>")!
} else {
// Request credentials if the user isn't logged in.
response = GCDWebServerDataResponse(html: "<html><body>auth fail</body></html>")!
response.statusCode = 401
response.setValue("Basic realm=\"test\"", forAdditionalHeader: "WWW-Authenticate")
}
return response
}
func htmlForImageBlockingTest(imageURL: String) -> String{
let html =
"""
<html><head><script>
function testImage(URL) {
var tester = new Image();
tester.onload = imageFound;
tester.onerror = imageNotFound;
tester.src = URL;
document.body.appendChild(tester);
}
function imageFound() {
alert('image loaded.');
}
function imageNotFound() {
alert('image not loaded.');
}
window.onload = function(e) {
// Disabling TP stats reporting using JS execution on the wkwebview happens async;
// setTimeout(1 sec) is plenty of delay to ensure the JS has executed.
setTimeout(() => { testImage('\(imageURL)'); }, 1000);
}
</script></head>
<body>TEST IMAGE BLOCKING</body></html>
"""
return html
}
// Add tracking protection check page
webServer.addHandler(forMethod: "GET", path: "/tracking-protection-test.html", request: GCDWebServerRequest.self) { (request: GCDWebServerRequest?) in
return GCDWebServerDataResponse(html: htmlForImageBlockingTest(imageURL: "http://ymail.com/favicon.ico"))
}
// Add image blocking test page
webServer.addHandler(forMethod: "GET", path: "/hide-images-test.html", request: GCDWebServerRequest.self) { (request: GCDWebServerRequest?) in
return GCDWebServerDataResponse(html: htmlForImageBlockingTest(imageURL: "https://www.mozilla.com/favicon.ico"))
}
if !webServer.start(withPort: 0, bonjourName: nil) {
XCTFail("Can't start the GCDWebServer")
}
// We use 127.0.0.1 explicitly here, rather than localhost, in order to avoid our
// history exclusion code (Bug 1188626).
let webRoot = "http://\(useLocalhostInsteadOfIP ? "localhost" : "127.0.0.1"):\(webServer.port)"
return webRoot
}
}
class SearchUtils {
static func navigateToSearchSettings(_ tester: KIFUITestActor) {
let engine = SearchUtils.getDefaultEngine().shortName
tester.tapView(withAccessibilityIdentifier: AccessibilityIdentifiers.Toolbar.settingsMenuButton)
tester.waitForAnimationsToFinish()
tester.tapView(withAccessibilityLabel: "Settings")
tester.waitForView(withAccessibilityLabel: "Settings")
tester.tapView(withAccessibilityLabel: "Search, \(engine)")
tester.waitForView(withAccessibilityIdentifier: "Search")
}
static func navigateFromSearchSettings(_ tester: KIFUITestActor) {
tester.tapView(withAccessibilityLabel: "Settings")
tester.tapView(withAccessibilityLabel: "Done")
}
// Given that we're at the Search Settings sheet, select the named search engine as the default.
// Afterwards, we're still at the Search Settings sheet.
static func selectDefaultSearchEngineName(_ tester: KIFUITestActor, engineName: String) {
tester.tapView(withAccessibilityLabel: "Default Search Engine", traits: UIAccessibilityTraits.button)
tester.waitForView(withAccessibilityLabel: "Default Search Engine")
tester.tapView(withAccessibilityLabel: engineName)
tester.waitForView(withAccessibilityLabel: "Search")
}
// Given that we're at the Search Settings sheet, return the default search engine's name.
static func getDefaultSearchEngineName(_ tester: KIFUITestActor) -> String {
let view = tester.waitForCellWithAccessibilityLabel("Default Search Engine")
return view.accessibilityValue!
}
static func getDefaultEngine() -> OpenSearchEngine! {
guard let userProfile = (UIApplication.shared.delegate as? AppDelegate)?.profile else {
XCTFail("Unable to get a reference to the user's profile")
return nil
}
return userProfile.searchEngines.defaultEngine
}
/*
static func youTubeSearchEngine() -> OpenSearchEngine {
return mockSearchEngine("YouTube", template: "https://m.youtube.com/#/results?q={searchTerms}&sm=", icon: "youtube")!
}
static func mockSearchEngine(_ name: String, template: String, icon: String) -> OpenSearchEngine? {
guard let imagePath = Bundle(for: self).path(forResource: icon, ofType: "ico"),
let imageData = Data(contentsOfFile: imagePath),
let image = UIImage(data: imageData)
else {
XCTFail("Unable to load search engine image named \(icon).ico")
return nil
}
return OpenSearchEngine(engineID: nil, shortName: name, image: image, searchTemplate: template, suggestTemplate: nil, isCustomEngine: true)
}
*/
static func addCustomSearchEngine(_ engine: OpenSearchEngine) {
guard let userProfile = (UIApplication.shared.delegate as? AppDelegate)?.profile else {
XCTFail("Unable to get a reference to the user's profile")
return
}
userProfile.searchEngines.addSearchEngine(engine)
}
static func removeCustomSearchEngine(_ engine: OpenSearchEngine) {
guard let userProfile = (UIApplication.shared.delegate as? AppDelegate)?.profile else {
XCTFail("Unable to get a reference to the user's profile")
return
}
userProfile.searchEngines.deleteCustomEngine(engine)
}
}
// From iOS 10, below methods no longer works
class DynamicFontUtils {
// Need to leave time for the notification to propagate
static func bumpDynamicFontSize(_ tester: KIFUITestActor) {
let value = UIContentSizeCategory.accessibilityExtraLarge
UIApplication.shared.setValue(value, forKey: "preferredContentSizeCategory")
tester.wait(forTimeInterval: 0.3)
}
static func lowerDynamicFontSize(_ tester: KIFUITestActor) {
let value = UIContentSizeCategory.extraSmall
UIApplication.shared.setValue(value, forKey: "preferredContentSizeCategory")
tester.wait(forTimeInterval: 0.3)
}
static func restoreDynamicFontSize(_ tester: KIFUITestActor) {
let value = UIContentSizeCategory.medium
UIApplication.shared.setValue(value, forKey: "preferredContentSizeCategory")
tester.wait(forTimeInterval: 0.3)
}
}
class HomePageUtils {
static func navigateToHomePageSettings(_ tester: KIFUITestActor) {
tester.waitForAnimationsToFinish()
tester.tapView(withAccessibilityIdentifier: AccessibilityIdentifiers.Toolbar.settingsMenuButton)
tester.tapView(withAccessibilityLabel: "Settings")
tester.tapView(withAccessibilityIdentifier: "Homepage")
}
static func homePageSetting(_ tester: KIFUITestActor) -> String? {
let view = tester.waitForView(withAccessibilityIdentifier: "HomeAsCustomURLTextField")
guard let textField = view as? UITextField else {
XCTFail("View is not a textField: view is \(String(describing: view))")
return nil
}
return textField.text
}
static func navigateFromHomePageSettings(_ tester: KIFUITestActor) {
tester.tapView(withAccessibilityLabel: "Settings")
tester.tapView(withAccessibilityLabel: "Done")
}
}
| mpl-2.0 | b98e42539521bc8dc1b90b089c57bfac | 42.082391 | 165 | 0.659967 | 5.458043 | false | true | false | false |
larrynatalicio/15DaysofAnimationsinSwift | Animation 03 - MapLocationAnimation/MapLocationAnimation/SonarAnnotationView.swift | 1 | 2788 | //
// Sonar.swift
// MapLocationAnimation
//
// Created by Larry Natalicio on 4/17/16.
// Copyright © 2016 Larry Natalicio. All rights reserved.
//
import UIKit
import MapKit
class SonarAnnotationView: MKAnnotationView {
// MARK: - Types
struct Constants {
struct ColorPalette {
static let green = UIColor(red:0.00, green:0.87, blue:0.71, alpha:1.0)
}
}
// MARK: - Initializers
override init(annotation: MKAnnotation?, reuseIdentifier: String?) {
super.init(annotation: annotation, reuseIdentifier: reuseIdentifier)
startAnimation()
}
// MARK: - NSCoding
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
// MARK: - Convenience
func sonar(_ beginTime: CFTimeInterval) {
// The circle in its smallest size.
let circlePath1 = UIBezierPath(arcCenter: self.center, radius: CGFloat(3), startAngle: CGFloat(0), endAngle:CGFloat(M_PI * 2), clockwise: true)
// The circle in its largest size.
let circlePath2 = UIBezierPath(arcCenter: self.center, radius: CGFloat(80), startAngle: CGFloat(0), endAngle:CGFloat(M_PI * 2), clockwise: true)
// Configure the layer.
let shapeLayer = CAShapeLayer()
shapeLayer.strokeColor = Constants.ColorPalette.green.cgColor
shapeLayer.fillColor = Constants.ColorPalette.green.cgColor
// This is the path that's visible when there'd be no animation.
shapeLayer.path = circlePath1.cgPath
self.layer.addSublayer(shapeLayer)
// Animate the path.
let pathAnimation = CABasicAnimation(keyPath: "path")
pathAnimation.fromValue = circlePath1.cgPath
pathAnimation.toValue = circlePath2.cgPath
// Animate the alpha value.
let alphaAnimation = CABasicAnimation(keyPath: "opacity")
alphaAnimation.fromValue = 0.8
alphaAnimation.toValue = 0
// We want both path and alpha animations to run together perfectly, so
// we put them into an animation group.
let animationGroup = CAAnimationGroup()
animationGroup.beginTime = beginTime
animationGroup.animations = [pathAnimation, alphaAnimation]
animationGroup.duration = 2.76
animationGroup.repeatCount = FLT_MAX
animationGroup.isRemovedOnCompletion = false
animationGroup.fillMode = kCAFillModeForwards
// Add the animation to the layer.
shapeLayer.add(animationGroup, forKey: "sonar")
}
func startAnimation() {
sonar(CACurrentMediaTime())
sonar(CACurrentMediaTime() + 0.92)
sonar(CACurrentMediaTime() + 1.84)
}
}
| mit | 8e4aac5cf1e83d0345660715a555fac7 | 32.987805 | 152 | 0.646215 | 5.01259 | false | false | false | false |
ninjaprox/Inkwell | Inkwell/Inkwell/Storage.swift | 1 | 3063 | //
// Storage.swift
// InkwellExample
//
// Copyright (c) 2017 Vinh Nguyen
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
//
protocol Storable {
var nameDictionaryURL: URL { get }
func URL(for font: Font) -> URL
}
final class Storage: Storable {
private let domain = "me.vinhis.Inkwell"
private let metadataFile = "googleFonts.json"
private let fontsFolder = "fonts"
private let nameDictionaryFile = "nameDictionary.plist"
/// The URL to Google Fonts metadata file.
lazy var metadataURL: URL = {
return self.domainURL.appendingPathComponent(self.metadataFile)
}()
/// The URL to fonts folder.
lazy var fontsURL: URL = {
return self.domainURL.appendingPathComponent(self.fontsFolder, isDirectory: true)
}()
/// The URL to name dictionary file.
lazy var nameDictionaryURL: URL = {
return self.domainURL.appendingPathComponent(self.nameDictionaryFile)
}()
lazy var domainURL: URL = {
let documentURL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)[0]
return documentURL
.appendingPathComponent(self.domain, isDirectory: true)
}()
/// Check if the file of specified font exists.
///
/// - Parameter font: The font needed to check its file.
/// - Returns: `true` if the file exists, otherwise `false`.
func fileExists(for font: Font) -> Bool {
let fontURL = fontsURL.appendingPathComponent("\(font.filename)")
return FileManager.default.fileExists(atPath: fontURL.path)
}
/// Check if the Google Fonts metadata file exists.
///
/// - Returns: `true` if the file exists, otherwised `false`.
func googleFontsMetadataExists() -> Bool {
return FileManager.default.fileExists(atPath: metadataURL.path)
}
func URL(for font: Font) -> URL {
return fontsURL.appendingPathComponent("\(font.filename)")
}
func removeGoogleFontsMetadata() {
try? FileManager.default.removeItem(at: metadataURL)
}
}
| mit | 62763f09327d646dba6752f95d20e160 | 35.464286 | 99 | 0.702253 | 4.471533 | false | false | false | false |
iOS-Connect/Connect | Connnect/NewChannelViewController.swift | 1 | 952 | //
// NewChannelViewController.swift
// Connnect
//
// Created by Stella Su on 11/19/16.
// Copyright © 2016 iOS-Connect. All rights reserved.
//
import UIKit
class NewChannelViewController: UIViewController {
@IBOutlet weak var newButton: UIButton!
@IBOutlet weak var newTextField: UITextField!
@IBAction func newChannel(sender: UIButton) {
guard let newChannelName = newTextField.text else { return }
guard newChannelName != ""
else { return }
AppDelegate.shared.client.subscribe(
toChannels: [newChannelName], withPresence: true)
var current = (UserDefaults.standard.array(forKey: channelKey) ?? [Any]()) as? [String]
if current == nil {
current = [String]()
}
current!.append(newChannelName)
UserDefaults.standard.set(current!, forKey: channelKey)
AppDelegate.shared.openMainViewController()
}
}
| mit | efd8be5ae052a71ddd9cadb5a64023af | 27.818182 | 95 | 0.643533 | 4.594203 | false | false | false | false |
liuxianghong/GreenBaby | 工程/greenbaby/greenbaby/ViewController/Forum/ForumThreadsDetailViewController.swift | 1 | 11384 | //
// ForumThreadsDetailViewController.swift
// greenbaby
//
// Created by 刘向宏 on 15/12/17.
// Copyright © 2015年 刘向宏. All rights reserved.
//
import UIKit
protocol ForumThreadsDetailVCDelegate : NSObjectProtocol{
func didPraiseOrCommplate(index : Int,dic : [String : AnyObject])
}
class ForumThreadsDetailViewController: UIViewController,UITextViewDelegate ,UIScrollViewDelegate,UITableViewDelegate,UITableViewDataSource{
var dic : [String : AnyObject]!
var goodNumber : Int = 0
var commentNumber : Int = 0
var dataDic : NSDictionary! = NSDictionary()
var commentsArray : NSArray! = NSArray()
var index = 0
weak var forumThreadsDetailVCDelegate : ForumThreadsDetailVCDelegate!
@IBOutlet weak var tableView : UITableView!
@IBOutlet weak var inputTextView : UIView!
@IBOutlet weak var inputField : UITextView!
@IBOutlet weak var constraint : NSLayoutConstraint!
@IBOutlet weak var inputConstraint : NSLayoutConstraint!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
self.tableView.estimatedRowHeight = 220.0;
self.tableView.rowHeight = UITableViewAutomaticDimension;
self.tableView.tableFooterView = UIView();
inputField.layer.borderWidth = 1/UIScreen.mainScreen().scale
inputField.layer.borderColor = UIColor.lightGrayColor().CGColor
inputField.layer.masksToBounds = true
inputField.layer.cornerRadius = 4;
inputField.text = " "
inputConstraint.constant = inputField.contentSize.height
inputField.text = ""
goodNumber = dic["praiseCount"] as! Int
commentNumber = dic["commentCount"] as! Int
//当键盘出来的时候通过通知来获取键盘的信息
//注册为键盘的监听着
let center = NSNotificationCenter.defaultCenter()
center.addObserver(self, selector: "keyNotification:", name: UIKeyboardWillChangeFrameNotification, object: nil)
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
self.tableView.reloadData()
self.loadData(true)
}
override func viewWillDisappear(animated: Bool) {
super.viewWillDisappear(animated)
let center = NSNotificationCenter.defaultCenter()
center.removeObserver(self, name: UIKeyboardWillChangeFrameNotification, object: nil)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func loadData(show : Bool){
var hud : MBProgressHUD! = nil
if show{
hud = MBProgressHUD.showHUDAddedTo(self.view, animated: true)
}
let userId = NSUserDefaults.standardUserDefaults().objectForKey("userId")
let dicP : Dictionary<String,AnyObject> = ["forumId" : self.dic["threadId"]!,"userId" : userId!,"showThread": true,"showComment": true]
ForumRequest.GetForumThreadsDetailWithParameters(dicP, success: { (object) -> Void in
print(object)
let dicd:NSDictionary = object as! NSDictionary
let state:Int = dicd["state"] as! Int
if state == 0{
self.dataDic = dicd["data"] as! NSDictionary
if self.dataDic["comments"] != nil{
self.commentsArray = self.dataDic["comments"] as! NSArray
self.tableView.reloadData()
}
if show{
hud.hide(true)
}
}else{
if show{
hud.mode = .Text
hud.detailsLabelText = dicd["description"] as! String
hud.hide(true, afterDelay: 1.5)
}
}
}) { (error : NSError!) -> Void in
if show{
hud.mode = .Text
hud.detailsLabelText = error.domain
hud.hide(true, afterDelay: 1.5)
}
}
}
@IBAction func goodClick(){
self.upDateGood(true)
}
@IBAction func upDateGood(bo : Bool){
let userId = NSUserDefaults.standardUserDefaults().objectForKey("userId")
let dicP : Dictionary<String,AnyObject> = ["forumId" : self.dic["threadId"]!,"userId" : userId!]
ForumRequest.UpdateForumPraiseWithParameters(dicP, success: { (object) -> Void in
print(object)
let dicd:NSDictionary = object as! NSDictionary
let state:Int = dicd["state"] as! Int
let data = dicd["data"] as! Int
if state == 0{
if data == 0{
self.goodNumber++
}
else{
self.goodNumber--
}
self.dic["praiseCount"] = self.goodNumber
self.tableView.reloadData()
self.forumThreadsDetailVCDelegate.didPraiseOrCommplate(self.index, dic: self.dic)
}else{
}
}) { (error : NSError!) -> Void in
}
}
@IBAction func sendClick(){
if self.inputField.text!.isEmpty{
return
}
self.inputField.resignFirstResponder()
let hud = MBProgressHUD.showHUDAddedTo(self.view, animated: true)
let userId = NSUserDefaults.standardUserDefaults().objectForKey("userId")
let dicP : Dictionary<String,AnyObject> = ["forumId" : self.dic["threadId"]!,"userId" : userId!,"submit": true,"location": UserInfo.CurrentUser().city!,"comment" : self.inputField.text!]
ForumRequest.UpdateForumCommentWithParameters(dicP, success: { (object) -> Void in
print(object)
let dicd:NSDictionary = object as! NSDictionary
let state:Int = dicd["state"] as! Int
if state == 0{
hud.mode = .Text
hud.detailsLabelText = "评论成功"
hud.hide(true, afterDelay: 1.5)
self.inputField.text = ""
self.inputConstraint.constant = self.inputField.contentSize.height
self.commentNumber++
self.dic["commentCount"] = self.commentNumber
self.forumThreadsDetailVCDelegate.didPraiseOrCommplate(self.index, dic: self.dic)
self.loadData(false)
}else{
hud.mode = .Text
hud.detailsLabelText = dicd["description"] as! String
hud.hide(true, afterDelay: 1.5)
}
}) { (error : NSError!) -> Void in
hud.mode = .Text
hud.detailsLabelText = error.domain
hud.hide(true, afterDelay: 1.5)
}
}
func keyNotification(notification : NSNotification){
let rect = (notification.userInfo!["UIKeyboardFrameEndUserInfoKey"] as! NSValue).CGRectValue()
let r1 = self.view.convertRect(rect, fromView: self.view.window)
dispatch_after(dispatch_time(0, 0), dispatch_get_main_queue()) { () -> Void in
let duration = notification.userInfo![UIKeyboardAnimationDurationUserInfoKey]?.doubleValue
self.constraint.constant = self.view.frame.size.height - r1.origin.y
self.view.setNeedsUpdateConstraints()
UIView.animateWithDuration(duration!, animations: { () -> Void in
self.view.layoutIfNeeded()
let curve = notification.userInfo![UIKeyboardAnimationCurveUserInfoKey]?.integerValue
UIView.setAnimationCurve(UIViewAnimationCurve(rawValue: curve!)!)
})
}
}
// MARK: - UITextFieldDelegate
func textView(textView: UITextView, shouldChangeTextInRange range: NSRange, replacementText text: String) -> Bool{
if inputConstraint.constant != textView.contentSize.height{
inputConstraint.constant = textView.contentSize.height
self.view.needsUpdateConstraints()
self.view.setNeedsLayout()
}
return true
}
// MARK: - UITextFieldDelegate
func scrollViewDidScroll(scrollView: UIScrollView) {
if !scrollView.isEqual(inputField){
self.inputField.resignFirstResponder()
}
}
// MARK: - Table view data source
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
// #warning Incomplete implementation, return the number of sections
return 2
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// #warning Incomplete implementation, return the number of rows
if section == 0{
return 1
}
return 1+commentsArray.count
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
if indexPath.section == 0{
let cell = tableView.dequeueReusableCellWithIdentifier("ForumThreadsDetailHeadTableViewCell", forIndexPath: indexPath) as! ForumThreadsDetailHeadTableViewCell
// Configure the cell...
cell.dataDic = dic as NSDictionary//dic
return cell
}
else if indexPath.section == 1 && indexPath.row == 0{
let cell = tableView.dequeueReusableCellWithIdentifier("ForumThreadsDetailCommentHeadTableViewCell", forIndexPath: indexPath) as! ForumThreadsDetailCommentHeadTableViewCell
// Configure the cell...
var commentCount = dataDic["commentCount"]
if commentCount == nil{
commentCount = dic["commentCount"]!
}
cell.numberLable.text = "评论(\(commentCount as! Int))"
return cell
}
else {
let cell = tableView.dequeueReusableCellWithIdentifier("ForumThreadsDetailCommentTableViewCell", forIndexPath: indexPath) as! ForumThreadsDetailCommentTableViewCell
// Configure the cell...
let commentsDic = commentsArray[indexPath.row-1] as! NSDictionary
cell.dataDic = commentsDic
return cell
}
}
func tableView(tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
return 8
}
func tableView(tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
let view = UIView()
view.backgroundColor = UIColor.groupTableViewBackgroundColor()
return view
}
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
tableView.deselectRowAtIndexPath(indexPath, animated: 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.
}
*/
}
| lgpl-3.0 | bb76ffdfbd68b962cb13192eae1555dc | 38.083045 | 194 | 0.602302 | 5.39914 | false | false | false | false |
zhuhaow/soca | soca/Rule/CountryRule.swift | 1 | 695 | //
// CountryRule.swift
// Soca
//
// Created by Zhuhao Wang on 2/23/15.
// Copyright (c) 2015 Zhuhao Wang. All rights reserved.
//
import Foundation
class CountryRule : Rule {
let countryCode: String
let match: Bool
let adapterFactory :AdapterFactory
init(countryCode: String, match: Bool, adapterFactory: AdapterFactory) {
self.countryCode = countryCode
self.match = match
self.adapterFactory = adapterFactory
super.init()
}
override func match(var request :ConnectMessage) -> AdapterFactory? {
if (request.country != countryCode) != match {
return adapterFactory
}
return nil
}
}
| mit | 60995debb37577e19f7b83171fa48228 | 22.965517 | 76 | 0.634532 | 4.455128 | false | false | false | false |
csnu17/My-Swift-learning | reference-value-types/ValueSemanticsPart1.playground/Contents.swift | 1 | 1401 | import Foundation
// Reference Types:
class Dog {
var wasFed = false
}
let dog = Dog()
let puppy = dog
puppy.wasFed = true
dog.wasFed // true
puppy.wasFed // true
// Value Types:
var a = 42
var b = a
b += 1
a // 42
b // 43
struct Cat {
var wasFed = false
}
var cat = Cat()
var kitty = cat
kitty.wasFed = true
cat.wasFed // false
kitty.wasFed // true
//
struct Point: CustomStringConvertible {
var x: Float
var y: Float
var description: String {
return "{x: \(x), y: \(y)}"
}
}
extension Point: Equatable { }
func ==(lhs: Point, rhs: Point) -> Bool {
return lhs.x == rhs.x && lhs.y == rhs.y
}
struct Shape {
var center: Point
}
let point1 = Point(x: 2, y: 3)
let point2 = Point(x: 2, y: 3)
point1 == point2
let initialPoint = Point(x: 0, y: 0)
let circle = Shape(center: initialPoint)
var square = Shape(center: initialPoint)
square.center == circle.center
square.center.x = 5 // {x: 5.0, y: 0.0}
circle.center // {x: 0.0, y: 0.0}
square.center == circle.center
//
class Account {
var balance = 0.0
}
class Person {
let account: Account
init(_ account: Account) {
self.account = account
}
}
let account = Account()
let person1 = Person(account)
let person2 = Person(account)
person2.account.balance += 100.0
person1.account.balance // 100
person2.account.balance // 100 | mit | 1eb00ca96ec66500b175b8368401eb57 | 14.577778 | 43 | 0.608851 | 2.987207 | false | false | false | false |
Alua-Kinzhebayeva/iOS-PDF-Reader | Sources/Classes/PDFPageView.swift | 1 | 8908 | //
// PDFPageView.swift
// PDFReader
//
// Created by ALUA KINZHEBAYEVA on 4/23/15.
// Copyright (c) 2015 AK. All rights reserved.
//
import UIKit
/// Delegate that is informed of important interaction events with the current `PDFPageView`
protocol PDFPageViewDelegate: class {
/// User has tapped on the page view
func handleSingleTap(_ pdfPageView: PDFPageView)
}
/// An interactable page of a document
internal final class PDFPageView: UIScrollView {
/// The TiledPDFView that is currently front most.
private var tiledPDFView: TiledView
/// Current scale of the scrolling view
private var scale: CGFloat
/// Number of zoom levels possible when double tapping
private let zoomLevels: CGFloat = 2
/// View which contains all of our content
private var contentView: UIView
/// A low resolution image of the PDF page that is displayed until the TiledPDFView renders its content.
private let backgroundImageView: UIImageView
/// Page reference being displayed
private let pdfPage: CGPDFPage
/// Current amount being zoomed
private var zoomAmount: CGFloat?
/// Delegate that is informed of important interaction events
private weak var pageViewDelegate: PDFPageViewDelegate?
/// Instantiates a scrollable page view
///
/// - parameter frame: frame of the view
/// - parameter document: document to be displayed
/// - parameter pageNumber: specific page number of the document to display
/// - parameter backgroundImage: background image of the page to display while rendering
/// - parameter pageViewDelegate: delegate notified of any important interaction events
///
/// - returns: a freshly initialized page view
init(frame: CGRect, document: PDFDocument, pageNumber: Int, backgroundImage: UIImage?, pageViewDelegate: PDFPageViewDelegate?) {
guard let pageRef = document.coreDocument.page(at: pageNumber + 1) else { fatalError() }
pdfPage = pageRef
self.pageViewDelegate = pageViewDelegate
let originalPageRect = pageRef.originalPageRect
scale = min(frame.width/originalPageRect.width, frame.height/originalPageRect.height)
let scaledPageRectSize = CGSize(width: originalPageRect.width * scale, height: originalPageRect.height * scale)
let scaledPageRect = CGRect(origin: originalPageRect.origin, size: scaledPageRectSize)
guard !scaledPageRect.isEmpty else { fatalError() }
// Create our content view based on the size of the PDF page
contentView = UIView(frame: scaledPageRect)
backgroundImageView = UIImageView(image: backgroundImage)
backgroundImageView.frame = contentView.bounds
// Create the TiledPDFView and scale it to fit the content view.
tiledPDFView = TiledView(frame: contentView.bounds, scale: scale, newPage: pdfPage)
super.init(frame: frame)
let targetRect = bounds.insetBy(dx: 0, dy: 0)
var zoomScale = zoomScaleThatFits(targetRect.size, source: bounds.size)
minimumZoomScale = zoomScale // Set the minimum and maximum zoom scales
maximumZoomScale = zoomScale * (zoomLevels * zoomLevels) // Max number of zoom levels
zoomAmount = (maximumZoomScale - minimumZoomScale) / zoomLevels
scale = 1
if zoomScale > minimumZoomScale {
zoomScale = minimumZoomScale
}
contentView.addSubview(backgroundImageView)
contentView.sendSubviewToBack(backgroundImageView)
contentView.addSubview(tiledPDFView)
addSubview(contentView)
let doubleTapOne = UITapGestureRecognizer(target: self, action:#selector(handleDoubleTap))
doubleTapOne.numberOfTapsRequired = 2
doubleTapOne.cancelsTouchesInView = false
addGestureRecognizer(doubleTapOne)
let singleTapOne = UITapGestureRecognizer(target: self, action:#selector(handleSingleTap))
singleTapOne.numberOfTapsRequired = 1
singleTapOne.cancelsTouchesInView = false
addGestureRecognizer(singleTapOne)
singleTapOne.require(toFail: doubleTapOne)
bouncesZoom = false
decelerationRate = UIScrollView.DecelerationRate.fast
delegate = self
autoresizesSubviews = true
autoresizingMask = [.flexibleHeight, .flexibleWidth]
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
// Use layoutSubviews to center the PDF page in the view.
override func layoutSubviews() {
super.layoutSubviews()
// Center the image as it becomes smaller than the size of the screen.
let contentViewSize = contentView.frame.size
// Center horizontally.
let xOffset: CGFloat
if contentViewSize.width < bounds.width {
xOffset = (bounds.width - contentViewSize.width) / 2
} else {
xOffset = 0
}
// Center vertically.
let yOffset: CGFloat
if contentViewSize.height < bounds.height {
yOffset = (bounds.height - contentViewSize.height) / 2
} else {
yOffset = 0
}
contentView.frame = CGRect(origin: CGPoint(x: xOffset, y: yOffset), size: contentViewSize)
// To handle the interaction between CATiledLayer and high resolution screens, set the
// tiling view's contentScaleFactor to 1.0. If this step were omitted, the content scale factor
// would be 2.0 on high resolution screens, which would cause the CATiledLayer to ask for tiles of the wrong scale.
tiledPDFView.contentScaleFactor = 1
}
/// Notifies the delegate that a single tap was performed
@objc func handleSingleTap(_ tapRecognizer: UITapGestureRecognizer) {
pageViewDelegate?.handleSingleTap(self)
}
/// Zooms in and out accordingly, based on the current zoom level
@objc func handleDoubleTap(_ tapRecognizer: UITapGestureRecognizer) {
var newScale = zoomScale * zoomLevels
if newScale >= maximumZoomScale {
newScale = minimumZoomScale
}
let zoomRect = zoomRectForScale(newScale, zoomPoint: tapRecognizer.location(in: tapRecognizer.view))
zoom(to: zoomRect, animated: true)
}
/// Calculates the zoom scale given a target size and a source size
///
/// - parameter target: size of the target rect
/// - parameter source: size of the source rect
///
/// - returns: the zoom scale of the target in relation to the source
private func zoomScaleThatFits(_ target: CGSize, source: CGSize) -> CGFloat {
let widthScale = target.width / source.width
let heightScale = target.height / source.height
return (widthScale < heightScale) ? widthScale : heightScale
}
/// Calculates the new zoom rect given a desired scale and a point to zoom on
///
/// - parameter scale: desired scale to zoom to
/// - parameter zoomPoint: the reference point to zoom on
///
/// - returns: a new zoom rect
private func zoomRectForScale(_ scale: CGFloat, zoomPoint: CGPoint) -> CGRect {
// Normalize current content size back to content scale of 1.0f
let updatedContentSize = CGSize(width: contentSize.width/zoomScale, height: contentSize.height/zoomScale)
let translatedZoomPoint = CGPoint(x: (zoomPoint.x / bounds.width) * updatedContentSize.width,
y: (zoomPoint.y / bounds.height) * updatedContentSize.height)
// derive the size of the region to zoom to
let zoomSize = CGSize(width: bounds.width / scale, height: bounds.height / scale)
// offset the zoom rect so the actual zoom point is in the middle of the rectangle
return CGRect(x: translatedZoomPoint.x - zoomSize.width / 2.0,
y: translatedZoomPoint.y - zoomSize.height / 2.0,
width: zoomSize.width,
height: zoomSize.height)
}
}
extension PDFPageView: UIScrollViewDelegate {
/// A UIScrollView delegate callback, called when the user starts zooming.
/// Return the content view
func viewForZooming(in scrollView: UIScrollView) -> UIView? {
return contentView
}
/// A UIScrollView delegate callback, called when the user stops zooming.
/// When the user stops zooming, create a new Tiled
/// PDFView based on the new zoom level and draw it on top of the old TiledPDFView.
func scrollViewDidEndZooming(_ scrollView: UIScrollView, with view: UIView?, atScale scale: CGFloat) {
self.scale = scale
}
}
| mit | 78973b303b24dce80c4f5d5988476486 | 40.821596 | 132 | 0.664122 | 5.471744 | false | false | false | false |
overtake/TelegramSwift | Telegram-Mac/VideoEditorThumbs.swift | 1 | 4281 | //
// VideoEditorThumbs.swift
// Telegram
//
// Created by Mikhail Filimonov on 16/07/2020.
// Copyright © 2020 Telegram. All rights reserved.
//
import Cocoa
import SwiftSignalKit
import TGUIKit
import FastBlur
func generateVideoScrubberThumbs(for asset: AVComposition, composition: AVVideoComposition?, size: NSSize, count: Int, gradually: Bool, blur: Bool) -> Signal<([CGImage], Bool), NoError> {
return Signal { subscriber in
var cancelled = false
let videoDuration = asset.duration
let generator = AVAssetImageGenerator(asset: asset)
let size = size.multipliedByScreenScale()
var frameForTimes = [NSValue]()
let sampleCounts = count
let totalTimeLength = Int(videoDuration.seconds * Double(videoDuration.timescale))
let step = totalTimeLength / sampleCounts
for i in 0 ..< sampleCounts {
let cmTime = CMTimeMake(value: Int64(i * step), timescale: Int32(videoDuration.timescale))
frameForTimes.append(NSValue(time: cmTime))
}
generator.appliesPreferredTrackTransform = true
generator.maximumSize = size
generator.requestedTimeToleranceBefore = CMTime.zero
generator.requestedTimeToleranceAfter = CMTime.zero
generator.videoComposition = composition
var images:[(image: CGImage, fake: Bool)] = []
var blurred: CGImage?
generator.generateCGImagesAsynchronously(forTimes: frameForTimes, completionHandler: { (requestedTime, image, actualTime, result, error) in
if let image = image, result == .succeeded {
images.removeAll(where: { $0.fake })
images.append((image: image, fake: false))
if images.count < count, let image = images.first?.image, blur {
if blurred == nil {
let thumbnailContext = DrawingContext(size: size, scale: 1.0)
thumbnailContext.withFlippedContext { c in
c.interpolationQuality = .none
c.draw(image, in: CGRect(origin: CGPoint(), size: size))
}
telegramFastBlurMore(Int32(size.width), Int32(size.height), Int32(thumbnailContext.bytesPerRow), thumbnailContext.bytes)
blurred = thumbnailContext.generateImage()
}
if let image = blurred {
while images.count < count {
images.append((image: image, fake: true))
}
}
}
}
if gradually {
subscriber.putNext((images.map { $0.image }, false))
}
if images.filter({ !$0.fake }).count == frameForTimes.count, !cancelled {
subscriber.putNext((images.map { $0.image }, true))
subscriber.putCompletion()
}
})
return ActionDisposable { [weak generator] in
Queue.concurrentBackgroundQueue().async {
generator?.cancelAllCGImageGeneration()
cancelled = true
}
}
} |> runOn(.concurrentBackgroundQueue())
}
func generateVideoAvatarPreview(for asset: AVComposition, composition: AVVideoComposition?, highSize: NSSize, lowSize: NSSize, at seconds: Double) -> Signal<(CGImage?, CGImage?), NoError> {
return Signal { subscriber in
let imageGenerator = AVAssetImageGenerator(asset: asset)
let highSize = highSize.multipliedByScreenScale()
imageGenerator.maximumSize = highSize
imageGenerator.appliesPreferredTrackTransform = true
imageGenerator.requestedTimeToleranceBefore = .zero
imageGenerator.requestedTimeToleranceAfter = .zero
imageGenerator.videoComposition = composition
let highRes = try? imageGenerator.copyCGImage(at: CMTimeMakeWithSeconds(seconds, preferredTimescale: 1000), actualTime: nil)
subscriber.putNext((highRes, highRes))
subscriber.putCompletion()
return ActionDisposable {
}
} |> runOn(.concurrentDefaultQueue())
}
| gpl-2.0 | 5c8516182b32bff3841c12ac4dd9dd2b | 41.376238 | 189 | 0.600935 | 5.473146 | false | false | false | false |
citysite102/kapi-kaffeine | kapi-kaffeine/kapi-kaffeine/KPInputRecommendCell.swift | 1 | 2075 | //
// KPInputRecommendCell.swift
// kapi-kaffeine
//
// Created by YU CHONKAO on 2017/7/15.
// Copyright © 2017年 kapi-kaffeine. All rights reserved.
//
import UIKit
class KPInputRecommendCell: UITableViewCell {
lazy var titleLabel: UILabel = {
let label = UILabel()
label.font = UIFont.systemFont(ofSize: 16.0)
label.textColor = KPColorPalette.KPTextColor.grayColor_level3
label.text = "老木咖啡"
label.lineBreakMode = .byTruncatingTail
return label
}()
lazy var addressLabel: UILabel = {
let label = UILabel()
label.font = UIFont.systemFont(ofSize: 16.0)
label.textColor = KPColorPalette.KPTextColor.grayColor_level4
label.text = "台北市大安區忠孝東路20號102樓"
label.lineBreakMode = .byTruncatingTail
return label
}()
override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
addSubview(titleLabel)
titleLabel.addConstraints(fromStringArray: ["H:|-16-[$self(<=180)]"])
titleLabel.addConstraintForCenterAligningToSuperview(in: .vertical)
addSubview(addressLabel)
addressLabel.addConstraints(fromStringArray: ["H:[$self(<=140)]-16-|"])
addressLabel.addConstraintForCenterAligningToSuperview(in: .vertical)
let separator = UIView()
separator.backgroundColor = KPColorPalette.KPBackgroundColor.grayColor_level6
addSubview(separator)
separator.addConstraints(fromStringArray: ["V:[$self(1)]|",
"H:|-16-[$self]|"])
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
}
}
| mit | 60e1a9158d9065f8e5e5b03c1ecb7781 | 31.380952 | 85 | 0.633333 | 4.868735 | false | false | false | false |
CodexCasts/13-Titanium-and-Today-Extensions-with-Ti.Wormhole | TiExtensions/modules/iphone/ti.wormhole/1.0.2/example/xcode/WormholeExample/TodaySwift/TodayViewController.swift | 1 | 2398 | /**
* Copyright (c) 2015 by Benjamin Bahrenburg. All Rights Reserved.
* Licensed under the terms of the MIT License
* Please see the LICENSE included with this distribution for details.
*
*/
import UIKit
import NotificationCenter
import Foundation
let sampleGroupIdentifier = "group.appworkbench.TodayExtenionWormhole";
let sampleWormDirectory = "tiwormhole";
let sampleEventName = "wormEvent";
let sampleFieldName = "displayNumber";
class TodayViewController: UIViewController, NCWidgetProviding {
var displayCount = 0;
let wormhole = MMWormholeClient(applicationGroupIdentifier: sampleGroupIdentifier,
optionalDirectory: sampleWormDirectory)
@IBOutlet weak var countLabel: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
self.preferredContentSize = CGSizeMake(320, 50);
addMessageListener(sampleEventName)
initDisplayCounter(sampleEventName)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
func widgetPerformUpdateWithCompletionHandler(completionHandler: ((NCUpdateResult) -> Void)!) {
completionHandler(NCUpdateResult.NewData)
}
func addMessageListener(eventName : String){
self.wormhole.listenForMessageWithIdentifier(eventName, listener:{(messageObject:AnyObject!) -> Void in
if((messageObject[sampleFieldName]) != nil){
self.displayCount = messageObject[sampleFieldName] as! Int!
self.displayCounter()
}
})
}
func initDisplayCounter(eventName:String){
let savedMessage: AnyObject? = wormhole.messageWithIdentifier(eventName);
if((savedMessage?[sampleFieldName]) != nil){
self.displayCount = savedMessage?[sampleFieldName] as! Int!
self.displayCounter()
}
}
func updateCounter(){
wormhole.passMessageObject([sampleFieldName : displayCount], identifier: sampleEventName)
displayCounter()
}
func displayCounter() {
self.countLabel.text = "Count:" + String(displayCount)
}
@IBAction func addCountHandler(sender: UIButton) {
displayCount++;
updateCounter()
}
@IBAction func subtractCountHandler(sender: UIButton) {
displayCount--;
updateCounter()
}
}
| apache-2.0 | b1cea02521e5efa5ac03c1d35efee465 | 30.552632 | 111 | 0.67181 | 5.437642 | false | false | false | false |
Jnosh/swift | stdlib/public/core/ArrayBuffer.swift | 17 | 18255 | //===--- ArrayBuffer.swift - Dynamic storage for Swift Array --------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
//
// This is the class that implements the storage and object management for
// Swift Array.
//
//===----------------------------------------------------------------------===//
#if _runtime(_ObjC)
import SwiftShims
internal typealias _ArrayBridgeStorage
= _BridgeStorage<_ContiguousArrayStorageBase, _NSArrayCore>
@_versioned
@_fixed_layout
internal struct _ArrayBuffer<Element> : _ArrayBufferProtocol {
/// Create an empty buffer.
@_inlineable
@_versioned
internal init() {
_storage = _ArrayBridgeStorage(native: _emptyArrayStorage)
}
@_inlineable
@_versioned // FIXME(abi): Used from tests
internal init(nsArray: _NSArrayCore) {
_sanityCheck(_isClassOrObjCExistential(Element.self))
_storage = _ArrayBridgeStorage(objC: nsArray)
}
/// Returns an `_ArrayBuffer<U>` containing the same elements.
///
/// - Precondition: The elements actually have dynamic type `U`, and `U`
/// is a class or `@objc` existential.
@_inlineable
@_versioned
internal func cast<U>(toBufferOf _: U.Type) -> _ArrayBuffer<U> {
_sanityCheck(_isClassOrObjCExistential(Element.self))
_sanityCheck(_isClassOrObjCExistential(U.self))
return _ArrayBuffer<U>(storage: _storage)
}
/// The spare bits that are set when a native array needs deferred
/// element type checking.
@_inlineable
@_versioned
internal var deferredTypeCheckMask: Int { return 1 }
/// Returns an `_ArrayBuffer<U>` containing the same elements,
/// deferring checking each element's `U`-ness until it is accessed.
///
/// - Precondition: `U` is a class or `@objc` existential derived from
/// `Element`.
@_inlineable
@_versioned
internal func downcast<U>(
toBufferWithDeferredTypeCheckOf _: U.Type
) -> _ArrayBuffer<U> {
_sanityCheck(_isClassOrObjCExistential(Element.self))
_sanityCheck(_isClassOrObjCExistential(U.self))
// FIXME: can't check that U is derived from Element pending
// <rdar://problem/20028320> generic metatype casting doesn't work
// _sanityCheck(U.self is Element.Type)
return _ArrayBuffer<U>(
storage: _ArrayBridgeStorage(
native: _native._storage, bits: deferredTypeCheckMask))
}
@_inlineable
@_versioned
internal var needsElementTypeCheck: Bool {
// NSArray's need an element typecheck when the element type isn't AnyObject
return !_isNativeTypeChecked && !(AnyObject.self is Element.Type)
}
//===--- private --------------------------------------------------------===//
@_inlineable
@_versioned
internal init(storage: _ArrayBridgeStorage) {
_storage = storage
}
@_versioned
internal var _storage: _ArrayBridgeStorage
}
extension _ArrayBuffer {
/// Adopt the storage of `source`.
@_inlineable
@_versioned
internal init(_buffer source: NativeBuffer, shiftedToStartIndex: Int) {
_sanityCheck(shiftedToStartIndex == 0, "shiftedToStartIndex must be 0")
_storage = _ArrayBridgeStorage(native: source._storage)
}
/// `true`, if the array is native and does not need a deferred type check.
@_inlineable
@_versioned
internal var arrayPropertyIsNativeTypeChecked: Bool {
return _isNativeTypeChecked
}
/// Returns `true` iff this buffer's storage is uniquely-referenced.
@_inlineable
@_versioned
internal mutating func isUniquelyReferenced() -> Bool {
if !_isClassOrObjCExistential(Element.self) {
return _storage.isUniquelyReferenced_native_noSpareBits()
}
return _storage.isUniquelyReferencedNative() && _isNative
}
/// Returns `true` iff this buffer's storage is either
/// uniquely-referenced or pinned.
@_inlineable
@_versioned
internal mutating func isUniquelyReferencedOrPinned() -> Bool {
if !_isClassOrObjCExistential(Element.self) {
return _storage.isUniquelyReferencedOrPinned_native_noSpareBits()
}
return _storage.isUniquelyReferencedOrPinnedNative() && _isNative
}
/// Convert to an NSArray.
///
/// O(1) if the element type is bridged verbatim, O(*n*) otherwise.
@_inlineable
@_versioned // FIXME(abi): Used from tests
internal func _asCocoaArray() -> _NSArrayCore {
return _fastPath(_isNative) ? _native._asCocoaArray() : _nonNative
}
/// If this buffer is backed by a uniquely-referenced mutable
/// `_ContiguousArrayBuffer` that can be grown in-place to allow the self
/// buffer store minimumCapacity elements, returns that buffer.
/// Otherwise, returns `nil`.
@_inlineable
@_versioned
internal mutating func requestUniqueMutableBackingBuffer(minimumCapacity: Int)
-> NativeBuffer? {
if _fastPath(isUniquelyReferenced()) {
let b = _native
if _fastPath(b.capacity >= minimumCapacity) {
return b
}
}
return nil
}
@_inlineable
@_versioned
internal mutating func isMutableAndUniquelyReferenced() -> Bool {
return isUniquelyReferenced()
}
@_inlineable
@_versioned
internal mutating func isMutableAndUniquelyReferencedOrPinned() -> Bool {
return isUniquelyReferencedOrPinned()
}
/// If this buffer is backed by a `_ContiguousArrayBuffer`
/// containing the same number of elements as `self`, return it.
/// Otherwise, return `nil`.
@_inlineable
@_versioned
internal func requestNativeBuffer() -> NativeBuffer? {
if !_isClassOrObjCExistential(Element.self) {
return _native
}
return _fastPath(_storage.isNative) ? _native : nil
}
// We have two versions of type check: one that takes a range and the other
// checks one element. The reason for this is that the ARC optimizer does not
// handle loops atm. and so can get blocked by the presence of a loop (over
// the range). This loop is not necessary for a single element access.
@_inlineable
@_versioned
@inline(never)
internal func _typeCheckSlowPath(_ index: Int) {
if _fastPath(_isNative) {
let element: AnyObject = cast(toBufferOf: AnyObject.self)._native[index]
_precondition(
element is Element,
"Down-casted Array element failed to match the target type")
}
else {
let ns = _nonNative
_precondition(
ns.objectAt(index) is Element,
"NSArray element failed to match the Swift Array Element type")
}
}
@_inlineable
@_versioned
internal func _typeCheck(_ subRange: Range<Int>) {
if !_isClassOrObjCExistential(Element.self) {
return
}
if _slowPath(needsElementTypeCheck) {
// Could be sped up, e.g. by using
// enumerateObjectsAtIndexes:options:usingBlock: in the
// non-native case.
for i in CountableRange(subRange) {
_typeCheckSlowPath(i)
}
}
}
/// Copy the elements in `bounds` from this buffer into uninitialized
/// memory starting at `target`. Return a pointer "past the end" of the
/// just-initialized memory.
@_inlineable
@_versioned
@discardableResult
internal func _copyContents(
subRange bounds: Range<Int>,
initializing target: UnsafeMutablePointer<Element>
) -> UnsafeMutablePointer<Element> {
_typeCheck(bounds)
if _fastPath(_isNative) {
return _native._copyContents(subRange: bounds, initializing: target)
}
let nonNative = _nonNative
let nsSubRange = SwiftShims._SwiftNSRange(
location: bounds.lowerBound,
length: bounds.upperBound - bounds.lowerBound)
let buffer = UnsafeMutableRawPointer(target).assumingMemoryBound(
to: AnyObject.self)
// Copies the references out of the NSArray without retaining them
nonNative.getObjects(buffer, range: nsSubRange)
// Make another pass to retain the copied objects
var result = target
for _ in CountableRange(bounds) {
result.initialize(to: result.pointee)
result += 1
}
return result
}
/// Returns a `_SliceBuffer` containing the given sub-range of elements in
/// `bounds` from this buffer.
@_inlineable
@_versioned
internal subscript(bounds: Range<Int>) -> _SliceBuffer<Element> {
get {
_typeCheck(bounds)
if _fastPath(_isNative) {
return _native[bounds]
}
let boundsCount = bounds.count
if boundsCount == 0 {
return _SliceBuffer(
_buffer: _ContiguousArrayBuffer<Element>(),
shiftedToStartIndex: bounds.lowerBound)
}
// Look for contiguous storage in the NSArray
let nonNative = self._nonNative
let cocoa = _CocoaArrayWrapper(nonNative)
let cocoaStorageBaseAddress =
cocoa.contiguousStorage(Range(self.indices))
if let cocoaStorageBaseAddress = cocoaStorageBaseAddress {
let basePtr = UnsafeMutableRawPointer(cocoaStorageBaseAddress)
.assumingMemoryBound(to: Element.self)
return _SliceBuffer(
owner: nonNative,
subscriptBaseAddress: basePtr,
indices: bounds,
hasNativeBuffer: false)
}
// No contiguous storage found; we must allocate
let result = _ContiguousArrayBuffer<Element>(
_uninitializedCount: boundsCount, minimumCapacity: 0)
// Tell Cocoa to copy the objects into our storage
cocoa.buffer.getObjects(
UnsafeMutableRawPointer(result.firstElementAddress)
.assumingMemoryBound(to: AnyObject.self),
range: _SwiftNSRange(location: bounds.lowerBound, length: boundsCount))
return _SliceBuffer(
_buffer: result, shiftedToStartIndex: bounds.lowerBound)
}
set {
fatalError("not implemented")
}
}
/// A pointer to the first element.
///
/// - Precondition: The elements are known to be stored contiguously.
@_inlineable
@_versioned
internal var firstElementAddress: UnsafeMutablePointer<Element> {
_sanityCheck(_isNative, "must be a native buffer")
return _native.firstElementAddress
}
@_inlineable
@_versioned
internal var firstElementAddressIfContiguous: UnsafeMutablePointer<Element>? {
return _fastPath(_isNative) ? firstElementAddress : nil
}
/// The number of elements the buffer stores.
@_inlineable
@_versioned
internal var count: Int {
@inline(__always)
get {
return _fastPath(_isNative) ? _native.count : _nonNative.count
}
set {
_sanityCheck(_isNative, "attempting to update count of Cocoa array")
_native.count = newValue
}
}
/// Traps if an inout violation is detected or if the buffer is
/// native and the subscript is out of range.
///
/// wasNative == _isNative in the absence of inout violations.
/// Because the optimizer can hoist the original check it might have
/// been invalidated by illegal user code.
@_inlineable
@_versioned
internal func _checkInoutAndNativeBounds(_ index: Int, wasNative: Bool) {
_precondition(
_isNative == wasNative,
"inout rules were violated: the array was overwritten")
if _fastPath(wasNative) {
_native._checkValidSubscript(index)
}
}
// TODO: gyb this
/// Traps if an inout violation is detected or if the buffer is
/// native and typechecked and the subscript is out of range.
///
/// wasNativeTypeChecked == _isNativeTypeChecked in the absence of
/// inout violations. Because the optimizer can hoist the original
/// check it might have been invalidated by illegal user code.
@_inlineable
@_versioned
internal func _checkInoutAndNativeTypeCheckedBounds(
_ index: Int, wasNativeTypeChecked: Bool
) {
_precondition(
_isNativeTypeChecked == wasNativeTypeChecked,
"inout rules were violated: the array was overwritten")
if _fastPath(wasNativeTypeChecked) {
_native._checkValidSubscript(index)
}
}
/// The number of elements the buffer can store without reallocation.
@_inlineable
@_versioned
internal var capacity: Int {
return _fastPath(_isNative) ? _native.capacity : _nonNative.count
}
@_inlineable
@_versioned
@inline(__always)
internal func getElement(_ i: Int, wasNativeTypeChecked: Bool) -> Element {
if _fastPath(wasNativeTypeChecked) {
return _nativeTypeChecked[i]
}
return unsafeBitCast(_getElementSlowPath(i), to: Element.self)
}
@_inlineable
@_versioned
@inline(never)
internal func _getElementSlowPath(_ i: Int) -> AnyObject {
_sanityCheck(
_isClassOrObjCExistential(Element.self),
"Only single reference elements can be indexed here.")
let element: AnyObject
if _isNative {
// _checkInoutAndNativeTypeCheckedBounds does no subscript
// checking for the native un-typechecked case. Therefore we
// have to do it here.
_native._checkValidSubscript(i)
element = cast(toBufferOf: AnyObject.self)._native[i]
_precondition(
element is Element,
"Down-casted Array element failed to match the target type")
} else {
// ObjC arrays do their own subscript checking.
element = _nonNative.objectAt(i)
_precondition(
element is Element,
"NSArray element failed to match the Swift Array Element type")
}
return element
}
/// Get or set the value of the ith element.
@_inlineable
@_versioned
internal subscript(i: Int) -> Element {
get {
return getElement(i, wasNativeTypeChecked: _isNativeTypeChecked)
}
nonmutating set {
if _fastPath(_isNative) {
_native[i] = newValue
}
else {
var refCopy = self
refCopy.replaceSubrange(
i..<(i + 1),
with: 1,
elementsOf: CollectionOfOne(newValue))
}
}
}
/// Call `body(p)`, where `p` is an `UnsafeBufferPointer` over the
/// underlying contiguous storage. If no such storage exists, it is
/// created on-demand.
@_inlineable
@_versioned
internal func withUnsafeBufferPointer<R>(
_ body: (UnsafeBufferPointer<Element>) throws -> R
) rethrows -> R {
if _fastPath(_isNative) {
defer { _fixLifetime(self) }
return try body(
UnsafeBufferPointer(start: firstElementAddress, count: count))
}
return try ContiguousArray(self).withUnsafeBufferPointer(body)
}
/// Call `body(p)`, where `p` is an `UnsafeMutableBufferPointer`
/// over the underlying contiguous storage.
///
/// - Precondition: Such contiguous storage exists or the buffer is empty.
@_inlineable
@_versioned
internal mutating func withUnsafeMutableBufferPointer<R>(
_ body: (UnsafeMutableBufferPointer<Element>) throws -> R
) rethrows -> R {
_sanityCheck(
_isNative || count == 0,
"Array is bridging an opaque NSArray; can't get a pointer to the elements"
)
defer { _fixLifetime(self) }
return try body(UnsafeMutableBufferPointer(
start: firstElementAddressIfContiguous, count: count))
}
/// An object that keeps the elements stored in this buffer alive.
@_inlineable
@_versioned
internal var owner: AnyObject {
return _fastPath(_isNative) ? _native._storage : _nonNative
}
/// An object that keeps the elements stored in this buffer alive.
///
/// - Precondition: This buffer is backed by a `_ContiguousArrayBuffer`.
@_inlineable
@_versioned
internal var nativeOwner: AnyObject {
_sanityCheck(_isNative, "Expect a native array")
return _native._storage
}
/// A value that identifies the storage used by the buffer. Two
/// buffers address the same elements when they have the same
/// identity and count.
@_inlineable
@_versioned
internal var identity: UnsafeRawPointer {
if _isNative {
return _native.identity
}
else {
return UnsafeRawPointer(Unmanaged.passUnretained(_nonNative).toOpaque())
}
}
//===--- Collection conformance -------------------------------------===//
/// The position of the first element in a non-empty collection.
///
/// In an empty collection, `startIndex == endIndex`.
@_inlineable
@_versioned
internal var startIndex: Int {
return 0
}
/// The collection's "past the end" position.
///
/// `endIndex` is not a valid argument to `subscript`, and is always
/// reachable from `startIndex` by zero or more applications of
/// `index(after:)`.
@_inlineable
@_versioned
internal var endIndex: Int {
return count
}
internal typealias Indices = CountableRange<Int>
//===--- private --------------------------------------------------------===//
internal typealias Storage = _ContiguousArrayStorage<Element>
internal typealias NativeBuffer = _ContiguousArrayBuffer<Element>
@_inlineable
@_versioned
internal var _isNative: Bool {
if !_isClassOrObjCExistential(Element.self) {
return true
} else {
return _storage.isNative
}
}
/// `true`, if the array is native and does not need a deferred type check.
@_inlineable
@_versioned
internal var _isNativeTypeChecked: Bool {
if !_isClassOrObjCExistential(Element.self) {
return true
} else {
return _storage.isNativeWithClearedSpareBits(deferredTypeCheckMask)
}
}
/// Our native representation.
///
/// - Precondition: `_isNative`.
@_inlineable
@_versioned
internal var _native: NativeBuffer {
return NativeBuffer(
_isClassOrObjCExistential(Element.self)
? _storage.nativeInstance : _storage.nativeInstance_noSpareBits)
}
/// Fast access to the native representation.
///
/// - Precondition: `_isNativeTypeChecked`.
@_inlineable
@_versioned
internal var _nativeTypeChecked: NativeBuffer {
return NativeBuffer(_storage.nativeInstance_noSpareBits)
}
@_inlineable
@_versioned
internal var _nonNative: _NSArrayCore {
@inline(__always)
get {
_sanityCheck(_isClassOrObjCExistential(Element.self))
return _storage.objCInstance
}
}
}
#endif
| apache-2.0 | 1de40a3ee673a183e184b10cee90816d | 29.680672 | 80 | 0.668474 | 4.874499 | false | false | false | false |
yanif/circator | MetabolicCompass/NutritionManager/NutritionManagerUIView.swift | 1 | 7370 | //
// UIView.swift
// MetabolicCompassNutritionManager
//
// Created by Edwin L. Whitman on 7/30/16.
// Copyright © 2016 Edwin L. Whitman. All rights reserved.
//
import UIKit
class UIPresentSubview : UIView {
var wasCanceled : (Void->Void)?
convenience init(backgroundTint tint : UIBlurEffectStyle) {
self.init(frame: CGRect.zero)
self.configureView(backgroundTint: tint)
}
func configureView(backgroundTint tint : UIBlurEffectStyle) {
let backgroundView = UIVisualEffectView(effect: UIBlurEffect(style: tint))
backgroundView.translatesAutoresizingMaskIntoConstraints = false
self.addSubview(backgroundView)
let backgroundViewConstraints : [NSLayoutConstraint] = [
backgroundView.leftAnchor.constraintEqualToAnchor(self.leftAnchor),
backgroundView.rightAnchor.constraintEqualToAnchor(self.rightAnchor),
backgroundView.topAnchor.constraintEqualToAnchor(self.topAnchor),
backgroundView.bottomAnchor.constraintEqualToAnchor(self.bottomAnchor)
]
self.addConstraints(backgroundViewConstraints)
}
static func presentSubview(subviewToPresent : UIView, backgroundTint tint : UIBlurEffectStyle = .Light, canceled : (Void->Void)? = nil) {
if let viewController = UIApplication.sharedApplication().keyWindow?.rootViewController {
presentSubviewOnView(subviewToPresent, presentingView: viewController.view, backgroundTint: tint, canceled: {
canceled?()
})
}
}
static func presentSubviewOnView(subviewToPresent : UIView, presentingView : UIView, backgroundTint tint : UIBlurEffectStyle = .Light, canceled : (Void->Void)? = nil) {
for view in presentingView.subviews {
if view is UIPresentSubview {
return
}
}
let view = UIPresentSubview(backgroundTint: tint)
view.wasCanceled = canceled
view.alpha = 0
view.translatesAutoresizingMaskIntoConstraints = false
presentingView.addSubview(view)
let preanimationViewConstraints : [NSLayoutConstraint] = [
view.topAnchor.constraintEqualToAnchor(presentingView.topAnchor),
view.bottomAnchor.constraintEqualToAnchor(presentingView.bottomAnchor),
view.leftAnchor.constraintEqualToAnchor(presentingView.leftAnchor),
view.rightAnchor.constraintEqualToAnchor(presentingView.rightAnchor)
]
presentingView.addConstraints(preanimationViewConstraints)
let cancelButton : UIButton = {
let button = UIButton()
button.backgroundColor = UIColor.clearColor()
button.translatesAutoresizingMaskIntoConstraints = false
button.clipsToBounds = true
button.layer.borderColor = tint == .Light ? UIColor.whiteColor().CGColor : UIColor.blackColor().CGColor
button.layer.borderWidth = 3.525
button.addTarget(view.self, action: #selector(UIPresentSubview.cancel(_:)), forControlEvents: .TouchUpInside)
button.setTitle("+", forState: .Normal)
button.titleLabel?.font = UIFont.systemFontOfSize(72, weight: UIFontWeightThin)
button.contentEdgeInsets = UIEdgeInsetsMake(-12, 0, 0, 0)
button.transform = CGAffineTransformMakeRotation(CGFloat(M_PI_4))
button.setTitleColor(tint == .Light ? UIColor.whiteColor() : UIColor.blackColor(), forState: .Normal)
return button
}()
cancelButton.titleLabel?.textColor = tint == .Light ? UIColor.whiteColor() : UIColor.blackColor()
view.addSubview(cancelButton)
let cancelButtonConstraints : [NSLayoutConstraint] = [
cancelButton.bottomAnchor.constraintEqualToAnchor(view.bottomAnchor, constant: -15),
cancelButton.centerXAnchor.constraintEqualToAnchor(view.centerXAnchor),
cancelButton.heightAnchor.constraintEqualToConstant(60),
cancelButton.widthAnchor.constraintEqualToConstant(60)
]
view.addConstraints(cancelButtonConstraints)
subviewToPresent.translatesAutoresizingMaskIntoConstraints = false
view.addSubview(subviewToPresent)
let subviewToPresentConstraints : [NSLayoutConstraint] = [
subviewToPresent.topAnchor.constraintEqualToAnchor(view.topAnchor, constant: 15),
subviewToPresent.leftAnchor.constraintEqualToAnchor(view.leftAnchor, constant: 15),
subviewToPresent.rightAnchor.constraintEqualToAnchor(view.rightAnchor, constant: -15),
subviewToPresent.bottomAnchor.constraintEqualToAnchor(cancelButton.topAnchor, constant: -15)
]
view.addConstraints(subviewToPresentConstraints)
//prepares view for presentation
presentingView.layoutIfNeeded()
cancelButton.layer.cornerRadius = cancelButton.bounds.height/2
UIView.animateWithDuration(0.333, delay: 0, options: [.CurveEaseInOut], animations: {
view.alpha = 1
presentingView.layoutIfNeeded()
}, completion: nil)
}
func cancel(sender: UIButton) {
self.wasCanceled?()
UIView.animateWithDuration(0.333, delay: 0, options: [.CurveEaseInOut], animations: {
sender.superview?.alpha = 0
//sender.superview?.superview?.layoutIfNeeded()
}, completion: { complete in sender.superview?.removeFromSuperview()
})
}
}
class UIViewWithBlurredBackground : UIView {
convenience init(view : UIView, withBlurEffectStyle style : UIBlurEffectStyle) {
self.init(frame: CGRect.zero)
self.configureView(view, withBlurEffectStyle: style)
}
func configureView(view : UIView, withBlurEffectStyle style : UIBlurEffectStyle) {
let backgroundView = UIVisualEffectView(effect: UIBlurEffect(style: style))
backgroundView.translatesAutoresizingMaskIntoConstraints = false
self.addSubview(backgroundView)
let backgroundViewConstraints : [NSLayoutConstraint] = [
backgroundView.leftAnchor.constraintEqualToAnchor(self.leftAnchor),
backgroundView.rightAnchor.constraintEqualToAnchor(self.rightAnchor),
backgroundView.topAnchor.constraintEqualToAnchor(self.topAnchor),
backgroundView.bottomAnchor.constraintEqualToAnchor(self.bottomAnchor)
]
self.addConstraints(backgroundViewConstraints)
view.translatesAutoresizingMaskIntoConstraints = false
self.addSubview(view)
let viewConstraints : [NSLayoutConstraint] = [
view.leftAnchor.constraintEqualToAnchor(self.leftAnchor),
view.rightAnchor.constraintEqualToAnchor(self.rightAnchor),
view.topAnchor.constraintEqualToAnchor(self.topAnchor),
view.bottomAnchor.constraintEqualToAnchor(self.bottomAnchor)
]
self.addConstraints(viewConstraints)
}
} | apache-2.0 | a7cc1e5f74ee431738f29563fd6c1faf | 39.718232 | 172 | 0.658705 | 6.229079 | false | false | false | false |
voyages-sncf-technologies/Collor | Example/Collor/MenuSample/cell/MenuItemCollectionViewCell.swift | 1 | 2149 | //
// MenuItemCollectionViewCell.swift
// Collor
//
// Created by Guihal Gwenn on 14/08/2017.
// Copyright (c) 2017-present, Voyages-sncf.com. All rights reserved.. All rights reserved.
//
import UIKit
import Collor
final class MenuItemCollectionViewCell: UICollectionViewCell, CollectionCellAdaptable {
@IBOutlet weak var label: UILabel!
@IBOutlet weak var arrowImage: UIImageView!
var adapter:MenuItemAdapter?
var userEventDelegate:MenuUserEventDelegate?
override func awakeFromNib() {
super.awakeFromNib()
//example for user Event
let tapRecognizer = UITapGestureRecognizer(target: self, action: #selector(MenuItemCollectionViewCell.onTap(gr:)))
addGestureRecognizer(tapRecognizer)
}
@objc func onTap(gr:UIGestureRecognizer) {
guard let adapter = adapter, let delegate = userEventDelegate else {
return
}
delegate.onUserEvent(userEvent: .itemTap(adapter.example))
}
func update(with adapter: CollectionAdapter) {
guard let adapter = adapter as? MenuItemAdapter else {
fatalError("MenuItemAdapter required")
}
self.adapter = adapter
label.text = adapter.label
}
func set(delegate: CollectionUserEventDelegate?) {
userEventDelegate = delegate as? MenuUserEventDelegate
}
}
final class MenuItemDescriptor: CollectionCellDescribable {
let identifier: String = "MenuItemCollectionViewCell"
let className: String = "MenuItemCollectionViewCell"
var selectable:Bool = false
let adapter: MenuItemAdapter
init(adapter:MenuItemAdapter) {
self.adapter = adapter
}
func size(_ collectionView: UICollectionView, sectionDescriptor: CollectionSectionDescribable) -> CGSize {
let sectionInset = sectionDescriptor.sectionInset(collectionView)
let width:CGFloat = collectionView.bounds.width - sectionInset.left - sectionInset.right
return CGSize(width:width, height:55)
}
public func getAdapter() -> CollectionAdapter {
return adapter
}
}
| bsd-3-clause | f8e753a2ab403d8ed8bef04744459b33 | 29.267606 | 122 | 0.6859 | 5.141148 | false | false | false | false |
yanagiba/swift-transform | Sources/swift-transform/main.swift | 1 | 3519 | /*
Copyright 2017 Ryuichi Laboratories and the Yanagiba project contributors
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
import Foundation
import Bocho
import Source
import Transform
let dotYanagibaTransform = DotYanagibaTransform.loadFromDisk()
var cliArgs = CommandLine.arguments
cliArgs.remove(at: 0)
let cliOption = CLIOption(cliArgs)
if cliOption.contains("help") {
print("""
\(SWIFT_TRANSFORM) [options] <source0> [... <sourceN>]
<source0> ... specify the paths of source files.
-help, --help
Display available options
-version, --version
Display the version
--formats <parameter0>=<value0>[,...,<parameterN>=<valueN>]
Override the default coding styles
-o, --output <path>
Write output to <path>, default to console
When single input source is provided,
this needs to be the output path of the generated file
When multiple input sources are provided,
this should be the path to a common folder that holdes all generated files
For more information, please visit http://yanagiba.org/\(SWIFT_TRANSFORM)
""")
exit(0)
}
if cliOption.contains("version") {
print("""
Yanagiba's \(SWIFT_TRANSFORM) (http://yanagiba.org/\(SWIFT_TRANSFORM)):
version \(SWIFT_TRANSFORM_VERSION).
Yanagiba's swift-ast (http://yanagiba.org/swift-ast):
version \(SWIFT_AST_VERSION).
""")
exit(0)
}
let formats = computeFormats(dotYanagibaTransform, cliOption.readAsDictionary("-formats"))
let output = computeOutput(
dotYanagibaTransform, cliOption.readAsString("o") ?? cliOption.readAsString("-output"))
let filePaths = cliOption.arguments
var sourceFiles = [SourceFile]()
for filePath in filePaths {
guard let sourceFile = try? SourceReader.read(at: filePath) else {
print("Can't read file \(filePath)")
exit(-1)
}
sourceFiles.append(sourceFile)
}
if sourceFiles.count > 1, case .standardOutput = output {
print("Output folder must be specified with `-o` for transforming multiple files at once.")
exit(-1)
}
let commonPathPrefix = sourceFiles.map({ $0.identifier }).commonPathPrefix
let tokenizer = Tokenizer(options: formats)
let tokenJoiner = TokenJoiner(options: formats)
let generator = Generator(options: formats, tokenizer: tokenizer, tokenJoiner: tokenJoiner)
let driver = Driver(generator: generator)
for sourceFile in sourceFiles {
var outputHandle: FileHandle
switch output {
case .standardOutput:
outputHandle = .standardOutput
case .fileOutput(let outputPath):
if sourceFiles.count == 1 {
outputHandle = outputPath.fileHandle
} else {
var originalFilePath = sourceFile.identifier
let commonPrefixIndex = originalFilePath.index(originalFilePath.startIndex, offsetBy: commonPathPrefix.count)
originalFilePath = String(originalFilePath[commonPrefixIndex...])
let filePath = commonPathPrefix + outputPath + "/" + originalFilePath
outputHandle = filePath.fileHandle
}
}
driver.transform(sourceFile: sourceFile, outputHandle: outputHandle)
}
| apache-2.0 | a333aa31331d97f4c9871bff4749c8c7 | 30.702703 | 115 | 0.733731 | 4.387781 | false | false | false | false |
grpc/grpc-swift | Sources/GRPC/AsyncAwaitSupport/AsyncServerHandler/ServerHandlerStateMachine/ServerHandlerStateMachine+Idle.swift | 1 | 2979 | /*
* Copyright 2022, gRPC Authors All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#if compiler(>=5.6)
import NIOHPACK
@available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *)
extension ServerHandlerStateMachine {
/// In the 'Idle' state nothing has happened. To advance we must either receive metadata (i.e.
/// the request headers) and invoke the handler, or we are cancelled.
@usableFromInline
internal struct Idle {
@usableFromInline
typealias NextStateAndOutput<Output> = ServerHandlerStateMachine.NextStateAndOutput<
ServerHandlerStateMachine.Idle.NextState,
Output
>
/// The state of the inbound stream, i.e. the request stream.
@usableFromInline
internal private(set) var inboundState: ServerInterceptorStateMachine.InboundStreamState
@inlinable
init() {
self.inboundState = .idle
}
@inlinable
mutating func handleMetadata() -> Self.NextStateAndOutput<HandleMetadataAction> {
let action: HandleMetadataAction
switch self.inboundState.receiveMetadata() {
case .accept:
// We tell the caller to invoke the handler immediately: they should then call
// 'handlerInvoked' on the state machine which will cause a transition to the next state.
action = .invokeHandler
case .reject:
action = .cancel
}
return .init(nextState: .idle(self), output: action)
}
@inlinable
mutating func handleMessage() -> Self.NextStateAndOutput<HandleMessageAction> {
// We can't receive a message before the metadata, doing so is a protocol violation.
return .init(nextState: .idle(self), output: .cancel)
}
@inlinable
mutating func handleEnd() -> Self.NextStateAndOutput<HandleEndAction> {
// Receiving 'end' before we start is odd but okay, just cancel.
return .init(nextState: .idle(self), output: .cancel)
}
@inlinable
mutating func handlerInvoked(requestHeaders: HPACKHeaders) -> Self.NextStateAndOutput<Void> {
// The handler was invoked as a result of receiving metadata. Move to the next state.
return .init(nextState: .handling(from: self, requestHeaders: requestHeaders))
}
@inlinable
mutating func cancel() -> Self.NextStateAndOutput<CancelAction> {
// There's no handler to cancel. Move straight to finished.
return .init(nextState: .finished(from: self), output: .none)
}
}
}
#endif // compiler(>=5.6)
| apache-2.0 | 842cd0c3d2356aa59f7f2e8fd17e771d | 35.777778 | 97 | 0.704263 | 4.459581 | false | false | false | false |
nsakaimbo/TDD | ToDo/Model/ToDoItem.swift | 2 | 1970 | //
// ToDoItem.swift
// ToDo
//
// Created by Nicholas Sakaimbo on 8/29/16.
// Copyright © 2016 nick_skmbo. All rights reserved.
//
import Foundation
struct ToDoItem: Equatable {
let title: String
let itemDescription: String?
let timestamp: Double?
let location: Location?
init(title: String, itemDescription: String? = nil, timestamp: Double? = nil, location: Location? = nil) {
self.title = title
self.itemDescription = itemDescription
self.timestamp = timestamp
self.location = location
}
private enum PlistKeys: String {
case title
case itemDescription
case timeStamp
case location
}
var plistDict: NSDictionary {
var dict = [String:AnyObject]()
dict[PlistKeys.title.rawValue] = title as NSString
dict[PlistKeys.itemDescription.rawValue] = itemDescription as NSString?
dict[PlistKeys.timeStamp.rawValue] = timestamp as NSNumber?
dict[PlistKeys.location.rawValue] = location?.plistDict
return dict as NSDictionary
}
init?(dict: NSDictionary) {
guard let title = dict[PlistKeys.title.rawValue] as? String else {
return nil
}
self.title = title
self.itemDescription = dict[PlistKeys.itemDescription.rawValue] as? String
self.timestamp = dict[PlistKeys.timeStamp.rawValue] as? Double
if let locationDict = dict[PlistKeys.location.rawValue] as? NSDictionary {
self.location = Location(dict: locationDict)
} else {
self.location = nil
}
}
}
func == (lhs: ToDoItem, rhs: ToDoItem) -> Bool {
if lhs.title != rhs.title { return false }
if lhs.location != rhs.location{ return false }
if lhs.timestamp != rhs.timestamp { return false }
if lhs.itemDescription != rhs.itemDescription { return false }
return true
}
| mit | 3dbcea8f5e705ef9aa359a107ae02c31 | 27.955882 | 110 | 0.623159 | 4.643868 | false | false | false | false |
xuech/OMS-WH | OMS-WH/Classes/Home/Controller/IsNotReturnListViewController.swift | 1 | 4205 | //
// IsNotReturnListViewController.swift
// OMS-WH
//
// Created by ___Gwy on 2017/8/22.
// Copyright © 2017年 medlog. All rights reserved.
//
import UIKit
import SVProgressHUD
class IsNotReturnListViewController: OMSOrderTableViewController {
private let orgCode = UserDefaults.Global.readString(forKey: .orgCode)
// 当前页码
fileprivate var currentPage : Int = 1
// 是否加载更多
fileprivate var toLoadMore :Bool = false
fileprivate var orderListModel = [OrderListModel](){
didSet{
//按时间日期进行降序显示
orderListModel = orderListModel.sorted(by: { $0.initOperationDate.compare($1.initOperationDate) == ComparisonResult.orderedAscending})
tableView.reloadData()
}
}
override func viewDidLoad() {
super.viewDidLoad()
title = "超时未返库"
tableView.separatorStyle = .none
tableView.register(OrderListTableViewCell.self)
requstListData()
}
/// 请求数据
private func requstListData(){
guard let orgCode = orgCode else { return }
XCHRefershUI.show()
moyaNetWork.request(.commonRequst(paramters: ["day":"3","sOHandleByOrgCode":orgCode,"pageNum":"\(currentPage)","pageSize":"10"], api: "oms-api-v3/kanban/order/wait7DaysNotReturn")) { (result) in
XCHRefershUI.dismiss()
switch result {
case let .success(moyaResponse):
do {
let moyaJSON = try moyaResponse.filterSuccessfulStatusCodes()
let data = try moyaJSON.mapJSON() as! [String:AnyObject]
self.dealWithData(result: data)
}
catch {}
case .failure(_):
SVProgressHUD.showError("网络请求错误")
self.tableView.endHeaderRefreshing()
break
}
}
}
private func dealWithData(result:[String:AnyObject]){
self.tableView.endHeaderRefreshing()
guard result["code"] as! Int == 0 else
{
SVProgressHUD.showError(result["msg"]! as! String)
self.toLoadMore = false
return
}
let info = result["info"] as! [String:AnyObject]
if let list = info["list"] as? [[String:AnyObject]]{
if list.count > 0{
var child = [OrderListModel]()
for item in list{
child.append(OrderListModel.init(dict: item))
}
if info["hasNextPage"] as! NSNumber == 0 {
self.toLoadMore = false
self.currentPage -= 1
if self.currentPage == 0 {
self.orderListModel = child
}else{
self.orderListModel += child
}
}else{
self.toLoadMore = true
self.orderListModel += child
}
}else{
SVProgressHUD.showError("暂无订单")
}
}
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "OrderListTableViewCell") as! OrderListTableViewCell
let model = orderListModel[indexPath.section]
cell.orderListModel = model
cell.isNotReturnLB.isHidden = false
if let date = model.operationDate {
cell.isNotReturnLB.text = "超\(Method.getMethod().diffDate(searveStr: date))未返库"
}
return cell
}
override func numberOfSections(in tableView: UITableView) -> Int {
return orderListModel.count
}
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
tableView.deselectRow(at: indexPath, animated: true)
let orderModel = orderListModel[indexPath.section]
let detailVC = OrderDetailViewController()
detailVC.sONo = orderModel.sONo
navigationController?.pushViewController(detailVC, animated: true)
}
}
| mit | 1ee9be4f8083b063b55755fc226d232b | 34.162393 | 202 | 0.576325 | 5.194444 | false | false | false | false |
zwaldowski/URLGrey | URLGrey/NSFileManager+DirectoryContents.swift | 1 | 797 | //
// NSFileManager+DirectoryContents.swift
// URLGrey
//
// Created by Zachary Waldowski on 10/23/14.
// Copyright © 2014-2015. Some rights reserved.
//
import Foundation
// MARK: Directory Enumeration
extension NSFileManager {
public func directory(URL url: NSURL, fetchResources: [URLResourceType] = [], options mask: NSDirectoryEnumerationOptions = [], errorHandler handler: ((NSURL, NSError) -> Bool)? = nil) -> AnySequence<NSURL> {
let keyStrings = fetchResources.map { $0.key }
if let enumerator = enumeratorAtURL(url, includingPropertiesForKeys: keyStrings, options: mask, errorHandler: handler) {
return AnySequence(enumerator.lazy.map(unsafeDowncast))
} else {
return AnySequence(EmptyGenerator())
}
}
}
| mit | 53672b112491c1b4d9d6017f9e4d46a1 | 30.84 | 212 | 0.679648 | 4.497175 | false | false | false | false |
johndpope/ClangWrapper.Swift | ClangWrapper/TokenSequence.swift | 1 | 1323 | //
// TokenSequence.swift
// ClangWrapper
//
// Created by Hoon H. on 2015/01/21.
// Copyright (c) 2015 Eonil. All rights reserved.
//
//public struct TokenSequence: CollectionType {
public struct TokenSequence: SequenceType {
public func dispose() {
index.allTokenSequences.untrack(self)
clang_disposeTokens(rawtu, rawptr, rawcount)
}
public var startIndex:Int {
get {
return 0
}
}
public var endInded:Int {
get {
return Int(rawcount)
}
}
public subscript(index:Int) -> Token {
get {
precondition(index < Int(rawcount))
return Token(sequence: self, index: index)
}
}
public func generate() -> GeneratorOf<Token> {
var i = 0
return GeneratorOf { rawtk in
if i == Int(self.rawcount) {
return nil
} else {
let tk = Token(sequence: self, index: i)
i++
return tk
}
}
}
////
init(index:UnmanagedIndexRef, rawtu:CXTranslationUnit, rawptr: UnsafeMutablePointer<CXToken>, rawcount:UInt32) {
self.index = index
self.rawtu = rawtu
self.rawptr = rawptr
self.rawcount = rawcount
}
let index:UnmanagedIndexRef
let rawtu:CXTranslationUnit
let rawptr:UnsafeMutablePointer<CXToken>
let rawcount:UInt32
}
extension TokenSequence: TrackableRemoteObjectProxy {
var raw:UnsafeMutablePointer<CXToken> {
get {
return rawptr
}
}
}
| mit | f8dedc4a098b055015aedabe668413c2 | 17.375 | 113 | 0.684807 | 2.92053 | false | false | false | false |
lotpb/iosSQLswift | mySQLswift/EditData.swift | 1 | 62143 | //
// EditController.swift
// mySQLswift
//
// Created by Peter Balsamo on 1/4/16.
// Copyright © 2016 Peter Balsamo. All rights reserved.
//
import UIKit
import Parse
class EditData: UIViewController, UITableViewDelegate, UITableViewDataSource, UIPickerViewDataSource, UIPickerViewDelegate, UITextFieldDelegate {
@IBOutlet weak var tableView: UITableView?
@IBOutlet weak var first: UITextField!
@IBOutlet weak var last: UITextField!
@IBOutlet weak var company: UITextField!
@IBOutlet weak var profileImageView: UIImageView?
var activeImage: UIImageView?
var datePickerView : UIDatePicker = UIDatePicker()
var pickerView : UIPickerView = UIPickerView()
private var pickOption = ["Call", "Follow", "Looks Good", "Future", "Bought", "Dead", "Cancel", "Sold"]
private var pickRate = ["A", "B", "C", "D", "F"]
private var pickContract = ["A & S Home Improvement", "Islandwide Gutters", "Ashland Home Improvement", "John Kat Windows", "Jose Rosa", "Peter Balsamo"]
//var salesArray : NSMutableArray = NSMutableArray()
//var callbackArray : NSMutableArray = NSMutableArray()
//var contractorArray : NSMutableArray = NSMutableArray()
//var rateArray : NSMutableArray = NSMutableArray()
var date : UITextField!
var address : UITextField!
var city : UITextField!
var state : UITextField!
var zip : UITextField!
var aptDate : UITextField!
var phone : UITextField!
var salesman : UITextField!
var jobName : UITextField!
var adName : UITextField!
var amount : UITextField!
var email : UITextField!
var spouse : UITextField!
var callback : UITextField!
var start : UITextField! //cust
var complete : UITextField! //cust
var comment : UITextView!
var formController : NSString?
var status : NSString?
var objectId : NSString?
var custNo : NSString?
var leadNo : NSString?
var time : NSString?
var rate : NSString? //cust
var saleNo : NSString?
var jobNo : NSString?
var adNo : NSString?
var photo : NSString?
var photo1 : NSString?
var photo2 : NSString?
var frm11 : NSString?
var frm12 : NSString?
var frm13 : NSString?
var frm14 : NSString?
var frm15 : NSString?
var frm16 : NSString?
var frm17 : NSString?
var frm18 : NSString?
var frm19 : NSString?
var frm20 : NSString?
var frm21 : NSString?
var frm22 : NSString?
var frm23 : NSString?
var frm24 : NSString?
var frm25 : NSString?
var frm26 : NSString?
var frm27 : NSString?
var frm28 : NSString?
var frm29 : NSString?
var frm30 : NSString?
var frm31 : NSString? //start
var frm32 : NSString? //completion
var defaults = NSUserDefaults.standardUserDefaults()
var simpleStepper : UIStepper!
var lookupItem : String?
var pasteBoard = UIPasteboard.generalPasteboard()
override func viewDidLoad() {
super.viewDidLoad()
clearFormData()
let titleButton: UIButton = UIButton(frame: CGRectMake(0, 0, 100, 32))
titleButton.setTitle(String(format: "%@ %@", self.status!, self.formController!), forState: UIControlState.Normal)
titleButton.titleLabel?.font = Font.navlabel
titleButton.titleLabel?.textAlignment = NSTextAlignment.Center
titleButton.setTitleColor(UIColor.whiteColor(), forState: UIControlState.Normal)
titleButton.addTarget(self, action: Selector(), forControlEvents: UIControlEvents.TouchUpInside)
self.navigationItem.titleView = titleButton
self.tableView!.delegate = self
self.tableView!.dataSource = self
self.tableView!.estimatedRowHeight = 44
self.tableView!.rowHeight = UITableViewAutomaticDimension
self.tableView!.backgroundColor = UIColor.whiteColor()
self.tableView!.tableFooterView = UIView(frame: .zero)
self.pickerView.delegate = self
self.pickerView.dataSource = self
NSNotificationCenter.defaultCenter().addObserver(self, selector: (#selector(EditData.updatePicker)), name: UITextFieldTextDidBeginEditingNotification, object: nil)
//self.pickerView.backgroundColor = UIColor.whiteColor()
//self.datePickerView.backgroundColor = UIColor.whiteColor()
let saveButton = UIBarButtonItem(barButtonSystemItem: .Save, target: self, action: #selector(EditData.updateData))
let buttons:NSArray = [saveButton]
self.navigationItem.rightBarButtonItems = buttons as? [UIBarButtonItem]
if (status == "New") {
self.frm30 = "1"
}
if (status == "Edit") {
parseLookup()
}
profileImageView!.layer.cornerRadius = profileImageView!.frame.size.width/2
profileImageView!.layer.masksToBounds = true
}
override func viewDidAppear(animated: Bool) {
super.viewDidAppear(animated)
passFieldData()
loadFormData()
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
//navigationController?.hidesBarsOnSwipe = true
self.navigationController?.navigationBar.tintColor = UIColor.whiteColor()
self.navigationController?.navigationBar.barTintColor = UIColor(white:0.45, alpha:1.0)
}
override func viewWillDisappear(animated: Bool) {
super.viewWillDisappear(animated)
NSNotificationCenter.defaultCenter().removeObserver(self)
//navigationController?.hidesBarsOnSwipe = false
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: - Table View
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if (self.formController == "Customer") {
return 17
} else {
return 15
}
}
func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat
{
if indexPath.row == 14 {
return 100
}
return 44
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) as UITableViewCell
let textframe: UITextField?
let textviewframe: UITextView?
let aptframe: UITextField?
let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd"
let dateString = dateFormatter.stringFromDate((NSDate()) as NSDate)
aptframe = UITextField(frame:CGRect(x: 220, y: 7, width: 80, height: 30))
if UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiom.Pad {
textframe = UITextField(frame:CGRect(x: 118, y: 7, width: 250, height: 30))
textviewframe = UITextView(frame:CGRect(x: 118, y: 7, width: 250, height: 85))
activeImage = UIImageView(frame:CGRect(x: 118, y: 10, width: 18, height: 22))
textframe!.font = Font.Edittitle
aptframe!.font = Font.Edittitle
textviewframe!.font = Font.Edittitle
} else {
textframe = UITextField(frame:CGRect(x: 118, y: 7, width: 205, height: 30))
textviewframe = UITextView(frame:CGRect(x: 118, y: 7, width: 240, height: 85))
activeImage = UIImageView(frame:CGRect(x: 118, y: 10, width: 18, height: 22))
textframe!.font = Font.Edittitle
aptframe!.font = Font.Edittitle
textviewframe!.font = Font.Edittitle
}
textframe!.autocorrectionType = UITextAutocorrectionType.No
textframe!.clearButtonMode = .WhileEditing
textframe!.autocapitalizationType = UITextAutocapitalizationType.Words
textframe!.textColor = UIColor.blackColor()
self.comment?.autocorrectionType = UITextAutocorrectionType.Default
self.callback?.clearButtonMode = .Never
self.zip?.keyboardType = UIKeyboardType.DecimalPad
if (formController == "Leads" || formController == "Customer") {
self.amount?.keyboardType = UIKeyboardType.DecimalPad
}
if (formController == "Customer") {
self.callback?.keyboardType = UIKeyboardType.DecimalPad
}
if (formController == "Vendor") {
self.last?.keyboardType = UIKeyboardType.URL
self.salesman?.keyboardType = UIKeyboardType.NumbersAndPunctuation
self.jobName?.keyboardType = UIKeyboardType.NumbersAndPunctuation
self.adName?.keyboardType = UIKeyboardType.NumbersAndPunctuation
}
if (formController == "Employee") {
self.salesman?.keyboardType = UIKeyboardType.NumbersAndPunctuation
self.jobName?.keyboardType = UIKeyboardType.NumbersAndPunctuation
self.adName?.keyboardType = UIKeyboardType.NumbersAndPunctuation
}
self.email?.keyboardType = UIKeyboardType.EmailAddress
self.phone?.keyboardType = UIKeyboardType.NumbersAndPunctuation
self.email?.returnKeyType = UIReturnKeyType.Next
if (indexPath.row == 0) {
let theSwitch = UISwitch(frame:CGRectZero)
self.activeImage?.contentMode = .ScaleAspectFill
if self.frm30 == "1" {
theSwitch.on = true
self.activeImage!.image = UIImage(named:"iosStar.png")
cell.textLabel!.text = "Active"
} else {
theSwitch.on = false
self.activeImage!.image = UIImage(named:"iosStarNA.png")
cell.textLabel!.text = "Inactive"
}
theSwitch.onTintColor = UIColor(red:0.0, green:122.0/255.0, blue:1.0, alpha: 1.0)
theSwitch.tintColor = UIColor.lightGrayColor()
theSwitch.addTarget(self, action: #selector(EditData.changeSwitch), forControlEvents: .ValueChanged)
cell.addSubview(theSwitch)
cell.accessoryView = theSwitch
cell.contentView.addSubview(activeImage!)
} else if (indexPath.row == 1) {
self.date = textframe
self.date!.tag = 0
if self.frm18 == nil {
self.date!.text = ""
} else {
self.date!.text = self.frm18 as? String
}
if (self.formController == "Leads" || self.formController == "Customer") {
if (self.status == "New") {
self.date?.text = dateString
}
self.date?.inputView = datePickerView
datePickerView.datePickerMode = UIDatePickerMode.Date
datePickerView.addTarget(self, action: #selector(EditData.handleDatePicker), forControlEvents: UIControlEvents.ValueChanged)
}
if (self.formController == "Vendor") {
self.date?.placeholder = "Profession"
cell.textLabel!.text = "Profession"
} else if (self.formController == "Employee") {
self.date!.placeholder = "Title"
cell.textLabel!.text = "Title"
} else {
self.date?.placeholder = "Date"
cell.textLabel!.text = "Date"
}
cell.contentView.addSubview(self.date!)
} else if (indexPath.row == 2) {
self.address = textframe
if self.frm14 == nil {
self.address!.text = ""
} else {
self.address!.text = self.frm14 as? String
}
self.address!.placeholder = "Address"
cell.textLabel!.text = "Address"
cell.contentView.addSubview(self.address!)
} else if (indexPath.row == 3) {
self.city = textframe
if self.frm15 == nil {
self.city!.text = ""
} else {
self.city!.text = self.frm15 as? String
}
cell.accessoryType = UITableViewCellAccessoryType.DisclosureIndicator
self.city!.placeholder = "City"
cell.textLabel!.text = "City"
cell.contentView.addSubview(self.city!)
} else if (indexPath.row == 4) {
self.state = textframe
if self.frm16 == nil {
self.state!.text = ""
} else {
self.state!.text = self.frm16 as? String
}
self.state!.placeholder = "State"
cell.textLabel!.text = "State"
cell.contentView.addSubview(self.state!)
self.zip = aptframe
self.zip!.placeholder = "Zip"
if self.frm17 == nil {
self.zip!.text = ""
} else {
self.zip!.text = self.frm17 as? String
}
cell.contentView.addSubview(self.zip!)
} else if (indexPath.row == 5) {
self.aptDate = textframe
if self.frm19 == nil {
self.aptDate!.text = ""
} else {
self.aptDate!.text = self.frm19 as? String
}
if (self.formController == "Customer") {
self.aptDate!.placeholder = "Rate"
cell.textLabel!.text = "Rate"
self.aptDate?.inputView = self.pickerView
} else if (self.formController == "Vendor") {
self.aptDate!.placeholder = "Assistant"
cell.textLabel!.text = "Assistant"
} else if (self.formController == "Employee") {
self.aptDate!.placeholder = "Middle"
cell.textLabel!.text = "Middle"
} else { //leads
if (self.status == "New") {
self.aptDate?.text = dateString
}
self.aptDate!.tag = 4
self.aptDate!.placeholder = "Apt Date"
cell.textLabel!.text = "Apt Date"
self.aptDate!.inputView = datePickerView
datePickerView.datePickerMode = UIDatePickerMode.Date
datePickerView.addTarget(self, action: #selector(EditData.handleDatePicker), forControlEvents: UIControlEvents.ValueChanged)
//datePickerView.backgroundColor = UIColor.whiteColor()
}
cell.contentView.addSubview(self.aptDate!)
} else if (indexPath.row == 6) {
self.phone = textframe
self.phone!.placeholder = "Phone"
if (self.frm20 == nil) {
self.phone!.text = defaults.stringForKey("areacodeKey")
} else {
self.phone!.text = self.frm20 as? String
}
cell.textLabel!.text = "Phone"
cell.contentView.addSubview(self.phone!)
} else if (indexPath.row == 7) {
self.salesman = textframe
self.salesman!.adjustsFontSizeToFitWidth = true
if self.frm21 == nil {
self.salesman!.text = ""
} else {
self.salesman!.text = self.frm21 as? String
}
if (self.formController == "Vendor") {
self.salesman!.placeholder = "Phone 1"
cell.textLabel!.text = "Phone 1"
} else if (self.formController == "Employee") {
self.salesman!.placeholder = "Work Phone"
cell.textLabel!.text = "Work Phone"
} else {
self.salesman!.placeholder = "Salesman"
cell.textLabel!.text = "Salesman"
cell.accessoryType = UITableViewCellAccessoryType.DisclosureIndicator
}
cell.contentView.addSubview(self.salesman!)
} else if (indexPath.row == 8) {
self.jobName = textframe
if self.frm22 == nil {
self.jobName!.text = ""
} else {
self.jobName!.text = self.frm22 as? String
}
if (self.formController == "Vendor") {
self.jobName!.placeholder = "Phone 2"
cell.textLabel!.text = "Phone 2"
} else if (self.formController == "Employee") {
self.jobName!.placeholder = "Cell Phone"
cell.textLabel!.text = "Cell Phone"
} else {
self.jobName!.placeholder = "Job"
cell.textLabel!.text = "Job"
cell.accessoryType = UITableViewCellAccessoryType.DisclosureIndicator
}
cell.contentView.addSubview(self.jobName!)
} else if (indexPath.row == 9) {
self.adName = textframe
self.adName!.placeholder = "Advertiser"
if self.frm23 == nil {
self.adName!.text = ""
} else {
self.adName!.text = self.frm23 as? String
}
if ((self.formController == "Leads") || (self.formController == "Customer")) {
cell.accessoryType = UITableViewCellAccessoryType.DisclosureIndicator
}
if (self.formController == "Vendor") {
self.adName!.placeholder = "Phone 3"
cell.textLabel!.text = "phone 3"
} else if (self.formController == "Employee") {
self.adName!.placeholder = "Social Security"
cell.textLabel!.text = "Social Sec"
} else if (self.formController == "Customer") {
self.adName!.placeholder = "Product"
cell.textLabel!.text = "Product"
} else {
cell.textLabel!.text = "Advertiser"
}
cell.contentView.addSubview(self.adName!)
} else if(indexPath.row == 10) {
self.amount = textframe
if ((self.formController == "Leads") || (self.formController == "Customer")) {
if (self.status == "New") {
let simpleStepper = UIStepper(frame:CGRectZero)
simpleStepper.tag = 10
simpleStepper.value = 0 //Double(self.amount.text!)!
simpleStepper.minimumValue = 0
simpleStepper.maximumValue = 10000
simpleStepper.stepValue = 100
simpleStepper.tintColor = UIColor.grayColor()
cell.accessoryView = simpleStepper
simpleStepper.addTarget(self, action: #selector(EditData.stepperValueDidChange), forControlEvents: UIControlEvents.ValueChanged)
}
}
self.amount!.placeholder = "Amount"
if self.frm24 == nil {
self.amount!.text = ""
} else {
self.amount!.text = self.frm24 as? String
}
cell.textLabel!.text = "Amount"
if ((self.formController == "Vendor") || (self.formController == "Employee")) {
self.amount!.placeholder = "Department"
cell.textLabel!.text = "Department"
}
cell.contentView.addSubview(self.amount!)
} else if (indexPath.row == 11) {
self.email = textframe
self.email!.placeholder = "Email"
if self.frm25 == nil {
self.email!.text = ""
} else {
let myString = self.frm25 as? String
self.email!.text = myString!.removeWhiteSpace() //extension
}
cell.textLabel!.text = "Email"
cell.contentView.addSubview(self.email!)
} else if(indexPath.row == 12) {
self.spouse = textframe
self.spouse!.placeholder = "Spouse"
if self.frm26 == nil {
self.spouse!.text = ""
} else {
self.spouse!.text = self.frm26 as? String
}
if (formController == "Vendor") {
self.spouse!.placeholder = "Office"
cell.textLabel!.text = "Office"
} else if (formController == "Employee") {
self.spouse!.placeholder = "Country"
cell.textLabel!.text = "Country"
} else {
cell.textLabel!.text = "Spouse"
}
cell.contentView.addSubview(self.spouse!)
} else if (indexPath.row == 13) {
self.callback = textframe
if self.frm27 == nil {
self.callback!.text = ""
} else {
self.callback!.text = self.frm27 as? String
}
if (self.formController == "Customer") {
self.callback!.placeholder = "Quan"
cell.textLabel!.text = "# Windows"
let simpleStepper = UIStepper(frame:CGRectZero)
simpleStepper.tag = 13
if (self.status == "Edit") {
simpleStepper.value = Double(self.callback.text!)!
} else {
simpleStepper.value = 0
}
simpleStepper.stepValue = 1
simpleStepper.tintColor = UIColor.grayColor()
cell.accessoryView = simpleStepper
simpleStepper.addTarget(self, action: #selector(EditData.stepperValueDidChange), forControlEvents: UIControlEvents.ValueChanged)
}
else if (self.formController == "Vendor") {
self.callback!.hidden = true //Field
self.callback!.placeholder = ""
cell.textLabel!.text = ""
}
else if (self.formController == "Employee") {
self.callback!.placeholder = "Manager"
cell.textLabel!.text = "Manager"
}
else {
self.callback!.placeholder = "Call Back"
cell.textLabel!.text = "Call Back"
self.callback?.inputView = self.pickerView
}
cell.contentView.addSubview(self.callback!)
} else if (indexPath.row == 14) {
self.comment = textviewframe
if self.frm28 == nil {
self.comment!.text = ""
} else {
self.comment!.text = self.frm28 as? String
}
cell.textLabel!.text = "Comments"
cell.contentView.addSubview(self.comment!)
} else if(indexPath.row == 15) {
self.start = textframe
//self.start!.tag = 15
self.start!.placeholder = "Start Date"
if self.frm31 == nil {
self.start!.text = ""
} else {
self.start!.text = self.frm31 as? String
}
self.start!.inputView = datePickerView
datePickerView.addTarget(self, action: #selector(EditData.handleDatePicker), forControlEvents: UIControlEvents.ValueChanged)
cell.textLabel!.text = "Start Date"
cell.contentView.addSubview(self.start!)
} else if(indexPath.row == 16) {
self.complete = textframe
//self.complete!.tag = 16
self.complete!.placeholder = "Completion Date"
if self.frm32 == nil {
self.complete!.text = ""
} else {
self.complete!.text = self.frm32 as? String
}
self.complete!.inputView = datePickerView
datePickerView.addTarget(self, action: #selector(EditData.handleDatePicker), forControlEvents: UIControlEvents.ValueChanged)
cell.textLabel!.text = "End Date"
cell.contentView.addSubview(self.complete!)
}
return cell
}
// MARK: - Table Header/Footer
func tableView(tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
return 20.0
}
func tableView(tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
return 40.0
}
// MARK: - Content Menu
func tableView(tableView: UITableView, shouldShowMenuForRowAtIndexPath indexPath: NSIndexPath) -> Bool {
return true
}
func tableView(tableView: UITableView, canPerformAction action: Selector, forRowAtIndexPath indexPath: NSIndexPath, withSender sender: AnyObject?) -> Bool {
if (action == #selector(NSObject.copy(_:))) {
return true
}
return false
}
func tableView(tableView: UITableView, performAction action: Selector, forRowAtIndexPath indexPath: NSIndexPath, withSender sender: AnyObject?) {
let cell = tableView.cellForRowAtIndexPath(indexPath)
pasteBoard.string = cell!.textLabel?.text
}
// MARK: - Switch
func changeSwitch(sender: UISwitch) {
if (sender.on) {
self.frm30 = "1"
} else {
self.frm30 = "0"
}
self.tableView!.reloadData()
}
// MARK: - StepperValueChanged
func stepperValueDidChange(sender: UIStepper) {
if (sender.tag == 13) {
self.callback?.text = "\(Int(sender.value))"
} else if (sender.tag == 10) {
self.amount?.text = "\(Int(sender.value))"
}
}
// MARK: - TextField
func textFieldShouldReturn(textField: UITextField) -> Bool { //delegate method
textField.resignFirstResponder()
return true
}
// MARK: - PickView
func updatePicker(){
self.pickerView.reloadAllComponents()
}
func numberOfComponentsInPickerView(pickerView: UIPickerView) -> Int {
return 1
}
func pickerView(pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
if callback.isFirstResponder() {
return pickOption.count
} else if aptDate.isFirstResponder() {
return pickRate.count
} else if company.isFirstResponder() {
return pickContract.count
} else {
return 0
}
}
func pickerView(pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
if callback.isFirstResponder() {
return "\(pickOption[row])"
} else if aptDate.isFirstResponder() {
return "\(pickRate[row])"
} else if company.isFirstResponder() {
return "\(pickContract[row])"
}
return nil
}
func pickerView(pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
if callback.isFirstResponder() {
self.callback.text = pickOption[row]
} else if aptDate.isFirstResponder() {
self.aptDate.text = pickRate[row]
} else if company.isFirstResponder() {
self.company.text = pickContract[row]
}
}
// MARK: - Datepicker
func handleDatePicker(sender: UIDatePicker) {
let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd"
if date.isFirstResponder() {
self.date?.text = dateFormatter.stringFromDate(sender.date)
} else if aptDate.isFirstResponder() {
self.aptDate?.text = dateFormatter.stringFromDate(sender.date)
} else if start.isFirstResponder() {
self.start?.text = dateFormatter.stringFromDate(sender.date)
} else if complete.isFirstResponder() {
self.complete?.text = dateFormatter.stringFromDate(sender.date)
}
}
// MARK: - FieldData Header
func passFieldData() {
self.first.font = Font.Edittitle
self.last.font = Font.Edittitle
self.company.font = Font.Edittitle
if (self.formController == "Leads" || self.formController == "Customer") {
self.last.borderStyle = UITextBorderStyle.RoundedRect
self.last.layer.borderColor = UIColor(red:151/255.0, green:193/255.0, blue:252/255.0, alpha: 1.0).CGColor
self.last.layer.borderWidth = 2.0
self.last.layer.cornerRadius = 7.0
}
if (self.formController == "Vendor" || self.formController == "Employee") {
self.first.borderStyle = UITextBorderStyle.RoundedRect
self.first.layer.borderColor = UIColor(red:151/255.0, green:193/255.0, blue:252/255.0, alpha: 1.0).CGColor
self.first.layer.borderWidth = 2.0
self.first.layer.cornerRadius = 7.0
}
if self.frm11 != nil {
let myString1 = self.frm11 as? String
self.first.text = myString1!.removeWhiteSpace()
} else {
self.first.text = ""
}
if self.frm12 != nil {
let myString2 = self.frm12 as? String
self.last.text = myString2!.removeWhiteSpace()
} else {
self.last.text = ""
}
if self.frm13 != nil {
let myString3 = self.frm13 as? String
self.company.text = myString3!.removeWhiteSpace()
} else {
self.company.text = ""
}
if (formController == "Customer") {
if (self.status == "New") {
self.company?.hidden = true
} else {
self.company.placeholder = "Contractor"
self.company?.inputView = self.pickerView
}
} else if (self.formController == "Vendor") {
self.first.placeholder = "Company"
self.last.placeholder = "Webpage"
self.company.placeholder = "Manager"
} else if (formController == "Employee") {
self.first.placeholder = "First"
self.last.placeholder = "Last"
self.company.placeholder = "Subcontractor"
} else {
self.company.hidden = true
}
}
// MARK: - Parse
func parseLookup() {
if (self.formController == "Leads") {
let query = PFQuery(className:"Advertising")
query.whereKey("AdNo", equalTo:self.frm23!)
query.cachePolicy = PFCachePolicy.CacheThenNetwork
query.getFirstObjectInBackgroundWithBlock {(object: PFObject?, error: NSError?) -> Void in
if error == nil {
self.adName!.text = object!.objectForKey("Advertiser") as? String
}
}
} else if (self.formController == "Customer") {
let query = PFQuery(className:"Product")
query.whereKey("ProductNo", equalTo:self.frm23!)
query.cachePolicy = PFCachePolicy.CacheThenNetwork
query.getFirstObjectInBackgroundWithBlock {(object: PFObject?, error: NSError?) -> Void in
if error == nil {
self.adName!.text = object!.objectForKey("Products") as? String
}
}
}
if (self.formController == "Leads" || self.formController == "Customer") {
let query = PFQuery(className:"Job")
query.whereKey("JobNo", equalTo:self.frm22!)
query.cachePolicy = PFCachePolicy.CacheThenNetwork
query.getFirstObjectInBackgroundWithBlock {(object: PFObject?, error: NSError?) -> Void in
if error == nil {
self.jobName!.text = object!.objectForKey("Description") as? String
}
}
let query1 = PFQuery(className:"Salesman")
query1.whereKey("SalesNo", equalTo:self.frm21!)
query1.cachePolicy = PFCachePolicy.CacheThenNetwork
query1.getFirstObjectInBackgroundWithBlock {(object: PFObject?, error: NSError?) -> Void in
if error == nil {
self.salesman!.text = object!.objectForKey("Salesman") as? String
}
}
}
}
// MARK: - Load Form Data
func loadFormData() {
if (self.first.text == "") {
self.first.text = defaults.stringForKey("first")
}
if (self.last.text == "") {
self.last.text = defaults.stringForKey("last")
}
if (self.company.text == "") {
self.company.text = defaults.stringForKey("company")
}
}
// MARK: Clear Form Data
func clearFormData() {
self.defaults.removeObjectForKey("first")
self.defaults.removeObjectForKey("last")
self.defaults.removeObjectForKey("company")
}
// MARK: Save Form Data
func saveFormData() {
if (self.first.text != "") {
self.defaults.setObject(self.first.text, forKey: "first")
}
if (self.last.text != "") {
self.defaults.setObject(self.last.text, forKey: "last")
}
if (self.company.text != "") {
self.defaults.setObject(self.company.text, forKey: "company")
}
}
// MARK: - Move Keyboard
// FIXME:
func textFieldDidBeginEditing(textField: UITextField) {
animateViewMoving(true, moveValue: 100)
}
func textFieldDidEndEditing(textField: UITextField) {
animateViewMoving(false, moveValue: 100)
}
func animateViewMoving (up:Bool, moveValue :CGFloat){
let movementDuration:NSTimeInterval = 0.3
let movement:CGFloat = ( up ? -moveValue : moveValue)
UIView.beginAnimations( "animateView", context: nil)
UIView.setAnimationBeginsFromCurrentState(true)
UIView.setAnimationDuration(movementDuration )
self.view.frame = CGRectOffset(self.view.frame, 0, movement)
UIView.commitAnimations()
}
// MARK: - Segues
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
if (indexPath.row == 3) {
lookupItem = "City"
self.performSegueWithIdentifier("lookupDataSegue", sender: self)
}
if (indexPath.row == 7) {
lookupItem = "Salesman"
self.performSegueWithIdentifier("lookupDataSegue", sender: self)
}
if (indexPath.row == 8) {
lookupItem = "Job"
self.performSegueWithIdentifier("lookupDataSegue", sender: self)
}
if (indexPath.row == 9) {
if (self.formController == "Customer") {
lookupItem = "Product"
} else {
lookupItem = "Advertiser"
}
self.performSegueWithIdentifier("lookupDataSegue", sender: self)
}
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if segue.identifier == "lookupDataSegue" {
saveFormData()
let controller = segue.destinationViewController as? LookupData
controller!.delegate = self
controller!.lookupItem = lookupItem
}
}
// MARK: - Update Data
func updateData() {
let numberFormatter = NSNumberFormatter()
numberFormatter.numberStyle = .NoStyle
if (self.formController == "Leads") {
let myActive : NSNumber = numberFormatter.numberFromString((self.frm30 as? String)!)!
var Lead = self.leadNo
if Lead == nil { Lead = "" }
let myLead = numberFormatter.numberFromString(Lead as! String)
var Amount = self.amount.text
if Amount == nil { Amount = "" }
let myAmount = numberFormatter.numberFromString(Amount!)
var Zip = self.zip.text
if Zip == nil { Zip = "" }
let myZip = numberFormatter.numberFromString(Zip!)
var Sale = self.saleNo
if Sale == nil { Sale = "" }
let mySale = numberFormatter.numberFromString(Sale as! String)
var Job = self.jobNo
if Job == nil { Job = "" }
let myJob = numberFormatter.numberFromString(Job as! String)
var Ad = self.adNo
if Ad == nil { Ad = "" }
let myAd = numberFormatter.numberFromString(Ad as! String)
if (self.status == "Edit") { //Edit Lead
let query = PFQuery(className:"Leads")
query.whereKey("objectId", equalTo:self.objectId!)
query.getFirstObjectInBackgroundWithBlock {(updateblog: PFObject?, error: NSError?) -> Void in
if error == nil {
updateblog!.setObject(myLead ?? NSNumber(integer:-1), forKey:"LeadNo")
updateblog!.setObject(myActive ?? NSNumber(integer:-1), forKey:"Active")
updateblog!.setObject(self.date.text ?? NSNull(), forKey:"Date")
updateblog!.setObject(self.first.text ?? NSNull(), forKey:"First")
updateblog!.setObject(self.last.text ?? NSNull(), forKey:"LastName")
updateblog!.setObject(self.address.text ?? NSNull(), forKey:"Address")
updateblog!.setObject(self.city.text ?? NSNull(), forKey:"City")
updateblog!.setObject(self.state.text ?? NSNull(), forKey:"State")
updateblog!.setObject(myZip ?? NSNumber(integer:-1), forKey:"Zip")
updateblog!.setObject(self.phone.text ?? NSNull(), forKey:"Phone")
updateblog!.setObject(self.aptDate.text ?? NSNull(), forKey:"AptDate")
updateblog!.setObject(self.email.text ?? NSNull(), forKey:"Email")
updateblog!.setObject(myAmount ?? NSNumber(integer:-1), forKey:"Amount")
updateblog!.setObject(self.spouse.text ?? NSNull(), forKey:"Spouse")
updateblog!.setObject(self.callback.text ?? NSNull(), forKey:"CallBack")
updateblog!.setObject(mySale ?? NSNumber(integer:-1), forKey:"SalesNo")
updateblog!.setObject(myJob ?? NSNumber(integer:-1), forKey:"JobNo")
updateblog!.setObject(myAd ?? NSNumber(integer:-1), forKey:"AdNo")
updateblog!.setObject(self.comment.text ?? NSNull(), forKey:"Coments")
//updateblog!.setObject(self.photo.text ?? NSNull(), forKey:"Photo")
updateblog!.saveEventually()
self.navigationController?.popToRootViewControllerAnimated(true)
//self.simpleAlert("Upload Complete", message: "Successfully updated the data")
} else {
self.simpleAlert("Upload Failure", message: "Failure updating the data")
}
}
//self.navigationController?.popToRootViewControllerAnimated(true)
} else { //Save Lead
let saveblog:PFObject = PFObject(className:"Leads")
saveblog.setObject(self.leadNo ?? NSNumber(integer:-1), forKey:"LeadNo")
saveblog.setObject(myActive ?? NSNumber(integer:1), forKey:"Active")
saveblog.setObject(self.date.text ?? NSNull(), forKey:"Date")
saveblog.setObject(self.first.text ?? NSNull(), forKey:"First")
saveblog.setObject(self.last.text ?? NSNull(), forKey:"LastName")
saveblog.setObject(self.address.text ?? NSNull(), forKey:"Address")
saveblog.setObject(self.city.text ?? NSNull(), forKey:"City")
saveblog.setObject(self.state.text ?? NSNull(), forKey:"State")
saveblog.setObject(myZip ?? NSNumber(integer:-1), forKey:"Zip")
saveblog.setObject(self.phone.text ?? NSNull(), forKey:"Phone")
saveblog.setObject(self.aptDate.text ?? NSNull(), forKey:"AptDate")
saveblog.setObject(self.email.text ?? NSNull(), forKey:"Email")
saveblog.setObject(myAmount ?? NSNumber(integer:0), forKey:"Amount")
saveblog.setObject(self.spouse.text ?? NSNull(), forKey:"Spouse")
saveblog.setObject(self.callback.text ?? NSNull(), forKey:"CallBack")
saveblog.setObject(mySale ?? NSNumber(integer:-1), forKey:"SalesNo")
saveblog.setObject(myJob ?? NSNumber(integer:-1), forKey:"JobNo")
saveblog.setObject(myAd ?? NSNumber(integer:-1), forKey:"AdNo")
saveblog.setObject(self.comment.text ?? NSNull(), forKey:"Coments")
saveblog.setObject(self.photo ?? NSNull(), forKey:"Photo")
PFACL.setDefaultACL(PFACL(), withAccessForCurrentUser: true)
saveblog.saveInBackgroundWithBlock { (success: Bool, error: NSError?) -> Void in
if success == true {
self.navigationController?.popToRootViewControllerAnimated(true)
//self.simpleAlert("Upload Complete", message: "Successfully updated the data")
} else {
self.simpleAlert("Upload Failure", message: "Failure updating the data")
}
}
}
} else if (self.formController == "Customer") {
let myActive : NSNumber = numberFormatter.numberFromString(self.frm30! as String)!
var Cust = self.custNo
if Cust == nil { Cust = "" }
let myCust = numberFormatter.numberFromString(Cust as! String)
var Lead = self.leadNo
if Lead == nil { Lead = "" }
let myLead = numberFormatter.numberFromString(Lead as! String)
var Amount = (self.amount.text)
if Amount == nil { Amount = "" }
let myAmount = numberFormatter.numberFromString(Amount!)
var Zip = self.zip.text
if Zip == nil { Zip = "" }
let myZip = numberFormatter.numberFromString(Zip!)
var Sale = self.saleNo
if Sale == nil { Sale = "" }
let mySale = numberFormatter.numberFromString(Sale! as String)
var Job = self.jobNo
if Job == nil { Job = "" }
let myJob = numberFormatter.numberFromString(Job! as String)
var Ad = self.adNo
if Ad == nil { Ad = "" }
let myAd = numberFormatter.numberFromString(Ad! as String)
var Quan = self.callback.text
if Quan == nil { Quan = "" }
let myQuan = numberFormatter.numberFromString(Quan! as String)
if (self.status == "Edit") { //Edit Customer
let query = PFQuery(className:"Customer")
query.whereKey("objectId", equalTo:self.objectId!)
query.getFirstObjectInBackgroundWithBlock {(updateblog: PFObject?, error: NSError?) -> Void in
if error == nil {
updateblog!.setObject(myCust ?? NSNumber(integer:-1), forKey:"CustNo")
updateblog!.setObject(myLead ?? NSNumber(integer:-1), forKey:"LeadNo")
updateblog!.setObject(myActive ?? NSNumber(integer:1), forKey:"Active")
updateblog!.setObject(self.date.text ?? NSNull(), forKey:"Date")
updateblog!.setObject(self.first.text ?? NSNull(), forKey:"First")
updateblog!.setObject(self.last.text ?? NSNull(), forKey:"LastName")
updateblog!.setObject(self.address.text ?? NSNull(), forKey:"Address")
updateblog!.setObject(self.city.text ?? NSNull(), forKey:"City")
updateblog!.setObject(self.state.text ?? NSNull(), forKey:"State")
updateblog!.setObject(myZip ?? NSNumber(integer:-1), forKey:"Zip")
updateblog!.setObject(self.phone.text ?? NSNull(), forKey:"Phone")
updateblog!.setObject(myQuan ?? NSNumber(integer:-1), forKey:"Quan")
updateblog!.setObject(self.email.text ?? NSNull(), forKey:"Email")
updateblog!.setObject(myAmount ?? NSNumber(integer:-1), forKey:"Amount")
updateblog!.setObject(self.spouse.text ?? NSNull(), forKey:"Spouse")
updateblog!.setObject(self.aptDate.text ?? NSNull(), forKey:"Rate")
updateblog!.setObject(mySale ?? NSNumber(integer:-1), forKey:"SalesNo")
updateblog!.setObject(myJob ?? NSNumber(integer:-1), forKey:"JobNo")
updateblog!.setObject(myAd ?? NSNumber(integer:-1), forKey:"ProductNo")
updateblog!.setObject(self.start.text ?? NSNull(), forKey:"Start")
updateblog!.setObject(self.complete.text ?? NSNull(), forKey:"Completion")
updateblog!.setObject(self.comment.text ?? NSNull(), forKey:"Comments")
updateblog!.setObject(self.company.text ?? NSNull(), forKey:"Contractor")
updateblog!.setObject(self.photo ?? NSNull(), forKey:"Photo")
updateblog!.setObject(self.photo1 ?? NSNull(), forKey:"Photo1")
updateblog!.setObject(self.photo2 ?? NSNull(), forKey:"Photo2")
updateblog!.setObject(self.time ?? NSNull(), forKey:"Time")
updateblog!.saveEventually()
self.navigationController?.popToRootViewControllerAnimated(true)
//self.simpleAlert("Upload Complete", message: "Successfully updated the data")
} else {
self.simpleAlert("Upload Failure", message: "Failure updating the data")
}
}
} else { //Save Customer
let saveblog:PFObject = PFObject(className:"Customer")
saveblog.setObject(myCust ?? NSNumber(integer:-1), forKey:"CustNo")
saveblog.setObject(myLead ?? NSNumber(integer:-1), forKey:"LeadNo")
saveblog.setObject(myActive ?? NSNumber(integer:1), forKey:"Active")
saveblog.setObject(self.date.text ?? NSNull(), forKey:"Date")
saveblog.setObject(self.first.text ?? NSNull(), forKey:"First")
saveblog.setObject(self.last.text ?? NSNull(), forKey:"LastName")
saveblog.setObject(self.company.text ?? NSNull(), forKey:"Contractor")
saveblog.setObject(self.address.text ?? NSNull(), forKey:"Address")
saveblog.setObject(self.city.text ?? NSNull(), forKey:"City")
saveblog.setObject(self.state.text ?? NSNull(), forKey:"State")
saveblog.setObject(myZip ?? NSNumber(integer:-1), forKey:"Zip")
saveblog.setObject(self.phone.text ?? NSNull(), forKey:"Phone")
saveblog.setObject(self.aptDate.text ?? NSNull(), forKey:"Rate")
saveblog.setObject(mySale ?? NSNumber(integer:-1), forKey:"SalesNo")
saveblog.setObject(myJob ?? NSNumber(integer:-1), forKey:"JobNo")
saveblog.setObject(myAd ?? NSNumber(integer:-1), forKey:"ProductNo")
saveblog.setObject(myAmount ?? NSNumber(integer:0), forKey:"Amount")
saveblog.setObject(myQuan ?? NSNumber(integer:-1), forKey:"Quan")
saveblog.setObject(self.email.text ?? NSNull(), forKey:"Email")
saveblog.setObject(self.spouse.text ?? NSNull(), forKey:"Spouse")
saveblog.setObject(self.callback.text ?? NSNull(), forKey:"CallBack")
saveblog.setObject(self.start.text ?? NSNull(), forKey:"Start")
saveblog.setObject(self.complete.text ?? NSNull(), forKey:"Completion")
saveblog.setObject(self.comment.text ?? NSNull(), forKey:"Comment")
saveblog.setObject(NSNull(), forKey:"Photo")
PFACL.setDefaultACL(PFACL(), withAccessForCurrentUser: true)
saveblog.saveInBackgroundWithBlock { (success: Bool, error: NSError?) -> Void in
if success == true {
self.navigationController?.popToRootViewControllerAnimated(true)
//self.simpleAlert("Upload Complete", message: "Successfully updated the data")
} else {
self.simpleAlert("Upload Failure", message: "Failure updating the data")
}
}
}
} else if (self.formController == "Vendor") {
var Active = (self.frm30 as? String)
if Active == nil { Active = "0" }
let myActive = numberFormatter.numberFromString(Active!)
var Lead = (self.leadNo)
if Lead == nil { Lead = "-1" }
let myLead = numberFormatter.numberFromString(Lead! as String)
if (self.status == "Edit") { //Edit Vendor
let query = PFQuery(className:"Vendors")
query.whereKey("objectId", equalTo:self.objectId!)
query.getFirstObjectInBackgroundWithBlock {(updateblog: PFObject?, error: NSError?) -> Void in
if error == nil {
updateblog!.setObject(myLead!, forKey:"VendorNo")
updateblog!.setObject(myActive!, forKey:"Active")
updateblog!.setObject(self.first.text ?? NSNull(), forKey:"Vendor")
updateblog!.setObject(self.address.text ?? NSNull(), forKey:"Address")
updateblog!.setObject(self.city.text ?? NSNull(), forKey:"City")
updateblog!.setObject(self.state.text ?? NSNull(), forKey:"State")
updateblog!.setObject(self.zip.text ?? NSNull(), forKey:"Zip")
updateblog!.setObject(self.phone.text ?? NSNull(), forKey:"Phone")
updateblog!.setObject(self.salesman.text ?? NSNull(), forKey:"Phone1")
updateblog!.setObject(self.jobName.text ?? NSNull(), forKey:"Phone2")
updateblog!.setObject(self.adName.text ?? NSNull(), forKey:"Phone3")
updateblog!.setObject(self.email.text ?? NSNull(), forKey:"Email")
updateblog!.setObject(self.last.text ?? NSNull(), forKey:"WebPage")
updateblog!.setObject(self.amount.text ?? NSNull(), forKey:"Department")
updateblog!.setObject(self.spouse.text ?? NSNull(), forKey:"Office")
updateblog!.setObject(self.company.text ?? NSNull(), forKey:"Manager")
updateblog!.setObject(self.date.text ?? NSNull(), forKey:"Profession")
updateblog!.setObject(self.aptDate.text ?? NSNull(), forKey:"Assistant")
updateblog!.setObject(self.comment.text ?? NSNull(), forKey:"Comments")
updateblog!.saveEventually()
self.navigationController?.popToRootViewControllerAnimated(true)
//self.simpleAlert("Upload Complete", message: "Successfully updated the data")
} else {
self.simpleAlert("Upload Failure", message: "Failure updating the data")
}
}
} else { //Save Vendor
let saveVend:PFObject = PFObject(className:"Vendors")
saveVend.setObject(myLead!, forKey:"VendorNo")
saveVend.setObject(myActive!, forKey:"Active")
saveVend.setObject(self.first.text ?? NSNull(), forKey:"Vendor")
saveVend.setObject(self.address.text ?? NSNull(), forKey:"Address")
saveVend.setObject(self.city.text ?? NSNull(), forKey:"City")
saveVend.setObject(self.state.text ?? NSNull(), forKey:"State")
saveVend.setObject(self.zip.text ?? NSNumber(integer:-1), forKey:"Zip")
saveVend.setObject(self.phone.text ?? NSNull(), forKey:"Phone")
saveVend.setObject(self.salesman.text ?? NSNull(), forKey:"Phone1")
saveVend.setObject(self.jobName.text ?? NSNull(), forKey:"Phone2")
saveVend.setObject(self.adName.text ?? NSNull(), forKey:"Phone3")
saveVend.setObject(self.email.text ?? NSNull(), forKey:"Email")
saveVend.setObject(self.last.text ?? NSNull(), forKey:"WebPage")
saveVend.setObject(self.amount.text ?? NSNull(), forKey:"Department")
saveVend.setObject(self.spouse.text ?? NSNull(), forKey:"Office")
saveVend.setObject(self.company.text ?? NSNull(), forKey:"Manager")
saveVend.setObject(self.date.text ?? NSNull(), forKey:"Profession")
saveVend.setObject(self.aptDate.text ?? NSNull(), forKey:"Assistant")
saveVend.setObject(self.comment.text ?? NSNull(), forKey:"Comments")
PFACL.setDefaultACL(PFACL(), withAccessForCurrentUser: true)
saveVend.saveInBackgroundWithBlock { (success: Bool, error: NSError?) -> Void in
if success == true {
self.navigationController?.popToRootViewControllerAnimated(true)
//self.simpleAlert("Upload Complete", message: "Successfully updated the data")
} else {
self.simpleAlert("Upload Failure", message: "Failure updating the data")
}
}
}
} else if (self.formController == "Employee") {
var Active = (self.frm30 as? String)
if Active == nil { Active = "0" }
let myActive = numberFormatter.numberFromString(Active!)
var Lead = (self.leadNo as? String)
if Lead == nil { Lead = "-1" }
let myLead = numberFormatter.numberFromString(Lead!)
if (self.status == "Edit") { //Edit Employee
let query = PFQuery(className:"Employee")
query.whereKey("objectId", equalTo:self.objectId!)
query.getFirstObjectInBackgroundWithBlock {(updateblog: PFObject?, error: NSError?) -> Void in
if error == nil {
updateblog!.setObject(myLead!, forKey:"EmployeeNo")
updateblog!.setObject(myActive!, forKey:"Active")
updateblog!.setObject(self.company.text ?? NSNull(), forKey:"Company")
updateblog!.setObject(self.address.text ?? NSNull(), forKey:"Address")
updateblog!.setObject(self.city.text ?? NSNull(), forKey:"City")
updateblog!.setObject(self.state.text ?? NSNull(), forKey:"State")
updateblog!.setObject(self.zip.text ?? NSNull(), forKey:"Zip")
updateblog!.setObject(self.phone.text ?? NSNull(), forKey:"HomePhone")
updateblog!.setObject(self.salesman.text ?? NSNull(), forKey:"WorkPhone")
updateblog!.setObject(self.jobName.text ?? NSNull(), forKey:"CellPhone")
updateblog!.setObject(self.adName.text ?? NSNull(), forKey:"SS")
updateblog!.setObject(self.email.text ?? NSNull(), forKey:"Email")
updateblog!.setObject(self.last.text ?? NSNull(), forKey:"Last")
updateblog!.setObject(self.amount.text ?? NSNull(), forKey:"Department")
updateblog!.setObject(self.spouse.text ?? NSNull(), forKey:"Country")
updateblog!.setObject(self.first.text ?? NSNull(), forKey:"First")
updateblog!.setObject(self.callback.text ?? NSNull(), forKey:"Manager")
updateblog!.setObject(self.date.text ?? NSNull(), forKey:"Title")
updateblog!.setObject(self.aptDate.text ?? NSNull(), forKey:"Middle")
updateblog!.setObject(self.comment.text ?? NSNull(), forKey:"Comments")
updateblog!.saveEventually()
self.navigationController?.popToRootViewControllerAnimated(true)
//self.simpleAlert("Upload Complete", message: "Successfully updated the data")
} else {
self.simpleAlert("Upload Failure", message: "Failure updating the data")
}
}
} else { //Save Employee
let saveblog:PFObject = PFObject(className:"Employee")
saveblog.setObject(NSNumber(integer:-1), forKey:"EmployeeNo")
saveblog.setObject(NSNumber(integer:1), forKey:"Active")
saveblog.setObject(self.company.text ?? NSNull(), forKey:"Company")
saveblog.setObject(self.address.text ?? NSNull(), forKey:"Address")
saveblog.setObject(self.city.text ?? NSNull(), forKey:"City")
saveblog.setObject(self.state.text ?? NSNull(), forKey:"State")
saveblog.setObject(self.zip.text ?? NSNull(), forKey:"Zip")
saveblog.setObject(self.phone.text ?? NSNull(), forKey:"HomePhone")
saveblog.setObject(self.salesman.text ?? NSNull(), forKey:"WorkPhone")
saveblog.setObject(self.jobName.text ?? NSNull(), forKey:"CellPhone")
saveblog.setObject(self.adName.text ?? NSNull(), forKey:"SS")
saveblog.setObject(self.date.text ?? NSNull(), forKey:"Country")
saveblog.setObject(self.email.text ?? NSNull(), forKey:"Email")
saveblog.setObject(self.last.text ?? NSNull(), forKey:"Last")
saveblog.setObject(self.amount.text ?? NSNull(), forKey:"Department")
saveblog.setObject(self.aptDate.text ?? NSNull(), forKey:"Middle")
saveblog.setObject(self.first.text ?? NSNull(), forKey:"First")
saveblog.setObject(self.callback.text ?? NSNull(), forKey:"Manager")
saveblog.setObject(self.spouse.text ?? NSNull(), forKey:"Title")
saveblog.setObject(self.comment.text ?? NSNull(), forKey:"Comments")
PFACL.setDefaultACL(PFACL(), withAccessForCurrentUser: true)
saveblog.saveInBackgroundWithBlock { (success: Bool, error: NSError?) -> Void in
if success == true {
self.navigationController?.popToRootViewControllerAnimated(true)
//self.simpleAlert("Upload Complete", message: "Successfully updated the data")
} else {
self.simpleAlert("Upload Failure", message: "Failure updating the data")
}
}
}
}
}
}
extension EditData: LookupDataDelegate {
func cityFromController(passedData: NSString) {
self.city.text = passedData as String
}
func stateFromController(passedData: NSString) {
self.state.text = passedData as String
}
func zipFromController(passedData: NSString) {
self.zip.text = passedData as String
}
func salesFromController(passedData: NSString) {
self.saleNo = passedData as String
}
func salesNameFromController(passedData: NSString) {
self.salesman.text = passedData as String
}
func jobFromController(passedData: NSString) {
self.jobNo = passedData as String
}
func jobNameFromController(passedData: NSString) {
self.jobName.text = passedData as String
}
func productFromController(passedData: NSString) {
self.adNo = passedData as String
}
func productNameFromController(passedData: NSString) {
self.adName.text = passedData as String
}
}
| gpl-2.0 | 2d73771c4301b26d5b35972ecd40ccb9 | 43.10362 | 171 | 0.546442 | 5.315825 | false | false | false | false |
HabitRPG/habitrpg-ios | HabitRPG/TableViewDataSources/GuildsOverviewDataSource.swift | 1 | 3973 | //
// GuildsOverviewDataSource.swift
// Habitica
//
// Created by Phillip Thelen on 02.04.18.
// Copyright © 2018 HabitRPG Inc. All rights reserved.
//
import Foundation
import Habitica_Models
import ReactiveSwift
class GuildsOverviewDataSource: BaseReactiveTableViewDataSource<GroupProtocol> {
@objc var predicate: NSPredicate? {
didSet {
fetchGuilds()
}
}
var isShowingPrivateGuilds: Bool = true {
didSet {
updatePredicate()
}
}
var searchText: String? {
didSet {
updatePredicate()
}
}
var invitationListView: GroupInvitationListView?
private var fetchGuildsDisposable: Disposable?
private let socialRepository = SocialRepository()
private let userRepository = UserRepository()
private var membershipIDs = [String]()
override init() {
super.init()
sections.append(ItemSection<GroupProtocol>())
fetchGuilds()
self.predicate = getPredicate()
disposable.add(socialRepository.getGroupMemberships().on(value: {[weak self]memberships, _ in
self?.membershipIDs.removeAll()
memberships.forEach({ (membership) in
if let groupID = membership.groupID {
self?.membershipIDs.append(groupID)
}
})
self?.updatePredicate()
}).start())
disposable.add(userRepository.getUser().on(value: {[weak self] user in
self?.invitationListView?.set(invitations: user.invitations.filter({ (invitation) -> Bool in
return !invitation.isPartyInvitation
}))
self?.tableView?.setNeedsLayout()
}).start())
}
private func fetchGuilds() {
if let disposable = fetchGuildsDisposable, !disposable.isDisposed {
disposable.dispose()
}
if let predicate = self.predicate {
DispatchQueue.main.async {[weak self] in
self?.fetchGuildsDisposable = self?.socialRepository.getGroups(predicate: predicate).on(value: {[weak self](guilds, changes) in
self?.sections[0].items = guilds
self?.notify(changes: changes)
}).start()
}
}
}
override func retrieveData(completed: (() -> Void)?) {
var guildType = "guilds"
if !isShowingPrivateGuilds {
guildType = "privateGuilds,publicGuilds"
}
socialRepository.retrieveGroups(guildType).observeCompleted {
if let action = completed {
action()
}
}
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: isShowingPrivateGuilds ? "MyGuildCell" : "PublicGuildCell", for: indexPath)
if let guild = item(at: indexPath) {
if let myGuildCell = cell as? MyGuildCell {
myGuildCell.configure(group: guild)
} else if let publicGuildCell = cell as? PublicGuildCell {
publicGuildCell.configure(group: guild)
}
}
return cell
}
private func updatePredicate() {
predicate = getPredicate()
}
private func getPredicate() -> NSPredicate {
var predicates = [NSPredicate]()
if isShowingPrivateGuilds {
predicates.append(NSPredicate(format: "type == 'guild' && id IN %@", membershipIDs))
} else {
predicates.append(NSPredicate(format: "type == 'guild'"))
}
if let searchText = searchText, searchText.isEmpty == false {
predicates.append(NSPredicate(format: "name CONTAINS[cd] %@ || summary CONTAINS[cd] %@", searchText, searchText))
}
return NSCompoundPredicate(andPredicateWithSubpredicates: predicates)
}
}
| gpl-3.0 | b3c1582ca934f74a784fc325b6c6ebf6 | 32.378151 | 140 | 0.597936 | 5.226316 | false | false | false | false |
RoRoche/iOSSwiftStarter | iOSSwiftStarter/Pods/ReactKit/ReactKit/UIKit/UIGestureRecognizer+Stream.swift | 4 | 1254 | //
// UIGestureRecognizer+Stream.swift
// ReactKit
//
// Created by Yasuhiro Inami on 2014/10/03.
// Copyright (c) 2014年 Yasuhiro Inami. All rights reserved.
//
import UIKit
// NOTE: see also UIControl+Stream
public extension UIGestureRecognizer
{
public func stream<T>(map: UIGestureRecognizer? -> T) -> Stream<T>
{
return Stream<T> { [weak self] progress, fulfill, reject, configure in
let target = _TargetActionProxy { (self_: AnyObject?) in
progress(map(self_ as? UIGestureRecognizer))
}
configure.pause = {
if let self_ = self {
self_.removeTarget(target, action: _targetActionSelector)
}
}
configure.resume = {
if let self_ = self {
self_.addTarget(target, action: _targetActionSelector)
}
}
configure.cancel = {
if let self_ = self {
self_.removeTarget(target, action: _targetActionSelector)
}
}
configure.resume?()
}.name("\(_summary(self))") |> takeUntil(self.deinitStream)
}
} | apache-2.0 | a61173e3b396f4a2e887c5acfe02dd60 | 28.833333 | 78 | 0.51278 | 4.871595 | false | true | false | false |
woshishui1243/LYCustomEmoticonKeyboard | Source/EmoticonCellView.swift | 1 | 2757 | //
// EmoticonCellView.swift
// LYCustomEmotionKeyboard
//
// Created by 李禹 on 15/11/30.
// Copyright © 2015年 dayu. All rights reserved.
//
import UIKit
class EmoticonCellView: UIButton {
override init(frame: CGRect) {
super.init(frame: frame);
self.adjustsImageWhenHighlighted = false;
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder);
self.adjustsImageWhenHighlighted = false;
}
var emoticon: Emoticon? {
didSet {
if emoticon!.isDeleteBtn {
var image = UIImage(named: emoticon!.png!);
if ((UIDevice.currentDevice().systemVersion as NSString).floatValue >= 7.0) {
image = image?.imageWithRenderingMode(UIImageRenderingMode.AlwaysOriginal);
}
self.setImage(image, forState: UIControlState.Normal);
self.setTitle(nil, forState: UIControlState.Normal);
}else if let name = emoticon!.png {
UIView.setAnimationsEnabled(false);
let bundlePath = (NSBundle.mainBundle().pathForResource("Emoticons.bundle", ofType: nil) as NSString!);
let path = (bundlePath.stringByAppendingPathComponent(emoticon!.emoticon_group_path!) as NSString).stringByAppendingPathComponent(name);
var image = UIImage(contentsOfFile: path);
if ((UIDevice.currentDevice().systemVersion as NSString).floatValue >= 7.0) {
image = image?.imageWithRenderingMode(UIImageRenderingMode.AlwaysOriginal);
}
self.setImage(image, forState: UIControlState.Normal);
self.setTitle(nil, forState: UIControlState.Normal);
let delayInSeconds = 0.1;
let popTime = dispatch_time(DISPATCH_TIME_NOW, Int64(delayInSeconds * Double(NSEC_PER_SEC)))
dispatch_after(popTime, dispatch_get_main_queue()) { () -> Void in
UIView.setAnimationsEnabled(true);
}
}else if let emoji = emoticon!.emoji {
UIView.setAnimationsEnabled(false);
self.titleLabel!.font = UIFont.systemFontOfSize(32)
self.setTitle(emoji, forState: UIControlState.Normal);
self.setImage(nil, forState: UIControlState.Normal);
let delayInSeconds = 0.1;
let popTime = dispatch_time(DISPATCH_TIME_NOW, Int64(delayInSeconds * Double(NSEC_PER_SEC)))
dispatch_after(popTime, dispatch_get_main_queue()) { () -> Void in
UIView.setAnimationsEnabled(true);
}
}
}
}
}
| mit | 47f9e85f932ad6df2be7b75369a7ac30 | 40.044776 | 152 | 0.586545 | 5.228137 | false | false | false | false |
blockchain/My-Wallet-V3-iOS | Blockchain/Announcements/Kinds/OneTime/ApplePayAnnouncement.swift | 1 | 3496 | // Copyright © Blockchain Luxembourg S.A. All rights reserved.
import AnalyticsKit
import DIKit
import PlatformKit
import PlatformUIKit
import RxCocoa
import RxSwift
import SwiftUI
import ToolKit
/// Announcement that introduces Apple Pay
final class ApplePayAnnouncement: OneTimeAnnouncement, ActionableAnnouncement {
private typealias LocalizedString = LocalizationConstants.AnnouncementCards.ApplePay
// MARK: - Properties
var viewModel: AnnouncementCardViewModel {
let button = ButtonViewModel.primary(
with: LocalizedString.ctaButton,
background: .primaryButton
)
button.tapRelay
.bind { [weak self] in
guard let self = self else { return }
self.analyticsRecorder.record(event: self.actionAnalyticsEvent)
self.markRemoved()
self.action()
self.dismiss()
}
.disposed(by: disposeBag)
return AnnouncementCardViewModel(
type: type,
badgeImage: .init(
image: .local(name: "icon-applepay", bundle: .platformUIKit),
contentColor: nil,
backgroundColor: .clear,
cornerRadius: .none,
size: .edge(40)
),
title: LocalizedString.title,
description: LocalizedString.description,
buttons: [button],
dismissState: .dismissible { [weak self] in
guard let self = self else { return }
self.analyticsRecorder.record(event: self.dismissAnalyticsEvent)
self.markRemoved()
self.dismiss()
},
didAppear: { [weak self] in
guard let self = self else { return }
self.analyticsRecorder.record(event: self.didAppearAnalyticsEvent)
}
)
}
var associatedAppModes: [AppMode] {
[AppMode.trading, AppMode.legacy]
}
var shouldShow: Bool {
!isDismissed
}
let type = AnnouncementType.applePay
let analyticsRecorder: AnalyticsEventRecorderAPI
let dismiss: CardAnnouncementAction
let recorder: AnnouncementRecorder
let action: CardAnnouncementAction
private let disposeBag = DisposeBag()
// MARK: - Setup
init(
cacheSuite: CacheSuite = resolve(),
analyticsRecorder: AnalyticsEventRecorderAPI = resolve(),
errorRecorder: ErrorRecording = CrashlyticsRecorder(),
dismiss: @escaping CardAnnouncementAction,
action: @escaping CardAnnouncementAction
) {
recorder = AnnouncementRecorder(cache: cacheSuite, errorRecorder: errorRecorder)
self.analyticsRecorder = analyticsRecorder
self.dismiss = dismiss
self.action = action
}
}
// MARK: SwiftUI Preview
#if DEBUG
struct ApplePayAnnouncementContainer: UIViewRepresentable {
typealias UIViewType = AnnouncementCardView
func makeUIView(context: Context) -> UIViewType {
let presenter = ApplePayAnnouncement(dismiss: {}, action: {})
return AnnouncementCardView(using: presenter.viewModel)
}
func updateUIView(_ uiView: UIViewType, context: Context) {}
}
struct ApplePayAnnouncementContainer_Previews: PreviewProvider {
static var previews: some View {
Group {
ApplePayAnnouncementContainer().colorScheme(.light)
}.previewLayout(.fixed(width: 375, height: 250))
}
}
#endif
| lgpl-3.0 | cef646063d363c752d9827efb3c62e1d | 29.929204 | 88 | 0.637196 | 5.512618 | false | false | false | false |
NordicSemiconductor/IOS-Pods-DFU-Library | Example/iOSDFULibrary/DFU Test Performer/DFUTestSet.swift | 1 | 4610 | /*
* Copyright (c) 2019, Nordic Semiconductor
* 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.
*
* 3. Neither the name of the copyright holder nor the names of its contributors may
* be used to endorse or promote products derived from this software without
* specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
* IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
* INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
* WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
import Foundation
import iOSDFULibrary
import CoreBluetooth
enum DFUTestError : Error {
case fileNotFound
case invalidFirmware
}
typealias AdvertisingData = [String : Any]
typealias Filter = (AdvertisingData) -> Bool
typealias ServiceModifier = (DFUServiceInitiator) -> ()
protocol DFUTestSet {
/**
The list contains number of tripples:
[0] firmware to be sent in this step,
[1] DfuServiceInitiator modifier,
[2] step description to show on the screen,
[3] optional expected error, in case the test is expected to fail,
[4] filter method to be used to find the next target. The first map is the advertisement data.
The last step returns nil as 'next'.
*/
var steps: [(firmware: DFUFirmware, options: ServiceModifier?, expectedError: DFUError?, description: String, next: Filter?)]? { get }
}
extension DFUTestSet {
var totalParts: Int {
guard let steps = steps else {
return 0
}
var i = 0
for step in steps {
i += step.firmware.parts
}
return i
}
}
class FilterBy {
static func name(_ name: String) -> Filter? {
return {
(advertisementData: AdvertisingData) -> Bool in
return advertisementData[CBAdvertisementDataLocalNameKey] as! String? == name
}
}
}
class Option {
static let prn : (UInt16) -> ServiceModifier = {
aPRNValue in
return {
initiator in initiator.packetReceiptNotificationParameter = aPRNValue
}
}
static let experimentalButtonlessEnabled : ServiceModifier = {
initiator in initiator.enableUnsafeExperimentalButtonlessServiceInSecureDfu = true
}
}
extension DFUFirmware {
private static func from(urlToZipFile url: URL?, type: DFUFirmwareType) throws -> DFUFirmware {
guard url != nil else {
throw DFUTestError.fileNotFound
}
let firmware = DFUFirmware(urlToZipFile: url!, type: type)
guard firmware != nil else {
throw DFUTestError.invalidFirmware
}
return firmware!
}
static func from(zip name: String, locatedIn subdirectory: String) throws -> DFUFirmware {
let url = Bundle.main.url(forResource: name, withExtension: "zip", subdirectory: subdirectory)
return try DFUFirmware.from(urlToZipFile: url, type: .softdeviceBootloaderApplication)
}
static func from(zip name: String, locatedIn subdirectory: String, withType type: DFUFirmwareType) throws -> DFUFirmware {
let url = Bundle.main.url(forResource: name, withExtension: "zip", subdirectory: subdirectory)
return try DFUFirmware.from(urlToZipFile: url, type: type)
}
static func fromCustomZip() throws -> DFUFirmware {
let urls = Bundle.main.urls(forResourcesWithExtension: "zip", subdirectory: "Firmwares/Custom")
return try DFUFirmware.from(urlToZipFile: urls?.first, type: .softdeviceBootloaderApplication)
}
}
| bsd-3-clause | 838abcf49382da107a33dbcffdd2cc49 | 35.88 | 138 | 0.699783 | 4.723361 | false | false | false | false |
qiuncheng/study-for-swift | learn-rx-swift/Chocotastic-starter/Pods/RxSwift/RxSwift/Observables/Observable+Time.swift | 3 | 12744 | //
// Observable+Time.swift
// Rx
//
// Created by Krunoslav Zaher on 3/22/15.
// Copyright © 2015 Krunoslav Zaher. All rights reserved.
//
import Foundation
// MARK: throttle
extension ObservableType {
/**
Returns an Observable that emits the first and the latest item emitted by the source Observable during sequential time windows of a specified duration.
This operator makes sure that no two elements are emitted in less then dueTime.
- seealso: [debounce operator on reactivex.io](http://reactivex.io/documentation/operators/debounce.html)
- parameter dueTime: Throttling duration for each element.
- parameter latest: Should latest element received in a dueTime wide time window since last element emission be emitted.
- parameter scheduler: Scheduler to run the throttle timers and send events on.
- returns: The throttled sequence.
*/
// @warn_unused_result(message:"http://git.io/rxs.uo")
public func throttle(_ dueTime: RxTimeInterval, latest: Bool = true, scheduler: SchedulerType)
-> Observable<E> {
return Throttle(source: self.asObservable(), dueTime: dueTime, latest: latest, scheduler: scheduler)
}
/**
Ignores elements from an observable sequence which are followed by another element within a specified relative time duration, using the specified scheduler to run throttling timers.
- seealso: [debounce operator on reactivex.io](http://reactivex.io/documentation/operators/debounce.html)
- parameter dueTime: Throttling duration for each element.
- parameter scheduler: Scheduler to run the throttle timers and send events on.
- returns: The throttled sequence.
*/
// @warn_unused_result(message:"http://git.io/rxs.uo")
public func debounce(_ dueTime: RxTimeInterval, scheduler: SchedulerType)
-> Observable<E> {
return Debounce(source: self.asObservable(), dueTime: dueTime, scheduler: scheduler)
}
}
// MARK: sample
extension ObservableType {
/**
Samples the source observable sequence using a samper observable sequence producing sampling ticks.
Upon each sampling tick, the latest element (if any) in the source sequence during the last sampling interval is sent to the resulting sequence.
**In case there were no new elements between sampler ticks, no element is sent to the resulting sequence.**
- seealso: [sample operator on reactivex.io](http://reactivex.io/documentation/operators/sample.html)
- parameter sampler: Sampling tick sequence.
- returns: Sampled observable sequence.
*/
// @warn_unused_result(message:"http://git.io/rxs.uo")
public func sample<O: ObservableType>(_ sampler: O)
-> Observable<E> {
return Sample(source: self.asObservable(), sampler: sampler.asObservable(), onlyNew: true)
}
}
extension Observable where Element : SignedInteger {
/**
Returns an observable sequence that produces a value after each period, using the specified scheduler to run timers and to send out observer messages.
- seealso: [interval operator on reactivex.io](http://reactivex.io/documentation/operators/interval.html)
- parameter period: Period for producing the values in the resulting sequence.
- parameter scheduler: Scheduler to run the timer on.
- returns: An observable sequence that produces a value after each period.
*/
// @warn_unused_result(message:"http://git.io/rxs.uo")
public static func interval(_ period: RxTimeInterval, scheduler: SchedulerType)
-> Observable<E> {
return Timer(dueTime: period,
period: period,
scheduler: scheduler
)
}
}
// MARK: timer
extension Observable where Element: SignedInteger {
/**
Returns an observable sequence that periodically produces a value after the specified initial relative due time has elapsed, using the specified scheduler to run timers.
- seealso: [timer operator on reactivex.io](http://reactivex.io/documentation/operators/timer.html)
- parameter dueTime: Relative time at which to produce the first value.
- parameter period: Period to produce subsequent values.
- parameter scheduler: Scheduler to run timers on.
- returns: An observable sequence that produces a value after due time has elapsed and then each period.
*/
// @warn_unused_result(message:"http://git.io/rxs.uo")
public static func timer(_ dueTime: RxTimeInterval, period: RxTimeInterval? = nil, scheduler: SchedulerType)
-> Observable<E> {
return Timer(
dueTime: dueTime,
period: period,
scheduler: scheduler
)
}
}
// MARK: take
extension ObservableType {
/**
Takes elements for the specified duration from the start of the observable source sequence, using the specified scheduler to run timers.
- seealso: [take operator on reactivex.io](http://reactivex.io/documentation/operators/take.html)
- parameter duration: Duration for taking elements from the start of the sequence.
- parameter scheduler: Scheduler to run the timer on.
- returns: An observable sequence with the elements taken during the specified duration from the start of the source sequence.
*/
// @warn_unused_result(message:"http://git.io/rxs.uo")
public func take(_ duration: RxTimeInterval, scheduler: SchedulerType)
-> Observable<E> {
return TakeTime(source: self.asObservable(), duration: duration, scheduler: scheduler)
}
}
// MARK: skip
extension ObservableType {
/**
Skips elements for the specified duration from the start of the observable source sequence, using the specified scheduler to run timers.
- seealso: [skip operator on reactivex.io](http://reactivex.io/documentation/operators/skip.html)
- parameter duration: Duration for skipping elements from the start of the sequence.
- parameter scheduler: Scheduler to run the timer on.
- returns: An observable sequence with the elements skipped during the specified duration from the start of the source sequence.
*/
// @warn_unused_result(message:"http://git.io/rxs.uo")
public func skip(_ duration: RxTimeInterval, scheduler: SchedulerType)
-> Observable<E> {
return SkipTime(source: self.asObservable(), duration: duration, scheduler: scheduler)
}
}
// MARK: ignoreElements
extension ObservableType {
/**
Skips elements and completes (or errors) when the receiver completes (or errors). Equivalent to filter that always returns false.
- seealso: [ignoreElements operator on reactivex.io](http://reactivex.io/documentation/operators/ignoreelements.html)
- returns: An observable sequence that skips all elements of the source sequence.
*/
// @warn_unused_result(message:"http://git.io/rxs.uo")
public func ignoreElements()
-> Observable<E> {
return filter { _ -> Bool in
return false
}
}
}
// MARK: delaySubscription
extension ObservableType {
/**
Time shifts the observable sequence by delaying the subscription with the specified relative time duration, using the specified scheduler to run timers.
- seealso: [delay operator on reactivex.io](http://reactivex.io/documentation/operators/delay.html)
- parameter dueTime: Relative time shift of the subscription.
- parameter scheduler: Scheduler to run the subscription delay timer on.
- returns: Time-shifted sequence.
*/
// @warn_unused_result(message:"http://git.io/rxs.uo")
public func delaySubscription(_ dueTime: RxTimeInterval, scheduler: SchedulerType)
-> Observable<E> {
return DelaySubscription(source: self.asObservable(), dueTime: dueTime, scheduler: scheduler)
}
}
// MARK: buffer
extension ObservableType {
/**
Projects each element of an observable sequence into a buffer that's sent out when either it's full or a given amount of time has elapsed, using the specified scheduler to run timers.
A useful real-world analogy of this overload is the behavior of a ferry leaving the dock when all seats are taken, or at the scheduled time of departure, whichever event occurs first.
- seealso: [buffer operator on reactivex.io](http://reactivex.io/documentation/operators/buffer.html)
- parameter timeSpan: Maximum time length of a buffer.
- parameter count: Maximum element count of a buffer.
- parameter scheduler: Scheduler to run buffering timers on.
- returns: An observable sequence of buffers.
*/
// @warn_unused_result(message:"http://git.io/rxs.uo")
public func buffer(timeSpan: RxTimeInterval, count: Int, scheduler: SchedulerType)
-> Observable<[E]> {
return BufferTimeCount(source: self.asObservable(), timeSpan: timeSpan, count: count, scheduler: scheduler)
}
}
// MARK: window
extension ObservableType {
/**
Projects each element of an observable sequence into a window that is completed when either it’s full or a given amount of time has elapsed.
- seealso: [window operator on reactivex.io](http://reactivex.io/documentation/operators/window.html)
- parameter timeSpan: Maximum time length of a window.
- parameter count: Maximum element count of a window.
- parameter scheduler: Scheduler to run windowing timers on.
- returns: An observable sequence of windows (instances of `Observable`).
*/
// @warn_unused_result(message:"http://git.io/rxs.uo")
public func window(timeSpan: RxTimeInterval, count: Int, scheduler: SchedulerType)
-> Observable<Observable<E>> {
return WindowTimeCount(source: self.asObservable(), timeSpan: timeSpan, count: count, scheduler: scheduler)
}
}
// MARK: timeout
extension ObservableType {
/**
Applies a timeout policy for each element in the observable sequence. If the next element isn't received within the specified timeout duration starting from its predecessor, a TimeoutError is propagated to the observer.
- seealso: [timeout operator on reactivex.io](http://reactivex.io/documentation/operators/timeout.html)
- parameter dueTime: Maximum duration between values before a timeout occurs.
- parameter scheduler: Scheduler to run the timeout timer on.
- returns: An observable sequence with a TimeoutError in case of a timeout.
*/
// @warn_unused_result(message:"http://git.io/rxs.uo")
public func timeout(_ dueTime: RxTimeInterval, scheduler: SchedulerType)
-> Observable<E> {
return Timeout(source: self.asObservable(), dueTime: dueTime, other: Observable.error(RxError.timeout), scheduler: scheduler)
}
/**
Applies a timeout policy for each element in the observable sequence, using the specified scheduler to run timeout timers. If the next element isn't received within the specified timeout duration starting from its predecessor, the other observable sequence is used to produce future messages from that point on.
- seealso: [timeout operator on reactivex.io](http://reactivex.io/documentation/operators/timeout.html)
- parameter dueTime: Maximum duration between values before a timeout occurs.
- parameter other: Sequence to return in case of a timeout.
- parameter scheduler: Scheduler to run the timeout timer on.
- returns: The source sequence switching to the other sequence in case of a timeout.
*/
// @warn_unused_result(message:"http://git.io/rxs.uo")
public func timeout<O: ObservableConvertibleType>(_ dueTime: RxTimeInterval, other: O, scheduler: SchedulerType)
-> Observable<E> where E == O.E {
return Timeout(source: self.asObservable(), dueTime: dueTime, other: other.asObservable(), scheduler: scheduler)
}
}
// MARK: delay
extension ObservableType {
/**
Returns an observable sequence by the source observable sequence shifted forward in time by a specified delay. Error events from the source observable sequence are not delayed.
- seealso: [delay operator on reactivex.io](http://reactivex.io/documentation/operators/delay.html)
- parameter dueTime: Relative time shift of the source by.
- parameter scheduler: Scheduler to run the subscription delay timer on.
- returns: the source Observable shifted in time by the specified delay.
*/
// @warn_unused_result(message="http://git.io/rxs.uo")
public func delay(_ dueTime: RxTimeInterval, scheduler: SchedulerType)
-> Observable<E> {
return Delay(source: self.asObservable(), dueTime: dueTime, scheduler: scheduler)
}
}
| mit | 95164eb091b9ec231121df97e5d66fa8 | 42.484642 | 316 | 0.709442 | 4.770124 | false | false | false | false |
calkinssean/TIY-Assignments | Day 14/iReview/BorderButton.swift | 1 | 672 | //
// BorderButton.swift
// iReview
//
// Created by Sean Calkins on 2/18/16.
// Copyright © 2016 Sean Calkins. All rights reserved.
//
import UIKit
import QuartzCore
@IBDesignable
class BorderButton: UIButton {
@IBInspectable var cornerRadius: CGFloat = 0 {
didSet {
layer.cornerRadius = cornerRadius
layer.masksToBounds = cornerRadius > 0
}
}
@IBInspectable var borderWidth: CGFloat = 0 {
didSet {
layer.borderWidth = borderWidth
}
}
@IBInspectable var borderColor: UIColor? {
didSet {
layer.borderColor = borderColor?.CGColor
}
}
}
| cc0-1.0 | 57fbad8ae2f01ecdb4f7423b06269941 | 19.96875 | 55 | 0.596125 | 4.725352 | false | false | false | false |
Karumi/BothamNetworking | BothamNetworking/HTTPEncoder.swift | 1 | 4273 | //
// HTTPEncoder.swift
// BothamNetworking
//
// Created by Pedro Vicente Gomez on 29/12/15.
// Copyright © 2015 GoKarumi S.L. All rights reserved.
//
import Foundation
class HTTPEncoder {
/**
Given a HTTPRequest instance performs the body encoding based on a Content-Type request header.
This class only supports two different encodings: "application/x-www-form-urlencoded"
and "application/json".
If the request does not contain any "Content-Type" header the body is not encoded and the return
value is nil.
@param request to encode
@return encoded body based on the request headers or nil if there is no any valid Content-Type
configured.
*/
static func encodeBody(_ request: HTTPRequest) -> Data? {
let contentType = request.headers?["Content-Type"] ?? ""
switch contentType {
case "application/x-www-form-urlencoded":
return query(request.body).data(
using: String.Encoding.utf8,
allowLossyConversion: false)
case "application/json":
if let body = request.body {
let options = JSONSerialization.WritingOptions()
return try? JSONSerialization.data(withJSONObject: body, options: options)
} else {
return nil
}
default:
return nil
}
}
// The x-www-form-urlencoded code comes from this repository https://github.com/Alamofire/Alamofire
private static func query(_ parameters: [String: AnyObject]?) -> String {
guard let parameters = parameters else {
return ""
}
var components: [(String, String)] = []
for key in parameters.keys.sorted(by: <) {
let value = parameters[key]!
components += queryComponents(key, String(describing: value))
}
return (components.map { "\($0)=\($1)" }).joined(separator: "&")
}
private static func queryComponents(_ key: String, _ value: String?) -> [(String, String)] {
var components: [(String, String)] = []
if let value = value {
components.append((escape(key), escape("\(value)")))
} else {
components.append((escape(key), ""))
}
return components
}
private static func escape(_ string: String) -> String {
let generalDelimitersToEncode = ":#[]@" // does not include "?" or "/" due to RFC 3986 - Section 3.4
let subDelimitersToEncode = "!$&'()*+,;="
let allowedCharacterSet = (CharacterSet.urlQueryAllowed as NSCharacterSet)
.mutableCopy() as! NSMutableCharacterSet
allowedCharacterSet.removeCharacters(in: generalDelimitersToEncode + subDelimitersToEncode)
var escaped = ""
//===================================================================================================
//
// Batching is required for escaping due to an internal bug in iOS 8.1 and 8.2. Encoding more than a few
// hundred Chinense characters causes various malloc error crashes. To avoid this issue until iOS 8 is no
// longer supported, batching MUST be used for encoding. This introduces roughly a 20% overhead. For more
// info, please refer to:
//
// - https://github.com/Alamofire/Alamofire/issues/206
//
//===================================================================================================
if #available(iOS 8.3, *) {
escaped = string.addingPercentEncoding(withAllowedCharacters: allowedCharacterSet as CharacterSet) ?? string
} else {
let batchSize = 50
var index = string.startIndex
while index != string.endIndex {
let startIndex = index
let endIndex = string.index(index, offsetBy: batchSize, limitedBy: string.endIndex)!
let substring = string[startIndex..<endIndex]
escaped += substring.addingPercentEncoding(withAllowedCharacters: allowedCharacterSet as CharacterSet)
?? String(substring)
index = endIndex
}
}
return escaped
}
}
| apache-2.0 | bf19881acc3638a1b433230ba85d8f10 | 36.473684 | 120 | 0.573268 | 5.3601 | false | false | false | false |
DzinVision/digit-recogniser-ios | Digit Recogniser/DrawView.swift | 1 | 3770 | //
// DrawView.swift
// Digit Recogniser
//
// Created by Vid Drobnič on 28/01/2017.
// Copyright © 2017 Vid Drobnič. All rights reserved.
//
import UIKit
protocol DrawViewDelegate: class {
func drawViewDidDraw(image: String)
}
class DrawView: UIView {
let path = UIBezierPath()
var incrementalImage: UIImage?
var points = [CGPoint](repeating: CGPoint(), count: 5)
var ctr = 0
var timers = [Timer]()
let lineWidth: CGFloat = 6.0
weak var delegate: DrawViewDelegate?
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
isMultipleTouchEnabled = false
backgroundColor = UIColor.white
path.lineWidth = lineWidth
setBorder()
}
override init(frame: CGRect) {
super.init(frame: frame)
isMultipleTouchEnabled = false
path.lineWidth = lineWidth
setBorder()
}
func setBorder() {
layer.borderColor = UIColor.black.cgColor
layer.borderWidth = 3.0
}
override func draw(_ rect: CGRect) {
incrementalImage?.draw(in: rect)
path.stroke()
}
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
for timer in timers {
timer.invalidate()
}
timers = []
ctr = 0
let touch = touches.first!
points[0] = touch.location(in: self)
}
override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {
let touch = touches.first!
let point = touch.location(in: self)
ctr += 1
points[ctr] = point
if ctr == 4 {
points[3] = CGPoint(x: (points[2].x + points[4].x)/2.0, y: (points[2].y + points[4].y)/2.0)
path.move(to: points[0])
path.addCurve(to: points[3], controlPoint1: points[1], controlPoint2: points[2])
setNeedsDisplay()
points[0] = points[3]
points[1] = points[4]
ctr = 1
}
}
override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
drawBitmap()
setNeedsDisplay()
path.removeAllPoints()
ctr = 0
let timer = Timer.scheduledTimer(withTimeInterval: 0.4, repeats: false) {timer in
if let pixelData = self.incrementalImage?.resizedImage().pixelData() {
var image = ""
for pixel in pixelData {
image += "\(pixel)"
}
self.delegate?.drawViewDidDraw(image: image)
}
UIGraphicsBeginImageContextWithOptions(self.bounds.size, true, 0.0)
let rectpath = UIBezierPath(rect: self.bounds)
UIColor.white.setFill()
rectpath.fill()
self.incrementalImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
self.setNeedsDisplay()
}
timers.append(timer)
}
override func touchesCancelled(_ touches: Set<UITouch>, with event: UIEvent?) {
touchesEnded(touches, with: event)
}
func drawBitmap() {
UIGraphicsBeginImageContextWithOptions(bounds.size, true, 0.0)
if incrementalImage == nil {
let rectpath = UIBezierPath(rect: bounds)
UIColor.white.setFill()
rectpath.fill()
}
incrementalImage?.draw(at: CGPoint())
UIColor.black.setStroke()
path.stroke()
incrementalImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
}
}
| gpl-3.0 | b365133022417b3106e6e691facb7c09 | 27.323308 | 103 | 0.554287 | 4.786531 | false | false | false | false |
anthonypuppo/GDAXSwift | GDAXSwift/Classes/GDAXAccountHold.swift | 1 | 1739 | //
// GDAX24HRStats.swift
// GDAXSwift
//
// Created by Anthony on 6/6/17.
// Copyright © 2017 Anthony Puppo. All rights reserved.
//
public struct GDAXAccountHold: JSONInitializable {
public let id: String
public let accountID: String
public let createdAt: Date
public let updatedAt: Date
public let amount: Double
public let type: GDAXAccountHoldType
public let ref: String
internal init(json: Any) throws {
var jsonData: Data?
if let json = json as? Data {
jsonData = json
} else {
jsonData = try JSONSerialization.data(withJSONObject: json, options: [])
}
guard let json = jsonData?.json else {
throw GDAXError.invalidResponseData
}
guard let id = json["id"] as? String else {
throw GDAXError.responseParsingFailure("id")
}
guard let accountID = json["account_id"] as? String else {
throw GDAXError.responseParsingFailure("account_id")
}
guard let createdAt = (json["created_at"] as? String)?.dateFromISO8601 else {
throw GDAXError.responseParsingFailure("created_at")
}
guard let updatedAt = (json["updated_at"] as? String)?.dateFromISO8601 else {
throw GDAXError.responseParsingFailure("updated_at")
}
guard let amount = Double(json["amount"] as? String ?? "") else {
throw GDAXError.responseParsingFailure("amount")
}
guard let type = GDAXAccountHoldType(rawValue: json["type"] as? String ?? "") else {
throw GDAXError.responseParsingFailure("type")
}
guard let ref = json["ref"] as? String else {
throw GDAXError.responseParsingFailure("ref")
}
self.id = id
self.accountID = accountID
self.createdAt = createdAt
self.updatedAt = updatedAt
self.amount = amount
self.type = type
self.ref = ref
}
}
| mit | e2fef7c0caa4ca9e00ac28617061dde1 | 24.188406 | 86 | 0.693326 | 3.713675 | false | false | false | false |
RobotRebels/SwiftLessons | students_trashspace/pnaumov/MyBaseGeometryFigure.playground/Contents.swift | 1 | 4022 | //: Playground - noun: a place where people can play
import UIKit
enum GeometryType {
case noType
case circle
case rectangle
}
protocol GeometryProtocol {
var centerX: Int { get set } // координата центра фигуры на оси X
var centerY: Int { get set } // координата центра фигуры на оси Y
var rotationAngle: Float { get set } // угол поворота фигуры относительно оси X
var length: Int { get set }
var width: Int { get set }
func calcPerimeter() -> Float // метод рассчитывающий периметр фигуры
func calcArea() -> Float // метод рассчитывающий площадь фигуры
}
class MyBaseGeometryFigure: GeometryProtocol {
private var color: MyBaseGeometryFigureTypeColor = .noColor
var type: GeometryType = .noType
var blah: String = "123"
var centerX: Int
var centerY: Int
var length: Int
var width: Int
var rotationAngle: Float
static let sidesCount: Int = 4
init(centerX: Int, centerY: Int, side: Int, rotationAngle: Float) {
self.width = side
self.length = side
self.centerX = centerX
self.centerY = centerY
self.rotationAngle = rotationAngle
}
func calcPerimeter() -> Float {
return Float(SquareFigure.sidesCount * width)
}
// площадь фигуры
func calcArea() -> Float {
return pow(Float(width), 2.0)
}
func squareColorType() {
print("Квадрат желтого цвета")
}
func circleColorType() {
print("Круг черного цвета")
}
func rectangleColorType() {
print("Прямоугольник синего цвета")
}
func rhombusColorType() {
print("Ромб красного цвета")
}
// установка нового цвета фигуры
func setNewColor(newColor: MyBaseGeometryFigureTypeColor) {
color = newColor
}
}
enum MyBaseGeometryFigureTypeColor: String {
case noColor = "Без цвета"
case red = "Красный"
case blue = "Синий"
case black = "Черный"
case yellow = "Желтый"
}
class SquareFigure: MyBaseGeometryFigure {
override init(centerX: Int, centerY: Int, side: Int, rotationAngle: Float) {
super.init(centerX: centerX, centerY: centerY, side: side, rotationAngle: rotationAngle)
type = .rectangle
}
func placeIntoAxisCenter() {
centerX = 0
centerY = 0
}
// проверка пересечения фигур
func isCrossingFigure(otherFigure: GeometryProtocol) -> Bool {
return false
}
override func setNewColor(newColor: MyBaseGeometryFigureTypeColor) {
super.setNewColor(newColor: newColor)
print("Цвет установлен ", newColor.rawValue)
}
func respaceNewColor() {
}
}
var aaa = SquareFigure(centerX: 111, centerY: 11, side: 111, rotationAngle: 11.1)
aaa.setNewColor(newColor: .red)
var bbb = MyBaseGeometryFigure(centerX: 111, centerY: 11, side: 111, rotationAngle: 11.1)
print(bbb.type)
//С учетом полученных знаний зарефакторить (переписать немного Ваш класс геометрической фигуры):
//- один из протоколов заменить на базовый класс;
//- придумать два перечисляемых типа (enum) - один с rawType - String и один с другим rawType, использовать эти типы в базовом классе или в протоколе или уже в Вашем классе;
//- обязательно сделать для одного из методов протокола дефолтную реализацию;
| mit | 0ff6fda21ac851f7a958b653a4fc0738 | 23.941176 | 174 | 0.651238 | 3.682953 | false | false | false | false |
OrangeJam/iSchool | iSchool/GradesTableViewController.swift | 1 | 4737 | //
// GradesTableViewController.swift
// iSchool
//
// Created by Kári Helgason on 16/09/14.
// Copyright (c) 2014 OrangeJam. All rights reserved.
//
import UIKit
class GradesTableViewController: UITableViewController, UITableViewDataSource, UITableViewDelegate {
@IBOutlet weak var emptyLabel: UILabel!
var data: ([[Grade]])?
@IBOutlet weak var gradsTitle: UINavigationItem!
override func viewDidLoad() {
self.refreshControl = UIRefreshControl()
self.refreshControl?.tintColor = UIColor.grayColor()
self.refreshControl?.addTarget(self,
action: "reloadData",
forControlEvents: .ValueChanged
)
self.emptyLabel.frame = CGRect(x: 0, y: 0, width: self.tableView.bounds.width, height: self.emptyLabel.frame.height)
// Set the text of the empty label.
self.emptyLabel.text = NSLocalizedString("No grades", comment: "Text for the empty label when there are no grades")
tableView.delegate = self
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
NSNotificationCenter.defaultCenter().addObserver(self,
selector: "refreshData",
name: Notification.grade.rawValue,
object: nil
)
NSNotificationCenter.defaultCenter().addObserver(self,
selector: "endRefresh",
name: Notification.networkError.rawValue,
object: nil
)
data = DataStore.sharedInstance.getGrades()
gradsTitle.title = NSLocalizedString("Grades", comment: "The title in the Grades view")
}
override func viewWillDisappear(animated: Bool) {
NSNotificationCenter.defaultCenter().removeObserver(self)
}
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
if let data = self.data {
self.emptyLabel.hidden = !(data.count == 0)
return data.count
} else {
self.emptyLabel.hidden = false
return 0
}
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if let section = data?[section] {
return section.count
} else {
return 0
}
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("GradesTableViewCell") as GradesTableViewCell
if let grade = data?[indexPath.section][indexPath.row] {
cell.SetGrade(grade)
}
return cell
}
override func tableView(tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
return CGFloat(30)
}
override func tableView(tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
let view = UIView(frame: CGRect(x: 0, y: 0, width: self.view.frame.size.width, height: 30))
view.backgroundColor = UIColor(white: 1.0, alpha: 0.95)
let label = UILabel(frame: CGRect(x: 20, y: 6, width: self.view.frame.size.width, height: 20))
if let title = data?[section].first?.course {
label.font = UIFont(name: "System", size: 10)
label.text = title
} else {
return nil
}
let redLine = UIView(frame: CGRect(x: 0, y: 29, width: self.view.frame.size.width, height: 1))
redLine.backgroundColor = UIColor(red: 204, green: 0, blue: 0, alpha: 1)
view.addSubview(label)
view.addSubview(redLine)
return view;
}
func refreshData() {
self.refreshControl?.endRefreshing()
data = DataStore.sharedInstance.getGrades()
self.tableView.reloadData()
}
func reloadData() {
DataStore.sharedInstance.fetchAssignments()
}
func endRefresh() {
refreshControl?.endRefreshing()
}
override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
if let detail = self.storyboard?.instantiateViewControllerWithIdentifier("DetailView") as? DetailViewController {
if let grade = data?[indexPath.section][indexPath.row] {
detail.setDetailForURL(NSURL(string: grade.URL)!, title: grade.name)
let bbItem = UIBarButtonItem(title: NSLocalizedString("Back", comment: "Back button to go back to grades table view"), style: .Plain, target: nil, action: nil)
navigationItem.backBarButtonItem = bbItem
navigationController?.pushViewController(detail, animated: true)
}
}
}
}
| bsd-3-clause | 0b3694c44cdabdadc5a21e0eca341049 | 36.291339 | 175 | 0.634291 | 4.923077 | false | false | false | false |
zapdroid/RXWeather | Pods/Nimble/Sources/Lib/CwlPreconditionTesting/CwlPreconditionTesting/CwlCatchBadInstruction.swift | 1 | 10098 | //
// CwlCatchBadInstruction.swift
// CwlPreconditionTesting
//
// Created by Matt Gallagher on 2016/01/10.
// Copyright © 2016 Matt Gallagher ( http://cocoawithlove.com ). All rights reserved.
//
// Permission to use, copy, modify, and/or distribute this software for any
// purpose with or without fee is hereby granted, provided that the above
// copyright notice and this permission notice appear in all copies.
//
// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
// WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
// MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
// SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
// WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
// ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR
// IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
//
import Foundation
#if SWIFT_PACKAGE
import CwlCatchException
import CwlMachBadInstructionHandler
#endif
#if arch(x86_64)
private enum PthreadError: Error { case code(Int32) }
private enum MachExcServer: Error { case code(kern_return_t) }
/// A quick function for converting Mach error results into Swift errors
private func kernCheck(_ f: () -> Int32) throws {
let r = f()
guard r == KERN_SUCCESS else {
throw NSError(domain: NSMachErrorDomain, code: Int(r), userInfo: nil)
}
}
extension execTypesCountTuple {
mutating func pointer<R>(in block: (UnsafeMutablePointer<T>) -> R) -> R {
return withUnsafeMutablePointer(to: &self) { p -> R in
p.withMemoryRebound(to: T.self, capacity: EXC_TYPES_COUNT) { ptr -> R in
return block(ptr)
}
}
}
}
extension request_mach_exception_raise_t {
mutating func withMsgHeaderPointer<R>(in block: (UnsafeMutablePointer<mach_msg_header_t>) -> R) -> R {
return withUnsafeMutablePointer(to: &self) { p -> R in
p.withMemoryRebound(to: mach_msg_header_t.self, capacity: 1) { ptr -> R in
return block(ptr)
}
}
}
}
extension reply_mach_exception_raise_state_t {
mutating func withMsgHeaderPointer<R>(in block: (UnsafeMutablePointer<mach_msg_header_t>) -> R) -> R {
return withUnsafeMutablePointer(to: &self) { p -> R in
p.withMemoryRebound(to: mach_msg_header_t.self, capacity: 1) { ptr -> R in
return block(ptr)
}
}
}
}
/// A structure used to store context associated with the Mach message port
private struct MachContext {
var masks = execTypesCountTuple<exception_mask_t>()
var count: mach_msg_type_number_t = 0
var ports = execTypesCountTuple<mach_port_t>()
var behaviors = execTypesCountTuple<exception_behavior_t>()
var flavors = execTypesCountTuple<thread_state_flavor_t>()
var currentExceptionPort: mach_port_t = 0
var handlerThread: pthread_t?
mutating func withUnsafeMutablePointers<R>(in block: (UnsafeMutablePointer<exception_mask_t>, UnsafeMutablePointer<mach_port_t>, UnsafeMutablePointer<exception_behavior_t>, UnsafeMutablePointer<thread_state_flavor_t>) -> R) -> R {
return masks.pointer { masksPtr in
ports.pointer { portsPtr in
return behaviors.pointer { behaviorsPtr in
flavors.pointer { flavorsPtr in
return block(masksPtr, portsPtr, behaviorsPtr, flavorsPtr)
}
}
}
}
}
}
/// A function for receiving mach messages and parsing the first with mach_exc_server (and if any others are received, throwing them away).
private func machMessageHandler(_ arg: UnsafeMutableRawPointer) -> UnsafeMutableRawPointer? {
let context = arg.assumingMemoryBound(to: MachContext.self).pointee
var request = request_mach_exception_raise_t()
var reply = reply_mach_exception_raise_state_t()
var handledfirstException = false
repeat { do {
// Request the next mach message from the port
request.Head.msgh_local_port = context.currentExceptionPort
request.Head.msgh_size = UInt32(MemoryLayout<request_mach_exception_raise_t>.size)
try kernCheck { request.withMsgHeaderPointer { requestPtr in
mach_msg(requestPtr, MACH_RCV_MSG | MACH_RCV_INTERRUPT, 0, request.Head.msgh_size, context.currentExceptionPort, 0, UInt32(MACH_PORT_NULL))
} }
// Prepare the reply structure
reply.Head.msgh_bits = MACH_MSGH_BITS(MACH_MSGH_BITS_REMOTE(request.Head.msgh_bits), 0)
reply.Head.msgh_local_port = UInt32(MACH_PORT_NULL)
reply.Head.msgh_remote_port = request.Head.msgh_remote_port
reply.Head.msgh_size = UInt32(MemoryLayout<reply_mach_exception_raise_state_t>.size)
reply.NDR = NDR_record
if !handledfirstException {
// Use the MiG generated server to invoke our handler for the request and fill in the rest of the reply structure
guard request.withMsgHeaderPointer(in: { requestPtr in reply.withMsgHeaderPointer { replyPtr in
mach_exc_server(requestPtr, replyPtr)
} }) != 0 else { throw MachExcServer.code(reply.RetCode) }
handledfirstException = true
} else {
// If multiple fatal errors occur, don't handle subsquent errors (let the program crash)
reply.RetCode = KERN_FAILURE
}
// Send the reply
try kernCheck { reply.withMsgHeaderPointer { replyPtr in
mach_msg(replyPtr, MACH_SEND_MSG, reply.Head.msgh_size, 0, UInt32(MACH_PORT_NULL), 0, UInt32(MACH_PORT_NULL))
} }
} catch let error as NSError where error.domain == NSMachErrorDomain && (error.code == Int(MACH_RCV_PORT_CHANGED) || error.code == Int(MACH_RCV_INVALID_NAME)) {
// Port was already closed before we started or closed while we were listening.
// This means the controlling thread shut down.
return nil
} catch {
// Should never be reached but this is testing code, don't try to recover, just abort
fatalError("Mach message error: \(error)")
} } while true
}
/// Run the provided block. If a mach "BAD_INSTRUCTION" exception is raised, catch it and return a BadInstructionException (which captures stack information about the throw site, if desired). Otherwise return nil.
/// NOTE: This function is only intended for use in test harnesses – use in a distributed build is almost certainly a bad choice. If a "BAD_INSTRUCTION" exception is raised, the block will be exited before completion via Objective-C exception. The risks associated with an Objective-C exception apply here: most Swift/Objective-C functions are *not* exception-safe. Memory may be leaked and the program will not necessarily be left in a safe state.
/// - parameter block: a function without parameters that will be run
/// - returns: if an EXC_BAD_INSTRUCTION is raised during the execution of `block` then a BadInstructionException will be returned, otherwise `nil`.
public func catchBadInstruction(in block: () -> Void) -> BadInstructionException? {
var context = MachContext()
var result: BadInstructionException?
do {
var handlerThread: pthread_t?
defer {
// 8. Wait for the thread to terminate *if* we actually made it to the creation point
// The mach port should be destroyed *before* calling pthread_join to avoid a deadlock.
if handlerThread != nil {
pthread_join(handlerThread!, nil)
}
}
try kernCheck {
// 1. Create the mach port
mach_port_allocate(mach_task_self_, MACH_PORT_RIGHT_RECEIVE, &context.currentExceptionPort)
}
defer {
// 7. Cleanup the mach port
mach_port_destroy(mach_task_self_, context.currentExceptionPort)
}
try kernCheck {
// 2. Configure the mach port
mach_port_insert_right(mach_task_self_, context.currentExceptionPort, context.currentExceptionPort, MACH_MSG_TYPE_MAKE_SEND)
}
try kernCheck { context.withUnsafeMutablePointers { masksPtr, portsPtr, behaviorsPtr, flavorsPtr in
// 3. Apply the mach port as the handler for this thread
thread_swap_exception_ports(mach_thread_self(), EXC_MASK_BAD_INSTRUCTION, context.currentExceptionPort, Int32(bitPattern: UInt32(EXCEPTION_STATE) | MACH_EXCEPTION_CODES), x86_THREAD_STATE64, masksPtr, &context.count, portsPtr, behaviorsPtr, flavorsPtr)
} }
defer { context.withUnsafeMutablePointers { masksPtr, portsPtr, behaviorsPtr, flavorsPtr in
// 6. Unapply the mach port
_ = thread_swap_exception_ports(mach_thread_self(), EXC_MASK_BAD_INSTRUCTION, 0, EXCEPTION_DEFAULT, THREAD_STATE_NONE, masksPtr, &context.count, portsPtr, behaviorsPtr, flavorsPtr)
} }
try withUnsafeMutablePointer(to: &context) { c throws in
// 4. Create the thread
let e = pthread_create(&handlerThread, nil, machMessageHandler, c)
guard e == 0 else { throw PthreadError.code(e) }
// 5. Run the block
result = BadInstructionException.catchException(in: block)
}
} catch {
// Should never be reached but this is testing code, don't try to recover, just abort
fatalError("Mach port error: \(error)")
}
return result
}
#endif
| mit | c561a475e7955a9276ec3ff31673d97e | 49.984848 | 452 | 0.634473 | 4.609589 | false | false | false | false |
zapdroid/RXWeather | Pods/RxSwift/RxSwift/Subjects/PublishSubject.swift | 1 | 3938 | //
// PublishSubject.swift
// RxSwift
//
// Created by Krunoslav Zaher on 2/11/15.
// Copyright © 2015 Krunoslav Zaher. All rights reserved.
//
/// Represents an object that is both an observable sequence as well as an observer.
///
/// Each notification is broadcasted to all subscribed observers.
public final class PublishSubject<Element>
: Observable<Element>
, SubjectType
, Cancelable
, ObserverType
, SynchronizedUnsubscribeType {
public typealias SubjectObserverType = PublishSubject<Element>
typealias Observers = AnyObserver<Element>.s
typealias DisposeKey = Observers.KeyType
/// Indicates whether the subject has any observers
public var hasObservers: Bool {
_lock.lock()
let count = _observers.count > 0
_lock.unlock()
return count
}
private let _lock = RecursiveLock()
// state
private var _isDisposed = false
private var _observers = Observers()
private var _stopped = false
private var _stoppedEvent = nil as Event<Element>?
/// Indicates whether the subject has been isDisposed.
public var isDisposed: Bool {
return _isDisposed
}
/// Creates a subject.
public override init() {
super.init()
#if TRACE_RESOURCES
_ = Resources.incrementTotal()
#endif
}
/// Notifies all subscribed observers about next event.
///
/// - parameter event: Event to send to the observers.
public func on(_ event: Event<Element>) {
dispatch(_synchronized_on(event), event)
}
func _synchronized_on(_ event: Event<E>) -> Observers {
_lock.lock(); defer { _lock.unlock() }
switch event {
case .next:
if _isDisposed || _stopped {
return Observers()
}
return _observers
case .completed, .error:
if _stoppedEvent == nil {
_stoppedEvent = event
_stopped = true
let observers = _observers
_observers.removeAll()
return observers
}
return Observers()
}
}
/**
Subscribes an observer to the subject.
- parameter observer: Observer to subscribe to the subject.
- returns: Disposable object that can be used to unsubscribe the observer from the subject.
*/
public override func subscribe<O: ObserverType>(_ observer: O) -> Disposable where O.E == Element {
_lock.lock()
let subscription = _synchronized_subscribe(observer)
_lock.unlock()
return subscription
}
func _synchronized_subscribe<O: ObserverType>(_ observer: O) -> Disposable where O.E == E {
if let stoppedEvent = _stoppedEvent {
observer.on(stoppedEvent)
return Disposables.create()
}
if _isDisposed {
observer.on(.error(RxError.disposed(object: self)))
return Disposables.create()
}
let key = _observers.insert(observer.on)
return SubscriptionDisposable(owner: self, key: key)
}
func synchronizedUnsubscribe(_ disposeKey: DisposeKey) {
_lock.lock()
_synchronized_unsubscribe(disposeKey)
_lock.unlock()
}
func _synchronized_unsubscribe(_ disposeKey: DisposeKey) {
_ = _observers.removeKey(disposeKey)
}
/// Returns observer interface for subject.
public func asObserver() -> PublishSubject<Element> {
return self
}
/// Unsubscribe all observers and release resources.
public func dispose() {
_lock.lock()
_synchronized_dispose()
_lock.unlock()
}
final func _synchronized_dispose() {
_isDisposed = true
_observers.removeAll()
_stoppedEvent = nil
}
#if TRACE_RESOURCES
deinit {
_ = Resources.decrementTotal()
}
#endif
}
| mit | 94e8e3860de51314373c064a9393df12 | 26.725352 | 103 | 0.602235 | 4.97096 | false | false | false | false |
iosprogrammingwithswift/iosprogrammingwithswift | 04_Swift2015_Final.playground/Pages/14_Initialization.xcplaygroundpage/Contents.swift | 1 | 5163 | //: [Previous](@previous) | [Next](@next)
import UIKit
//: Setting Initial Values for Stored Properties
struct Fahrenheit {
var temperature: Double
init() {
temperature = 32.0
}
}
var f = Fahrenheit()
print("The default temperature is \(f.temperature)° Fahrenheit")
// prints "The default temperature is 32.0° Fahrenheit"
//: Initialization Parameters
struct Celsius {
var temperatureInCelsius: Double
init(fromFahrenheit fahrenheit: Double) {
temperatureInCelsius = (fahrenheit - 32.0) / 1.8
}
init(fromKelvin kelvin: Double) {
temperatureInCelsius = kelvin - 273.15
}
init(_ celsius: Double) {
temperatureInCelsius = celsius
}
}
let boilingPointOfWater = Celsius(fromFahrenheit: 212.0)
// boilingPointOfWater.temperatureInCelsius is 100.0
let freezingPointOfWater = Celsius(fromKelvin: 273.15)
// freezingPointOfWater.temperatureInCelsius is 0.0
let bodyTemperature = Celsius(37.0)
// bodyTemperature.temperatureInCelsius is 37.0
//: Optional Property Types
class SurveyQuestion {
var text: String
var response: String?
init(text: String) {
self.text = text
}
func ask() {
print(text)
}
}
let cheeseQuestion = SurveyQuestion(text: "Do you like cheese?")
cheeseQuestion.ask()
// prints "Do you like cheese?"
cheeseQuestion.response = "Yes, I do like cheese."
//: Default Initializers
class ShoppingListItemDefault {
var name: String?
var quantity = 1
var purchased = false
}
var item = ShoppingListItemDefault()
//: Class Inheritance and Initialization
/*:
Initializer Delegation for Class Types
To simplify the relationships between designated and convenience initializers, Swift applies the following three rules for delegation calls between initializers:
* Rule 1
A designated initializer must call a designated initializer from its immediate superclass.
* Rule 2
A convenience initializer must call another initializer from the same class.
* Rule 3
A convenience initializer must ultimately call a designated initializer.
A simple way to remember this is:
* Designated initializers must always delegate up.
* Convenience initializers must always delegate across.
*/
[#Image(imageLiteral: "initializerDelegation01_2x.png")#]
[#Image(imageLiteral: "initializerDelegation02_2x.png")#]
class Food {
var name: String
init(name: String) {
self.name = name
}
convenience init() {
self.init(name: "[Unnamed]")
}
}
[#Image(imageLiteral: "initializersExample01_2x.png")#]
let namedMeat = Food(name: "Bacon")
// namedMeat's name is "Bacon"
let mysteryMeat = Food()
// mysteryMeat's name is "[Unnamed]"
class RecipeIngredient: Food {
var quantity: Int
init(name: String, quantity: Int) {
self.quantity = quantity
super.init(name: name)
}
override convenience init(name: String) {
self.init(name: name, quantity: 1)
}
}
[#Image(imageLiteral: "initializersExample02_2x.png")#]
let oneMysteryItem = RecipeIngredient()
let oneBacon = RecipeIngredient(name: "Bacon")
let sixEggs = RecipeIngredient(name: "Eggs", quantity: 6)
class ShoppingListItem: RecipeIngredient {
var purchased = false
var description: String {
var output = "\(quantity) x \(name)"
output += purchased ? " ✔" : " ✘"
return output
}
}
[#Image(imageLiteral: "initializersExample03_2x.png")#]
var breakfastList = [
ShoppingListItem(),
ShoppingListItem(name: "Bacon"),
ShoppingListItem(name: "Eggs", quantity: 6),
]
breakfastList[0].name = "Orange juice"
breakfastList[0].purchased = true
for item in breakfastList {
print(item.description)
}
// 1 x Orange juice ✔
// 1 x Bacon ✘
// 6 x Eggs ✘
//: Failable Initializers
struct Animal {
let species: String
init?(species: String) {
if species.isEmpty { return nil }
self.species = species
}
}
let someCreature = Animal(species: "Giraffe")
// someCreature is of type Animal?, not Animal
if let giraffe = someCreature {
print("An animal was initialized with a species of \(giraffe.species)")
}
// prints "An animal was initialized with a species of Giraffe"
let anonymousCreature = Animal(species: "")
// anonymousCreature is of type Animal?, not Animal
if anonymousCreature == nil {
print("The anonymous creature could not be initialized")
}
// prints "The anonymous creature could not be initialized"
//: Required Initializers
class SomeClass {
required init() {
// initializer implementation goes here
}
}
class SomeSubclass: SomeClass {
required init() {
// subclass implementation of the required initializer goes here
}
}
/*:
largely Based of [Apple's Swift Language Guide: Initialization](https://developer.apple.com/library/ios/documentation/Swift/Conceptual/Swift_Programming_Language/Initialization.html#//apple_ref/doc/uid/TP40014097-CH18-ID203 ) & [Apple's A Swift Tour](https://developer.apple.com/library/ios/documentation/Swift/Conceptual/Swift_Programming_Language/GuidedTour.html#//apple_ref/doc/uid/TP40014097-CH2-ID1 )
*/
//: [Previous](@previous) | [Next](@next)
| mit | 3ef1ffd7335e94821c5738658a585a68 | 25.828125 | 405 | 0.706076 | 4.104382 | false | false | false | false |
Acidburn0zzz/firefox-ios | Sync/LoginPayload.swift | 9 | 4077 | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
import Foundation
import Shared
import XCGLogger
import SwiftyJSON
private let log = Logger.syncLogger
open class LoginPayload: CleartextPayloadJSON {
fileprivate static let OptionalStringFields = [
"formSubmitURL",
"httpRealm",
]
fileprivate static let OptionalNumericFields = [
"timeLastUsed",
"timeCreated",
"timePasswordChanged",
"timesUsed",
]
fileprivate static let RequiredStringFields = [
"hostname",
"username",
"password",
"usernameField",
"passwordField",
]
open class func fromJSON(_ json: JSON) -> LoginPayload? {
let p = LoginPayload(json)
if p.isValid() {
return p
}
return nil
}
override open func isValid() -> Bool {
if !super.isValid() {
return false
}
if self["deleted"].bool ?? false {
return true
}
if !LoginPayload.RequiredStringFields.every({ self[$0].isString() }) {
return false
}
if !LoginPayload.OptionalStringFields.every({ field in
let val = self[field]
// Yup, 404 is not found, so this means "string or nothing".
let valid = val.isString() || val.isNull() || val.error?.errorCode == 404
if !valid {
log.debug("Field \(field) is invalid: \(val)")
}
return valid
}) {
return false
}
if !LoginPayload.OptionalNumericFields.every({ field in
let val = self[field]
// Yup, 404 is not found, so this means "number or nothing".
// We only check for number because we're including timestamps as NSNumbers.
let valid = val.isNumber() || val.isNull() || val.error?.errorCode == 404
if !valid {
log.debug("Field \(field) is invalid: \(val)")
}
return valid
}) {
return false
}
return true
}
open var hostname: String {
return self["hostname"].string!
}
open var username: String {
return self["username"].string!
}
open var password: String {
return self["password"].string!
}
open var usernameField: String {
return self["usernameField"].string!
}
open var passwordField: String {
return self["passwordField"].string!
}
open var formSubmitURL: String? {
return self["formSubmitURL"].string
}
open var httpRealm: String? {
return self["httpRealm"].string
}
fileprivate func timestamp(_ field: String) -> Timestamp? {
let json = self[field]
if let i = json.int64, i > 0 {
return Timestamp(i)
}
return nil
}
open var timesUsed: Int? {
return self["timesUsed"].int
}
open var timeCreated: Timestamp? {
return self.timestamp("timeCreated")
}
open var timeLastUsed: Timestamp? {
return self.timestamp("timeLastUsed")
}
open var timePasswordChanged: Timestamp? {
return self.timestamp("timePasswordChanged")
}
override open func equalPayloads(_ obj: CleartextPayloadJSON) -> Bool {
if let p = obj as? LoginPayload {
if !super.equalPayloads(p) {
return false
}
if p.deleted || self.deleted {
return self.deleted == p.deleted
}
// If either record is deleted, these other fields might be missing.
// But we just checked, so we're good to roll on.
return LoginPayload.RequiredStringFields.every({ field in
p[field].string == self[field].string
})
// TODO: optional fields.
}
return false
}
}
| mpl-2.0 | dba9a2801033a151daa77ce5c1fe1ccc | 25.134615 | 88 | 0.557518 | 4.888489 | false | false | false | false |
SanctionCo/pilot-ios | pilot/ValidationForm.swift | 1 | 2809 | //
// ValidationForm.swift
// pilot
//
// Created by Nick Eckert on 12/12/17.
// Copyright © 2017 sanction. All rights reserved.
//
import Foundation
// Implement this protocol to create forms for validating user input
protocol ValidationForm {
func validate() -> ValidationError?
}
extension ValidationForm {
func validateEmail(email: String?) -> ValidationError? {
guard let email = email else {
return ValidationError(code: ValidationError.ErrorCode.errorInvalidEmail,
message: ValidationError.ErrorMessage.messageInvalidEmail)
}
var validationError: ValidationError? = nil
if email.isEmpty {
validationError = ValidationError(code: ValidationError.ErrorCode.errorCodeEmptyText,
message: ValidationError.ErrorMessage.messageEmptyEmail)
} else {
let regexEmail: String = "[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,64}"
let predicate = NSPredicate(format: "SELF MATCHES %@", regexEmail)
let result = predicate.evaluate(with: email)
if !result {
validationError = ValidationError(code: ValidationError.ErrorCode.errorInvalidEmail,
message: ValidationError.ErrorMessage.messageInvalidEmail)
}
}
return validationError
}
func validatePassword(password: String?) -> ValidationError? {
guard let password = password else {
return ValidationError(code: ValidationError.ErrorCode.errorInvalidPassword,
message: ValidationError.ErrorMessage.messageInvalidPassword)
}
var validationError: ValidationError? = nil
if password.isEmpty {
validationError = ValidationError(code: ValidationError.ErrorCode.errorInvalidPassword,
message: ValidationError.ErrorMessage.messageEmptyPassword)
}
return validationError
}
func validateEqualPasswords(passwordOne: String?, passwordTwo: String?) -> ValidationError? {
guard let passwordOne = passwordOne else {
return ValidationError(code: ValidationError.ErrorCode.errorInvalidPassword,
message: ValidationError.ErrorMessage.messageInvalidPassword)
}
guard let passwordTwo = passwordTwo else {
return ValidationError(code: ValidationError.ErrorCode.errorInvalidPassword,
message: ValidationError.ErrorMessage.messageInvalidPassword)
}
var validationError: ValidationError? = nil
if passwordOne != passwordTwo {
validationError = ValidationError(code: ValidationError.ErrorCode.errorCodeMissMatchPasswords,
message: ValidationError.ErrorMessage.messageMissMatchPasswords)
}
return validationError
}
}
| mit | 38bbb588139b045ecffa48fdbf08e824 | 35 | 104 | 0.678063 | 5.527559 | false | false | false | false |
smashingboxes/BuildNumberLabel | BuildNumberLabelTests/BuildNumberLabelTests.swift | 1 | 1403 | //
// BuildNumberLabelTests.swift
// BuildNumberLabelTests
//
// Created by David Sweetman on 1/22/16.
// Copyright © 2016 smashingboxes. All rights reserved.
//
import XCTest
@testable import BuildNumberLabel
class BuildNumberLabelTests: XCTestCase {
var testBundle: Bundle {
let bundleId = "com.smashingboxes.BuildNumberLabelTests"
return Bundle.allBundles.first(where: { $0.bundleIdentifier == bundleId })!
}
func testVersionNumberInString() {
let version = testBundle.object(forInfoDictionaryKey: "CFBundleShortVersionString")
let label = BuildNumberLabel.create(bundle: testBundle)
XCTAssertTrue(label.text!.contains("\(version!)"))
}
func testBuildNumberInString() {
let build = testBundle.object(forInfoDictionaryKey: String(kCFBundleVersionKey))
let label = BuildNumberLabel.create(bundle: testBundle)
XCTAssertTrue(label.text!.contains("\(build!)"))
}
func testUsesFont() {
let font = UIFont(name: "Avenir", size: 20.0)
let label = BuildNumberLabel.create(font: font)
XCTAssertTrue(label.font.fontName == font?.fontName)
XCTAssertTrue(label.font.pointSize == font?.pointSize)
}
func testUsesColor() {
let label = BuildNumberLabel.create(color: UIColor.red)
XCTAssertTrue(label.textColor.isEqual(UIColor.red))
}
}
| mit | a0baeb276507afecb1cdf09a786d96ab | 31.604651 | 91 | 0.68331 | 4.688963 | false | true | false | false |
ospr/UIPlayground | UIPlaygroundUI/SpringBoardAppLaunchTransitionAnimator.swift | 1 | 8608 | //
// SpringBoardAppLaunchTransitionAnimator.swift
// UIPlayground
//
// Created by Kip Nicol on 9/26/16.
// Copyright © 2016 Kip Nicol. All rights reserved.
//
import Foundation
class SpringBoardAppLaunchTransitionAnimator: NSObject, UIViewControllerAnimatedTransitioning {
let isPresenting: Bool
let appIconButton: UIButton
let springBoardViewController: SpringBoardViewController
var startingCornerRadius = CGFloat(14)
var otherAppZoomScale = CGFloat(5)
var wallpaperZoomScale = CGFloat(1.5)
var duration: TimeInterval {
return isPresenting ? TimeInterval(0.65) : TimeInterval(0.5)
}
var animationTimingParameters = UISpringTimingParameters(dampingRatio: 4.56)
init(appIconButton: UIButton, springBoardViewController: SpringBoardViewController, isPresenting: Bool) {
self.appIconButton = appIconButton
self.springBoardViewController = springBoardViewController
self.isPresenting = isPresenting
super.init()
}
func transitionDuration(using transitionContext: UIViewControllerContextTransitioning?) -> TimeInterval {
return duration
}
func animateTransition(using transitionContext: UIViewControllerContextTransitioning) {
let containerView = transitionContext.containerView
let toViewController = transitionContext.viewController(forKey: .to)!
let fromViewController = transitionContext.viewController(forKey: .from)!
let toView = toViewController.view!
let finalFrame = transitionContext.finalFrame(for: fromViewController)
let appInitialView = isPresenting ? toView : fromViewController.view!
let appIconFrame = appIconButton.convert(appIconButton.frame, to: nil)
let wallpaperSnapshotView = springBoardViewController.wallpaperView.simulatorFix_snapshotView(afterScreenUpdates: false)!
containerView.addSubview(wallpaperSnapshotView)
let (appCollectionContainerView, appCollectionSnapshotView) = setupAppCollectionContainerView(for: containerView.bounds, appIconFrame: appIconFrame)
containerView.addSubview(appCollectionContainerView)
let (appIconContainerView, appInitialViewSnapshot) = setupAppIconContainerView(for: appIconFrame, with: appInitialView)
containerView.addSubview(appIconContainerView)
// Initialize frame values
appCollectionContainerView.frame = containerView.bounds
wallpaperSnapshotView.frame = containerView.bounds
appIconContainerView.frame = appIconFrame
// Setup a block used for updating views for animation states
let updateViewsForAnimation: (Bool) -> () = { isLaunched in
appCollectionContainerView.transform = isLaunched ? CGAffineTransform(scaleX: self.otherAppZoomScale, y: self.otherAppZoomScale) : CGAffineTransform.identity
wallpaperSnapshotView.transform = isLaunched ? CGAffineTransform(scaleX: self.wallpaperZoomScale, y: self.wallpaperZoomScale) : CGAffineTransform.identity
appIconContainerView.frame = isLaunched ? finalFrame : appIconFrame
appCollectionSnapshotView.alpha = isLaunched ? 0 : 1
appInitialViewSnapshot.alpha = isLaunched ? 2 : 0
}
// Initialize views for the current state (not the end animated state)
updateViewsForAnimation(!isPresenting)
// Build animation
let animator = UIViewPropertyAnimator(duration: duration, timingParameters: animationTimingParameters)
animator.addAnimations {
updateViewsForAnimation(self.isPresenting)
}
animator.addCompletion { (position) in
appIconContainerView.removeFromSuperview()
wallpaperSnapshotView.removeFromSuperview()
appCollectionContainerView.removeFromSuperview()
if self.isPresenting {
containerView.addSubview(toView)
}
transitionContext.completeTransition(position == .end && !transitionContext.transitionWasCancelled)
}
animator.startAnimation()
// Animate corner radius seprately since CALayer properties can't be animated
// directly by using UIView animation mechanisms
let startRadius = isPresenting ? startingCornerRadius : 0
let endRadius = isPresenting ? 0 : startingCornerRadius
appIconContainerView.layer.cornerRadius = endRadius
appIconContainerView.clipsToBounds = true
let animation = CABasicAnimation(keyPath: #keyPath(CALayer.cornerRadius))
animation.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionLinear)
animation.fromValue = startRadius
animation.toValue = appIconContainerView.layer.cornerRadius
animation.duration = duration * 0.65
appIconContainerView.layer.add(animation, forKey: "cornerRadius")
}
// MARK: - Setting up views
private func setupAppCollectionContainerView(for bounds: CGRect, appIconFrame: CGRect) -> (UIView, UIView) {
let appCollectionContainerView = UIView()
// Move the anchor point to the center of the app that is being launched so that
// the zoom animation will look like we are going into that app
appCollectionContainerView.layer.anchorPoint = CGPoint(x: appIconFrame.midX / bounds.maxX,
y: appIconFrame.midY / bounds.maxY)
appCollectionContainerView.frame = bounds
let dockViewSnapshot = SpringBoardDockView()
let currentDockViewFrame = springBoardViewController.dockView.frame
appCollectionContainerView.addSubview(dockViewSnapshot)
dockViewSnapshot.frame = CGRect(x: currentDockViewFrame.origin.x, y: currentDockViewFrame.origin.y,
width: appCollectionContainerView.bounds.width, height: currentDockViewFrame.height)
dockViewSnapshot.autoresizingMask = [.flexibleWidth, .flexibleTopMargin]
let appCollectionSnapshotView = UIImageView()
appCollectionContainerView.addSubview(appCollectionSnapshotView)
appCollectionSnapshotView.image = snapshotImageForZoomingAppIcons(from: springBoardViewController)
appCollectionSnapshotView.frame = appCollectionContainerView.bounds
appCollectionSnapshotView.autoresizingMask = [.flexibleWidth, .flexibleHeight]
return (appCollectionContainerView, appCollectionSnapshotView)
}
private func setupAppIconContainerView(for appIconFrame: CGRect, with appInitialView: UIView) -> (UIView, UIView) {
// Note on iPhone 7/7+ simulator there is a white flicker when calling this with true set
// rdar://28808781
let appInitialViewSnapshot = appInitialView.simulatorFix_snapshotView(afterScreenUpdates: true)!
let appIconContainerView = UIView()
let appIconImageView = appIconButton.simulatorFix_snapshotView(afterScreenUpdates: false)!
appIconContainerView.addSubview(appIconImageView)
appIconImageView.frame = appIconContainerView.bounds
appIconImageView.autoresizingMask = [.flexibleHeight, .flexibleWidth]
appIconContainerView.addSubview(appInitialViewSnapshot)
appInitialViewSnapshot.frame = appIconContainerView.bounds
appInitialViewSnapshot.autoresizingMask = [.flexibleHeight, .flexibleWidth]
return (appIconContainerView, appInitialViewSnapshot)
}
// MARK: - Creating snapshots
private func snapshotImageForZoomingAppIcons(from viewController: SpringBoardViewController) -> UIImage {
let springBoardView = viewController.containerView
// Slightly increase the scale here so that when the image is zoomed things still look sharp
let imageScale = springBoardView.window!.screen.scale * 2
// Get a snapshot of the app collection without the selected button
let snapshotImage = springBoardView.snapshotImage(withScale: imageScale)
// Mask out the app icon
let imageBounds = springBoardView.bounds
let finalImage = UIGraphicsImageRenderer(size: imageBounds.size, scale: imageScale, opaque: false).image { (context) in
snapshotImage.draw(in: imageBounds)
let appIconFrame = appIconButton.convert(appIconButton.frame, to: nil)
UIColor.clear.setFill()
context.fill(appIconFrame)
}
return finalImage
}
}
| mit | 85970db8388fe0771005415b102bfc9b | 49.040698 | 169 | 0.714418 | 6.250545 | false | false | false | false |
lukejmann/FBLA2017 | Pods/Hero/Sources/Debug Plugin/HeroDebugPlugin.swift | 1 | 6512 | // The MIT License (MIT)
//
// Copyright (c) 2016 Luke Zhao <[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
#if os(iOS)
public class HeroDebugPlugin: HeroPlugin {
public static var showOnTop: Bool = false
var debugView: HeroDebugView?
var zPositionMap = [UIView: CGFloat]()
var addedLayers: [CALayer] = []
var updating = false
override public func animate(fromViews: [UIView], toViews: [UIView]) -> TimeInterval {
if Hero.shared.forceNotInteractive { return 0 }
var hasArc = false
for v in context.fromViews + context.toViews {
if context[v]?.arc != nil && context[v]?.position != nil {
hasArc = true
break
}
}
let debugView = HeroDebugView(initialProcess: Hero.shared.presenting ? 0.0 : 1.0, showCurveButton:hasArc, showOnTop:HeroDebugPlugin.showOnTop)
debugView.frame = Hero.shared.container.bounds
debugView.delegate = self
UIApplication.shared.keyWindow!.addSubview(debugView)
debugView.layoutSubviews()
self.debugView = debugView
UIView.animate(withDuration: 0.4) {
debugView.showControls = true
}
return .infinity
}
public override func resume(timePassed: TimeInterval, reverse: Bool) -> TimeInterval {
guard let debugView = debugView else { return 0.4 }
debugView.delegate = nil
UIView.animate(withDuration: 0.4) {
debugView.showControls = false
debugView.debugSlider.setValue(roundf(debugView.progress), animated: true)
}
on3D(wants3D: false)
return 0.4
}
public override func clean() {
debugView?.removeFromSuperview()
debugView = nil
}
}
extension HeroDebugPlugin:HeroDebugViewDelegate {
public func onDone() {
guard let debugView = debugView else { return }
let seekValue = Hero.shared.presenting ? debugView.progress : 1.0 - debugView.progress
if seekValue > 0.5 {
Hero.shared.end()
} else {
Hero.shared.cancel()
}
}
public func onProcessSliderChanged(progress: Float) {
let seekValue = Hero.shared.presenting ? progress : 1.0 - progress
Hero.shared.update(progress: Double(seekValue))
}
func onPerspectiveChanged(translation: CGPoint, rotation: CGFloat, scale: CGFloat) {
var t = CATransform3DIdentity
t.m34 = -1 / 4_000
t = CATransform3DTranslate(t, translation.x, translation.y, 0)
t = CATransform3DScale(t, scale, scale, 1)
t = CATransform3DRotate(t, rotation, 0, 1, 0)
Hero.shared.container.layer.sublayerTransform = t
}
func animateZPosition(view: UIView, to: CGFloat) {
let a = CABasicAnimation(keyPath: "zPosition")
a.fromValue = view.layer.value(forKeyPath: "zPosition")
a.toValue = NSNumber(value: Double(to))
a.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseInEaseOut)
a.duration = 0.4
view.layer.add(a, forKey: "zPosition")
view.layer.zPosition = to
}
func onDisplayArcCurve(wantsCurve: Bool) {
for layer in addedLayers {
layer.removeFromSuperlayer()
addedLayers.removeAll()
}
if wantsCurve {
for layer in Hero.shared.container.layer.sublayers! {
for (_, anim) in layer.animations {
if let keyframeAnim = anim as? CAKeyframeAnimation, let path = keyframeAnim.path {
let s = CAShapeLayer()
s.zPosition = layer.zPosition + 10
s.path = path
s.strokeColor = UIColor.blue.cgColor
s.fillColor = UIColor.clear.cgColor
Hero.shared.container.layer.addSublayer(s)
addedLayers.append(s)
}
}
}
}
}
func on3D(wants3D: Bool) {
var t = CATransform3DIdentity
if wants3D {
var viewsWithZPosition = Set<UIView>()
for view in Hero.shared.container.subviews {
if view.layer.zPosition != 0 {
viewsWithZPosition.insert(view)
zPositionMap[view] = view.layer.zPosition
}
}
let viewsWithoutZPosition = Hero.shared.container.subviews.filter { return !viewsWithZPosition.contains($0) }
let viewsWithPositiveZPosition = viewsWithZPosition.filter { return $0.layer.zPosition > 0 }
for (i, v) in viewsWithoutZPosition.enumerated() {
animateZPosition(view:v, to:CGFloat(i * 10))
}
var maxZPosition: CGFloat = 0
for v in viewsWithPositiveZPosition {
maxZPosition = max(maxZPosition, v.layer.zPosition)
animateZPosition(view:v, to:v.layer.zPosition + CGFloat(viewsWithoutZPosition.count * 10))
}
t.m34 = -1 / 4_000
t = CATransform3DTranslate(t, debugView!.translation.x, debugView!.translation.y, 0)
t = CATransform3DScale(t, debugView!.scale, debugView!.scale, 1)
t = CATransform3DRotate(t, debugView!.rotation, 0, 1, 0)
} else {
for v in Hero.shared.container.subviews {
animateZPosition(view:v, to:self.zPositionMap[v] ?? 0)
}
self.zPositionMap.removeAll()
}
let a = CABasicAnimation(keyPath: "sublayerTransform")
a.fromValue = Hero.shared.container.layer.value(forKeyPath: "sublayerTransform")
a.toValue = NSValue(caTransform3D: t)
a.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseInEaseOut)
a.duration = 0.4
UIView.animate(withDuration:0.4) {
self.context.container.backgroundColor = UIColor(white: 0.85, alpha: 1.0)
}
Hero.shared.container.layer.add(a, forKey: "debug")
Hero.shared.container.layer.sublayerTransform = t
}
}
#endif
| mit | e2876a4e030fc6718383409ed35b5044 | 34.584699 | 146 | 0.688575 | 4.124129 | false | false | false | false |
GENG-GitHub/weibo-gd | GDWeibo/Class/Module/Discover/View/GDMainTabBar.swift | 1 | 1877 | //
// GDMainTabBar.swift
// GDWeibo
//
// Created by geng on 15/10/27.
// Copyright © 2015年 geng. All rights reserved.
//
import UIKit
class GDMainTabBar: UITabBar
{
private let count: CGFloat = 5
override func layoutSubviews() {
super.layoutSubviews()
//计算宽度
let width = bounds.width / count
//设置frame
let frame = CGRect(x: 0, y: 0, width: width, height: bounds.height)
//设置索引
var index = 0
//遍历子控件,设置frame
for view in subviews
{
if view is UIControl
{
print("view:\(view)")
view.frame = CGRect(x: width * CGFloat(index) , y: 0, width: width, height: bounds.height)
// view.frame = CGRectOffset(frame , width * CGFloat(index) , 0)
index += index == 1 ? 2 : 1
}
}
//设置按钮的frame
composeButton.frame = CGRectOffset(frame, width * 2, 0)
}
//懒加载按钮
private lazy var composeButton: UIButton = {
//创建按钮
let btn = UIButton()
//按钮的图片
btn.setImage(UIImage(named: "tabbar_compose_icon_add"), forState: UIControlState.Normal)
btn.setImage(UIImage(named: "tabbar_compose_icon_add_highlighted"), forState: UIControlState.Highlighted)
//按钮的背景
btn.setBackgroundImage(UIImage(named: "tabbar_compose_button"), forState:UIControlState.Normal)
btn.setBackgroundImage(UIImage(named: "tabbar_compose_button_highlighted"), forState: UIControlState.Highlighted)
self.addSubview(btn)
return btn
}()
}
| apache-2.0 | ca62aa5b486a08e86684023cfec1983e | 23.189189 | 121 | 0.523464 | 4.698163 | false | false | false | false |
nst/CrashReports | CrashReports/Document.swift | 1 | 3579 | //
// Document.swift
// CrashReports
//
// Created by Nicolas Seriot on 18/11/15.
// Copyright © 2015 seriot.ch. All rights reserved.
//
import Cocoa
class Document: NSDocument {
@IBOutlet var textView: NSTextView!
var crashReportPath: String?
var crashReportInterpreted: String?
var font: NSFont
override init() {
self.font = NSFont.userFixedPitchFont(ofSize: 11)!
super.init()
}
override func windowControllerDidLoadNib(_ aController: NSWindowController) {
super.windowControllerDidLoadNib(aController)
// Add any code here that needs to be executed once the windowController has loaded the document's window.
guard let scriptPath = Bundle.main.path(forResource: "symbolicatecrash", ofType: "pl") else { return }
guard let crashReportPath = self.crashReportPath else { return }
self.textView.isSelectable = true
self.textView.isEditable = false
self.textView.font = self.font
self.textView.textColor = NSColor.disabledControlTextColor
do {
self.textView.string = try NSString(contentsOfFile:crashReportPath, encoding:String.Encoding.utf8.rawValue) as String
} catch let error as NSError {
let alert = NSAlert(error:error)
alert.runModal()
return
}
var taskHasReceivedData = false
let task = Process()
task.launchPath = "/usr/bin/perl"
task.arguments = [scriptPath, crashReportPath]
task.standardOutput = Pipe()
// task.standardError = task.standardOutput
let readabilityHandler: (FileHandle!) -> Void = { file in
let data = file.availableData
var mas = NSMutableAttributedString(string: "")
if let s = NSString(data: data, encoding: String.Encoding.utf8.rawValue) {
mas = NSMutableAttributedString(string: s as String)
}
mas.addAttribute(NSFontAttributeName, value: self.font, range: NSMakeRange(0, mas.length))
DispatchQueue.main.async { [unowned self] in
if(taskHasReceivedData == false) {
self.textView.string = ""
taskHasReceivedData = true
}
self.textView.textColor = NSColor.controlTextColor
self.textView.textStorage?.append(mas)
}
}
let terminationHandler: (Process!) -> Void = { task in
DispatchQueue.main.async {
guard let output = task.standardOutput as? Pipe else { return }
output.fileHandleForReading.readabilityHandler = nil
Swift.print("-- task terminated")
}
}
guard let output = task.standardOutput as? Pipe else { return }
output.fileHandleForReading.readabilityHandler = readabilityHandler
task.terminationHandler = terminationHandler
task.launch()
}
override class func autosavesInPlace() -> Bool {
return true
}
override var windowNibName: String? {
// Returns the nib file name of the document
// If you need to use a subclass of NSWindowController or if your document supports multiple NSWindowControllers, you should remove this property and override -makeWindowControllers instead.
return "Document"
}
override func read(from url: URL, ofType typeName: String) throws {
self.crashReportPath = url.path
}
}
| mit | 9d428043879ebef1a53e8cfb7288c8dd | 33.403846 | 198 | 0.620738 | 5.163059 | false | false | false | false |
carabina/FunkySwift | Source/Array.swift | 1 | 5264 | //
// Array.swift
// FuncySwift
//
// Created by Donnacha Oisín Kidney on 27/05/2015.
//
//
import Foundation
internal extension Array {
/**
Returns the combinations of a given length of self
:param: n length of the combinations
:returns: an array of combinations
*/
func combinations(n: Int) -> [[T]] {
var (objects, combos) = (self, [[T]]())
if n == 0 { combos = [[]] } else {
while !objects.isEmpty {
let element = objects.removeLast()
combos.extend(objects.combinations(n - 1).map{ $0 + [element] })
}
}
return combos
}
/**
Returns the combinations with repetition of a given length of self
:param: n length of the combinations
:returns: an array of combinations
*/
func combosWithRep(n: Int) -> [[T]] {
var (objects, combos) = (self, [[T]]())
if n == 0 { combos = [[]] } else {
while let element = objects.last {
combos.extend(objects.combosWithRep(n - 1).map{ $0 + [element] })
objects.removeLast()
}
}
return combos
}
/**
Returns the permutations with repetition of a given length of self
:param: n length of the permutations
:returns: an array of permutations
*/
func permsWithRep(n: Int) -> [[T]] {
return Swift.reduce(1..<n, self.map{[$0]}) {
prevPerms, _ in
prevPerms.flatMap{
prevPerm in self.map{ prevPerm + [$0] }
}
}
}
/**
Returns all the permutations with repetition of self
*/
func permsWithRep() -> [[T]] { return permsWithRep(self.count) }
/**
Returns all the permutations of self
*/
func perms() -> [[T]] { return {(var ar) in ar.heaps(ar.count)}(self) }
/**
Heap's algorithm
*/
private mutating func heaps(n: Int) -> [[T]] {
return n == 1 ? [self] :
Swift.reduce(0..<n, [[T]]()) {
(var shuffles, i) in
shuffles.extend(self.heaps(n - 1))
swap(&self[n % 2 == 0 ? i : 0], &self[n - 1])
return shuffles
}
}
/**
Returns all the permutations of a given length of self
:param: n length of the permutations
*/
func perms(n: Int) -> [[T]] {
return self.combinations(n).flatMap{$0.perms()}
}
/**
Returns a random element of self
*/
func randomElement() -> T {
return self[Int(arc4random_uniform(UInt32(self.count)))]
}
/**
randomly shuffles self, via the Fisher-Yates shuffle
*/
mutating func shuffle() {
for i in lazy(1..<self.count).reverse() {
swap(&self[i], &self[Int(arc4random_uniform(UInt32(i)))])
}
}
/**
returns self randomly shuffled, via the Fisher-Yates shuffle
*/
func shuffled() -> [T] {
var ar = self
ar.shuffle()
return ar
}
/**
Returns the next permutation of self in lexicographical order according to the closure isOrderedBefore
:param: isOrderedBefore a closure that returns true if its first argument is ordered before its second
*/
mutating func nextLexPerm(isOrderedBefore: (T, T) -> Bool) -> [T]? {
var (l, k) = (self.endIndex, self.endIndex.predecessor())
while isOrderedBefore(self[k], self[--k]) {if k == 0 {return nil}}
while !isOrderedBefore(self[k], self[--l]) {}
swap(&self[k++], &self[l])
Swift.reverse(self[k..<self.endIndex])
return self
}
/**
Returns a lazy generator of permutations of self in lexicographical order according to the closure isOrderedBefore
:param: isOrderedBefore a closure that returns true if its first argument is ordered before its second
:returns: a LazySequence of arrays
*/
func lexPermsOf(isOrderedBefore: (T, T) -> Bool) -> LazySequence<GeneratorOf<[T]>> {
var a = self
return lazy( GeneratorOf{ a.nextLexPerm(isOrderedBefore) })
}
/**
returns an array of chunks of self, all of length n. The last chunk may be smaller than n.
*/
func chunk(n: Int) -> [ArraySlice<T>] {
return ArraySlice(self).chunk(n)
}
/**
an endless repetition of self
*/
func cycle() -> LazySequence<GeneratorOf<T>> {
var g = self.generate()
return lazy( GeneratorOf {for;;g = self.generate(){if let n = g.next(){return n}}} )
}
/**
returns a LazySequence of the elements of self with "with" inserted between every element
:param: with the element to insert between every element of self
*/
func interpose(with: T) -> LazySequence<GeneratorOf<T>> {
var (i, g) = (0, self.generate())
return lazy( GeneratorOf {
i ^= 1
return i == 0 ? with : g.next()
} )
}
/**
returns an array of arrays, each array containing one element from every array, in every possible combination
*/
func everyOf<S: SequenceType where S.Generator.Element == T>(ar: S...) -> [[T]] {
return ar.reduce(self.map{[$0]}){pa, la in pa.flatMap{pe in Swift.map(la){pe + [$0]}}}
}
subscript(r: OpenEndedRange<Int>) -> ArraySlice<T> {
return self[r.start..<self.count]
}
subscript(r: OpenStartedRange<Int>) -> ArraySlice<T> {
return self[0..<r.end]
}
}
extension ArraySlice {
/**
returns an array of chunks of self, all of length n. The last chunk may be smaller than n.
*/
func chunk(n: Int) -> [ArraySlice<T>] {
return self.count <= n ? [self] : [self[0..<n]] + self[n..<self.count].chunk(n)
}
}
| mit | 05316f69025e58ba5578a015133509c7 | 26.128866 | 116 | 0.613908 | 3.690743 | false | false | false | false |
OpsLabJPL/MarsImagesIOS | MarsImagesIOS/MER.swift | 1 | 8499 | //
// MER.swift
// MarsImagesIOS
//
// Created by Mark Powell on 7/28/17.
// Copyright © 2017 Mark Powell. All rights reserved.
//
import Foundation
class MER: Mission {
let SOL = "Sol"
let LTST = "LTST"
let RMC = "RMC"
let COURSE = "Course"
enum TitleState {
case START,
SOL_NUMBER,
IMAGESET_ID,
INSTRUMENT_NAME,
MARS_LOCAL_TIME,
DISTANCE,
YAW,
PITCH,
ROLL,
TILT,
ROVER_MOTION_COUNTER
}
override init() {
super.init()
self.eyeIndex = 23
self.instrumentIndex = 1
self.sampleTypeIndex = 12
self.cameraFOVs["N"] = 0.78539816
self.cameraFOVs["P"] = 0.27925268
}
override func getSortableImageFilename(url: String) -> String {
let tokens = url.components(separatedBy: "/")
if tokens.count > 0 {
let filename = tokens[tokens.count-1]
if filename.hasPrefix("Sol") {
return "0" //sort Cornell Pancam images first
}
else if (filename.hasPrefix("1") || filename.hasPrefix("2")) && filename.count == 31 {
let index = filename.index(filename.startIndex, offsetBy: 23)
return filename.substring(from: index)
}
return filename
}
return url
}
override func rowTitle(_ title: String) -> String {
let merTitle = tokenize(title) as! MERTitle
if merTitle.instrumentName == "Course Plot" {
let distanceFormatted = String.localizedStringWithFormat("%.2f", merTitle.distance)
return "Drive for \(distanceFormatted) meters"
}
return merTitle.instrumentName
}
override func caption(_ title: String) -> String {
if let t = tokenize(title) as? MERTitle {
if (t.instrumentName == "Course Plot") {
return String(format:"Drive for %.2f meters on Sol %d", t.distance, t.sol)
}
else {
return "\(t.instrumentName) image taken on Sol \(t.sol)."
}
}
else {
return super.caption(title)
}
}
override func tokenize(_ title: String) -> Title {
var mer = MERTitle()
let tokens = title.components(separatedBy: " ")
var state = TitleState.START
for word in tokens {
if word == SOL {
state = TitleState.SOL_NUMBER
continue
}
else if word == LTST {
state = TitleState.MARS_LOCAL_TIME
continue
}
else if word == RMC {
state = TitleState.ROVER_MOTION_COUNTER
continue
}
var indices:[Int] = []
switch (state) {
case .START:
break
case .SOL_NUMBER:
mer.sol = Int(word)!
state = TitleState.IMAGESET_ID
break
case .IMAGESET_ID:
if word == COURSE {
mer = parseCoursePlotTitle(title: title, mer: mer)
return mer
} else {
mer.imageSetID = word
}
state = TitleState.INSTRUMENT_NAME
break
case .INSTRUMENT_NAME:
if mer.instrumentName.isEmpty {
mer.instrumentName = String(word)
} else {
mer.instrumentName.append(" \(word)")
}
break
case .MARS_LOCAL_TIME:
mer.marsLocalTime = word
break
case .ROVER_MOTION_COUNTER:
indices = word.components(separatedBy: "-").map { Int($0)! }
mer.siteIndex = indices[0]
mer.driveIndex = indices[1]
break
default:
print("Unexpected state in parsing image title: \(state)")
break
}
}
return mer
}
func parseCoursePlotTitle(title:String, mer: MERTitle) -> MERTitle {
let tokens = title.components(separatedBy: " ")
var state = TitleState.START
for word in tokens {
if word == COURSE {
mer.instrumentName = "Course Plot"
} else if word == "Distance" {
state = TitleState.DISTANCE
continue
} else if word == "yaw" {
state = TitleState.YAW
continue
} else if word == "pitch" {
state = TitleState.PITCH
continue
} else if word == "roll" {
state = TitleState.ROLL
continue
} else if word == "tilt" {
state = TitleState.TILT
continue
} else if word == "RMC" {
state = TitleState.ROVER_MOTION_COUNTER
continue
}
var indices:[Int] = []
switch (state) {
case .START:
break
case .DISTANCE:
mer.distance = Double(word)!
break
case .YAW:
mer.yaw = Double(word)!
break
case .PITCH:
mer.pitch = Double(word)!
break
case .ROLL:
mer.roll = Double(word)!
break
case .TILT:
mer.tilt = Double(word)!
break
case .ROVER_MOTION_COUNTER:
indices = word.components(separatedBy: "-").map { Int($0)! }
mer.siteIndex = indices[0]
mer.driveIndex = indices[1]
break
default:
print("Unexpected state in parsing course plot title: \(state)")
}
}
return mer
}
override func imageName(imageId: String) -> String {
if imageId.range(of:"False") != nil {
return "Color"
}
let irange = imageId.index(imageId.startIndex, offsetBy: instrumentIndex)..<imageId.index(imageId.startIndex, offsetBy: instrumentIndex+1)
let instrument = imageId[irange]
if instrument == "N" || instrument == "F" || instrument == "R" {
let erange = imageId.index(imageId.startIndex, offsetBy: eyeIndex)..<imageId.index(imageId.startIndex, offsetBy:eyeIndex+1)
let eye = imageId[erange]
if eye == "L" {
return "Left"
} else {
return "Right"
}
} else if instrument == "P" {
let prange = imageId.index(imageId.startIndex, offsetBy: eyeIndex)..<imageId.index(imageId.startIndex, offsetBy:eyeIndex+2)
return String(imageId[prange])
}
return ""
}
override func stereoImageIndices(imageIDs: [String]) -> (Int,Int)? {
let imageid = imageIDs[0]
let instrument = getInstrument(imageId: imageid)
if !isStereo(instrument: instrument) {
return nil
}
var leftImageIndex = -1;
var rightImageIndex = -1;
var index = 0;
for imageId in imageIDs {
let eye = getEye(imageId: imageId)
if leftImageIndex == -1 && eye=="L" && !imageId.hasPrefix("Sol") {
leftImageIndex = index;
}
if rightImageIndex == -1 && eye=="R" {
rightImageIndex = index;
}
index += 1;
}
if (leftImageIndex >= 0 && rightImageIndex >= 0) {
return (Int(leftImageIndex), Int(rightImageIndex))
}
return nil
}
func isStereo(instrument:String) -> Bool {
return instrument == "F" || instrument == "R" || instrument == "N" || instrument == "P"
}
override func getCameraId(imageId: String) -> String {
if imageId.range(of:"Sol") != nil {
return "P";
} else {
return imageId[1]
}
}
override func mastPosition() -> [Double] {
return [0.456,0.026,-1.0969]
}
}
class MERTitle: Title {
var distance = 0.0
var yaw = 0.0
var pitch = 0.0
var roll = 0.0
var tilt = 0.0
}
| apache-2.0 | fadd0133b623fef79a576697777c7965 | 30.591078 | 146 | 0.479525 | 4.723735 | false | false | false | false |
yazhenggit/wbtest | 微博项目练习/微博项目练习/Classes/Module/Home/StatusForwardCell.swift | 1 | 2576 | //
// StatusForwardCell.swift
// 微博项目练习
//
// Created by 王亚征 on 15/10/16.
// Copyright © 2015年 yazheng. All rights reserved.
//
import UIKit
class StatusForwardCell: StatusCell {
override var status:Status? {
didSet {
let userName = status?.retweeted_status?.user?.name ?? ""
let text = status?.retweeted_status?.text ?? ""
forwardLabel.text = "@" + userName + ":" + text
}
}
// MARK: - 设置 UI
override func setupUI() {
super.setupUI()
// 1. 添加控件
contentView.insertSubview(backButton, belowSubview: pictureView)
contentView.insertSubview(forwardLabel, aboveSubview: backButton)
// forwardLabel.text = "dasdfsdf"
// 2. 自动布局
// 1>背景按钮
backButton.ff_AlignVertical(type: ff_AlignType.BottomLeft, referView: contentLabel, size: nil, offset: CGPoint(x: -statusCellControlMargin, y: statusCellControlMargin))
backButton.ff_AlignVertical(type: ff_AlignType.TopRight, referView: bottomView, size: nil)
// 2> 转发文字
forwardLabel.ff_AlignInner(type: ff_AlignType.TopLeft, referView: backButton, size: nil, offset: CGPoint(x: statusCellControlMargin, y: statusCellControlMargin))
contentView.addConstraint(NSLayoutConstraint(item: forwardLabel, attribute: NSLayoutAttribute.Width, relatedBy: NSLayoutRelation.Equal, toItem: contentView, attribute: NSLayoutAttribute.Width, multiplier: 1.0, constant: -2 * statusCellControlMargin))
// 3> 配图视图
let cons = pictureView.ff_AlignVertical(type: ff_AlignType.BottomLeft, referView: forwardLabel, size: CGSize(width: 290, height: 90), offset: CGPoint(x: 0, y: statusCellControlMargin))
pictureTopCons = pictureView.ff_Constraint(cons, attribute: NSLayoutAttribute.Top)
pictureWidthCons = pictureView.ff_Constraint(cons, attribute: NSLayoutAttribute.Width)
pictureHightCons = pictureView.ff_Constraint(cons, attribute: NSLayoutAttribute.Height)
}
// MARK: - 懒加载控件
/// 背景按钮
private lazy var backButton: UIButton = {
let btn = UIButton()
btn.backgroundColor = UIColor(white: 0.9, alpha: 1.0)
return btn
}()
/// 转发文字
/// 转发文字
private lazy var forwardLabel: UILabel = {
let label = UILabel(color: UIColor.darkGrayColor(), fontSize: 14)
label.numberOfLines = 0
label.preferredMaxLayoutWidth = UIScreen.mainScreen().bounds.width - 2*statusCellControlMargin
return label
}()
} | mit | 920c746c5fb36f1a6f32538679ae53fa | 41 | 258 | 0.682277 | 4.407473 | false | false | false | false |
johnpatrickmorgan/Sparse | Sources/SparseTests/DotStrings/DotStringsParserTests.swift | 1 | 2908 | //
// DotStringsTests.swift
// Sparse
//
// Created by John Morgan on 03/12/2016.
// Copyright © 2016 CocoaPods. All rights reserved.
//
import Foundation
import Quick
import Nimble
@testable import Sparse
class DotStringsSpec: QuickSpec {
override func spec() {
describe("the DotStrings parser") {
let parser = DotStringsParser.stringsParser
it("should produce the same output as plist serialization") {
let input = dotStringsExample
let stream = Stream(input)
let data = input.data(using: .utf8)!
if let output = shouldNotThrow({ try parser.parse(stream) }),
let plist = shouldNotThrow({ try PropertyListSerialization.propertyList(from: data, format: nil)}) as? [String: String] {
var dict = [String : String]()
for entry in output {
dict[entry.key] = entry.translation
}
expect(dict).to(equal(plist))
}
}
}
describe("the kvp parser") {
let parser = DotStringsParser.kvp
it("should correctly parse an uncommented key-value pair") {
let input = "\"K: \\\"commentless key\"=\"V: commentless translation\";"
let stream = Stream(input)
if let output = shouldNotThrow({ try parser.parse(stream) }) {
expect(output.0).to(equal("K: \"commentless key"))
expect(output.1).to(equal("V: commentless translation"))
}
}
}
describe("the entry parser") {
let parser = DotStringsParser.entryObject
it("should correctly parse an uncommented key-value pair") {
let input = "\"K: commentless key\" = \"V: commentless translation\";"
let stream = Stream(input)
if let output = shouldNotThrow({ try parser.parse(stream) }) {
expect(output.key).to(equal("K: commentless key"))
expect(output.translation).to(equal("V: commentless translation"))
}
}
}
describe("the entries parser") {
let parser = DotStringsParser.entries
it("should correctly parse an uncommented key-value pair") {
let input = "\"K: commentless key\" = \"V: commentless translation\";"
let stream = Stream(input)
if let output = shouldNotThrow({ try parser.parse(stream) }) {
expect(stream.isAtEnd).to(equal(true))
expect(output).toNot(beNil())
expect(output.count).to(equal(1))
}
}
}
}
}
| mit | c2e34a711699d1f94ff0bab260103e51 | 37.25 | 141 | 0.510492 | 5.117958 | false | false | false | false |
laurentVeliscek/AudioKit | AudioKit/Common/Playgrounds/Synthesis.playground/Pages/Telephone.xcplaygroundpage/Contents.swift | 1 | 4021 | //: ## Telephone
//: ### AudioKit is great for sound design. This playground creates canonical telephone sounds.
import XCPlayground
import AudioKit
//: ### Dial Tone
//: A dial tone is simply two sine waves at specific frequencies
let dialTone = AKOperationGenerator() { _ in
let dialTone1 = AKOperation.sineWave(frequency: 350)
let dialTone2 = AKOperation.sineWave(frequency: 440)
return mixer(dialTone1, dialTone2) * 0.3
}
//: ### Telephone Ringing
//: The ringing sound is also a pair of frequencies that play for 2 seconds,
//: and repeats every 6 seconds.
let ringing = AKOperationGenerator() { _ in
let ringingTone1 = AKOperation.sineWave(frequency: 480)
let ringingTone2 = AKOperation.sineWave(frequency: 440)
let ringingToneMix = mixer(ringingTone1, ringingTone2)
let ringTrigger = AKOperation.metronome(frequency: 0.1666) // 1 / 6 seconds
let rings = ringingToneMix.triggeredWithEnvelope(
trigger: ringTrigger,
attack: 0.01, hold: 2, release: 0.01)
return rings * 0.4
}
//: ### Busy Signal
//: The busy signal is similar as well, just a different set of parameters.
let busy = AKOperationGenerator() { _ in
let busySignalTone1 = AKOperation.sineWave(frequency: 480)
let busySignalTone2 = AKOperation.sineWave(frequency: 620)
let busySignalTone = mixer(busySignalTone1, busySignalTone2)
let busyTrigger = AKOperation.metronome(frequency: 2)
let busySignal = busySignalTone.triggeredWithEnvelope(
trigger: busyTrigger,
attack: 0.01, hold: 0.25, release: 0.01)
return busySignal * 0.4
}
//: ## Key presses
//: All the digits are also just combinations of sine waves
//:
//: Here is the canonical specification of DTMF Tones
var keys = [String: [Double]]()
keys["1"] = [697, 1209]
keys["2"] = [697, 1336]
keys["3"] = [697, 1477]
keys["4"] = [770, 1209]
keys["5"] = [770, 1336]
keys["6"] = [770, 1477]
keys["7"] = [852, 1209]
keys["8"] = [852, 1336]
keys["9"] = [852, 1477]
keys["*"] = [941, 1209]
keys["0"] = [941, 1336]
keys["#"] = [941, 1477]
let keypad = AKOperationGenerator() { parameters in
let keyPressTone = AKOperation.sineWave(frequency: AKOperation.parameters[1]) +
AKOperation.sineWave(frequency: AKOperation.parameters[2])
let momentaryPress = keyPressTone.triggeredWithEnvelope(
trigger:AKOperation.trigger, attack: 0.01, hold: 0.1, release: 0.01)
return momentaryPress * 0.4
}
AudioKit.output = AKMixer(dialTone, ringing, busy, keypad)
AudioKit.start()
dialTone.start()
keypad.start()
//: User Interface Set up
class PlaygroundView: AKPlaygroundView {
override func setup() {
addTitle("Telephone")
addSubview(AKTelephoneView() { key, state in
switch key {
case "CALL":
if state == "down" {
busy.stop()
dialTone.stop()
if ringing.isStarted {
ringing.stop()
dialTone.start()
} else {
ringing.start()
}
}
case "BUSY":
if state == "down" {
ringing.stop()
dialTone.stop()
if busy.isStarted {
busy.stop()
dialTone.start()
} else {
busy.start()
}
}
default:
if state == "down" {
dialTone.stop()
ringing.stop()
busy.stop()
keypad.parameters[1] = keys[key]![0]
keypad.parameters[2] = keys[key]![1]
keypad.parameters[0] = 1
} else {
keypad.parameters[0] = 0
}
}
})
}
}
XCPlaygroundPage.currentPage.needsIndefiniteExecution = true
XCPlaygroundPage.currentPage.liveView = PlaygroundView()
| mit | eb59f41447a01ccd9ebcb1039ba4af99 | 30.414063 | 95 | 0.578712 | 4.291355 | false | false | false | false |
RemarkableIO/Publinks | Publinks-Example/Publinks-Example.playground/section-1.swift | 1 | 1752 | // Playground - noun: a place where people can play
import Publinks
// MARK: Publink with String value type
var stringPublink = Publink<String>()
stringPublink.subscribe() { (name: String) in
println("Hello, \(name)!")
}
stringPublink.publish("Ryan")
// MARK: Publink with optional String value type
var stringOptionalPublink = Publink<String?>()
stringOptionalPublink.subscribe() { (name: String?) in
// Publinks with optional type require nil check
if let name = name {
println("Hello, \(name)!")
} else {
println("Hello, world!")
}
}
// Publish nil value or empty optional
stringOptionalPublink.publish(nil)
stringOptionalPublink.publish(Optional<String>())
stringOptionalPublink.publish("Alex")
// MARK: Publink with named subscriptions
var anotherStringPublink = Publink<String>()
anotherStringPublink.subscribeNamed("some-identifier") { (name: String) in
println("Hello, \(name)!")
}
// The following is immediately published to one subscriber
anotherStringPublink.publish("Matt")
// The following unsubscribes the subscriber with "some-identifier"
anotherStringPublink.unsubscribe("some-identifier")
// The following is immediately published to zero subscribers
anotherStringPublink.publish("Lulu")
// The following will be called immediately upon subscription with "Lulu" (the last published value)
anotherStringPublink.subscribe() { (name: String) in
println("Hello, \(name)!")
}
// Prevent subscription being called immediately with last value
anotherStringPublink.callsLast = false
// The following will not be called immediately upon subscription because callsLast is now set to false
anotherStringPublink.subscribe() { (name: String) in
println("Hello, \(name)!")
}
| mit | 362f8ca0c153c6610d611ea0a6f7adbc | 24.764706 | 103 | 0.742009 | 4.435443 | false | false | false | false |
iAlexander/Obminka | XtraLibraries/Core.data/Row.swift | 4 | 6310 | // Row.swift
// Eureka ( https://github.com/xmartlabs/Eureka )
//
// Copyright (c) 2016 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
open class RowOf<T>: BaseRow where T: Equatable{
private var _value: T? {
didSet {
guard _value != oldValue else { return }
guard let form = section?.form else { return }
if let delegate = form.delegate {
delegate.valueHasBeenChanged(for: self, oldValue: oldValue, newValue: value)
callbackOnChange?()
}
guard let t = tag else { return }
form.tagToValues[t] = (value != nil ? value! : NSNull())
if let rowObservers = form.rowObservers[t]?[.hidden] {
for rowObserver in rowObservers {
(rowObserver as? Hidable)?.evaluateHidden()
}
}
if let rowObservers = form.rowObservers[t]?[.disabled] {
for rowObserver in rowObservers {
(rowObserver as? Disableable)?.evaluateDisabled()
}
}
}
}
/// The typed value of this row.
open var value: T? {
set (newValue) {
_value = newValue
guard let _ = section?.form else { return }
wasChanged = true
if validationOptions.contains(.validatesOnChange) || (wasBlurred && validationOptions.contains(.validatesOnChangeAfterBlurred)) || (!isValid && validationOptions != .validatesOnDemand) {
validate()
}
}
get {
return _value
}
}
/// The untyped value of this row.
public override var baseValue: Any? {
get { return value }
set { value = newValue as? T }
}
/// Block variable used to get the String that should be displayed for the value of this row.
public var displayValueFor: ((T?) -> String?)? = {
return $0.map { String(describing: $0) }
}
public required init(tag: String?) {
super.init(tag: tag)
}
internal var rules: [ValidationRuleHelper<T>] = []
@discardableResult
public override func validate() -> [ValidationError] {
validationErrors = rules.flatMap { $0.validateFn(value) }
return validationErrors
}
/// Add a Validation rule for the Row
/// - Parameter rule: RuleType object to add
public func add<Rule: RuleType>(rule: Rule) where T == Rule.RowValueType {
let validFn: ((T?) -> ValidationError?) = { (val: T?) in
return rule.isValid(value: val)
}
rules.append(ValidationRuleHelper(validateFn: validFn, rule: rule))
}
/// Add a Validation rule set for the Row
/// - Parameter ruleSet: RuleSet<T> set of rules to add
public func add(ruleSet: RuleSet<T>) {
rules.append(contentsOf: ruleSet.rules)
}
public func remove(ruleWithIdentifier identifier: String) {
if let index = rules.index(where: { (validationRuleHelper) -> Bool in
return validationRuleHelper.rule.id == identifier
}) {
rules.remove(at: index)
}
}
public func removeAllRules() {
validationErrors.removeAll()
rules.removeAll()
}
}
/// Generic class that represents an Eureka row.
open class Row<Cell: CellType>: RowOf<Cell.Value>, TypedRowType where Cell: BaseCell {
/// Responsible for creating the cell for this row.
public var cellProvider = CellProvider<Cell>()
/// The type of the cell associated to this row.
public let cellType: Cell.Type! = Cell.self
private var _cell: Cell! {
didSet {
RowDefaults.cellSetup["\(type(of: self))"]?(_cell, self)
(callbackCellSetup as? ((Cell) -> Void))?(_cell)
}
}
/// The cell associated to this row.
public var cell: Cell! {
return _cell ?? {
let result = cellProvider.makeCell(style: self.cellStyle)
result.row = self
result.setup()
_cell = result
return _cell
}()
}
/// The untyped cell associated to this row
public override var baseCell: BaseCell { return cell }
public required init(tag: String?) {
super.init(tag: tag)
}
/**
Method that reloads the cell
*/
override open func updateCell() {
super.updateCell()
cell.update()
customUpdateCell()
RowDefaults.cellUpdate["\(type(of: self))"]?(cell, self)
callbackCellUpdate?()
}
/**
Method called when the cell belonging to this row was selected. Must call the corresponding method in its cell.
*/
open override func didSelect() {
super.didSelect()
if !isDisabled {
cell?.didSelect()
}
customDidSelect()
callbackCellOnSelection?()
}
/**
Will be called inside `didSelect` method of the row. Can be used to customize row selection from the definition of the row.
*/
open func customDidSelect() {}
/**
Will be called inside `updateCell` method of the row. Can be used to customize reloading a row from its definition.
*/
open func customUpdateCell() {}
}
| mit | 10cfd324338ef5a51cf1547c1bc91e46 | 32.743316 | 199 | 0.613471 | 4.660266 | false | false | false | false |
wordpress-mobile/WordPress-Aztec-iOS | Aztec/Classes/Constants/Metrics.swift | 2 | 569 | import CoreGraphics
import Foundation
/// A collection of constants and metrics shared between the Aztec importer
/// and the editor.
///
public enum Metrics {
public static var defaultIndentation = CGFloat(12)
public static var maxIndentation = CGFloat(200)
public static var listTextIndentation = CGFloat(12)
public static var listTextCharIndentation = CGFloat(8)
public static var listMinimumIndentChars = 3
public static var tabStepInterval = 4
public static var tabStepCount = 12
public static var paragraphSpacing = CGFloat(6)
}
| gpl-2.0 | 3606216256810006a9df96c3561bdbf8 | 32.470588 | 75 | 0.757469 | 4.741667 | false | false | false | false |
tinrobots/Mechanica | Sources/CoreGraphics/CGPoint+Utils.swift | 1 | 3658 | #if os(macOS) || os(iOS) || os(tvOS) || os(watchOS)
import CoreGraphics.CGGeometry
extension CGPoint {
/// **Mechanica**
///
/// Returns the distance between two points.
/// - Parameters:
/// - point1: The first point.
/// - point2: The second point.
/// - Returns: the distance between between two points.
static func distance(from point1: CGPoint, to point2: CGPoint) -> CGFloat {
// return sqrt(pow(point2.x - point1.x, 2) + pow(point2.y - point1.y, 2))
return hypot(point1.x - point2.x, point1.y - point2.y)
}
/// **Mechanica**
///
/// Returns the distance between `self` and another `point`..
/// - Parameter point: The point to which to calculate the distance.
/// - Returns: the distance between `self` and `point`.
public func distance(to point: CGPoint) -> CGFloat {
return CGPoint.distance(from: self, to: point)
}
/// **Mechanica**
///
/// Checks if a point is on a straight line.
/// - Parameters:
/// - firstPoint: The first point that defines a straight line.
/// - secondPoint: The second point that defines a straight line.
/// - Returns: *true* if `self` lies on the straigth lined defined by `firstPoint` and `secondPoint`.
public func isOnStraightLine(passingThrough firstPoint: CGPoint, and secondPoint: CGPoint) -> Bool {
let point1 = (firstPoint.y - self.y) * (firstPoint.x - secondPoint.x)
let point2 = (firstPoint.y - secondPoint.y) * (firstPoint.x - self.x)
return point1 == point2
}
}
// MARK: - Operators
extension CGPoint {
/// **Mechanica**
///
/// Adds two `CGPoints`.
///
/// Example:
///
/// CGPoint(x: 1, y: 2) + CGPoint(x: 10, y: 11) -> CGPoint(x: 11, y: 13)
///
public static func + (lhs: CGPoint, rhs: CGPoint) -> CGPoint {
return CGPoint(x: lhs.x + rhs.x, y: lhs.y + rhs.y)
}
/// **Mechanica**
///
/// Adds a `CGPoint` to `self`.
///
/// Example:
///
/// var point = CGPoint(x: 1, y: 2)
/// point += CGPoint(x: 0, y: 0) -> point is equal to CGPoint(x: 11, y: 13)
///
public static func += (lhs: inout CGPoint, rhs: CGPoint) {
lhs = CGPoint(x: lhs.x + rhs.x, y: lhs.y + rhs.y)
}
/// **Mechanica**
///
/// Subtracts two `CGPoints`.
///
/// Example:
///
/// CGPoint(x: 1, y: 2) - CGPoint(x: 10, y: 11) -> CGPoint(x: -9, y: -9)
///
public static func - (lhs: CGPoint, rhs: CGPoint) -> CGPoint {
return CGPoint(x: lhs.x - rhs.x, y: lhs.y - rhs.y)
}
/// **Mechanica**
///
/// Subtracts a `CGPoint` from `self`.
///
/// Example:
///
/// var point = CGPoint(x: 1, y: 2)
/// point -= CGPoint(x: 10, y: 11) -> point is equal to CGPoint(x: -9, y: -9)
///
public static func -= (lhs: inout CGPoint, rhs: CGPoint) {
lhs = CGPoint(x: lhs.x - rhs.x, y: lhs.y - rhs.y)
}
/// **Mechanica**
///
/// Multiplies a `CGPoint` with a scalar.
///
/// Example:
///
/// CGPoint(x: 1, y: 2) * 3 -> CGPoint(x: 3, y: 6)
///
public static func * (point: CGPoint, scalar: CGFloat) -> CGPoint {
return CGPoint(x: point.x * scalar, y: point.y * scalar)
}
/// **Mechanica**
///
/// Multiply `self` with a scalar.
///
/// Example:
///
/// var point = CGPoint(x: 1, y: 2)
/// point *= 3 -> point is equal to CGPoint(x: 3, y: 6)
///
public static func *= (point: inout CGPoint, scalar: CGFloat) {
point = CGPoint(x: point.x * scalar, y: point.y * scalar)
}
}
#endif
| mit | bc7f93f0eacdaa9661959b597e6d6ae2 | 29.739496 | 105 | 0.536905 | 3.434742 | false | false | false | false |
apple/swift-system | Tests/SystemTests/FilePathTests/FilePathSyntaxTest.swift | 1 | 35586 | /*
This source file is part of the Swift System open source project
Copyright (c) 2020 Apple Inc. and the Swift System project authors
Licensed under Apache License v2.0 with Runtime Library Exception
See https://swift.org/LICENSE.txt for license information
*/
import XCTest
#if SYSTEM_PACKAGE
import SystemPackage
#else
import System
#endif
private struct SyntaxTestCase: TestCase {
// Whether we want the path to be constructed and syntactically
// manipulated as though it were a Windows path
let isWindows: Bool
// We defer forming the path until `runAllTests()` executes,
// so that we can switch between unix and windows behavior.
let pathStr: String
let normalized: String
let absolute: Bool
let root: String?
let relative: String
let dirname: String
let basename: String?
let stem: String?
let `extension`: String?
let components: [String]
let lexicallyNormalized: String
var file: StaticString
var line: UInt
}
extension SyntaxTestCase {
// Convenience constructor which can substitute sensible defaults
private static func testCase(
isWindows: Bool,
_ path: String,
// Nil `normalized` means use `path`
normalized: String?,
// Nil means use the precense of a root
absolute: Bool?,
// Nil `root` means no root. Nil `relative` means use `normalized`
root: String?, relative: String?,
// Nil `dirname` requires nil `basename` and means use `normalized`
dirname: String?, basename: String?,
// `nil` stem means use `basename`
stem: String?, extension: String?,
components: [String],
// Nil `lexicallyNormalized` means use `normalized`
lexicallyNormalized: String?,
file: StaticString, line: UInt
) -> SyntaxTestCase {
if dirname == nil {
assert(basename == nil )
}
let normalized = normalized ?? path
let lexicallyNormalized = lexicallyNormalized ?? normalized
let absolute = absolute ?? (root != nil)
let relative = relative ?? normalized
let dirname = dirname ?? (normalized)
let stem = stem ?? basename
return SyntaxTestCase(
isWindows: isWindows,
pathStr: path,
normalized: normalized,
absolute: absolute,
root: root, relative: relative,
dirname: dirname, basename: basename,
stem: stem, extension: `extension`,
components: components,
lexicallyNormalized: lexicallyNormalized,
file: file, line: line)
}
// Conveience constructor for unix path test cases
static func unix(
_ path: String,
normalized: String? = nil,
root: String? = nil, relative: String? = nil,
dirname: String? = nil, basename: String? = nil,
stem: String? = nil, extension: String? = nil,
components: [String],
lexicallyNormalized: String? = nil,
file: StaticString = #file, line: UInt = #line
) -> SyntaxTestCase {
.testCase(
isWindows: false,
path,
normalized: normalized,
absolute: nil,
root: root, relative: relative,
dirname: dirname, basename: basename,
stem: stem, extension: `extension`,
components: components,
lexicallyNormalized: lexicallyNormalized,
file: file, line: line)
}
// Conveience constructor for unix path test cases
static func windows(
_ path: String,
normalized: String? = nil,
absolute: Bool,
root: String? = nil, relative: String? = nil,
dirname: String? = nil, basename: String? = nil,
stem: String? = nil, extension: String? = nil,
components: [String],
lexicallyNormalized: String? = nil,
file: StaticString = #file, line: UInt = #line
) -> SyntaxTestCase {
.testCase(
isWindows: true,
path,
normalized: normalized,
absolute: absolute,
root: root, relative: relative,
dirname: dirname, basename: basename,
stem: stem, extension: `extension`,
components: components,
lexicallyNormalized: lexicallyNormalized,
file: file, line: line)
}
}
/*System 0.0.2, @available(macOS 12.0, iOS 15.0, watchOS 8.0, tvOS 15.0, *)*/
extension SyntaxTestCase {
func testComponents(_ path: FilePath, expected: [String]) {
let expectedComponents = expected.map { FilePath.Component($0)! }
expectEqualSequence(expectedComponents, Array(path.components),
"expected components")
expectEqualSequence(expectedComponents, Array(path.removingRoot().components),
"expected components")
expectEqualSequence(expectedComponents, path.components)
expectEqual(expectedComponents.first, path.components.first)
expectEqual(expectedComponents.last, path.components.last)
expectEqual(path, FilePath(root: path.root, expectedComponents), "init<C>(root:components)")
expectEqual(path, FilePath(root: path.root, path.components), "init<C>(root:components)")
expectEqual(path, FilePath(
root: path.root, path.components[...]),
"init(_ components: Slice)")
let reversedPathComponents = path.components.reversed()
expectEqual(expectedComponents.count, reversedPathComponents.count)
expectEqualSequence(expectedComponents.reversed(), reversedPathComponents, "reversed")
expectEqualSequence(
expectedComponents, reversedPathComponents.reversed(), "doubly reversed")
expectEqualSequence(path.removingRoot().components, path.components,
"relativeComponents")
let doublyReversed = FilePath(
root: nil, path.removingRoot().components.reversed()
).components.reversed()
expectEqualSequence(path.removingRoot().components, doublyReversed,
"relative path doubly reversed")
expectTrue(path.starts(with: path.removingLastComponent()),
"starts(with: dirname)")
expectEqual(path.removingLastComponent(), FilePath(
root: path.root, path.components.dropLast()),
"ComponentView.dirname")
var prefixComps = expectedComponents
var prefixBasenamePath = path
var prefixPopLastPath = path
var compView = path.components[...]
var prefixDirname = path.removingLastComponent()
while !prefixComps.isEmpty {
expectTrue(path.starts(with: FilePath(root: path.root, prefixComps)), "startswith")
expectTrue(path.starts(with: prefixBasenamePath), "startswith")
expectTrue(path.starts(with: prefixPopLastPath), "startswith")
expectEqual(prefixBasenamePath, prefixPopLastPath, "popLast/basename")
expectEqual(prefixBasenamePath, FilePath(root: path.root, compView),
"popLast/basename")
prefixComps.removeLast()
prefixBasenamePath = prefixBasenamePath.removingLastComponent()
prefixPopLastPath.removeLastComponent()
compView = compView.dropLast()
expectEqual(prefixBasenamePath, prefixDirname, "prefix dirname")
prefixDirname = prefixDirname.removingLastComponent()
}
var suffixComps = expectedComponents
compView = path.components[...]
while !suffixComps.isEmpty {
expectTrue(path.ends(with: FilePath(root: nil, suffixComps)), "endswith")
expectEqual(FilePath(root: nil, compView), FilePath(root: nil, suffixComps))
suffixComps.removeFirst()
compView = compView.dropFirst()
}
// FIXME: If we add operator `/` back, uncomment this
#if false
let slashPath = _path.components.reduce("", /)
let pushPath: FilePath = _path.components.reduce(
into: "", { $0.pushLast($1) })
expectEqual(_path, slashPath, "`/`")
expectEqual(_path, pushPath, "pushLast")
#endif
}
func runAllTests() {
// Assert we were set up correctly if non-nil
func assertNonEmpty<C: Collection>(_ c: C?) {
assert(c == nil || !c!.isEmpty)
}
assertNonEmpty(root)
assertNonEmpty(basename)
assertNonEmpty(stem)
withWindowsPaths(enabled: isWindows) {
let path = FilePath(pathStr)
expectTrue((path == "") == path.isEmpty, "isEmpty")
expectEqual(normalized, path.description, "normalized")
var copy = path
copy.lexicallyNormalize()
expectEqual(copy == path, path.isLexicallyNormal, "isLexicallyNormal")
expectEqual(lexicallyNormalized, copy.description, "lexically normalized")
expectEqual(copy, path.lexicallyNormalized(), "lexicallyNormal")
expectEqual(absolute, path.isAbsolute, "absolute")
expectEqual(!absolute, path.isRelative, "!absolute")
expectEqual(root, path.root?.description, "root")
expectEqual(relative, path.removingRoot().description, "relative")
if path.isRelative {
if path.root == nil {
expectEqual(path, path.removingRoot(), "relative idempotent")
} else {
expectTrue(isWindows)
expectFalse(path == path.removingRoot())
var relPathCopy = path.removingRoot()
relPathCopy.root = path.root
expectEqual(path, relPathCopy)
// TODO: Windows root analysis tests
}
} else {
var pathCopy = path
pathCopy.root = nil
expectEqual(pathCopy, path.removingRoot(), "set nil root")
expectEqual(relative, path.removingRoot().description, "set root to nil")
pathCopy.root = path.root
expectTrue(pathCopy.isAbsolute)
expectEqual(path, pathCopy)
expectTrue(path.root != nil)
}
if let root = path.root {
var pathCopy = path
pathCopy.components.removeAll()
expectEqual(FilePath(root: root), pathCopy, "set empty relative")
} else {
var pathCopy = path
pathCopy.components.removeAll()
expectTrue(pathCopy.isEmpty, "set empty relative")
}
expectEqual(dirname, path.removingLastComponent().description, "dirname")
expectEqual(basename, path.lastComponent?.description, "basename")
do {
var path = path
var pathCopy = path
while !path.removingRoot().isEmpty {
pathCopy = pathCopy.removingLastComponent()
path.removeLastComponent()
expectEqual(path, pathCopy)
}
}
expectEqual(stem, path.stem, "stem")
expectEqual(`extension`, path.extension, "extension")
if let base = path.lastComponent {
expectEqual(path.stem, base.stem)
expectEqual(path.extension, base.extension)
}
var pathCopy = path
while pathCopy.extension != nil {
var name = pathCopy.lastComponent!.description
name.removeSubrange(name.lastIndex(of: ".")!...)
pathCopy.extension = nil
expectEqual(name, pathCopy.lastComponent!.description, "set nil extension (2)")
}
expectTrue(pathCopy.extension == nil, "set nil extension")
pathCopy = path
pathCopy.removeAll(keepingCapacity: true)
expectTrue(pathCopy.isEmpty)
testComponents(path, expected: self.components)
}
}
}
private struct WindowsRootTestCase: TestCase {
// We defer forming the path until `runAllTests()` executes,
// so that we can switch between unix and windows behavior.
let rootStr: String
let expected: String
let absolute: Bool
var file: StaticString
var line: UInt
}
/*System 0.0.2, @available(macOS 12.0, iOS 15.0, watchOS 8.0, tvOS 15.0, *)*/
extension WindowsRootTestCase {
func runAllTests() {
withWindowsPaths(enabled: true) {
let path = FilePath(rootStr)
expectEqual(expected, path.string)
expectNotNil(path.root)
expectEqual(path, FilePath(root: path.root ?? ""))
expectTrue(path.components.isEmpty)
expectTrue(path.removingRoot().isEmpty)
expectTrue(path.isLexicallyNormal)
}
}
}
/*System 0.0.2, @available(macOS 12.0, iOS 15.0, watchOS 8.0, tvOS 15.0, *)*/
final class FilePathSyntaxTest: XCTestCase {
func testPathSyntax() {
let unixPaths: Array<SyntaxTestCase> = [
.unix("", components: []),
.unix(
"/",
root: "/", relative: "",
components: []
),
.unix(
"/..",
root: "/", relative: "..",
dirname: "/", basename: "..",
components: [".."],
lexicallyNormalized: "/"
),
.unix(
"/.",
root: "/", relative: ".",
dirname: "/", basename: ".",
components: ["."],
lexicallyNormalized: "/"
),
.unix(
"/../.",
root: "/", relative: "../.",
dirname: "/..", basename: ".",
components: ["..", "."],
lexicallyNormalized: "/"
),
.unix(
".",
dirname: "", basename: ".",
components: ["."],
lexicallyNormalized: ""
),
.unix(
"..",
dirname: "", basename: "..",
components: [".."],
lexicallyNormalized: ".."
),
.unix(
"./..",
dirname: ".", basename: "..",
components: [".", ".."],
lexicallyNormalized: ".."
),
.unix(
"../.",
dirname: "..", basename: ".",
components: ["..", "."],
lexicallyNormalized: ".."
),
.unix(
"../..",
dirname: "..", basename: "..",
components: ["..", ".."],
lexicallyNormalized: "../.."
),
.unix(
"a/../..",
dirname: "a/..", basename: "..",
components: ["a", "..", ".."],
lexicallyNormalized: ".."
),
.unix(
"a/.././.././../b",
dirname: "a/.././.././..", basename: "b",
components: ["a", "..", ".", "..", ".", "..", "b"],
lexicallyNormalized: "../../b"
),
.unix(
"/a/.././.././../b",
root: "/", relative: "a/.././.././../b",
dirname: "/a/.././.././..", basename: "b",
components: ["a", "..", ".", "..", ".", "..", "b"],
lexicallyNormalized: "/b"
),
.unix(
"./.",
dirname: ".", basename: ".",
components: [".", "."],
lexicallyNormalized: ""
),
.unix(
"foo.txt",
dirname: "", basename: "foo.txt",
stem: "foo", extension: "txt",
components: ["foo.txt"]
),
.unix(
"a/foo/bar/../..",
dirname: "a/foo/bar/..", basename: "..",
components: ["a", "foo", "bar", "..", ".."],
lexicallyNormalized: "a"
),
.unix(
"a/./foo/bar/.././../.",
dirname: "a/./foo/bar/.././..", basename: ".",
components: ["a", ".", "foo", "bar", "..", ".", "..", "."],
lexicallyNormalized: "a"
),
.unix(
"a/../b",
dirname: "a/..", basename: "b",
components: ["a", "..", "b"],
lexicallyNormalized: "b"
),
.unix(
"/a/../b/../c/../../d",
root: "/", relative: "a/../b/../c/../../d",
dirname: "/a/../b/../c/../..", basename: "d",
components: ["a", "..", "b", "..", "c", "..", "..", "d"],
lexicallyNormalized: "/d"
),
.unix(
"/usr/bin/ls",
root: "/", relative: "usr/bin/ls",
dirname: "/usr/bin", basename: "ls",
components: ["usr", "bin", "ls"]
),
.unix(
"bin/ls",
dirname: "bin", basename: "ls",
components: ["bin", "ls"]
),
.unix(
"~/bar.app",
dirname: "~", basename: "bar.app",
stem: "bar", extension: "app",
components: ["~", "bar.app"]
),
.unix(
"~/bar.app.bak/",
normalized: "~/bar.app.bak",
dirname: "~", basename: "bar.app.bak",
stem: "bar.app", extension: "bak",
components: ["~", "bar.app.bak"]
),
.unix(
"/tmp/.",
root: "/", relative: "tmp/.",
dirname: "/tmp", basename: ".",
components: ["tmp", "."],
lexicallyNormalized: "/tmp"
),
.unix(
"/tmp/..",
root: "/", relative: "tmp/..",
dirname: "/tmp", basename: "..",
components: ["tmp", ".."],
lexicallyNormalized: "/"
),
.unix(
"/tmp/../",
normalized: "/tmp/..",
root: "/", relative: "tmp/..",
dirname: "/tmp", basename: "..",
components: ["tmp", ".."],
lexicallyNormalized: "/"
),
.unix(
"/tmp/./a/../b",
root: "/", relative: "tmp/./a/../b",
dirname: "/tmp/./a/..", basename: "b",
components: ["tmp", ".", "a", "..", "b"],
lexicallyNormalized: "/tmp/b"
),
.unix(
"/tmp/.hidden",
root: "/", relative: "tmp/.hidden",
dirname: "/tmp", basename: ".hidden",
components: ["tmp", ".hidden"]
),
.unix(
"/tmp/.hidden.",
root: "/", relative: "tmp/.hidden.",
dirname: "/tmp", basename: ".hidden.",
stem: ".hidden", extension: "",
components: ["tmp", ".hidden."]
),
.unix(
"/tmp/.hidden.o",
root: "/", relative: "tmp/.hidden.o",
dirname: "/tmp", basename: ".hidden.o",
stem: ".hidden", extension: "o",
components: ["tmp", ".hidden.o"]
),
.unix(
"/tmp/.hidden.o.",
root: "/", relative: "tmp/.hidden.o.",
dirname: "/tmp", basename: ".hidden.o.",
stem: ".hidden.o", extension: "",
components: ["tmp", ".hidden.o."]
),
// Backslash is not a separator, nor a root
.unix(
#"\bin\.\ls"#,
dirname: "", basename: #"\bin\.\ls"#,
stem: #"\bin\"#, extension: #"\ls"#,
components: [#"\bin\.\ls"#]
),
]
let windowsPaths: Array<SyntaxTestCase> = [
.windows(#""#, absolute: false, components: []),
.windows(
#"C"#,
absolute: false,
dirname: "", basename: "C",
components: ["C"]
),
.windows(
#"C:"#,
absolute: false,
root: #"C:"#, relative: #""#,
components: []
),
.windows(
#"C:\"#,
absolute: true,
root: #"C:\"#, relative: #""#,
components: []
),
.windows(
#"C:\foo\bar.exe"#,
absolute: true,
root: #"C:\"#, relative: #"foo\bar.exe"#,
dirname: #"C:\foo"#, basename: "bar.exe",
stem: "bar", extension: "exe",
components: ["foo", "bar.exe"]
),
.windows(
#"C:foo\bar"#,
absolute: false,
root: #"C:"#, relative: #"foo\bar"#,
dirname: #"C:foo"#, basename: "bar",
components: ["foo", "bar"]
),
.windows(
#"C:foo\bar\..\.."#,
absolute: false,
root: #"C:"#, relative: #"foo\bar\..\.."#,
dirname: #"C:foo\bar\.."#, basename: "..",
components: ["foo", "bar", "..", ".."],
lexicallyNormalized: "C:"
),
.windows(
#"C:foo\bar\..\..\.."#,
absolute: false,
root: #"C:"#, relative: #"foo\bar\..\..\.."#,
dirname: #"C:foo\bar\..\.."#, basename: "..",
components: ["foo", "bar", "..", "..", ".."],
lexicallyNormalized: "C:"
),
.windows(
#"\foo\bar.exe"#,
absolute: false,
root: #"\"#, relative: #"foo\bar.exe"#,
dirname: #"\foo"#, basename: "bar.exe",
stem: "bar", extension: "exe",
components: ["foo", "bar.exe"]
),
.windows(
#"foo\bar.exe"#,
absolute: false,
dirname: #"foo"#, basename: "bar.exe",
stem: "bar", extension: "exe",
components: ["foo", "bar.exe"]
),
.windows(
#"\\?\device\"#,
absolute: true,
root: #"\\?\device\"#, relative: "",
components: []
),
.windows(
#"\\?\device\folder\file.exe"#,
absolute: true,
root: #"\\?\device\"#, relative: #"folder\file.exe"#,
dirname: #"\\?\device\folder"#, basename: "file.exe",
stem: "file", extension: "exe",
components: ["folder", "file.exe"]
),
.windows(
#"\\?\UNC\server\share\"#,
absolute: true,
root: #"\\?\UNC\server\share\"#, relative: #""#,
components: []
),
.windows(
#"\\?\UNC\server\share\folder\file.txt"#,
absolute: true,
root: #"\\?\UNC\server\share\"#, relative: #"folder\file.txt"#,
dirname: #"\\?\UNC\server\share\folder"#, basename: "file.txt",
stem: "file", extension: "txt",
components: ["folder", "file.txt"]
),
.windows(
#"\\server\share\"#,
absolute: true,
root: #"\\server\share\"#, relative: "",
components: []
),
.windows(
#"\\server\share\folder\file.txt"#,
absolute: true,
root: #"\\server\share\"#, relative: #"folder\file.txt"#,
dirname: #"\\server\share\folder"#, basename: "file.txt",
stem: "file", extension: "txt",
components: ["folder", "file.txt"]
),
.windows(
#"\\server\share\folder\file.txt\.."#,
absolute: true,
root: #"\\server\share\"#, relative: #"folder\file.txt\.."#,
dirname: #"\\server\share\folder\file.txt"#, basename: "..",
components: ["folder", "file.txt", ".."],
lexicallyNormalized: #"\\server\share\folder"#
),
.windows(
#"\\server\share\folder\file.txt\..\.."#,
absolute: true,
root: #"\\server\share\"#, relative: #"folder\file.txt\..\.."#,
dirname: #"\\server\share\folder\file.txt\.."#, basename: "..",
components: ["folder", "file.txt", "..", ".."],
lexicallyNormalized: #"\\server\share\"#
),
.windows(
#"\\server\share\folder\file.txt\..\..\..\.."#,
absolute: true,
root: #"\\server\share\"#, relative: #"folder\file.txt\..\..\..\.."#,
dirname: #"\\server\share\folder\file.txt\..\..\.."#, basename: "..",
components: ["folder", "file.txt", "..", "..", "..", ".."],
lexicallyNormalized: #"\\server\share\"#
),
// Actually a rooted relative path
.windows(
#"\server\share\folder\file.txt\..\..\.."#,
absolute: false,
root: #"\"#, relative: #"server\share\folder\file.txt\..\..\.."#,
dirname: #"\server\share\folder\file.txt\..\.."#, basename: "..",
components: ["server", "share", "folder", "file.txt", "..", "..", ".."],
lexicallyNormalized: #"\server"#
),
.windows(
#"\\?\Volume{12345678-abcd-1111-2222-123445789abc}\folder\file"#,
absolute: true,
root: #"\\?\Volume{12345678-abcd-1111-2222-123445789abc}\"#,
relative: #"folder\file"#,
dirname: #"\\?\Volume{12345678-abcd-1111-2222-123445789abc}\folder"#,
basename: "file",
components: ["folder", "file"]
)
// TODO: partially-formed Windows roots, we should fully form them...
]
for test in unixPaths {
test.runAllTests()
}
for test in windowsPaths {
test.runAllTests()
}
}
func testPrefixSuffix() {
let startswith: Array<(String, String)> = [
("/usr/bin/ls", "/"),
("/usr/bin/ls", "/usr"),
("/usr/bin/ls", "/usr/bin"),
("/usr/bin/ls", "/usr/bin/ls"),
("/usr/bin/ls", "/usr/bin/ls//"),
("/usr/bin/ls", ""),
]
let noStartswith: Array<(String, String)> = [
("/usr/bin/ls", "/u"),
("/usr/bin/ls", "/us"),
("/usr/bin/ls", "/usr/bi"),
("/usr/bin/ls", "usr/bin/ls"),
("/usr/bin/ls", "usr/"),
("/usr/bin/ls", "ls"),
]
for (path, pre) in startswith {
XCTAssert(FilePath(path).starts(with: FilePath(pre)))
}
for (path, pre) in noStartswith {
XCTAssertFalse(FilePath(path).starts(with: FilePath(pre)))
}
let endswith: Array<(String, String)> = [
("/usr/bin/ls", "ls"),
("/usr/bin/ls", "bin/ls"),
("/usr/bin/ls", "usr/bin/ls"),
("/usr/bin/ls", "/usr/bin/ls"),
("/usr/bin/ls", "/usr/bin/ls///"),
("/usr/bin/ls", ""),
]
let noEndswith: Array<(String, String)> = [
("/usr/bin/ls", "/ls"),
("/usr/bin/ls", "/bin/ls"),
("/usr/bin/ls", "/usr/bin"),
("/usr/bin/ls", "foo"),
]
for (path, suf) in endswith {
XCTAssert(FilePath(path).ends(with: FilePath(suf)))
}
for (path, suf) in noEndswith {
XCTAssertFalse(FilePath(path).ends(with: FilePath(suf)))
}
}
func testLexicallyRelative() {
let path: FilePath = "/usr/local/bin"
XCTAssert(path.lexicallyRelative(toBase: "/usr/local") == "bin")
XCTAssert(path.lexicallyRelative(toBase: "/usr/local/bin/ls") == "..")
XCTAssert(path.lexicallyRelative(toBase: "/tmp/foo.txt") == "../../usr/local/bin")
XCTAssert(path.lexicallyRelative(toBase: "local/bin") == nil)
let rel = FilePath(root: nil, path.components)
XCTAssert(rel.lexicallyRelative(toBase: "/usr/local") == nil)
XCTAssert(rel.lexicallyRelative(toBase: "usr/local") == "bin")
XCTAssert(rel.lexicallyRelative(toBase: "usr/local/bin/ls") == "..")
XCTAssert(rel.lexicallyRelative(toBase: "tmp/foo.txt") == "../../usr/local/bin")
XCTAssert(rel.lexicallyRelative(toBase: "local/bin") == "../../usr/local/bin")
// TODO: Test Windows path with root pushed
}
func testAdHocMutations() {
var path: FilePath = "/usr/local/bin"
func expect(
_ s: String,
_ file: StaticString = #file,
_ line: UInt = #line
) {
if path == FilePath(s) { return }
defer { print("expected: \(s), actual: \(path)") }
XCTAssert(false, file: file, line: line)
}
// Run `body`, restoring `path` afterwards
func restoreAfter(
body: () -> ()
) {
let copy = path
defer { path = copy }
body()
}
restoreAfter {
path.root = nil
expect("usr/local/bin")
path.components = FilePath("ls").components
expect("ls")
}
restoreAfter {
path.components = FilePath("/bin/ls").components
expect("/bin/ls")
path.components.removeAll()
expect("/")
}
restoreAfter {
path = path.removingLastComponent().appending("lib")
expect("/usr/local/lib")
path = path.removingLastComponent()
expect("/usr/local")
path = path.removingLastComponent().appending("bin")
expect("/usr/bin")
}
restoreAfter {
path = FilePath("~").appending(path.lastComponent!)
expect("~/bin")
path = FilePath("").appending(path.lastComponent!)
expect("bin")
path = FilePath("").appending(path.lastComponent!)
expect("bin")
path = FilePath("/usr/local").appending(path.lastComponent!)
expect("/usr/local/bin")
}
restoreAfter {
path.removeLastComponent()
expect("/usr/local")
path.removeLastComponent()
expect("/usr")
path.removeLastComponent()
expect("/")
path.removeLastComponent()
expect("/")
path.removeAll()
expect("")
path.append("tmp")
expect("tmp")
path.append("cat")
expect("tmp/cat")
path.push("/")
expect("/")
path.append(".")
expect("/.")
XCTAssert(path.components.last!.kind == .currentDirectory)
path.lexicallyNormalize()
expect("/")
path.append("..")
expect("/..")
XCTAssert(path.components.last!.kind == .parentDirectory)
path.lexicallyNormalize()
expect("/")
path.append("foo")
path.append("..")
expect("/foo/..")
path.lexicallyNormalize()
expect("/")
}
restoreAfter {
path.append("ls")
expect("/usr/local/bin/ls")
path.extension = "exe"
expect("/usr/local/bin/ls.exe")
path.extension = "txt"
expect("/usr/local/bin/ls.txt")
path.extension = nil
expect("/usr/local/bin/ls")
path.extension = ""
expect("/usr/local/bin/ls.")
XCTAssert(path.extension == "")
path.extension = "txt"
expect("/usr/local/bin/ls.txt")
}
restoreAfter {
path.append("..")
expect("/usr/local/bin/..")
XCTAssert(path.components.last!.kind == .parentDirectory)
path.extension = "txt"
expect("/usr/local/bin/..")
XCTAssert(path.components.last!.kind == .parentDirectory)
path.removeAll()
expect("")
path.extension = "txt"
expect("")
path.append("/")
expect("/")
path.extension = "txt"
expect("/")
}
restoreAfter {
XCTAssert(!path.removePrefix("/usr/bin"))
expect("/usr/local/bin")
XCTAssert(!path.removePrefix("/us"))
expect("/usr/local/bin")
XCTAssert(path.removePrefix("/usr/local"))
expect("bin")
XCTAssert(path.removePrefix("bin"))
expect("")
}
restoreAfter {
path.append("utils/widget/")
expect("/usr/local/bin/utils/widget")
path.append("/bin///ls")
expect("/usr/local/bin/utils/widget/bin/ls")
path.push("/bin/ls")
expect("/bin/ls")
path.append("/")
expect("/bin/ls")
path.push("/")
expect("/")
path.append("tmp")
expect("/tmp")
path.append("foo/bar")
expect("/tmp/foo/bar")
XCTAssert(!path.isEmpty)
path.append(FilePath.Component("baz"))
expect("/tmp/foo/bar/baz")
path.append("/")
expect("/tmp/foo/bar/baz")
path.removeAll()
expect("")
XCTAssert(path.isEmpty)
path.append("")
expect("")
path.append("/bar/baz")
expect("/bar/baz")
path.removeAll()
expect("")
path.append(FilePath.Component("usr"))
expect("usr")
path.push("/bin/ls")
expect("/bin/ls")
path.removeAll()
expect("")
path.append("bar/baz")
expect("bar/baz")
path.append(["a", "b", "c"])
expect("bar/baz/a/b/c")
path.removeAll()
expect("")
path.append(["a", "b", "c"])
expect("a/b/c")
}
restoreAfter {
expect("/usr/local/bin")
path.push("bar/baz")
expect("/usr/local/bin/bar/baz")
path.push("/")
expect("/")
path.push("tmp")
expect("/tmp")
path.push("/dev/null")
expect("/dev/null")
}
restoreAfter {
let same = path.string
path.reserveCapacity(0)
expect(same)
path.reserveCapacity(1000)
expect(same)
}
restoreAfter {
XCTAssert(path.lexicallyContains("usr"))
XCTAssert(path.lexicallyContains("/usr"))
XCTAssert(path.lexicallyContains("local/bin"))
XCTAssert(!path.lexicallyContains("/local/bin"))
path.append("..")
XCTAssert(!path.lexicallyContains("local/bin"))
XCTAssert(path.lexicallyContains("local/bin/.."))
expect("/usr/local/bin/..")
XCTAssert(path.lexicallyContains("usr/local"))
XCTAssert(path.lexicallyContains("usr/local/."))
}
restoreAfter {
XCTAssert(path.lexicallyResolving("ls") == "/usr/local/bin/ls")
XCTAssert(path.lexicallyResolving("/ls") == "/usr/local/bin/ls")
XCTAssert(path.lexicallyResolving("../bin/ls") == nil)
XCTAssert(path.lexicallyResolving("/../bin/ls") == nil)
XCTAssert(path.lexicallyResolving("/../bin/../lib/target") == nil)
XCTAssert(path.lexicallyResolving("./ls/../../lib/target") == nil)
let staticContent: FilePath = "/var/www/my-website/static"
let links: [FilePath] =
["index.html", "/assets/main.css", "../../../../etc/passwd"]
let paths = links.map { staticContent.lexicallyResolving($0) }
XCTAssert(paths == [
"/var/www/my-website/static/index.html",
"/var/www/my-website/static/assets/main.css",
nil])
}
restoreAfter {
path = "/tmp"
let sub: FilePath = "foo/./bar/../baz/."
for comp in sub.components.filter({ $0.kind != .currentDirectory }) {
path.append(comp)
}
expect("/tmp/foo/bar/../baz")
}
restoreAfter {
path = "/usr/bin"
let binIdx = path.components.firstIndex(of: "bin")!
path.components.insert("local", at: binIdx)
expect("/usr/local/bin")
}
restoreAfter {
path = "/./home/./username/scripts/./tree"
let scriptIdx = path.components.lastIndex(of: "scripts")!
path.components.insert("bin", at: scriptIdx)
expect("/./home/./username/bin/scripts/./tree")
path.components.removeAll { $0.kind == .currentDirectory }
expect("/home/username/bin/scripts/tree")
}
restoreAfter {
path = "/usr/bin"
XCTAssert(path.removeLastComponent())
expect("/usr")
XCTAssert(path.removeLastComponent())
expect("/")
XCTAssertFalse(path.removeLastComponent())
expect("/")
}
restoreAfter {
path = ""
path.append("/var/www/website")
expect("/var/www/website")
path.append("static/assets")
expect("/var/www/website/static/assets")
path.append("/main.css")
expect("/var/www/website/static/assets/main.css")
}
}
func testFailableStringInitializers() {
let invalidComps: Array<String> = [
"", "/", "a/b",
]
let invalidRoots: Array<String> = [
"", "a", "a/b",
]
for c in invalidComps {
XCTAssertNil(FilePath.Component(c))
}
for c in invalidRoots {
XCTAssertNil(FilePath.Root(c))
}
// Due to SE-0213, this is how you call he failable init explicitly,
// otherwise it will be considered a literal `as` cast.
XCTAssertNil(FilePath.Component.init("/"))
}
func testPartialWindowsRoots() {
func partial(
_ str: String,
_ full: String,
absolute: Bool = true,
file: StaticString = #file, line: UInt = #line
) -> WindowsRootTestCase {
WindowsRootTestCase(
rootStr: str, expected: full, absolute: absolute,
file: file, line: line)
}
func full(
_ str: String, absolute: Bool = true,
file: StaticString = #file, line: UInt = #line
) -> WindowsRootTestCase {
partial(str, str, absolute: absolute,
file: file, line: line)
}
// TODO: Some of these are kinda funky (like `\\` -> `\\\\`), but
// I'm not aware of a sane fixup behavior here, so we go
// with a lesser of insanes.
let partialRootTestCases: [WindowsRootTestCase] = [
// Full roots
full(#"\"#, absolute: false),
full(#"C:"#, absolute: false),
full(#"C:\"#),
// Full UNCs (with omitted fields)
full(#"\\server\share\"#),
full(#"\\server\\"#),
full(#"\\\share\"#),
full(#"\\\\"#),
// Full device UNCs (with omitted fields)
full(#"\\.\UNC\server\share\"#),
full(#"\\.\UNC\server\\"#),
full(#"\\.\UNC\\share\"#),
full(#"\\.\UNC\\\"#),
// Full device (with omitted fields)
full(#"\\.\volume\"#),
full(#"\\.\\"#),
// Partial UNCs
partial(#"\\server\share"#, #"\\server\share\"#),
partial(#"\\server\"#, #"\\server\\"#),
partial(#"\\server"#, #"\\server\\"#),
partial(#"\\\\"#, #"\\\\"#),
partial(#"\\\"#, #"\\\\"#),
partial(#"\\"#, #"\\\\"#),
// Partial device UNCs
partial(#"\\.\UNC\server\share"#, #"\\.\UNC\server\share\"#),
partial(#"\\.\UNC\server\"#, #"\\.\UNC\server\\"#),
partial(#"\\.\UNC\server"#, #"\\.\UNC\server\\"#),
partial(#"\\.\UNC\\\"#, #"\\.\UNC\\\"#),
partial(#"\\.\UNC\\"#, #"\\.\UNC\\\"#),
partial(#"\\.\UNC\"#, #"\\.\UNC\\\"#),
partial(#"\\.\UNC"#, #"\\.\UNC\\\"#),
// Partial device
partial(#"\\.\volume"#, #"\\.\volume\"#),
partial(#"\\.\"#, #"\\.\\"#),
partial(#"\\."#, #"\\.\\"#),
]
for partialRootTest in partialRootTestCases {
partialRootTest.runAllTests()
}
}
}
| apache-2.0 | cdcca775825b7fb18596bb1ca23ecbbd | 27.767987 | 95 | 0.548221 | 4.222855 | false | false | false | false |
xiaowen707447083/startDemo | LanouCProject/LanouCProject/src/home/SmoreFrameView.swift | 1 | 5526 | //
// SmoreFrameView.swift
// LanouCProject
//
// Created by lanou on 15/8/21.
// Copyright (c) 2015年 lanou3g. All rights reserved.
//
import UIKit
class SmoreFrameView: UIView {
typealias funcBlockA = (String,String) -> ()//定义一个指针类型
typealias funcBlockB = (String) -> ()
override init(frame: CGRect) {
super.init(frame: frame)
// createMyView()
}
required init(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
var dataArr:Array<SmoreModel>!
var scrollerView:UIScrollView!
var topTitleText:String!
var itemBlock:funcBlockA?
var moreBlock:funcBlockB?
func createMyView(title:String,data:Array<SmoreModel>,blockItem:funcBlockA,blockMore:funcBlockB){
dataArr = data
topTitleText = title
itemBlock = blockItem
moreBlock = blockMore
self.backgroundColor = UIColor.whiteColor()//白色背景
var topView:UIView = UIView(frame: CGRectMake(0, 0, self.frame.size.width, 50))
var topTitle:UILabel = UILabel(frame: CGRectMake(10, 10, 100, 45))
topTitle.text = topTitleText
topTitle.font = UIFont.systemFontOfSize(16)
topTitle.textAlignment = NSTextAlignment.Left
topTitle.textColor = UIColor.blackColor()
topView.addSubview(topTitle)
var topRight:UILabel = UILabel(frame: CGRectMake(self.frame.width - 70, 10, 60, 45))
topRight.text = "更多 >"
topRight.textColor = UIColor(red: 100/255.0, green: 100/255.0, blue: 100/255.0, alpha: 1)
topRight.textAlignment = NSTextAlignment.Center
topRight.font = UIFont.systemFontOfSize(14)
topView.addSubview(topRight)
self.addSubview(topView)
//添加点击事件
topRight.userInteractionEnabled = true
var tap1 = UITapGestureRecognizer(target: self, action: Selector("ontouchMore"))
tap1.numberOfTapsRequired = 1
topRight.addGestureRecognizer(tap1)
var high:CGFloat = self.frame.height - 60
var width:CGFloat = high * 3/2
var width1:CGFloat = 10
//scrollerView布局
scrollerView = UIScrollView(frame: CGRectMake(0, 50, self.frame.size.width, self.frame.size.height - 50))
scrollerView.backgroundColor = UIColor.whiteColor()
scrollerView.contentSize = CGSizeMake((width + 10.0) * CGFloat(dataArr.count) + 10, high)
scrollerView.showsHorizontalScrollIndicator = false
self.addSubview(scrollerView)
for var i:Int = 0;i<dataArr.count;i++ {
var indexX:CGFloat = CGFloat(i)*width+(CGFloat(i)+1)*width1
var tempView:UIView = UIView(frame: CGRectMake(indexX, 0, width, high))
scrollerView.addSubview(tempView)
var tempSmore:SmoreModel = dataArr[i]
if (tempSmore.imageUrl? != nil) {//如果图片链接为空
var imgView = UIImageView(frame: CGRectMake(0, 0, width, high))
imgView.sd_setImageWithURL(NSURL(string: tempSmore.imageUrl!))
tempView.addSubview(imgView)
//覆盖层
var tempView2:UIView = UIView(frame: CGRectMake(indexX, 0, width, high))
tempView2.backgroundColor = UIColor.grayColor()
tempView2.alpha = 0.3
scrollerView.addSubview(tempView2)
}else {
tempView.backgroundColor = tempSmore.color //背景色
}
//文字框
var tempView1:UIView = UIView(frame: CGRectMake(indexX, 0, width, high))
tempView1.backgroundColor = UIColor.clearColor()
tempView1.alpha = 1
scrollerView.addSubview(tempView1)
var label1:UILabel = UILabel(frame: CGRectMake(0, high/2 - 25, width, 25))
label1.textAlignment = NSTextAlignment.Center
label1.textColor = UIColor.whiteColor()
label1.font = UIFont.boldSystemFontOfSize(16)
label1.text = tempSmore.title
tempView1.addSubview(label1)
var label2:UILabel = UILabel(frame: CGRectMake(0, high/2 + 5, width, 20))
label2.textAlignment = NSTextAlignment.Center
label2.textColor = UIColor.whiteColor()
label2.font = UIFont.systemFontOfSize(14)
label2.text = tempSmore.titleDis
tempView1.addSubview(label2)
//添加点击事件
var tap = SmoreUITapGestureRecognizer(target: self, action: Selector("ontouchItem:"))
tap.numberOfTapsRequired = 1
tap.myTag = i
tap.itemTitle = tempSmore.title
tempView1.addGestureRecognizer(tap)
}
}
func ontouchItem(tap:SmoreUITapGestureRecognizer){
println("你点击了'\(topTitleText)'下的'\(tap.itemTitle)'")
itemBlock?(topTitleText,tap.itemTitle)
}
func ontouchMore(){
println("你点击了'\(topTitleText)'的更多")
moreBlock?(topTitleText)
}
}
class SmoreUITapGestureRecognizer: UITapGestureRecognizer {
var myTag = 0; //标志
var itemTitle = "" //item的标题
}
class SmoreModel:NSObject {
var title:String!
var titleDis:String!
var imageUrl:String?
var color:UIColor?
} | apache-2.0 | d8c6e373728fff8564212148e8333e81 | 33.608974 | 113 | 0.605224 | 4.559122 | false | false | false | false |
nlap/NLSpinner | NLSpinnerDemo/ViewController.swift | 1 | 2052 | //
// ViewController.swift
// NLSpinnerDemo
//
// Created by Nathan Lapierre on 2017-03-13.
//
//
import Cocoa
import NLSpinner
class ViewController: NSViewController {
@IBOutlet weak var spinner : NLSpinner!
@IBOutlet weak var startStopButton : NSButton!
@IBOutlet weak var colorButton : NSButton!
@IBOutlet weak var speedButton : NSButton!
@IBOutlet weak var showWhenStopped : NSButton!
override func viewDidLoad() {
super.viewDidLoad()
spinner.startAnimation()
}
override var representedObject: Any? {
didSet {
}
}
//start and stopping is simple...
@IBAction func startStopSpinner(_ sender:AnyObject?) {
if (spinner.isAnimating) {
spinner.stopAnimation()
changeShowWhenStopped(self)
startStopButton.title = "Start"
colorButton.isEnabled = false
speedButton.isEnabled = false
} else {
spinner.startAnimation()
startStopButton.title = "Stop"
colorButton.isEnabled = true
speedButton.isEnabled = true
}
}
//...so is changing the color
@IBAction func changeSpinnerColor(_ sender:AnyObject?) {
spinner.foregroundColor = NSColor(red: CGFloat(drand48()), green: CGFloat(drand48()), blue: CGFloat(drand48()), alpha: 1.0)
}
//the speed is set by tickDelay, which is the delay in seconds before advancing the highlighted fin
@IBAction func changeSpinnerSpeed(_ sender:AnyObject?) {
if (spinner.tickDelay == 0.05) {
spinner.tickDelay = 0.01
} else {
spinner.tickDelay = 0.05
}
}
//can optionally hide spinner when stopped, otherwise it fades slightly
@IBAction func changeShowWhenStopped(_ sender:AnyObject?) {
if (showWhenStopped.state == NSControl.StateValue.on) {
spinner.isDisplayedWhenStopped = true
} else {
spinner.isDisplayedWhenStopped = false
}
}
}
| mit | 04db7e6217f71012e760fc113b777cb8 | 27.109589 | 131 | 0.616959 | 4.897375 | false | false | false | false |
EvansPie/EPDeckView | Pod/Classes/EPDeckViewAnimationManager.swift | 1 | 3498 | //
// DeckViewAnimationManager.swift
// EPDeckView
//
// Created by Evangelos Pittas on 25/02/16.
// Copyright © 2016 EP. All rights reserved.
//
// Released under an MIT license: http://opensource.org/licenses/MIT
//
import Foundation
import UIKit
public class EPDeckViewAnimationManager {
// MARK: CARDVIEW DRAGGING ANIMATION VARS
//________________________________________________________________________________________
// The limit (on the x-axis) which the card being dragged will move out of the screen or
// back in its position. It's measured from the top card's center.
public var actionMargin: CGFloat = 0.0
// The lower the rotation strength the larger the rotation angle of the card being dragged.
public var rotationStrength: CGFloat = 320.0
// The max rotation angle of the card being dragged.
public var rotationMax: CGFloat = 360.0
// This rotation angle will be achieved when the distance of the top card's center (i.e.
// the card being dragged) is equal to the rotationStrength.
public var rotationAngle: CGFloat = 22.5
public var scaleStrength: CGFloat = 4.0
// The max scaling percentage of the card being dragged. It takes values 0.0 ~> 1.0. E.g.
// if the scaleMax is 0.93 the minimum scaling that will be applied on the card is until
// it reached 7% of its original value.
public var scaleMax: CGFloat = 0.93
public var cardLeftFinishPoint: CGPoint = CGPointZero
public var cardRightFinishPoint: CGPoint = CGPointZero
// MARK: DECKVIEW ANIMATION VARS
//________________________________________________________________________________________
// A reference to the DeckView that is the owner of this DeckViewAnimationManager.
public var deckView: UIView?
// The animation duration of a card moving in/out of the screen, as well as the duration
// that the rest of the deck moves.
public var deckAnimationDuration: NSTimeInterval = 0.3
// The corner that serves as the anchor point.
public var deckAnchor: EPDeckViewAnchor = .BottomLeft
// The angle difference of the cards in the DeckView.
public var deckCardAngleDelta: CGFloat = 7.0
// The scale difference (as a percentage) of the cards in the DeckView.
public var deckViewCardScaleDelta: CGFloat = 0.08
// The transparancy difference of the cards in the DeckView. The last card is always
// completely transparent.
public var deckCardAlphaDelta: CGFloat = 0.05
// The number of visible cards in the DeckView (provided that they are not transparent).
public var deckMaxVisibleCards: Int = 5
// The deck's top card's center.
public var deckCenter: CGPoint = CGPointZero
public var frame: CGRect? {
didSet {
}
}
// MARK: - Initialization
public init() {
}
public init(frame: CGRect) {
self.frame = frame
self.deckCenter = CGPointMake((self.frame!.origin.x + self.frame!.size.width/2), (self.frame!.origin.y + self.frame!.size.height/2))
self.actionMargin = self.frame!.width / 2
self.cardLeftFinishPoint = CGPointMake(-self.frame!.width * 1.5, self.frame!.height / 3.0)
self.cardRightFinishPoint = CGPointMake(self.frame!.width * 1.5, self.frame!.height / 3.0)
}
}
| mit | 55dfa72df1cf72bc9110e13e7f9ec378 | 25.492424 | 140 | 0.622248 | 4.449109 | false | false | false | false |
nathan/hush | Hush/NSTextField+secure.swift | 1 | 923 | import Cocoa
extension NSTextField {
var secure: Bool {
get {return cell?.secure ?? false}
set {
guard newValue != secure else {return}
let new = newValue ? NSSecureTextFieldCell() : NSTextFieldCell()
if let attributed = placeholderAttributedString {
new.placeholderAttributedString = attributed
} else {
new.placeholderString = placeholderString
}
if allowsEditingTextAttributes {
new.attributedStringValue = attributedStringValue
} else {
new.stringValue = stringValue
}
new.isSelectable = isSelectable
new.isEditable = isEditable
new.isBezeled = isBezeled
new.bezelStyle = bezelStyle
new.font = font
cell = new
setNeedsDisplay()
}
}
}
extension NSCell {
var secure: Bool {get {return false}}
}
extension NSSecureTextFieldCell {
override var secure: Bool {get {return true}}
}
| unlicense | 9f4693c28a2e0f80d5fe33c26dc7247c | 25.371429 | 70 | 0.659805 | 4.989189 | false | false | false | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.