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 |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
morganabel/cordova-plugin-audio-playlist | src/ios/JukeboxItem.swift | 1 | 14669 | //
// JukeboxItem.swift
//
// Copyright (c) 2015 Teodor Patraş
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
import Foundation
import AVFoundation
import MediaPlayer
protocol JukeboxItemDelegate : class {
func jukeboxItemDidLoadPlayerItem(_ item: JukeboxItem)
func jukeboxItemReadyToPlay(_ item: JukeboxItem)
func jukeboxItemDidUpdate(_ item: JukeboxItem)
func jukeboxItemDidFail(_ item: JukeboxItem)
}
open class JukeboxItem: NSObject {
// MARK:- Properties -
fileprivate var didLoad = false
var delegate: JukeboxItemDelegate?
open var identifier: String
open var localId: String?
open var localTitle: String?
open let URL: Foundation.URL
open let remoteUrl: Foundation.URL
fileprivate(set) open var playerItem: AVPlayerItem?
fileprivate (set) open var currentTime: Double?
fileprivate(set) open lazy var meta = Meta()
/// Builder to supply custom metadata for item.
public var customMetaBuilder: MetaBuilder? {
didSet {
self.configureMetadata()
}
}
fileprivate var timer: Timer?
fileprivate let observedValue = "timedMetadata"
// MARK:- Initializer -
/**
Create an instance with an URL and local title
- parameter URL: local or remote URL of the audio file
- parameter localTitle: an optional title for the file
- returns: JukeboxItem instance
*/
public required init(URL : Foundation.URL, remoteUrl: Foundation.URL, localTitle : String? = nil, id: String? = nil) {
self.URL = URL
self.remoteUrl = remoteUrl
self.identifier = UUID().uuidString
self.localId = id
self.localTitle = localTitle
super.init()
configureMetadata()
}
override open func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
if change?[NSKeyValueChangeKey(rawValue:"name")] is NSNull {
delegate?.jukeboxItemDidFail(self)
return
}
if keyPath == observedValue {
if let item = playerItem , item === object as? AVPlayerItem {
guard let metadata = item.timedMetadata else { return }
for item in metadata {
if self.customMetaBuilder?.hasMetaItem(item) != true { // custom meta takes precedence
meta.process(metaItem: item)
}
}
}
scheduleNotification()
}
if keyPath == #keyPath(AVPlayerItem.status) {
let status: AVPlayerItemStatus
// Get the status change from the change dictionary
if let statusNumber = change?[.newKey] as? NSNumber {
status = AVPlayerItemStatus(rawValue: statusNumber.intValue)!
} else {
status = .unknown
}
// Switch over the status
switch status {
case .readyToPlay:
// Player item is ready to play.
self.delegate?.jukeboxItemReadyToPlay(self)
break
case .failed: break
// Player item failed. See error.
case .unknown: break
// Player item is not yet ready.
}
}
if keyPath == #keyPath(AVPlayerItem.isPlaybackLikelyToKeepUp) {
// Preloaded enough that it should play smoothly.
// If going to play at this point, check not curently .paused status
}
if keyPath == #keyPath(AVPlayerItem.isPlaybackBufferEmpty) {
// Playback likely to stall or end.
}
}
deinit {
removeObservers()
}
// MARK: - Internal methods -
func loadPlayerItem() {
if let item = playerItem {
refreshPlayerItem(withAsset: item.asset)
delegate?.jukeboxItemDidLoadPlayerItem(self)
return
} else if didLoad {
return
} else {
didLoad = true
}
loadAsync { (asset) -> () in
if self.validateAsset(asset) {
self.refreshPlayerItem(withAsset: asset)
self.delegate?.jukeboxItemDidLoadPlayerItem(self)
} else {
self.didLoad = false
}
}
}
func refreshPlayerItem(withAsset asset: AVAsset) {
// Removed any existing observers.
removeObservers()
// Create player item with asset.
playerItem = AVPlayerItem(asset: asset)
// Add observers for metadata and item status, respectively.
playerItem?.addObserver(self, forKeyPath: observedValue, options: NSKeyValueObservingOptions.new, context: nil)
playerItem?.addObserver(self, forKeyPath: #keyPath(AVPlayerItem.status), options: [.old, .new], context: nil)
playerItem?.addObserver(self, forKeyPath: #keyPath(AVPlayerItem.isPlaybackLikelyToKeepUp), options: NSKeyValueObservingOptions.new, context: nil)
playerItem?.addObserver(self, forKeyPath: #keyPath(AVPlayerItem.isPlaybackBufferEmpty), options: NSKeyValueObservingOptions.new, context: nil)
NotificationCenter.default.addObserver(self, selector: #selector(playerItemFailedToPlay(_:)), name: NSNotification.Name.AVPlayerItemFailedToPlayToEndTime, object: nil)
// Update metadata.
update()
}
func update() {
if let item = playerItem {
meta.duration = item.asset.duration.seconds
currentTime = item.currentTime().seconds
}
}
open override var description: String {
return "<JukeboxItem:\ntitle: \(meta.title)\nalbum: \(meta.album)\nartist:\(meta.artist)\nduration : \(meta.duration),\ncurrentTime : \(currentTime)\nURL: \(URL)>"
}
// MARK:- Private methods -
fileprivate func validateAsset(_ asset : AVURLAsset) -> Bool {
var e: NSError?
asset.statusOfValue(forKey: "duration", error: &e)
if let error = e {
var message = "\n\n***** Jukebox fatal error*****\n\n"
if error.code == -1022 {
message += "It looks like you're using Xcode 7 and due to an App Transport Security issue (absence of SSL-based HTTP) the asset cannot be loaded from the specified URL: \"\(URL)\".\nTo fix this issue, append the following to your .plist file:\n\n<key>NSAppTransportSecurity</key>\n<dict>\n\t<key>NSAllowsArbitraryLoads</key>\n\t<true/>\n</dict>\n\n"
fatalError(message)
}
if error.code == NSNotFound {
message += "Item not found at the specified URL: \"\(URL)\""
fatalError(message)
}
if error.code == NSURLErrorResourceUnavailable {
message += "Item not found at the specified URL: \"\(URL)\""
fatalError(message)
}
// Notify of failure.
self.delegate?.jukeboxItemDidFail(self)
return false
}
return true
}
@objc fileprivate func playerItemFailedToPlay(_ notification : Notification) {
let error = notification.userInfo?[AVPlayerItemFailedToPlayToEndTimeErrorKey] as? Error
}
fileprivate func scheduleNotification() {
timer?.invalidate()
timer = nil
timer = Timer.scheduledTimer(timeInterval: 0.5, target: self, selector: #selector(JukeboxItem.notifyDelegate), userInfo: nil, repeats: false)
}
func notifyDelegate() {
timer?.invalidate()
timer = nil
self.delegate?.jukeboxItemDidUpdate(self)
}
fileprivate func loadAsync(_ completion: @escaping (_ asset: AVURLAsset) -> ()) {
DispatchQueue.global(qos: .background).async {
let asset = AVURLAsset(url: self.URL, options: nil)
asset.loadValuesAsynchronously(forKeys: ["duration"], completionHandler: { () -> Void in
DispatchQueue.main.async {
completion(asset)
}
})
}
}
fileprivate func configureMetadata() {
// process custom metadata first
if let customMetaBuilder = self.customMetaBuilder {
self.meta.processBuilder(customMetaBuilder)
}
DispatchQueue.global(qos: .background).async {
let metadataArray = AVPlayerItem(url: self.URL).asset.commonMetadata
for item in metadataArray
{
item.loadValuesAsynchronously(forKeys: [AVMetadataKeySpaceCommon], completionHandler: { () -> Void in
self.meta.process(metaItem: item)
DispatchQueue.main.async {
self.scheduleNotification()
}
})
}
}
}
fileprivate func removeObservers() {
playerItem?.removeObserver(self, forKeyPath: observedValue)
playerItem?.removeObserver(self, forKeyPath: #keyPath(AVPlayerItem.status))
playerItem?.removeObserver(self, forKeyPath: #keyPath(AVPlayerItem.isPlaybackLikelyToKeepUp))
playerItem?.removeObserver(self, forKeyPath: #keyPath(AVPlayerItem.isPlaybackBufferEmpty))
NotificationCenter.default.removeObserver(self, name: NSNotification.Name.AVPlayerItemDidPlayToEndTime, object: nil)
}
/// Item Metadata
public class Meta: Any {
/// The duration of the item
internal(set) public var duration: Double?
/// The title of the item.
internal(set) public var title: String?
/// The album name of the item.
internal(set) public var album: String?
/// The artist name of the item.
internal(set) public var artist: String?
/// Album artwork for the item.
internal(set) public var artwork: UIImage?
}
/// Builder for custom Metadata
public class MetaBuilder: Meta {
public typealias MetaBuilderClosure = (MetaBuilder) -> ()
// MARK: Properties
private var _title: String?
public override var title: String? {
get {
return _title
} set (newTitle) {
_title = newTitle
}
}
private var _album: String?
public override var album: String? {
get {
return _album
} set (newAlbum) {
_album = newAlbum
}
}
private var _artist: String?
public override var artist: String? {
get {
return _artist
} set (newArtist) {
_artist = newArtist
}
}
private var _artwork: UIImage?
public override var artwork: UIImage? {
get {
return _artwork
} set (newArtwork) {
_artwork = newArtwork
}
}
// MARK: Init
public init(_ build: MetaBuilderClosure) {
super.init()
build(self)
}
}
}
private extension JukeboxItem.Meta {
func process(metaItem item: AVMetadataItem) {
switch item.commonKey
{
case "title"? :
title = item.value as? String
case "albumName"? :
album = item.value as? String
case "artist"? :
artist = item.value as? String
case "artwork"? :
processArtwork(fromMetadataItem : item)
default :
break
}
}
func processBuilder(_ metaBuilder: JukeboxItem.MetaBuilder) {
if let builderTitle = metaBuilder.title {
title = builderTitle
}
if let builderAlbum = metaBuilder.album {
album = builderAlbum
}
if let builderArtist = metaBuilder.artist {
artist = builderArtist
}
if let builderArtwork = metaBuilder.artwork {
artwork = builderArtwork
}
}
func processArtwork(fromMetadataItem item: AVMetadataItem) {
guard let value = item.value else { return }
let copiedValue: AnyObject = value.copy(with: nil) as AnyObject
if let dict = copiedValue as? [AnyHashable: Any] {
//AVMetadataKeySpaceID3
if let imageData = dict["data"] as? Data {
artwork = UIImage(data: imageData)
}
} else if let data = copiedValue as? Data{
//AVMetadataKeySpaceiTunes
artwork = UIImage(data: data)
}
}
}
fileprivate extension JukeboxItem.MetaBuilder {
/// Whether the metadata builder has a specific AVMetadataItem value
///
/// - Parameter metadataItem: The item to check for.
/// - Returns: Whether the metadata exists.
fileprivate func hasMetaItem(_ metadataItem: AVMetadataItem) -> Bool {
switch metadataItem.commonKey {
case "title"? :
return self.title != nil
case "albumName"? :
return self.album != nil
case "artist"? :
return self.artist != nil
case "artwork"? :
return self.artwork != nil
default :
return false
}
}
}
private extension CMTime {
var seconds: Double? {
let time = CMTimeGetSeconds(self)
guard time.isNaN == false else { return nil }
return time
}
} | mit | 281e088147a30ef71eb784e50ef0a29d | 33.760664 | 365 | 0.591014 | 5.190375 | false | false | false | false |
ingresse/ios-sdk | IngresseSDK/Helpers/DateHelper.swift | 1 | 1881 | //
// DateHelper.swift
// IngresseSDK
//
// Created by Rubens Gondek on 1/20/17.
// Copyright © 2016 Gondek. All rights reserved.
//
import Foundation
enum DateFormat: String {
case timestamp = "yyyy-MM-dd'T'HH:mm:ssZ"
case gmtTimestamp = "yyyy-MM-dd'T'HH:mm:ss'Z'"
case dateHourSpace = "dd/MM/yyyy HH:mm"
case dateHourAt = "dd/MM/yyyy 'às' HH:mm"
}
extension Date {
/// Transform into string based on format
///
/// - Parameter format: String format of desired output (default is "dd/MM/yyyy HH:mm")
/// - Returns: Date converted to string
func toString(format: DateFormat = .dateHourSpace) -> String {
let formatter = DateFormatter()
formatter.dateFormat = format.rawValue
formatter.timeZone = TimeZone(abbreviation: "GMT")
formatter.locale = Locale(identifier: "en_US_POSIX")
return formatter.string(from: self)
}
/// Get week day string with 3 characters
func weekDay() -> String {
let calendar = Calendar(identifier: Calendar.Identifier.gregorian)
let comp = (calendar as NSCalendar).components(.weekday, from: self)
guard let day = comp.weekday,
day > 0 && day <= 7
else { return "---" }
return ["DOM", "SEG", "TER", "QUA", "QUI", "SEX", "SAB"][day-1]
}
}
extension String {
/// Convert string to Date
///
/// - Parameter format: Current string format (default is "yyyy-MM-dd'T'HH:mm:ssZ")
/// - Returns: Date converted from string (Current date returned in case of error)
func toDate(format: DateFormat = .timestamp) -> Date {
let formatter = DateFormatter()
formatter.dateFormat = format.rawValue
let posix = Locale(identifier: "en_US_POSIX")
formatter.locale = posix
return formatter.date(from: self) ?? Date()
}
}
| mit | 765a6b6d0165c54dd255d065ebde076b | 30.316667 | 91 | 0.615753 | 3.882231 | false | false | false | false |
hejunbinlan/GRDB.swift | GRDB Tests/Public/Record/MinimalPrimaryKeySingleTests.swift | 2 | 13973 | import XCTest
import GRDB
// MinimalRowID is the most tiny class with a Single row primary key which
// supports read and write operations of Record.
class MinimalSingle: Record {
var UUID: String!
override class func databaseTableName() -> String? {
return "minimalSingles"
}
override var storedDatabaseDictionary: [String: DatabaseValueConvertible?] {
return ["UUID": UUID]
}
override func updateFromRow(row: Row) {
if let dbv = row["UUID"] { UUID = dbv.value() }
super.updateFromRow(row) // Subclasses are required to call super.
}
static func setupInDatabase(db: Database) throws {
try db.execute(
"CREATE TABLE minimalSingles (UUID TEXT NOT NULL PRIMARY KEY)")
}
}
class MinimalPrimaryKeySingleTests: GRDBTestCase {
override func setUp() {
super.setUp()
var migrator = DatabaseMigrator()
migrator.registerMigration("createMinimalSingle", MinimalSingle.setupInDatabase)
assertNoError {
try migrator.migrate(dbQueue)
}
}
// MARK: - Insert
func testInsertWithNilPrimaryKeyThrowsDatabaseError() {
assertNoError {
try dbQueue.inDatabase { db in
let record = MinimalSingle()
XCTAssertTrue(record.UUID == nil)
do {
try record.insert(db)
XCTFail("Expected DatabaseError")
} catch is DatabaseError {
// Expected DatabaseError
}
}
}
}
func testInsertWithNotNilPrimaryKeyThatDoesNotMatchAnyRowInsertsARow() {
assertNoError {
try dbQueue.inDatabase { db in
let record = MinimalSingle()
record.UUID = "theUUID"
try record.insert(db)
let row = Row.fetchOne(db, "SELECT * FROM minimalSingles WHERE UUID = ?", arguments: [record.UUID])!
for (key, value) in record.storedDatabaseDictionary {
if let dbv = row[key] {
XCTAssertEqual(dbv, value?.databaseValue ?? .Null)
} else {
XCTFail("Missing column \(key) in fetched row")
}
}
}
}
}
func testInsertWithNotNilPrimaryKeyThatMatchesARowThrowsDatabaseError() {
assertNoError {
try dbQueue.inDatabase { db in
let record = MinimalSingle()
record.UUID = "theUUID"
try record.insert(db)
do {
try record.insert(db)
XCTFail("Expected DatabaseError")
} catch is DatabaseError {
// Expected DatabaseError
}
}
}
}
func testInsertAfterDeleteInsertsARow() {
assertNoError {
try dbQueue.inDatabase { db in
let record = MinimalSingle()
record.UUID = "theUUID"
try record.insert(db)
try record.delete(db)
try record.insert(db)
let row = Row.fetchOne(db, "SELECT * FROM minimalSingles WHERE UUID = ?", arguments: [record.UUID])!
for (key, value) in record.storedDatabaseDictionary {
if let dbv = row[key] {
XCTAssertEqual(dbv, value?.databaseValue ?? .Null)
} else {
XCTFail("Missing column \(key) in fetched row")
}
}
}
}
}
// MARK: - Update
func testUpdateWithNotNilPrimaryKeyThatDoesNotMatchAnyRowThrowsRecordNotFound() {
assertNoError {
try dbQueue.inDatabase { db in
let record = MinimalSingle()
record.UUID = "theUUID"
do {
try record.update(db)
XCTFail("Expected RecordError.RecordNotFound")
} catch RecordError.RecordNotFound {
// Expected RecordError.RecordNotFound
}
}
}
}
func testUpdateWithNotNilPrimaryKeyThatMatchesARowUpdatesThatRow() {
assertNoError {
try dbQueue.inDatabase { db in
let record = MinimalSingle()
record.UUID = "theUUID"
try record.insert(db)
try record.update(db)
let row = Row.fetchOne(db, "SELECT * FROM minimalSingles WHERE UUID = ?", arguments: [record.UUID])!
for (key, value) in record.storedDatabaseDictionary {
if let dbv = row[key] {
XCTAssertEqual(dbv, value?.databaseValue ?? .Null)
} else {
XCTFail("Missing column \(key) in fetched row")
}
}
}
}
}
func testUpdateAfterDeleteThrowsRecordNotFound() {
assertNoError {
try dbQueue.inDatabase { db in
let record = MinimalSingle()
record.UUID = "theUUID"
try record.insert(db)
try record.delete(db)
do {
try record.update(db)
XCTFail("Expected RecordError.RecordNotFound")
} catch RecordError.RecordNotFound {
// Expected RecordError.RecordNotFound
}
}
}
}
// MARK: - Save
func testSaveWithNilPrimaryKeyThrowsDatabaseError() {
assertNoError {
try dbQueue.inDatabase { db in
let record = MinimalSingle()
XCTAssertTrue(record.UUID == nil)
do {
try record.save(db)
XCTFail("Expected DatabaseError")
} catch is DatabaseError {
// Expected DatabaseError
}
}
}
}
func testSaveWithNotNilPrimaryKeyThatDoesNotMatchAnyRowInsertsARow() {
assertNoError {
try dbQueue.inDatabase { db in
let record = MinimalSingle()
record.UUID = "theUUID"
try record.save(db)
let row = Row.fetchOne(db, "SELECT * FROM minimalSingles WHERE UUID = ?", arguments: [record.UUID])!
for (key, value) in record.storedDatabaseDictionary {
if let dbv = row[key] {
XCTAssertEqual(dbv, value?.databaseValue ?? .Null)
} else {
XCTFail("Missing column \(key) in fetched row")
}
}
}
}
}
func testSaveWithNotNilPrimaryKeyThatMatchesARowUpdatesThatRow() {
assertNoError {
try dbQueue.inDatabase { db in
let record = MinimalSingle()
record.UUID = "theUUID"
try record.insert(db)
try record.save(db)
let row = Row.fetchOne(db, "SELECT * FROM minimalSingles WHERE UUID = ?", arguments: [record.UUID])!
for (key, value) in record.storedDatabaseDictionary {
if let dbv = row[key] {
XCTAssertEqual(dbv, value?.databaseValue ?? .Null)
} else {
XCTFail("Missing column \(key) in fetched row")
}
}
}
}
}
func testSaveAfterDeleteInsertsARow() {
assertNoError {
try dbQueue.inDatabase { db in
let record = MinimalSingle()
record.UUID = "theUUID"
try record.insert(db)
try record.delete(db)
try record.save(db)
let row = Row.fetchOne(db, "SELECT * FROM minimalSingles WHERE UUID = ?", arguments: [record.UUID])!
for (key, value) in record.storedDatabaseDictionary {
if let dbv = row[key] {
XCTAssertEqual(dbv, value?.databaseValue ?? .Null)
} else {
XCTFail("Missing column \(key) in fetched row")
}
}
}
}
}
// MARK: - Delete
func testDeleteWithNotNilPrimaryKeyThatDoesNotMatchAnyRowDoesNothing() {
assertNoError {
try dbQueue.inDatabase { db in
let record = MinimalSingle()
record.UUID = "theUUID"
let deletionResult = try record.delete(db)
XCTAssertEqual(deletionResult, Record.DeletionResult.NoRowDeleted)
}
}
}
func testDeleteWithNotNilPrimaryKeyThatMatchesARowDeletesThatRow() {
assertNoError {
try dbQueue.inDatabase { db in
let record = MinimalSingle()
record.UUID = "theUUID"
try record.insert(db)
let deletionResult = try record.delete(db)
XCTAssertEqual(deletionResult, Record.DeletionResult.RowDeleted)
let row = Row.fetchOne(db, "SELECT * FROM minimalSingles WHERE UUID = ?", arguments: [record.UUID])
XCTAssertTrue(row == nil)
}
}
}
func testDeleteAfterDeleteDoesNothing() {
assertNoError {
try dbQueue.inDatabase { db in
let record = MinimalSingle()
record.UUID = "theUUID"
try record.insert(db)
var deletionResult = try record.delete(db)
XCTAssertEqual(deletionResult, Record.DeletionResult.RowDeleted)
deletionResult = try record.delete(db)
XCTAssertEqual(deletionResult, Record.DeletionResult.NoRowDeleted)
}
}
}
// MARK: - Reload
func testReloadWithNotNilPrimaryKeyThatDoesNotMatchAnyRowThrowsRecordNotFound() {
assertNoError {
try dbQueue.inDatabase { db in
let record = MinimalSingle()
record.UUID = "theUUID"
do {
try record.reload(db)
XCTFail("Expected RecordError.RecordNotFound")
} catch RecordError.RecordNotFound {
// Expected RecordError.RecordNotFound
}
}
}
}
func testReloadWithNotNilPrimaryKeyThatMatchesARowFetchesThatRow() {
assertNoError {
try dbQueue.inDatabase { db in
let record = MinimalSingle()
record.UUID = "theUUID"
try record.insert(db)
try record.reload(db)
let row = Row.fetchOne(db, "SELECT * FROM minimalSingles WHERE UUID = ?", arguments: [record.UUID])!
for (key, value) in record.storedDatabaseDictionary {
if let dbv = row[key] {
XCTAssertEqual(dbv, value?.databaseValue ?? .Null)
} else {
XCTFail("Missing column \(key) in fetched row")
}
}
}
}
}
func testReloadAfterDeleteThrowsRecordNotFound() {
assertNoError {
try dbQueue.inDatabase { db in
let record = MinimalSingle()
record.UUID = "theUUID"
try record.insert(db)
try record.delete(db)
do {
try record.reload(db)
XCTFail("Expected RecordError.RecordNotFound")
} catch RecordError.RecordNotFound {
// Expected RecordError.RecordNotFound
}
}
}
}
// MARK: - Select
func testSelectWithPrimaryKey() {
assertNoError {
try dbQueue.inDatabase { db in
let record = MinimalSingle()
record.UUID = "theUUID"
try record.insert(db)
let fetchedRecord = MinimalSingle.fetchOne(db, primaryKey: record.UUID)!
XCTAssertTrue(fetchedRecord.UUID == record.UUID)
}
}
}
func testSelectWithKey() {
assertNoError {
try dbQueue.inDatabase { db in
let record = MinimalSingle()
record.UUID = "theUUID"
try record.insert(db)
let fetchedRecord = MinimalSingle.fetchOne(db, key: ["UUID": record.UUID])!
XCTAssertTrue(fetchedRecord.UUID == record.UUID)
}
}
}
// MARK: - Exists
func testExistsWithNotNilPrimaryKeyThatDoesNotMatchAnyRowReturnsFalse() {
dbQueue.inDatabase { db in
let record = MinimalSingle()
record.UUID = "theUUID"
XCTAssertFalse(record.exists(db))
}
}
func testExistsWithNotNilPrimaryKeyThatMatchesARowReturnsTrue() {
assertNoError {
try dbQueue.inDatabase { db in
let record = MinimalSingle()
record.UUID = "theUUID"
try record.insert(db)
XCTAssertTrue(record.exists(db))
}
}
}
func testExistsAfterDeleteReturnsTrue() {
assertNoError {
try dbQueue.inDatabase { db in
let record = MinimalSingle()
record.UUID = "theUUID"
try record.insert(db)
try record.delete(db)
XCTAssertFalse(record.exists(db))
}
}
}
}
| mit | d4229295e9e588d1154ccec5f6173376 | 33.331695 | 116 | 0.501038 | 5.951022 | false | true | false | false |
overtake/TelegramSwift | packages/TGUIKit/Sources/TokenizedView.swift | 1 | 18328 | //
// TokenizedView.swift
// TGUIKit
//
// Created by keepcoder on 07/08/2017.
// Copyright © 2017 Telegram. All rights reserved.
//
import Cocoa
import SwiftSignalKit
public struct SearchToken : Equatable {
public let name:String
public let uniqueId:Int64
public init(name:String, uniqueId: Int64) {
self.name = name
self.uniqueId = uniqueId
}
}
public func ==(lhs:SearchToken, rhs: SearchToken) -> Bool {
return lhs.name == rhs.name && lhs.uniqueId == rhs.uniqueId
}
private class TokenView : Control {
fileprivate let token:SearchToken
private var isFailed: Bool = false
private let dismiss: ImageButton = ImageButton()
private let nameView: TextView = TextView()
fileprivate var immediatlyPaste: Bool = true
override var isSelected: Bool {
didSet {
updateLocalizationAndTheme(theme: presentation)
}
}
private let customTheme: ()->TokenizedView.Theme
init(_ token: SearchToken, maxSize: NSSize, onDismiss:@escaping()->Void, onSelect: @escaping()->Void, customTheme:@escaping()->TokenizedView.Theme) {
self.token = token
self.customTheme = customTheme
super.init()
self.layer?.cornerRadius = 6
let layout = TextViewLayout(.initialize(string: token.name, color: customTheme().underSelectColor, font: .normal(.title)), maximumNumberOfLines: 1)
layout.measure(width: maxSize.width - 30)
self.nameView.update(layout)
nameView.userInteractionEnabled = false
nameView.isSelectable = false
setFrameSize(NSMakeSize(layout.layoutSize.width + 30, maxSize.height))
dismiss.autohighlight = false
updateLocalizationAndTheme(theme: presentation)
needsLayout = true
addSubview(nameView)
addSubview(dismiss)
dismiss.set(handler: { _ in
onDismiss()
}, for: .Click)
set(handler: { _ in
onSelect()
}, for: .Click)
}
fileprivate func setFailed(_ isFailed: Bool, animated: Bool) {
self.isFailed = isFailed
self.updateLocalizationAndTheme(theme: presentation)
if isFailed {
self.shake()
}
}
fileprivate var isPerfectSized: Bool {
return nameView.textLayout?.isPerfectSized ?? false
}
override func change(size: NSSize, animated: Bool = true, _ save: Bool = true, removeOnCompletion: Bool = false, duration: Double = 0.2, timingFunction: CAMediaTimingFunctionName = CAMediaTimingFunctionName.easeOut, completion: ((Bool) -> Void)? = nil) {
nameView.textLayout?.measure(width: size.width - 30)
let size = NSMakeSize(min(((nameView.textLayout?.layoutSize.width ?? 0) + 30), size.width), size.height)
super.change(size: size, animated: animated, save, duration: duration, timingFunction: timingFunction)
let point = focus(dismiss.frame.size)
dismiss.change(pos: NSMakePoint(frame.width - 5 - dismiss.frame.width, point.minY), animated: animated)
nameView.update(nameView.textLayout)
}
override func layout() {
super.layout()
nameView.centerY(x: 5)
nameView.setFrameOrigin(5, nameView.frame.minY - 1)
dismiss.centerY(x: frame.width - 5 - dismiss.frame.width)
}
var _backgroundColor: NSColor {
var r:CGFloat = 0, g:CGFloat = 0, b:CGFloat = 0, a:CGFloat = 0
var redSelected = customTheme().redColor
redSelected.getRed(&r, green: &g, blue: &b, alpha: &a)
redSelected = NSColor(red: min(r + 0.1, 1.0), green: min(g + 0.1, 1.0), blue: min(b + 0.1, 1.0), alpha: a)
return isSelected ? (isFailed ? redSelected : customTheme().accentSelectColor) : (isFailed ? customTheme().redColor : customTheme().accentColor)
}
override func updateLocalizationAndTheme(theme: PresentationTheme) {
super.updateLocalizationAndTheme(theme: theme)
dismiss.set(image: #imageLiteral(resourceName: "Icon_SearchClear").precomposed(customTheme().underSelectColor.withAlphaComponent(0.7)), for: .Normal)
dismiss.set(image: #imageLiteral(resourceName: "Icon_SearchClear").precomposed(customTheme().underSelectColor), for: .Highlight)
_ = dismiss.sizeToFit()
nameView.backgroundColor = .clear
self.background = _backgroundColor
}
required public init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
required public init(frame frameRect: NSRect) {
fatalError("init(frame:) has not been implemented")
}
}
public protocol TokenizedProtocol : class {
func tokenizedViewDidChangedHeight(_ view: TokenizedView, height: CGFloat, animated: Bool)
}
public class TokenizedView: ScrollView, AppearanceViewProtocol, NSTextViewDelegate {
public struct Theme {
let background: NSColor
let grayBackground: NSColor
let textColor: NSColor
let grayTextColor: NSColor
let underSelectColor: NSColor
let accentColor: NSColor
let accentSelectColor: NSColor
let redColor: NSColor
public init(background: NSColor = presentation.colors.background,
grayBackground: NSColor = presentation.colors.grayBackground,
textColor: NSColor = presentation.colors.text,
grayTextColor: NSColor = presentation.colors.grayText,
underSelectColor: NSColor = presentation.colors.underSelectedColor,
accentColor: NSColor = presentation.colors.accent,
accentSelectColor: NSColor = presentation.colors.accentSelect,
redColor: NSColor = presentation.colors.redUI) {
self.background = background
self.textColor = textColor
self.grayBackground = grayBackground
self.grayTextColor = grayTextColor
self.underSelectColor = underSelectColor
self.accentColor = accentColor
self.accentSelectColor = accentSelectColor
self.redColor = redColor
}
}
private var tokens:[SearchToken] = []
private var failedTokens:[Int64] = []
private let container: View = View()
private let input:SearchTextField = SearchTextField()
private(set) public var state: SearchFieldState = .None {
didSet {
stateValue.set(state)
}
}
public let stateValue: ValuePromise<SearchFieldState> = ValuePromise(.None, ignoreRepeated: true)
private var selectedIndex: Int? = nil {
didSet {
for view in container.subviews {
if let view = view as? TokenView {
view.isSelected = selectedIndex != nil && view.token == tokens[selectedIndex!]
}
}
}
}
private let _tokensUpdater:Promise<[SearchToken]> = Promise([])
public var tokensUpdater:Signal<[SearchToken], NoError> {
return _tokensUpdater.get()
}
private let _textUpdater:ValuePromise<String> = ValuePromise("", ignoreRepeated: true)
public var textUpdater:Signal<String, NoError> {
return _textUpdater.get()
}
public weak var delegate: TokenizedProtocol? = nil
private let placeholder: TextView = TextView()
public func addTokens(tokens: [SearchToken], animated: Bool) -> Void {
self.tokens.append(contentsOf: tokens)
for token in tokens {
let view = TokenView(token, maxSize: NSMakeSize(80, 22), onDismiss: { [weak self] in
self?.removeTokens(uniqueIds: [token.uniqueId], animated: true)
}, onSelect: { [weak self] in
self?.selectedIndex = self?.tokens.firstIndex(of: token)
}, customTheme: self.customTheme)
container.addSubview(view)
}
_tokensUpdater.set(.single(self.tokens))
input.string = ""
textDidChange(Notification(name: NSText.didChangeNotification))
(contentView as? TGClipView)?.scroll(to: NSMakePoint(0, max(0, container.frame.height - frame.height)), animated: animated)
}
public func removeTokens(uniqueIds: [Int64], animated: Bool) {
for uniqueId in uniqueIds {
var index:Int? = nil
for i in 0 ..< tokens.count {
if tokens[i].uniqueId == uniqueId {
index = i
break
}
}
if let index = index {
tokens.remove(at: index)
for view in container.subviews {
if let view = view as? TokenView {
if view.token.uniqueId == uniqueId {
view.change(opacity: 0, animated: animated, completion: { [weak view] completed in
if completed {
view?.removeFromSuperview()
}
})
}
}
}
}
}
layoutContainer(animated: animated)
_tokensUpdater.set(.single(tokens))
}
private func layoutContainer(animated: Bool) {
CATransaction.begin()
let mainw = frame.width
let between = NSMakePoint(5, 4)
var point: NSPoint = between
var extraLine: Bool = false
let count = container.subviews.count
for i in 0 ..< count {
let subview = container.subviews[i]
let next = container.subviews[min(i + 1, count - 1)]
if let token = subview as? TokenView, token.layer?.opacity != 0 {
token.change(pos: point, animated: token.immediatlyPaste ? false : animated)
if animated, token.immediatlyPaste {
token.layer?.animateAlpha(from: 0, to: 1, duration: 0.2)
}
//token.change(size: NSMakeSize(100, token.frame.height), animated: animated)
token.immediatlyPaste = false
point.x += subview.frame.width + between.x
let dif = mainw - (point.x + (i == count - 1 ? mainw/3 : next.frame.width) + between.x)
if dif < between.x {
// if !token.isPerfectSized {
// token.change(size: NSMakeSize(frame.width - startPointX - between.x, token.frame.height), animated: animated)
// }
point.x = between.x
point.y += token.frame.height + between.y
}
}
if subview == container.subviews.last {
if mainw - point.x > mainw/3 {
extraLine = true
}
}
}
input.frame = NSMakeRect(point.x, point.y + 3, mainw - point.x - between.x, 16)
placeholder.change(pos: NSMakePoint(point.x + 6, point.y + 3), animated: animated)
placeholder.change(opacity: tokens.isEmpty ? 1.0 : 0.0, animated: animated)
let contentHeight = max(point.y + between.y + (extraLine ? 22 : 0), 30)
container.change(size: NSMakeSize(container.frame.width, contentHeight), animated: animated)
let height = min(contentHeight, 108)
if height != frame.height {
_change(size: NSMakeSize(mainw, height), animated: animated)
delegate?.tokenizedViewDidChangedHeight(self, height: height, animated: animated)
}
CATransaction.commit()
}
public func textView(_ textView: NSTextView, doCommandBy commandSelector: Selector) -> Bool {
let range = input.selectedRange()
if commandSelector == #selector(insertNewline(_:)) {
return true
}
if range.location == 0 {
if commandSelector == #selector(moveLeft(_:)) {
if let index = selectedIndex {
selectedIndex = max(index - 1, 0)
} else {
selectedIndex = tokens.count - 1
}
return true
} else if commandSelector == #selector(moveRight(_:)) {
if let index = selectedIndex {
if index + 1 == tokens.count {
selectedIndex = nil
input.setSelectedRange(NSMakeRange(input.string.length, 0))
} else {
selectedIndex = index + 1
}
return true
}
}
if commandSelector == #selector(deleteBackward(_:)) {
if let selectedIndex = selectedIndex {
removeTokens(uniqueIds: [tokens[selectedIndex].uniqueId], animated: true)
if selectedIndex != tokens.count {
self.selectedIndex = min(selectedIndex, tokens.count - 1)
} else {
self.selectedIndex = nil
input.setSelectedRange(NSMakeRange(input.string.length, 0))
}
return true
} else {
if !tokens.isEmpty {
self.selectedIndex = tokens.count - 1
return true
}
}
}
}
return false
}
open func textDidChange(_ notification: Notification) {
let pHidden = !input.string.isEmpty
if placeholder.isHidden != pHidden {
placeholder.isHidden = pHidden
}
if self.window?.firstResponder == self.input {
self.state = .Focus
}
_textUpdater.set(input.string)
selectedIndex = nil
}
public func textDidEndEditing(_ notification: Notification) {
self.didResignResponder()
}
public func textDidBeginEditing(_ notification: Notification) {
//self.didBecomeResponder()
}
public override var needsLayout: Bool {
set {
super.needsLayout = false
}
get {
return super.needsLayout
}
}
public override func layout() {
super.layout()
//layoutContainer(animated: false)
}
private let localizationFunc: (String)->String
private let placeholderKey: String
private let customTheme: ()->TokenizedView.Theme
required public init(frame frameRect: NSRect, localizationFunc: @escaping(String)->String, placeholderKey:String, customTheme: @escaping()->TokenizedView.Theme = { TokenizedView.Theme() }) {
self.localizationFunc = localizationFunc
self.placeholderKey = placeholderKey
self.customTheme = customTheme
super.init(frame: frameRect)
hasVerticalScroller = true
container.frame = bounds
container.autoresizingMask = [.width]
contentView.documentView = container
input.focusRingType = .none
input.backgroundColor = NSColor.clear
input.delegate = self
input.isRichText = false
input.textContainer?.widthTracksTextView = true
input.textContainer?.heightTracksTextView = false
input.isHorizontallyResizable = false
input.isVerticallyResizable = false
placeholder.set(handler: { [weak self] _ in
self?.window?.makeFirstResponder(self?.responder)
}, for: .Click)
input.font = .normal(.text)
container.addSubview(input)
container.addSubview(placeholder)
container.layer?.cornerRadius = 10
wantsLayer = true
self.layer?.cornerRadius = 10
self.layer?.backgroundColor = presentation.colors.grayBackground.cgColor
updateLocalizationAndTheme(theme: presentation)
}
public func markAsFailed(_ ids:[Int64], animated: Bool) {
self.failedTokens = ids
self.updateFailed(animated)
}
public func addTooltip(for id: Int64, text: String) {
for token in self.container.subviews {
if let token = token as? TokenView, token.token.uniqueId == id {
tooltip(for: token, text: text)
break
}
}
}
public func removeAllFailed(animated: Bool) {
self.failedTokens = []
self.updateFailed(animated)
}
private func updateFailed(_ animated: Bool) {
for token in self.container.subviews {
if let token = token as? TokenView {
token.setFailed(failedTokens.contains(token.token.uniqueId), animated: animated)
}
}
}
open func didResignResponder() {
state = .None
}
open func didBecomeResponder() {
state = .Focus
}
public var query: String {
return input.string
}
override public func becomeFirstResponder() -> Bool {
window?.makeFirstResponder(input)
return true
}
public var responder: NSResponder? {
return input
}
public func updateLocalizationAndTheme(theme: PresentationTheme) {
background = customTheme().background
contentView.background = customTheme().background
self.container.backgroundColor = customTheme().grayBackground
input.textColor = customTheme().textColor
input.insertionPointColor = customTheme().textColor
let placeholderLayout = TextViewLayout(.initialize(string: localizedString(placeholderKey), color: customTheme().grayTextColor, font: .normal(.title)), maximumNumberOfLines: 1)
placeholderLayout.measure(width: .greatestFiniteMagnitude)
placeholder.update(placeholderLayout)
placeholder.backgroundColor = customTheme().grayBackground
placeholder.isSelectable = false
layoutContainer(animated: false)
}
required public init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
| gpl-2.0 | f89232038fb0d238d91e420bd512704a | 35.801205 | 258 | 0.584002 | 5.122135 | false | false | false | false |
itsaboutcode/WordPress-iOS | WordPress/Classes/ViewRelated/What's New/Data store/AnnouncementsDataSource.swift | 1 | 1770 |
protocol AnnouncementsDataSource: UITableViewDataSource {
func registerCells(for tableView: UITableView)
var dataDidChange: (() -> Void)? { get set }
}
class FeatureAnnouncementsDataSource: NSObject, AnnouncementsDataSource {
private let store: AnnouncementsStore
private let cellTypes: [String: UITableViewCell.Type]
private var features: [WordPressKit.Feature] {
store.announcements.reduce(into: [WordPressKit.Feature](), {
$0.append(contentsOf: $1.features)
})
}
var dataDidChange: (() -> Void)?
init(store: AnnouncementsStore, cellTypes: [String: UITableViewCell.Type]) {
self.store = store
self.cellTypes = cellTypes
super.init()
}
func registerCells(for tableView: UITableView) {
cellTypes.forEach {
tableView.register($0.value, forCellReuseIdentifier: $0.key)
}
}
func numberOfSections(in: UITableView) -> Int {
return 1
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return features.count + 1
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
guard indexPath.row <= features.count - 1 else {
let cell = tableView.dequeueReusableCell(withIdentifier: "findOutMoreCell", for: indexPath) as? FindOutMoreCell ?? FindOutMoreCell()
cell.configure(with: URL(string: store.announcements.first?.detailsUrl ?? ""))
return cell
}
let cell = tableView.dequeueReusableCell(withIdentifier: "announcementCell", for: indexPath) as? AnnouncementCell ?? AnnouncementCell()
cell.configure(feature: features[indexPath.row])
return cell
}
}
| gpl-2.0 | 2fe0084b96d74481c80b2e15910ccd1d | 32.396226 | 144 | 0.668362 | 4.903047 | false | false | false | false |
heyogrady/SpaceEvaders | SpaceEvaders/Scoreboard.swift | 2 | 1736 | import SpriteKit
import GameKit
class Scoreboard {
var viewController: GameViewController?
let scoreboard = SKLabelNode(text: "Score: 0")
var score: Int = 0
var isHighScore = false
init(x: CGFloat, y: CGFloat) {
scoreboard.setScale(2.5)
scoreboard.fontName = "timeburner"
scoreboard.position = CGPoint(x: x, y: y)
scoreboard.horizontalAlignmentMode = .Left
scoreboard.zPosition = 10
}
func highScore() {
if score > NSUserDefaults.standardUserDefaults().integerForKey("highscore") {
NSUserDefaults.standardUserDefaults().setInteger(score, forKey: "highscore")
NSUserDefaults.standardUserDefaults().synchronize()
isHighScore = true
GCHelper.sharedInstance.reportLeaderboardIdentifier("leaderBoardID", score: score)
}
}
func addTo(parentNode: GameScene) -> Scoreboard {
parentNode.addChild(scoreboard)
return self
}
func addScore(score: Int) {
self.score += score
scoreboard.text = "Score: \(self.score)"
highScore()
}
func getScore() -> Int {
return score
}
func isHighscore() -> Bool {
return isHighScore
}
func getHighscoreLabel(size: CGSize) -> SKLabelNode {
let highscore = SKLabelNode(text: "High Score!")
highscore.position = CGPointMake(size.width / 2, size.height / 2 + 50)
highscore.fontColor = UIColor.redColor()
highscore.fontSize = 80
highscore.fontName = "timeburner"
highscore.runAction(SKAction.repeatActionForever(SKAction.sequence([SKAction.fadeInWithDuration(0.3), SKAction.fadeOutWithDuration(0.3)])))
return highscore
}
} | mit | ba0b3914f043f06e66c7fe3fc5ee60a1 | 30.017857 | 147 | 0.645161 | 4.808864 | false | false | false | false |
interstateone/Climate | Climate/View Controllers/DataViewController.swift | 1 | 4875 | //
// ViewController.swift
// Climate
//
// Created by Brandon Evans on 2014-07-18.
// Copyright (c) 2014 Brandon Evans. All rights reserved.
//
import UIKit
class DataViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
@IBOutlet var dataTableView: UITableView!
@IBOutlet var lastUpdatedButton: UIButton!
private var feed: Feed?
private let feedFormatter = FeedFormatter()
private let lastUpdatedFormatter = TTTTimeIntervalFormatter()
private var updateLabelTimer: NSTimer?
required init(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
override func viewDidLoad() {
super.viewDidLoad()
if let groupUserDefaults = NSUserDefaults(suiteName: "group.brandonevans.Climate") {
if let feedID = groupUserDefaults.valueForKey(SettingsFeedIDKey) as? NSString {
feed = Feed(feedID: feedID, handler: { [weak self] in
if let viewController = self {
viewController.updateUI()
viewController.updateLastUpdatedLabel()
viewController.updateStreams()
}
})
}
}
NSNotificationCenter.defaultCenter().addObserverForName(UIApplicationDidBecomeActiveNotification, object: nil, queue: NSOperationQueue.currentQueue(), usingBlock: { [weak self] (notification) -> Void in
self?.feed?.subscribe()
return
})
}
deinit {
NSNotificationCenter.defaultCenter().removeObserver(self, name: UIApplicationDidBecomeActiveNotification, object: nil)
}
override func viewDidAppear(animated: Bool) {
super.viewDidAppear(animated)
updateLabelTimer = NSTimer.scheduledTimerWithTimeInterval(1, target: self, selector: "updateLastUpdatedLabel", userInfo: nil, repeats: true);
updateLabelTimer!.tolerance = 0.5
if let feed = feed {
feed.subscribe()
feed.fetchIfNotSubscribed()
}
}
override func viewDidDisappear(animated: Bool) {
updateLabelTimer?.invalidate()
updateLabelTimer = nil
}
// MARK: UITableViewDataSource
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("DataCell", forIndexPath: indexPath) as DataCell
if let feed = feed {
let stream = feed.streams[indexPath.row] as XivelyDatastreamModel
cell.nameLabel.text = feedFormatter.humanizeStreamName(stream.info["id"] as NSString)
let unit = stream.info["unit"] as NSDictionary
let symbol = unit["symbol"] as NSString
let valueString = (stream.info["current_value"] as NSString) ?? "0"
let value = valueString.floatValue
cell.valueLabel.attributedText = formatValueColorized(value, symbol: symbol)
}
return cell
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
let streamCount = feed?.streams.count ?? 0
return streamCount
}
// MARK: Actions
@IBAction func fetchFeed(sender: AnyObject?) {
feed?.subscribe()
feed?.fetchIfNotSubscribed()
}
// MARK: Private
private func updateUI() {
dataTableView.reloadData()
}
internal func updateLastUpdatedLabel() {
if feed?.isSubscribed ?? false {
lastUpdatedButton.setTitle("Auto-updating", forState: .Normal)
}
else if let date = NSUserDefaults.standardUserDefaults().valueForKey(DataLastUpdatedKey) as? NSDate {
lastUpdatedButton.setTitle("Last updated \(lastUpdatedFormatter.stringForTimeIntervalFromDate(NSDate(), toDate: date))", forState: .Normal)
}
}
private func updateStreams() {
if let feed = feed {
let streamKeys = map(feed.streams, { (stream) -> String in
let s = stream as XivelyDatastreamModel
return s.info["id"] as String
})
if let groupDefaults = NSUserDefaults(suiteName: "group.brandonevans.Climate") {
groupDefaults.setObject(streamKeys, forKey: "AvailableStreamNames")
}
}
}
private func formatValueColorized(value: Float, symbol: String) -> NSAttributedString {
let formattedString = feedFormatter.formatValue(value, symbol: symbol)
let attributedString = NSMutableAttributedString(string: formattedString)
attributedString.addAttribute(NSForegroundColorAttributeName, value: UIColor.lightGrayColor(), range: NSMakeRange(attributedString.length - countElements(symbol), countElements(symbol)))
return attributedString
}
}
| mit | 1b18675539a130d4c521a0831c34535c | 36.21374 | 210 | 0.649026 | 5.392699 | false | false | false | false |
irshad281/IAImagePicker | IAImagePickerExample/IAImagePickerViewController.swift | 1 | 27198 | //
// IAImagePickerViewController.swift
// IAImagePickerExample
//
// Created by preeti rani on 26/04/17.
// Copyright © 2017 Innotical. All rights reserved.
//
import UIKit
import Photos
import AVFoundation
let keyWindow = UIApplication.shared.keyWindow
let screen_width = UIScreen.main.bounds.width
let screen_height = UIScreen.main.bounds.height
@objc protocol IAImagePickerDelegate1{
@objc optional func didFinishPickingMediaInfo(mediaInfo:[String:Any]? , pickedImage:UIImage?)
@objc optional func didCancelIAPicker()
}
enum MediaType{
case camera
case library
}
class PhotoCell: UICollectionViewCell {
let photoImageView:UIImageView = {
let imgView = UIImageView()
imgView.contentMode = .scaleAspectFill
imgView.clipsToBounds = true
imgView.translatesAutoresizingMaskIntoConstraints = false
imgView.isUserInteractionEnabled = true
return imgView
}()
override init(frame: CGRect) {
super.init(frame: frame)
self.addSubview(photoImageView)
self.backgroundColor = .clear
self.photoImageView.leftAnchor.constraint(equalTo: self.leftAnchor, constant: 0).isActive = true
self.photoImageView.rightAnchor.constraint(equalTo: self.rightAnchor, constant: 0).isActive = true
self.photoImageView.bottomAnchor.constraint(equalTo: self.bottomAnchor, constant: 0).isActive = true
self.photoImageView.topAnchor.constraint(equalTo: self.topAnchor, constant: 0).isActive = true
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
class IAImagePickerViewController: UIViewController , UICollectionViewDelegate , UICollectionViewDataSource , UIImagePickerControllerDelegate , UINavigationControllerDelegate{
let name = Bundle.main.infoDictionary![kCFBundleNameKey as String] as! String
var captureSession: AVCaptureSession?;
var previewLayer : AVCaptureVideoPreviewLayer?;
var captureDevice : AVCaptureDevice?
var stillImageOutput:AVCaptureStillImageOutput?
var photosArray = [PhotoModel]()
var orignalframe:CGRect?
var delegate:IAImagePickerDelegate1?
var capturedImageView:UIImageView?
var restrictionView:UIView!
var activity:UIActivityIndicatorView = UIActivityIndicatorView()
lazy var cameraView:UIView = {
let view = UIView.init(frame:CGRect.init(x: 0, y: 0, width: screen_width, height: screen_height))
view.backgroundColor = .white
return view
}()
lazy var photoCollectionView:UICollectionView = {
let flowLayout = UICollectionViewFlowLayout.init()
flowLayout.minimumLineSpacing = 5
flowLayout.itemSize = CGSize(width: 100, height: 100)
flowLayout.scrollDirection = .horizontal
let frame = CGRect.init(x: 0, y: screen_height - 200, width: screen_width, height: 100)
let photoCollectionView = UICollectionView.init(frame: frame, collectionViewLayout: flowLayout)
photoCollectionView.contentInset = UIEdgeInsetsMake(0, 0, 0, 0)
photoCollectionView.register(PhotoCell.self, forCellWithReuseIdentifier: "cellId")
photoCollectionView.backgroundColor = .clear
photoCollectionView.delegate = self
photoCollectionView.dataSource = self
return photoCollectionView
}()
lazy var crossButton:UIButton = {
let crossButton = UIButton.init(frame:CGRect.init(x: 20, y: 20, width: 30, height: 30))
crossButton.tintColor = .clear
crossButton.addTarget(self, action: #selector(self.handleCancel(_:)), for: .touchUpInside)
crossButton.setImage(#imageLiteral(resourceName: "multiply"), for: .normal)
return crossButton
}()
lazy var flashButton:UIButton = {
let flashButton = UIButton.init(frame:CGRect.init(x: screen_width - 50, y: 20, width: 30, height: 30))
flashButton.setImage(#imageLiteral(resourceName: "flashON"), for: .normal)
flashButton.setImage(#imageLiteral(resourceName: "flashOFF"), for: .selected)
flashButton.tintColor = .clear
flashButton.addTarget(self, action: #selector(self.handleFlash(_:)), for: .touchUpInside)
return flashButton
}()
lazy var captureButton:UIButton = {
let button = UIButton.init(frame: CGRect.init(x: 2, y: 2, width: 46, height: 46))
button.translatesAutoresizingMaskIntoConstraints = false
button.backgroundColor = .white
button.layer.cornerRadius = 23
button.clipsToBounds = true
button.addTarget(self, action: #selector(self.handleCapture(_:)), for: .touchUpInside)
return button
}()
lazy var useImageButton:UIButton = {
let button = UIButton.init(frame: CGRect.init(x: screen_width - 120, y: screen_height - 50, width: 100, height: 30))
button.setTitleColor(.white, for: .normal)
button.titleLabel?.font = UIFont.init(name: "Helvetica Neue", size: 15)
button.setTitle("USE PHOTO", for: .normal)
button.layer.cornerRadius = 3
button.layer.borderWidth = 1.0
button.backgroundColor = .black
button.layer.borderColor = UIColor.white.cgColor
button.clipsToBounds = true
button.addTarget(self, action: #selector(self.handleUseImage(_:)), for: .touchUpInside)
return button
}()
lazy var retakeButton:UIButton = {
let button = UIButton.init(frame: CGRect.init(x: 20, y: screen_height - 50, width: 80, height: 30))
button.setTitleColor(.white, for: .normal)
button.backgroundColor = .black
button.titleLabel?.font = UIFont.init(name: "Helvetica Neue", size: 15)
button.setTitle("RETAKE", for: .normal)
button.layer.cornerRadius = 3
button.layer.borderWidth = 1.0
button.layer.borderColor = UIColor.white.cgColor
button.clipsToBounds = true
button.addTarget(self, action: #selector(self.handleRetakePhoto(_:)), for: .touchUpInside)
return button
}()
lazy var captureView:UIView = {
let captureView = UIView.init(frame: CGRect.init(x: screen_width/2 - 25, y: screen_height - 70, width: 60, height: 60))
captureView.backgroundColor = .black
captureView.layer.cornerRadius = 30
captureView.clipsToBounds = true
captureView.layer.borderWidth = 5
captureView.layer.borderColor = UIColor.white.cgColor
let button = UIButton.init(frame: CGRect.init(x: 7.5, y: 7.5, width: 45, height: 45))
button.backgroundColor = .white
button.layer.cornerRadius = 22.5
button.clipsToBounds = true
button.addTarget(self, action: #selector(self.handleCapture(_:)), for: .touchUpInside)
captureView.addSubview(button)
return captureView
}()
lazy var albumButton:UIButton={
let albumButton = UIButton.init(frame:CGRect.init(x: 15, y: screen_height - 55, width: 45, height: 30))
albumButton.setImage(#imageLiteral(resourceName: "picture"), for: .normal)
albumButton.addTarget(self, action: #selector(self.hanldleOpenAlbum(_:)), for: .touchUpInside)
return albumButton
}()
func openSetting(_ sender:UIButton) {
print("Open Setting...")
let name = Bundle.main.infoDictionary![kCFBundleNameKey as String] as! String
print(name)
UIApplication.shared.openURL(URL(string: UIApplicationOpenSettingsURLString)!)
}
override func viewDidLoad() {
super.viewDidLoad()
self.flushSessionData()
self.view.backgroundColor = #colorLiteral(red: 0.9803921569, green: 0.9803921569, blue: 0.9803921569, alpha: 1)
self.captureSession = AVCaptureSession();
self.previewLayer = AVCaptureVideoPreviewLayer();
self.captureSession?.sessionPreset = AVCaptureSessionPresetHigh
self.stillImageOutput = AVCaptureStillImageOutput()
self.stillImageOutput?.outputSettings = [AVVideoCodecKey:AVVideoCodecJPEG]
self.photoCollectionView.reloadData()
_ = self.checkAutherizationStatusForCameraAndPhotoLibrary()
}
func addAfterPermission() {
accessPhotosFromLibrary()
let devices = AVCaptureDevice.devices()
// Loop through all the capture devices on this phone
for device in devices! {
// Make sure this particular device supports video
if ((device as AnyObject).hasMediaType(AVMediaTypeVideo)) {
// Finally check the position and confirm we've got the back camera
if((device as AnyObject).position == AVCaptureDevicePosition.back) {
self.captureDevice = device as? AVCaptureDevice
if self.captureDevice != nil {
self.beginSession()
}
}
}
}
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
}
func setUpViews(){
DispatchQueue.main.async {
self.cameraView.addSubview(self.crossButton)
self.cameraView.addSubview(self.flashButton)
self.cameraView.addSubview(self.albumButton)
self.cameraView.addSubview(self.captureView)
self.cameraView.addSubview(self.photoCollectionView)
}
}
func checkAutherizationStatusForCameraAndPhotoLibrary()->Bool{
var permissionStatus:Bool! = false
let libraryPermission = PHPhotoLibrary.authorizationStatus()
let cameraPermission = AVCaptureDevice.authorizationStatus(forMediaType: AVMediaTypeVideo)
if libraryPermission == .notDetermined || cameraPermission == .notDetermined{
PHPhotoLibrary.requestAuthorization({ (handlerStatus) in
if handlerStatus == .authorized{
if cameraPermission == .notDetermined{
self.checkPermissionForCamera()
}
permissionStatus = true
}else{
self.checkPermissionForCamera()
permissionStatus = false
}
})
}else{
if libraryPermission == .authorized && cameraPermission == .authorized{
DispatchQueue.main.async {
self.photoCollectionView.reloadData()
self.view.addSubview(self.cameraView)
self.addAfterPermission()
}
}else{
self.showRestrictionView(mediaType: .library)
}
}
return permissionStatus
}
func showRestrictionView(mediaType:MediaType){
if restrictionView != nil{
restrictionView.removeFromSuperview()
restrictionView = nil
}
DispatchQueue.main.async {
self.restrictionView = UIView.init(frame: UIScreen.main.bounds)
self.restrictionView.backgroundColor = .white
let imageView = UIImageView.init(frame: CGRect(x: screen_width/2 - 75, y: screen_height/2 - 145, width: 150, height: 150))
if mediaType == .camera{
imageView.image = #imageLiteral(resourceName: "camera3")
}else{
imageView.image = #imageLiteral(resourceName: "album")
}
self.restrictionView.addSubview(imageView)
let permissionDescriptionLable = UILabel.init(frame: CGRect.init(x: 10, y: screen_height/2 + 25, width: screen_width - 20, height: 60))
permissionDescriptionLable.numberOfLines = 0
permissionDescriptionLable.textColor = #colorLiteral(red: 0.1019607843, green: 0.3098039216, blue: 0.5098039216, alpha: 1)
permissionDescriptionLable.textAlignment = .center
permissionDescriptionLable.font = UIFont.init(name: "Helvetica Neue", size: 13)
permissionDescriptionLable.text = "Allow \(self.name) access to your camera to take photos within app.Go to Setting and turn on Photo and Camera"
self.restrictionView.addSubview(permissionDescriptionLable)
let openSettingButton = UIButton.init(frame: CGRect.init(x: screen_width/2 - 60, y: screen_height/2 + 105, width: 120, height: 30))
openSettingButton.setTitle("Open Setting", for: .normal)
openSettingButton.setTitleColor(#colorLiteral(red: 0.1019607843, green: 0.3098039216, blue: 0.5098039216, alpha: 1), for: .normal)
openSettingButton.addTarget(self, action: #selector(self.openSetting(_:)), for: .touchUpInside)
self.restrictionView.addSubview(openSettingButton)
self.view.addSubview(self.restrictionView)
self.view.bringSubview(toFront: self.restrictionView)
}
}
func checkPermissionForCamera(){
AVCaptureDevice.requestAccess(forMediaType: AVMediaTypeVideo, completionHandler: { (success) in
if success{
if let window = keyWindow{
DispatchQueue.main.async {
self.photoCollectionView.reloadData()
window.addSubview(self.cameraView)
self.addAfterPermission()
}
}
}else{
DispatchQueue.main.async {
self.showRestrictionView(mediaType: .library)
}
}
})
}
func configureDevice(flashMode:AVCaptureFlashMode) {
if let device = captureDevice {
do {
try device.lockForConfiguration()
if device.isFocusPointOfInterestSupported{
device.focusMode = .continuousAutoFocus
device.flashMode = flashMode
}
device.unlockForConfiguration()
} catch {
print(error.localizedDescription)
}
}
}
func beginSession() {
if (captureSession?.canAddOutput(stillImageOutput))! {
captureSession?.addOutput(stillImageOutput)
}
configureDevice(flashMode: .auto)
do {
captureSession?.startRunning()
captureSession?.addInput(try AVCaptureDeviceInput(device: captureDevice))
previewLayer = AVCaptureVideoPreviewLayer(session: captureSession)
previewLayer?.frame = cameraView.layer.frame
self.cameraView.layer.addSublayer(self.previewLayer!)
self.setUpViews()
} catch{
print(error.localizedDescription)
}
}
func handleFlash(_ sender:UIButton){
if sender.isSelected{
self.configureDevice(flashMode: .auto)
}else{
self.configureDevice(flashMode: .off)
}
sender.isSelected = !sender.isSelected
}
func handleCancel(_ sender:UIButton){
print("Handling dismiss.....")
UIView.animate(withDuration: 0.5, animations: {
self.cameraView.frame = CGRect(x: 0, y: screen_height, width: screen_width, height: screen_height)
self.dismiss(animated: true, completion: nil)
}) { (completed) in
self.cameraView.removeFromSuperview()
}
}
func handleUseImage(_ sender:UIButton){
print("Handling UseImage.....")
if let capturedImage = self.zoomedImageView{
UIView.animate(withDuration: 0.5, delay: 0, usingSpringWithDamping: 0.8, initialSpringVelocity: 0.5, options: .curveEaseOut, animations: {
self.cameraView.removeFromSuperview()
capturedImage.frame = CGRect(x: 0, y: screen_height, width: screen_width, height: screen_height)
self.delegate?.didFinishPickingMediaInfo!(mediaInfo: nil, pickedImage: self.zoomedImageView?.image)
self.dismiss(animated: true, completion: nil)
self.retakeButton.removeFromSuperview()
self.useImageButton.removeFromSuperview()
}, completion: { (completed) in
self.zoomedImageView?.removeFromSuperview()
self.zoomedImageView = nil
})
}
if let capturedPhoto = self.capturedImageView{
UIView.animate(withDuration: 0.5, delay: 0, usingSpringWithDamping: 0.8, initialSpringVelocity: 0.5, options: .curveEaseOut, animations: {
self.cameraView.removeFromSuperview()
capturedPhoto.frame = CGRect(x: 0, y: screen_height, width: screen_width, height: screen_height)
self.delegate?.didFinishPickingMediaInfo!(mediaInfo: nil, pickedImage: capturedPhoto.image)
self.dismiss(animated: true, completion: nil)
self.retakeButton.removeFromSuperview()
self.useImageButton.removeFromSuperview()
}, completion: { (completed) in
self.zoomedImageView?.removeFromSuperview()
self.zoomedImageView = nil
})
}
}
func handleRetakePhoto(_ sender:UIButton){
print("Handling Retake.....")
if let capturedImage = self.capturedImageView{
UIView.animate(withDuration: 0.33, animations: {
capturedImage.frame = CGRect(x: 0, y: screen_height, width: screen_width, height: screen_height)
self.retakeButton.removeFromSuperview()
self.useImageButton.removeFromSuperview()
}, completion: { (completed) in
self.capturedImageView?.removeFromSuperview()
self.capturedImageView = nil
})
}
if let capturedPhoto = self.zoomedImageView{
UIView.animate(withDuration: 0.33, animations: {
capturedPhoto.frame = self.orignalframe!
self.retakeButton.removeFromSuperview()
self.useImageButton.removeFromSuperview()
}, completion: { (completed) in
self.orignalImageView?.isHidden = false
self.zoomedImageView?.removeFromSuperview()
self.zoomedImageView = nil
})
}
}
func flushSessionData(){
captureSession = nil
captureDevice = nil
previewLayer?.removeFromSuperlayer()
previewLayer = nil
stillImageOutput = nil
}
func handleCapture(_ sender:UIButton){
print("Handling capture.....")
UIView.animate(withDuration: 0.33, animations: {
self.captureView.transform = CGAffineTransform(scaleX: 1.25, y: 1.25)
}) { (completed) in
self.captureView.transform = .identity
if let videoConnection = self.stillImageOutput?.connection(withMediaType: AVMediaTypeVideo) {
self.stillImageOutput?.captureStillImageAsynchronously(from: videoConnection) {
(imageDataSampleBuffer, error) -> Void in
if let imageData = AVCaptureStillImageOutput.jpegStillImageNSDataRepresentation(imageDataSampleBuffer){
let image = UIImage.init(data: imageData)
self.capturedImageView = UIImageView.init(frame: UIScreen.main.bounds)
self.capturedImageView?.image = image
keyWindow?.addSubview(self.capturedImageView!)
keyWindow?.addSubview(self.useImageButton)
keyWindow?.addSubview(self.retakeButton)
UIImageWriteToSavedPhotosAlbum(UIImage(data: imageData)!, nil, nil, nil)
}
}
}
}
}
func hanldleOpenAlbum(_ sender:UIButton){
print("Handling OpenAlbum.....")
let imagePickerController = UIImagePickerController.init()
imagePickerController.sourceType = .photoLibrary
imagePickerController.allowsEditing = true
imagePickerController.delegate = self
UIView.animate(withDuration: 0.50, delay: 0, usingSpringWithDamping: 0.9, initialSpringVelocity: 0.3, options: .curveEaseOut, animations: {
self.cameraView.frame = CGRect(x: 0, y: screen_height, width: screen_width, height: screen_height)
self.present(imagePickerController, animated: false, completion: nil)
}, completion: { (completed) in
self.cameraView.removeFromSuperview()
})
}
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
var image:UIImage?
if info["UIImagePickerControllerEditedImage"] != nil{
image = info["UIImagePickerControllerEditedImage"] as? UIImage
}else if info["UIImagePickerControllerOriginalImage"] != nil{
image = info["UIImagePickerControllerOriginalImage"] as? UIImage
}
self.delegate?.didFinishPickingMediaInfo!(mediaInfo: info, pickedImage: image)
picker.dismiss(animated: false, completion: nil)
self.dismiss(animated: true, completion: nil)
}
func imagePickerControllerDidCancel(_ picker: UIImagePickerController) {
picker.dismiss(animated: false, completion: nil)
self.dismiss(animated: true, completion: nil)
}
func accessPhotosFromLibrary(){
let fetchOption = PHFetchOptions.init()
fetchOption.fetchLimit = 100
fetchOption.sortDescriptors = [NSSortDescriptor.init(key: "creationDate", ascending: false)]
let assets = PHAsset.fetchAssets(with: PHAssetMediaType.image, options: fetchOption)
assets.enumerateObjects(options: .concurrent) { (assest, id, bool) in
self.photosArray.append(PhotoModel.getAssestsModel(assest: assest))
}
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return photosArray.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cellId", for: indexPath) as! PhotoCell
cell.photoImageView.image = self.photosArray[indexPath.item].photoImage
cell.photoImageView.addGestureRecognizer(UITapGestureRecognizer.init(target: self, action: #selector(handleTap(tap:))))
return cell
}
var orignalImageView:UIImageView?
var selectedAssest:PhotoModel?
var zoomedImageView:UIImageView?
func handleTap(tap:UITapGestureRecognizer){
if let indexPath = getIndexFromCollectionViewCell(tap.view!, collView: photoCollectionView){
print(indexPath.item)
selectedAssest = photosArray[indexPath.item]
orignalImageView = tap.view as? UIImageView
orignalImageView?.isHidden = true
orignalframe = orignalImageView?.convert((orignalImageView?.frame)!, to: nil)
if zoomedImageView != nil{
zoomedImageView?.removeFromSuperview()
zoomedImageView = nil
}
zoomedImageView = UIImageView.init(frame: orignalframe!)
zoomedImageView?.contentMode = .scaleAspectFill
zoomedImageView?.clipsToBounds = true
zoomedImageView?.isUserInteractionEnabled = true
zoomedImageView?.addGestureRecognizer(UIPanGestureRecognizer.init(target: self, action: #selector(handlePan(pan:))))
zoomedImageView?.image = getAssetThumbnail(asset: (selectedAssest?.assest!)!, size: PHImageManagerMaximumSize)
keyWindow?.addSubview(zoomedImageView!)
UIView.animate(withDuration: 0.5, animations: {
self.zoomedImageView?.frame = self.view.frame
}, completion: { (completed) in
keyWindow?.addSubview(self.useImageButton)
keyWindow?.addSubview(self.retakeButton)
})
}
}
func handlePan(pan:UIPanGestureRecognizer){
if pan.state == .began || pan.state == .changed {
let translation = pan.translation(in: self.view)
let piont = CGPoint(x: pan.view!.center.x + translation.x, y: pan.view!.center.y + translation.y)
print("POINT",piont)
pan.view!.center = piont
pan.setTranslation(CGPoint.zero, in: self.view)
self.retakeButton.alpha = 0
self.useImageButton.alpha = 0
}else if pan.state == .ended{
if let yPosition = pan.view?.center.y{
print("Y Position ",yPosition)
let maxDownpoint = self.view.frame.height - self.view.frame.height/4
print("MAX DOWN POINT",maxDownpoint)
if yPosition >= maxDownpoint{
dismissZoomedImageView()
}else{
UIView.animate(withDuration: 0.33, delay: 0, usingSpringWithDamping: 1, initialSpringVelocity: 0.3, options: .curveLinear, animations: {
self.zoomedImageView?.frame = CGRect(x: 0, y: 0, width: self.view.frame.width, height: self.view.frame.height)
self.retakeButton.alpha = 1
self.useImageButton.alpha = 1
}, completion: { (success) in
})
}
}
}
}
func dismissZoomedImageView(){
UIView.animate(withDuration: 0.33, delay: 0, usingSpringWithDamping: 0.8, initialSpringVelocity: 0.3, options: .curveLinear, animations: {
self.zoomedImageView?.frame = self.orignalframe!
self.useImageButton.removeFromSuperview()
self.retakeButton.removeFromSuperview()
}, completion: { (success) in
self.zoomedImageView?.removeFromSuperview()
self.zoomedImageView = nil
self.orignalImageView?.isHidden = false
self.useImageButton.alpha = 1
self.retakeButton.alpha = 1
})
}
}
func getAssetThumbnail(asset: PHAsset , size:CGSize) -> UIImage {
let manager = PHImageManager.default()
let option = PHImageRequestOptions()
var thumbnail = UIImage()
option.isSynchronous = true
option.resizeMode = .exact
option.deliveryMode = .fastFormat
manager.requestImage(for: asset, targetSize: size, contentMode: .default, options: option, resultHandler: {(result, info)->Void in
thumbnail = result!
})
return thumbnail
}
func getIndexFromCollectionViewCell(_ cellItem: UIView, collView: UICollectionView) -> IndexPath? {
let pointInTable: CGPoint = cellItem.convert(cellItem.bounds.origin, to: collView)
if let cellIndexPath = collView.indexPathForItem(at: pointInTable){
return cellIndexPath
}
return nil
}
class PhotoModel: NSObject {
var photoImage:UIImage?
var assest:PHAsset?
static func getAssestsModel(assest:PHAsset)->PhotoModel{
let photoModel = PhotoModel.init()
photoModel.assest = assest
photoModel.photoImage = getAssetThumbnail(asset: assest, size: CGSize(width: 250, height: 250))
return photoModel
}
}
| mit | 2984bb7e82f266fbd15399c46c1e2768 | 44.63255 | 175 | 0.638379 | 5.229187 | false | false | false | false |
bengottlieb/stack-watcher | StackWatcher/Controllers/Question Details/QuestionDetailsViewController.swift | 1 | 2102 | //
// QuestionDetailsViewController.swift
// StackWatcher
//
// Created by Ben Gottlieb on 6/4/14.
// Copyright (c) 2014 Stand Alone, Inc. All rights reserved.
//
import UIKit
class QuestionDetailsViewController: UIViewController {
deinit {
NSNotificationCenter.defaultCenter().removeObserver(self)
}
init() {
super.init(nibName: nil, bundle: nil)
self.navigationItem.rightBarButtonItem = self.reloadButton
NSNotificationCenter.defaultCenter().addObserver(self, selector: "didSelectQuestion:", name: StackInterface.DefaultInterface.questionSelectedNotificationName, object: nil)
// Custom initialization
}
convenience init(question: PostedQuestion) {
self.init()
self.loadQuestion(question)
}
func reload() {
self.webView.reload()
}
override func viewDidLoad() {
super.viewDidLoad()
if let pending = self.question {
self.loadQuestion(pending)
}
// Do any additional setup after loading the view.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func didSelectQuestion(note: NSNotification) {
self.loadQuestion(note.object as PostedQuestion)
}
var question: PostedQuestion?
func loadQuestion(question: PostedQuestion) {
self.question = question
var link = question.link
var url = NSURL(string: link)
var request = NSURLRequest(URL: url)
self.title = question.title
self.webView?.loadRequest(request)
}
/*
// #pragma 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.
}
*/
var reloadButton: UIBarButtonItem { return UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.Refresh, target: self, action: "reload") }
@IBOutlet var webView : UIWebView
}
| mit | 1f0ca40e514ce5d2f0b0b24fcb4ea526 | 26.298701 | 173 | 0.716936 | 4.425263 | false | false | false | false |
RaylnJiang/Swift_Learning_Project | Second Chapter-控制流/Second Chapter-控制流/For-In 循环.playground/Contents.swift | 1 | 999 | //: Playground - noun: a place where people can play
import Cocoa
/* For-In循环 */
/* -------------------------------------------------------------------
可以使用for-in循环来遍历一个集合中的所有元素。
可以遍历一个字典,来访问它的键值对。
------------------------------------------------------------------ */
for index in 1...5 {
// index 代表着闭区间内每一项的值
print("\(index) times 5 is \(index * 5)")
}
let baseValue = 2
let maxPower = 10
var sumValue = 1
for _ in 1...maxPower {
// 如果不需要知道闭区间的每一项的值,则可用 _ 代替
sumValue *= baseValue
}
print("sumValue is \(sumValue)")
var namesArray = ["张三", "李四", "王五", "赵六"]
for name in namesArray {
print("Hello \(name)!")
}
var animalDict = ["Dog": 4, "Cat": 4, "Snake": 0, "monkey": 2]
for (animalName, legCount) in animalDict {
print("\(animalName) has \(legCount) legs")
}
| apache-2.0 | 8d10444294936fa237156ccbcf5b1678 | 19.365854 | 70 | 0.494611 | 3.479167 | false | false | false | false |
mackoj/GOTiPad | GOTIpad/GameLogic/Player.swift | 1 | 806 | //
// Player.swift
// GOTIpad
//
// Created by jeffreymacko on 29/12/2015.
// Copyright © 2015 jeffreymacko. All rights reserved.
//
import Foundation
struct Player {
let name : String
let house : HouseHold
var ironThronePosition : UInt = 0
var valerianSwordPosition : UInt = 0
var kingsCourtPosition : UInt = 0
var starsLimit : UInt = 0
var victoryTrackPosition : UInt = 0
var supplyPosition : UInt = 0
var hasLost : Bool = false
var powerTokens : [PowerToken] = []
var lands : [Land] = []
var hand : [HouseHoldMemberCard] = []
var discardPile : [HouseHoldMemberCard] = []
init(playerName: String, houseHoldType : HouseHoldType) {
self.name = playerName
self.house = HouseHold(houseHold: houseHoldType)
}
}
| mit | 2082977c425e6da85022f4dc0f20a833 | 24.15625 | 61 | 0.640994 | 3.642534 | false | false | false | false |
movier/learn-ios | learn-ios/Playing Audio/PlayingAudioViewController.swift | 1 | 1943 | //
// PlayingAudioViewController.swift
// learn-ios
//
// Created by Oliver on 16/1/18.
// Copyright © 2016年 movier. All rights reserved.
//
import UIKit
import AVFoundation
class PlayingAudioViewController: UIViewController {
var player : AVAudioPlayer! = nil
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// http://www.raywenderlich.com/69369/audio-tutorial-ios-playing-audio-programatically-2014-edition
@IBAction func playButtonTapped(sender: UIButton) {
let path = NSBundle.mainBundle().pathForResource("1940_s_Slow_Dance_Sting", ofType:"mp3")
let fileURL = NSURL(fileURLWithPath: path!)
do {
try player = AVAudioPlayer(contentsOfURL: fileURL)
} catch {
print("Something went wrong!")
}
player.prepareToPlay()
player.play()
}
@IBAction func systemSoundServicesButtonTapped(sender: AnyObject) {
var soundID: SystemSoundID = 0
if let pewPewPath = NSBundle.mainBundle().pathForResource("1940_s_Slow_Dance_Sting", ofType:"mp3") {
let pewPewURL = NSURL.fileURLWithPath(pewPewPath)
AudioServicesCreateSystemSoundID(pewPewURL, &soundID)
AudioServicesPlaySystemSound(1001)
} else {
print("Could not find sound file")
}
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
| mit | 3f5ddcf30274108a75b40b5ab8cd605a | 30.803279 | 108 | 0.658763 | 4.754902 | false | false | false | false |
MillmanY/MMPlayerView | MMPlayerView/Classes/Swift/MMPlayerLayer.swift | 1 | 25154 | //
// MMPlayerLayer.swift
// Pods
//
// Created by Millman YANG on 2017/8/22.
//
//
import UIKit
import AVFoundation
// MARK: - Enum define
public extension MMPlayerLayer {
enum SubtitleType {
case srt(info: String)
}
enum CoverFitType {
case fitToPlayerView
case fitToVideoRect
}
}
public class MMPlayerLayer: AVPlayerLayer {
/**
Subtitle Setting
```
subtitleSetting.defaultFont = UIFont.systemFont(ofSize: 17)
subtitleSetting.defaultTextColor = .white
subtitleSetting.defaultLabelEdge = (20,10,10)
subtitleSetting.subtitleType = .srt(info: "XXX")
```
*/
public private(set) lazy var subtitleSetting: MMSubtitleSetting = {
return MMSubtitleSetting(delegate: self)
}()
/**
Set progress type on player center
```
mmplayerLayer.progressType = .custom(view: UIView & MMProgressProtocol)
```
*/
public var progressType: MMProgress.ProgressType = .default {
didSet {
indicator.set(progress: progressType)
}
}
/**
Set progress type on player center
```
// Cover view fit to videoRect
mmplayerLayer.coverFitType = .fitToVideoRect
// Cover view fit to playerLayer frame
mmplayerLayer.coverFitType = .fitToPlayerView
```
*/
public var coverFitType: MMPlayerLayer.CoverFitType = .fitToVideoRect {
didSet {
thumbImageView.contentMode = (coverFitType == .fitToVideoRect) ? .scaleAspectFit : .scaleAspectFill
self.updateCoverConstraint()
}
}
/**
Set cover view auto hide after n interval
```
// Cover view auto hide with n interval
mmplayerLayer.autoHideCoverType = .MMPlayerLayer.CoverAutoHideType.autoHide(after: 3.0)
// Cover view auto hide disable
mmplayerLayer.autoHideCoverType = .disable
```
*/
public var autoHideCoverType = CoverAutoHideType.autoHide(after: 3.0) {
didSet {
switch autoHideCoverType {
case .disable:
NSObject.cancelPreviousPerformRequests(withTarget: self, selector: #selector(MMPlayerLayer.showCover(isShow:)), object: nil)
case .autoHide(let after):
self.perform(#selector(MMPlayerLayer.showCover(isShow:)), with: nil, afterDelay: after)
}
}
}
/**
Set to show image before video ready
```
// Set thumbImageView
mmplayerLayer.thumbImageView.image = 'Background Image'
```
*/
public lazy var thumbImageView: UIImageView = {
let t = UIImageView()
t.clipsToBounds = true
return t
}()
/**
MMPlayerLayer will show in playView
```
// Set thumbImageView
mmplayerLayer.playView = cell.imageView
```
*/
public var playView: UIView? {
set {
if self.playView != newValue {
self._playView = newValue
}
} get {
return _playView
}
}
/**
Loop video when end
```
mmplayerLayer.repeatWhenEnd = true
```
*/
public var repeatWhenEnd: Bool = false
/**
Current cover view on mmplayerLayer
```
mmplayerLayer.coverView
```
*/
public private(set) var coverView: (UIView & MMPlayerCoverViewProtocol)?
/**
Auto play when video ready
*/
public var autoPlay = true
/**
Current player status
```
case ready
case unknown
case failed(err: String)
case playing
case pause
case end
```
*/
public var currentPlayStatus: PlayStatus = .unknown {
didSet {
if currentPlayStatus == oldValue {
return
}
if let block = self.playStatusBlock {
block(currentPlayStatus)
}
coverView?.currentPlayer(status: currentPlayStatus)
switch self.currentPlayStatus {
case .ready:
self.thumbImageView.isHidden = false
self.coverView?.isHidden = false
if self.autoPlay {
self.player?.play()
}
case .failed(err: _):
self.thumbImageView.isHidden = false
self.coverView?.isHidden = false
self.startLoading(isStart: false)
case .unknown:
self.thumbImageView.isHidden = false
self.coverView?.isHidden = true
self.startLoading(isStart: false)
default:
self.thumbImageView.isHidden = true
self.coverView?.isHidden = false
break
}
}
}
/**
Set AVPlayerItem cache in memory or not
```
case none
case memory(count: Int)
```
*/
public var cacheType: PlayerCacheType = .none
/**
Current play url
*/
public var playUrl: URL? {
get {
return (self.player?.currentItem?.asset as? AVURLAsset)?.url
}
}
public weak var mmDelegate: MMPlayerLayerProtocol?
/**
If true, player will fullscreen when roatate to landscape
```
mmplayerLayer.fullScreenWhenLandscape = true
```
*/
public var fullScreenWhenLandscape = true
/**
Player current orientation
```
mmplayerLayer.orientation = .protrait
mmplayerLayer.orientation = .landscapeLeft
mmplayerLayer.orientation = .landscapeRight
```
*/
public private(set) var orientation: PlayerOrientation = .protrait {
didSet {
self.landscapeWindow.update()
if orientation == oldValue { return }
self.layerOrientationBlock?(orientation)
}
}
public var isShrink: Bool {
return shrinkControl.isShrink
}
// MARK: - Private Parameter
lazy var subtitleView = MMSubtitleView()
lazy var shrinkControl = {
return MMPlayerShrinkControl(mmPlayerLayer: self)
}()
private lazy var bgView: UIView = {
let v = UIView()
v.translatesAutoresizingMaskIntoConstraints = false
v.addSubview(self.thumbImageView)
v.addSubview(self.indicator)
// self.indicator
// .mmLayout
// .setCenterX(anchor: v.centerXAnchor, type: .equal(constant: 0))
// .setCentoMerY(anchor: v.centerYAnchor, type: .equal(constant: 0))
self.indicator.mmLayout.layoutFitSuper()
self.thumbImageView.mmLayout.layoutFitSuper()
v.frame = .zero
v.backgroundColor = UIColor.clear
return v
}()
private lazy var tapGesture: UITapGestureRecognizer = {
let g = UITapGestureRecognizer(target: self, action: #selector(MMPlayerLayer.touchAction(gesture:)))
return g
}()
public private(set) lazy var landscapeWindow: MMLandscapeWindow = {
let window = MMLandscapeWindow(playerLayer: self)
return window
}()
weak private var _playView: UIView? {
willSet {
bgView.removeFromSuperview()
self.removeFromSuperlayer()
_playView?.removeGestureRecognizer(tapGesture)
} didSet {
guard let new = _playView else {
return
}
new.layer.insertSublayer(self, at: 0)
new.addSubview(self.bgView)
self.bgView.mmLayout.layoutFitSuper()
new.layoutIfNeeded()
self.updateCoverConstraint()
new.isUserInteractionEnabled = true
new.addGestureRecognizer(tapGesture)
}
}
private var asset: AVURLAsset?
private var isInitLayer = false
private var isCoverShow = false
private var timeObserver: Any?
private var isBackgroundPause = false
private var cahce = MMPlayerCache()
private var playStatusBlock: ((_ status: PlayStatus) ->Void)?
private var layerOrientationBlock: ((_ status: PlayerOrientation) ->Void)?
private var indicator = MMProgress()
// MARK: - Init
public override init(layer: Any) {
isInitLayer = true
super.init(layer: layer)
(layer as? MMPlayerLayer)?.isInitLayer = false
}
required public init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
public override init() {
super.init()
self.setup()
}
deinit {
if !isInitLayer {
self.removeAllObserver()
}
}
}
// MARK: - Public function
extension MMPlayerLayer {
public func shrinkView(onVC: UIViewController, isHiddenVC: Bool, maxWidth: CGFloat = 150.0, completedToView: (()->UIView?)?) {
shrinkControl.shrinkView(onVC: onVC, isHiddenVC: isHiddenVC, maxWidth: maxWidth, completedToView: completedToView)
}
/**
Set player current Orientation
```
mmplayerLayer.setOrientation(.protrait)
```
*/
public func setOrientation(_ status: PlayerOrientation) {
self.orientation = status
}
/**
If cover enable show on video, else hidden
*/
public func setCoverView(enable: Bool) {
self.coverView?.isHidden = !enable
self.tapGesture.isEnabled = enable
}
public func delayHideCover() {
self.showCover(isShow: true)
switch self.autoHideCoverType {
case .autoHide(let after):
NSObject.cancelPreviousPerformRequests(withTarget: self, selector: #selector(MMPlayerLayer.showCover(isShow:)), object: nil)
self.perform(#selector(MMPlayerLayer.showCover(isShow:)), with: nil, afterDelay: after)
default:
break
}
}
/**
Set player cover view
** Cover view need implement 'MMPlayerCoverViewProtocol' **
```
mmplayerLayer.replace(cover: XXX)
```
*/
public func replace(cover: UIView & MMPlayerCoverViewProtocol) {
if let c = self.coverView ,c.isMember(of: cover.classForCoder) {
c.alpha = 1.0
return
}
cover.backgroundColor = UIColor.clear
cover.layoutIfNeeded()
coverView?.removeFromSuperview()
coverView?.removeObserver?()
coverView = cover
coverView?.playLayer = self
bgView.insertSubview(cover, belowSubview: indicator)
cover.addObserver?()
self.updateCoverConstraint()
if let m = self.player?.isMuted {
cover.player?(isMuted: m)
}
cover.currentPlayer(status: self.currentPlayStatus)
}
/**
Get player play status
*/
public func getStatusBlock(value: ((_ status: PlayStatus) -> Void)?) {
self.playStatusBlock = value
}
/**
Get player orientation status
*/
public func getOrientationChange(status: ((_ status: PlayerOrientation) ->Void)?) {
self.layerOrientationBlock = status
}
public func set(asset: AVURLAsset?, lodDiskIfExist: Bool = true) {
if asset?.url == self.asset?.url {
return
}
if let will = asset ,
self.cahce.getItem(key: will.url) == nil,
let real = MMPlayerDownloader.shared.localFileFrom(url: will.url),
lodDiskIfExist {
switch real.type {
case .hls:
var statle = false
if let data = try? Data(contentsOf: real.localURL),
let convert = try? URL(resolvingBookmarkData: data, bookmarkDataIsStale: &statle) {
self.asset = AVURLAsset(url: convert)
} else {
self.asset = asset
}
case .mp4:
self.asset = AVURLAsset(url: real.localURL)
}
return
}
self.asset = asset
}
/**
Set player playUrl
*/
public func set(url: URL?, lodDiskIfExist: Bool = true) {
guard let u = url else {
self.set(asset: nil, lodDiskIfExist: lodDiskIfExist)
return
}
self.set(asset: AVURLAsset(url: u), lodDiskIfExist: lodDiskIfExist)
}
/**
Stop player and clear url
*/
public func invalidate() {
self.initStatus()
self.asset = nil
}
/**
Start player to play video
*/
public func resume() {
switch self.currentPlayStatus {
case .playing , .pause:
if (self.player?.currentItem?.asset as? AVURLAsset)?.url == self.asset?.url {
return
}
default:
break
}
self.initStatus()
guard let current = self.asset else {
return
}
self.startLoading(isStart: true)
if let cacheItem = self.cahce.getItem(key: current.url) , cacheItem.status == .readyToPlay {
self.player?.replaceCurrentItem(with: cacheItem)
} else {
current.loadValuesAsynchronously(forKeys: assetKeysRequiredToPlay) { [weak self] in
DispatchQueue.main.async {
let keys = assetKeysRequiredToPlay
if let a = self?.asset {
for key in keys {
var error: NSError?
let _ = a.statusOfValue(forKey: key, error: &error)
if let e = error {
self?.currentPlayStatus = .failed(err: e.localizedDescription)
return
}
}
let item = MMPlayerItem(asset: a, delegate: self)
switch self?.cacheType {
case .some(.memory(let count)):
self?.cahce.cacheCount = count
self?.cahce.appendCache(key: current.url, item: item)
default:
self?.cahce.removeAll()
}
self?.player?.replaceCurrentItem(with: item)
}
}
}
}
}
@objc func touchAction(gesture: UITapGestureRecognizer) {
switch self.currentPlayStatus {
case .unknown:
return
default: break
}
if let p = self.playView {
let point = gesture.location(in: p)
if self.videoRect.isEmpty || self.videoRect.contains(point) {
self.showCover(isShow: !self.isCoverShow)
}
mmDelegate?.touchInVideoRect(contain: self.videoRect.contains(point))
}
}
@objc public func showCover(isShow: Bool) {
self.isCoverShow = isShow
if isShow {
switch self.autoHideCoverType {
case .autoHide(let after):
NSObject.cancelPreviousPerformRequests(withTarget: self, selector: #selector(MMPlayerLayer.showCover(isShow:)), object: nil)
self.perform(#selector(MMPlayerLayer.showCover(isShow:)), with: nil, afterDelay: after)
default: break
}
}
if let cover = self.coverView ,
cover.responds(to: #selector(cover.coverView(isShow:))) {
cover.coverView!(isShow: isShow)
return
}
UIView.animate(withDuration: 0.2, animations: { [weak self] in
self?.coverView?.alpha = (isShow) ? 1.0 : 0.0
})
}
}
// MARK: - Private function
extension MMPlayerLayer {
private func setup() {
self.player = AVPlayer()
self.backgroundColor = UIColor.black.cgColor
self.progressType = .default
self.addPlayerObserver()
bgView.addSubview(subtitleView)
subtitleView.mmLayout.layoutFitSuper()
let edge = subtitleSetting.defaultLabelEdge
self.subtitleSetting.defaultLabelEdge = edge
NotificationCenter.default.addObserver(forName: UIDevice.orientationDidChangeNotification, object: nil, queue: nil) { [weak self] (_) in
guard let self = self, self.fullScreenWhenLandscape else {return}
switch UIDevice.current.orientation {
case .landscapeLeft:
self.orientation = .landscapeLeft
case .landscapeRight:
self.orientation = .landscapeRight
case .portrait:
self.orientation = .protrait
default: break
}
}
}
private func updateCoverConstraint() {
let vRect = self.coverFitType == .fitToVideoRect ? videoRect : bgView.bounds
if !vRect.isEmpty {
self.coverView?.isHidden = (self.tapGesture.isEnabled) ? false : true
self.coverView?.frame = vRect
}
if bgView.bounds == self.frame { return }
self.frame = bgView.bounds
}
private func startLoading(isStart: Bool) {
if isStart {
self.indicator.start()
} else {
self.indicator.stop()
}
}
}
// MARK: - Observer
extension MMPlayerLayer {
private func addPlayerObserver() {
NotificationCenter.default.removeObserver(self)
if timeObserver == nil {
timeObserver = self.player?.addPeriodicTimeObserver(forInterval: CMTimeMake(value: 1, timescale: 100), queue: DispatchQueue.main, using: { [weak self] (time) in
if time.isIndefinite {
return
}
if let sub = self?.subtitleSetting.subtitleObj {
switch sub {
case let srt as SubtitleConverter<SRT>:
let sec = time.seconds
srt.search(duration: sec, completed: { [weak self] (info) in
guard let self = self else {return}
self.subtitleView.update(infos: info, setting: self.subtitleSetting)
}, queue: DispatchQueue.main)
default:
break
}
}
if let cover = self?.coverView, cover.responds(to: #selector(cover.timerObserver(time:))) {
cover.timerObserver!(time: time)
}
})
}
NotificationCenter.default.addObserver(forName: UIApplication.willResignActiveNotification, object: nil, queue: nil, using: { [weak self] (nitification) in
switch self?.currentPlayStatus ?? .unknown {
case .pause:
self?.isBackgroundPause = true
default:
self?.isBackgroundPause = false
}
self?.player?.pause()
})
NotificationCenter.default.addObserver(forName: UIApplication.didBecomeActiveNotification, object: nil, queue: nil, using: { [weak self] (nitification) in
if self?.isBackgroundPause == false {
self?.player?.play()
}
self?.isBackgroundPause = false
})
NotificationCenter.default.addObserver(forName: .AVPlayerItemDidPlayToEndTime, object: nil, queue: nil, using: { [weak self] (_) in
if self?.repeatWhenEnd == true {
self?.player?.seek(to: CMTime.zero)
self?.player?.play()
} else if let s = self?.currentPlayStatus {
switch s {
case .playing, .pause:
if let u = self?.asset?.url {
self?.cahce.removeCache(key: u)
}
self?.currentPlayStatus = .end
default: break
}
}
})
self.addObserver(self, forKeyPath: "videoRect", options: [.new, .old], context: nil)
bgView.addObserver(self, forKeyPath: "frame", options: [.new, .old], context: nil)
bgView.addObserver(self, forKeyPath: "bounds", options: [.new, .old], context: nil)
self.player?.addObserver(self, forKeyPath: "muted", options: [.new, .old], context: nil)
self.player?.addObserver(self, forKeyPath: "rate", options: [.new, .old], context: nil)
}
override public func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
switch keyPath {
case "videoRect", "frame", "bounds":
let new = change?[.newKey] as? CGRect ?? .zero
let old = change?[.oldKey] as? CGRect ?? .zero
if new != old {
self.updateCoverConstraint()
}
case "muted":
let new = change?[.newKey] as? Bool ?? false
let old = change?[.oldKey] as? Bool ?? false
if new != old {
self.coverView?.player?(isMuted: new)
}
case "rate":
let new = change?[.newKey] as? Float ?? 1.0
let status = self.currentPlayStatus
switch status {
case .playing, .pause, .ready:
self.currentPlayStatus = (new == 0.0) ? .pause : .playing
case .end:
let total = self.player?.currentItem?.duration.seconds ?? 0.0
let current = self.player?.currentItem?.currentTime().seconds ?? 0.0
if current < total {
self.currentPlayStatus = (new == 0.0) ? .pause : .playing
}
default: break
}
default:
super.observeValue(forKeyPath: keyPath, of: object, change: change, context: context)
}
}
private func removeAllObserver() {
self.removeObserver(self, forKeyPath: "videoRect")
bgView.removeObserver(self, forKeyPath: "frame")
bgView.removeObserver(self, forKeyPath: "bounds")
self.player?.removeObserver(self, forKeyPath: "muted")
self.player?.removeObserver(self, forKeyPath: "rate")
self.player?.replaceCurrentItem(with: nil)
self.player?.pause()
NotificationCenter.default.removeObserver(self)
coverView?.removeObserver?()
if let t = timeObserver {
self.player?.removeTimeObserver(t)
timeObserver = nil
}
}
private func convertItemStatus() -> PlayStatus {
return self.player?.currentItem?.convertStatus() ?? .unknown
}
private func initStatus() {
self.currentPlayStatus = .unknown
self.isBackgroundPause = false
self.player?.replaceCurrentItem(with: nil)
self.showCover(isShow: false)
}
}
// MARK: - Download
extension MMPlayerLayer {
public func download(observer status: @escaping ((MMPlayerDownloader.DownloadStatus)->Void)) -> MMPlayerObservation? {
guard let asset = self.asset else {
status(.failed(err: "URL empty"))
return nil
}
if asset.url.isFileURL {
status(.failed(err: "Input fileURL are Invalid"))
return nil
}
MMPlayerDownloader.shared.download(asset: asset)
return self.observerDownload(status: status)
}
public func observerDownload(status: @escaping ((MMPlayerDownloader.DownloadStatus)->Void)) -> MMPlayerObservation? {
guard let url = self.asset?.url else {
status(.failed(err: "URL empty"))
return nil
}
return MMPlayerDownloader.shared.observe(downloadURL: url, status: status)
}
}
// MARK: - MMPlayerItem delegate
extension MMPlayerLayer: MMPlayerItemProtocol {
func status(change: AVPlayerItem.Status) {
let s = self.convertItemStatus()
switch s {
case .failed(_) , .unknown:
self.currentPlayStatus = s
case .ready:
switch self.currentPlayStatus {
case .ready:
if self.isBackgroundPause {
return
}
self.currentPlayStatus = s
case .failed(_) ,.unknown:
self.currentPlayStatus = s
default:
break
}
default:
break
}
}
func isPlaybackKeepUp(isKeepUp: Bool) {
if isKeepUp == true {
self.startLoading(isStart: false)
}
}
func isPlaybackEmpty(isEmpty: Bool) {
if isEmpty {
self.startLoading(isStart: true)
}
}
}
extension MMPlayerLayer: MMSubtitleSettingProtocol {
public func setting(_ mmsubtitleSetting: MMSubtitleSetting, fontChange: UIFont) {
}
public func setting(_ mmsubtitleSetting: MMSubtitleSetting, textColorChange: UIColor) {
}
public func setting(_ mmsubtitleSetting: MMSubtitleSetting, labelEdgeChange: (bottom: CGFloat, left: CGFloat, right: CGFloat)) {
}
public func setting(_ mmsubtitleSetting: MMSubtitleSetting, typeChange: MMSubtitleSetting.SubtitleType?) {
self.subtitleView.isHidden = typeChange == nil
}
}
| mit | 0bb5e34e09ffd0124fe18bfccc519a38 | 31.667532 | 172 | 0.56325 | 5.113641 | false | false | false | false |
davieds/WWDC | WWDC/DataStore.swift | 1 | 8451 | //
// DataStore.swift
// WWDC
//
// Created by Guilherme Rambo on 18/04/15.
// Copyright (c) 2015 Guilherme Rambo. All rights reserved.
//
import Foundation
private let _internalServiceURL = "http://wwdc.guilhermerambo.me/index.json"
private let _liveServiceURL = "http://wwdc.guilhermerambo.me/live.json"
private let _liveNextServiceURL = "http://wwdc.guilhermerambo.me/next.json"
private let _SharedStore = DataStore()
private let _MemoryCacheSize = 500*1024*1024
private let _DiskCacheSize = 1024*1024*1024
class DataStore: NSObject {
class var SharedStore: DataStore {
return _SharedStore
}
private let sharedCache = NSURLCache(memoryCapacity: _MemoryCacheSize, diskCapacity: _DiskCacheSize, diskPath: nil)
override init() {
super.init()
NSURLCache.setSharedURLCache(sharedCache)
loadFavorites()
}
typealias fetchSessionsCompletionHandler = (Bool, [Session]) -> Void
var appleSessionsURL: NSURL? = nil
private var _cachedSessions: [Session]? = nil
private(set) var cachedSessions: [Session]? {
get {
if _cachedSessions == nil {
self.fetchSessions({ (_, sessions) -> Void in
return sessions
})
}
return _cachedSessions
}
set {
_cachedSessions = newValue
}
}
let URLSession = NSURLSession(configuration: NSURLSessionConfiguration.defaultSessionConfiguration())
let URLSession2 = NSURLSession(configuration: NSURLSessionConfiguration.ephemeralSessionConfiguration())
func fetchSessions(completionHandler: fetchSessionsCompletionHandler) {
if appleSessionsURL != nil {
doFetchSessions(completionHandler)
} else {
let internalServiceURL = NSURL(string: _internalServiceURL)
URLSession.dataTaskWithURL(internalServiceURL!, completionHandler: { [unowned self] data, response, error in
if data == nil {
completionHandler(false, [])
return
}
let parsedJSON: JSON? = JSON(data: data!)
if let json = parsedJSON, dictionary = json.dictionary {
let appleURL = dictionary["url"]!.string!
self.appleSessionsURL = NSURL(string: appleURL)!
} else {
completionHandler(false, [])
return
}
self.doFetchSessions(completionHandler)
}).resume()
}
}
func fetchSessions(completionHandler: fetchSessionsCompletionHandler, disableCache: Bool) {
if disableCache {
if let url = appleSessionsURL {
sranddev()
appleSessionsURL = NSURL(string: "\(url.absoluteString)?\(rand())")
}
}
fetchSessions(completionHandler)
}
func doFetchSessions(completionHandler: fetchSessionsCompletionHandler) {
URLSession.dataTaskWithURL(appleSessionsURL!, completionHandler: { data, response, error in
if data == nil {
completionHandler(false, [])
return
}
if let container = JSON(data: data!).dictionary {
let jsonSessions = container["sessions"]!.array!
var sessions: [Session] = []
for jsonSession:JSON in jsonSessions {
var focuses:[String] = []
for focus:JSON in jsonSession["focus"].array! {
focuses.append(focus.string!)
}
if jsonSession["title"].string != nil && jsonSession["id"].int != nil && jsonSession["year"].int != nil {
let session = Session(date: jsonSession["date"].string,
description: jsonSession["description"].string!,
focus: focuses,
id: jsonSession["id"].int!,
slides: jsonSession["slides"].string,
title: jsonSession["title"].string!,
track: (jsonSession["track"].string != nil) ? jsonSession["track"].string! : "",
url: (jsonSession["url"].string != nil) ? jsonSession["url"].string! : "",
year: jsonSession["year"].int!,
hd_url: jsonSession["download_hd"].string)
sessions.append(session)
}
}
sessions = sessions.sort { sessionA, sessionB in
if(sessionA.year == sessionB.year) {
return sessionA.id < sessionB.id
} else {
return sessionA.year > sessionB.year
}
}
self.cachedSessions = sessions
completionHandler(true, sessions)
} else {
completionHandler(false, [])
}
}).resume()
}
func downloadSessionSlides(session: Session, completionHandler: (Bool, NSData?) -> Void) {
if session.slides == nil {
completionHandler(false, nil)
return
}
let task = URLSession.dataTaskWithURL(NSURL(string: session.slides!)!) { data, response, error in
if data != nil {
completionHandler(true, data)
} else {
completionHandler(false, nil)
}
}
task.resume()
}
let defaults = NSUserDefaults.standardUserDefaults()
func fetchSessionProgress(session: Session) -> Double {
return defaults.doubleForKey(session.progressKey)
}
func putSessionProgress(session: Session, progress: Double) {
defaults.setDouble(progress, forKey: session.progressKey)
}
func fetchSessionCurrentPosition(session: Session) -> Double {
return defaults.doubleForKey(session.currentPositionKey)
}
func putSessionCurrentPosition(session: Session, position: Double) {
defaults.setDouble(position, forKey: session.currentPositionKey)
}
private var favorites: [String] = []
private let favoritesKey = "Favorites"
private func loadFavorites() {
if let faves = defaults.arrayForKey(favoritesKey) as? [String] {
favorites = faves
}
}
private func storeFavorites() {
defaults.setObject(favorites, forKey: favoritesKey)
}
func fetchSessionIsFavorite(session: Session) -> Bool {
return favorites.contains(session.uniqueKey)
}
func putSessionIsFavorite(session: Session, favorite: Bool) {
if favorite {
favorites.append(session.uniqueKey)
} else {
favorites.remove(session.uniqueKey)
}
storeFavorites()
}
private var liveURL: NSURL {
get {
sranddev()
// adds a random number as a parameter to completely prevent any caching
return NSURL(string: "\(_liveServiceURL)?t=\(rand())&s=\(NSDate.timeIntervalSinceReferenceDate())")!
}
}
private var liveNextURL: NSURL {
get {
sranddev()
// adds a random number as a parameter to completely prevent any caching
return NSURL(string: "\(_liveNextServiceURL)?t=\(rand())&s=\(NSDate.timeIntervalSinceReferenceDate())")!
}
}
func checkForLiveEvent(completionHandler: (Bool, LiveEvent?) -> ()) {
let task = URLSession2.dataTaskWithURL(liveURL) { data, response, error in
if data == nil {
completionHandler(false, nil)
return
}
let jsonData = JSON(data: data!)
let event = LiveEvent(jsonObject: jsonData)
if event.isLiveRightNow {
completionHandler(true, event)
} else {
completionHandler(false, nil)
}
}
task.resume()
}
func fetchNextLiveEvent(completionHandler: (Bool, LiveEvent?) -> ()) {
let task = URLSession2.dataTaskWithURL(liveNextURL) { data, response, error in
if data == nil {
completionHandler(false, nil)
return
}
let jsonData = JSON(data: data!)
let event = LiveEvent(jsonObject: jsonData)
if event.title != "" {
completionHandler(true, event)
} else {
completionHandler(false, nil)
}
}
task.resume()
}
}
| bsd-2-clause | b095660966972ccecea117170ab84f21 | 32.669323 | 125 | 0.573778 | 5.128034 | false | false | false | false |
IngmarStein/swift | stdlib/private/SwiftPrivatePthreadExtras/PthreadBarriers.swift | 3 | 3655 | //===--- PthreadBarriers.swift --------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
#if os(OSX) || os(iOS) || os(watchOS) || os(tvOS)
import Darwin
#elseif os(Linux) || os(FreeBSD) || os(PS4) || os(Android)
import Glibc
#endif
//
// Implement pthread barriers.
//
// (OS X does not implement them.)
//
public struct _stdlib_pthread_barrierattr_t {
public init() {}
}
public func _stdlib_pthread_barrierattr_init(
_ attr: UnsafeMutablePointer<_stdlib_pthread_barrierattr_t>
) -> CInt {
return 0
}
public func _stdlib_pthread_barrierattr_destroy(
_ attr: UnsafeMutablePointer<_stdlib_pthread_barrierattr_t>
) -> CInt {
return 0
}
public var _stdlib_PTHREAD_BARRIER_SERIAL_THREAD: CInt {
return 1
}
public struct _stdlib_pthread_barrier_t {
var mutex: UnsafeMutablePointer<pthread_mutex_t>?
var cond: UnsafeMutablePointer<pthread_cond_t>?
/// The number of threads to synchronize.
var count: CUnsignedInt = 0
/// The number of threads already waiting on the barrier.
///
/// This shared variable is protected by `mutex`.
var numThreadsWaiting: CUnsignedInt = 0
public init() {}
}
public func _stdlib_pthread_barrier_init(
_ barrier: UnsafeMutablePointer<_stdlib_pthread_barrier_t>,
_ attr: UnsafeMutablePointer<_stdlib_pthread_barrierattr_t>?,
_ count: CUnsignedInt
) -> CInt {
barrier.pointee = _stdlib_pthread_barrier_t()
if count == 0 {
errno = EINVAL
return -1
}
barrier.pointee.mutex = UnsafeMutablePointer.allocate(capacity: 1)
if pthread_mutex_init(barrier.pointee.mutex!, nil) != 0 {
// FIXME: leaking memory.
return -1
}
barrier.pointee.cond = UnsafeMutablePointer.allocate(capacity: 1)
if pthread_cond_init(barrier.pointee.cond!, nil) != 0 {
// FIXME: leaking memory, leaking a mutex.
return -1
}
barrier.pointee.count = count
return 0
}
public func _stdlib_pthread_barrier_destroy(
_ barrier: UnsafeMutablePointer<_stdlib_pthread_barrier_t>
) -> CInt {
if pthread_cond_destroy(barrier.pointee.cond!) != 0 {
// FIXME: leaking memory, leaking a mutex.
return -1
}
if pthread_mutex_destroy(barrier.pointee.mutex!) != 0 {
// FIXME: leaking memory.
return -1
}
barrier.pointee.cond!.deinitialize()
barrier.pointee.cond!.deallocate(capacity: 1)
barrier.pointee.mutex!.deinitialize()
barrier.pointee.mutex!.deallocate(capacity: 1)
return 0
}
public func _stdlib_pthread_barrier_wait(
_ barrier: UnsafeMutablePointer<_stdlib_pthread_barrier_t>
) -> CInt {
if pthread_mutex_lock(barrier.pointee.mutex!) != 0 {
return -1
}
barrier.pointee.numThreadsWaiting += 1
if barrier.pointee.numThreadsWaiting < barrier.pointee.count {
// Put the thread to sleep.
if pthread_cond_wait(barrier.pointee.cond!, barrier.pointee.mutex!) != 0 {
return -1
}
if pthread_mutex_unlock(barrier.pointee.mutex!) != 0 {
return -1
}
return 0
} else {
// Reset thread count.
barrier.pointee.numThreadsWaiting = 0
// Wake up all threads.
if pthread_cond_broadcast(barrier.pointee.cond!) != 0 {
return -1
}
if pthread_mutex_unlock(barrier.pointee.mutex!) != 0 {
return -1
}
return _stdlib_PTHREAD_BARRIER_SERIAL_THREAD
}
}
| apache-2.0 | 8b413469743221cde752384241d5f6a3 | 26.900763 | 80 | 0.66539 | 3.847368 | false | false | false | false |
brentsimmons/Frontier | BeforeTheRename/UserTalk/UserTalk/Node/CaseConditionNode.swift | 1 | 1088 | //
// CaseConditionNode.swift
// UserTalk
//
// Created by Brent Simmons on 5/7/17.
// Copyright © 2017 Ranchero Software. All rights reserved.
//
import Foundation
import FrontierData
// case value // CaseNode
// x // CaseConditionNode
// thing() // BlockNode
final class CaseConditionNode: CodeTreeNode {
let operation = .caseItemOp
let textPosition: TextPosition
let conditionNode: CodeTreeNode
let blockNode: BlockNode
init(_ textPosition: TextPosition, _ conditionNode: CodeTreeNode, _ blockNode: BlockNode) {
self.textPosition = textPosition
self.conditionNode = conditionNode
self.blockNode = blockNode
}
func evaluateCondition(_ stack: Stack) throws -> Value {
do {
var ignoredBreakOperation: CodeTreeOperation = .noOp
return try condition.evaluate(stack, &breakOperation)
}
catch { throw error }
}
func evaluate(_ stack: Stack, _ breakOperation: inout CodeTreeOperation) throws -> Value {
stack.push()
defer {
stack.pop()
}
do {
try return blockNode.evaluate(stack, breakOperation)
}
catch { throw error }
}
}
| gpl-2.0 | 86fb7c1722fe0122ef4e036104bb64a3 | 19.903846 | 92 | 0.713891 | 3.672297 | false | false | false | false |
motoom/ios-apps | Pour3/Pour/Sounds/SoundManager.swift | 1 | 1625 |
import UIKit
import AVFoundation
class SoundManager {
var playersInitialized = false
var fillPlayer: AVAudioPlayer! // TODO: Map from soundname -> initialised AVAudioPlayer instances
var pourPlayer: AVAudioPlayer!
var drainPlayer: AVAudioPlayer!
init() {
// TODO: Initialize sounds in a loop.
let fillUrl = Bundle.main.url(forResource: "Fillup.wav", withExtension: nil)
do {
try fillPlayer = AVAudioPlayer(contentsOf: fillUrl!)
fillPlayer.prepareToPlay()
}
catch {
print("Fillup.wav not playable")
}
//
let pourUrl = Bundle.main.url(forResource: "Eau.wav", withExtension: nil)
do {
try pourPlayer = AVAudioPlayer(contentsOf: pourUrl!)
pourPlayer.prepareToPlay()
}
catch {
print("Eau.wav not playable")
}
//
let drainUrl = Bundle.main.url(forResource: "Toilet.wav", withExtension: nil)
do {
try drainPlayer = AVAudioPlayer(contentsOf: drainUrl!)
drainPlayer.prepareToPlay()
}
catch {
print("Toilet.wav not playable")
}
}
func sndFill() {
fillPlayer.currentTime = 0
fillPlayer.play()
}
func sndPour() {
pourPlayer.currentTime = 0
pourPlayer.play()
}
func sndDrain() {
drainPlayer.currentTime = 0
drainPlayer.play()
}
func sndStop() {
fillPlayer.stop()
pourPlayer.stop()
drainPlayer.stop()
}
}
| mit | 0e6727000e97961e9f27a2fefb84e281 | 24.390625 | 101 | 0.555077 | 4.969419 | false | false | false | false |
ranmocy/rCaltrain | ios/rCaltrain/Station.swift | 1 | 1329 | //
// Station.swift
// rCaltrain
//
// Created by Wanzhang Sheng on 10/25/14.
// Copyright (c) 2014-2015 Ranmocy. All rights reserved.
//
import Foundation
class Station {
// Class variables/methods
fileprivate struct StationStruct {
static var names = NSMutableOrderedSet()
static var idToStation = [Int: Station]()
static var nameToStations = [String: [Station]]()
}
class func getNames() -> [String] {
return (StationStruct.names.array as! [String]).sorted(by: <)
}
class func getStation(byId id: Int) -> Station? {
return StationStruct.idToStation[id]
}
class func getStations(byName name: String) -> [Station]? {
return StationStruct.nameToStations[name]
}
class func addStation(name: String, id: Int) {
let station = Station(name: name, id: id)
StationStruct.names.add(name)
StationStruct.idToStation[id] = station
if (StationStruct.nameToStations[name] != nil) {
StationStruct.nameToStations[name]!.append(station)
} else {
StationStruct.nameToStations[name] = [station]
}
}
// Instance variables/methods
let name: String
let id: Int
fileprivate init(name: String, id: Int) {
self.name = name
self.id = id
}
}
| mit | 36a95d1875aa655e888d7d32a8edd17f | 25.58 | 69 | 0.620015 | 4.051829 | false | false | false | false |
J3D1-WARR10R/WikiRaces | WikiRaces/Shared/Menu View Controllers/MenuViewController/MenuView/MedalScene.swift | 2 | 4392 | //
// MedalScene.swift
// WikiRaces
//
// Created by Andrew Finke on 3/6/19.
// Copyright © 2019 Andrew Finke. All rights reserved.
//
import SpriteKit
final class MedalScene: SKScene {
// MARK: Properties -
private let goldNode: SKNode
private let silverNode: SKNode
private let bronzeNode: SKNode
private let dnfNode: SKNode
// MARK: - Initalization -
override init(size: CGSize) {
let physicsBody = SKPhysicsBody(circleOfRadius: 5)
physicsBody.allowsRotation = true
physicsBody.linearDamping = 1.75
physicsBody.angularDamping = 0.75
func texture(for text: String, width: CGFloat = 50) -> SKTexture {
let size = CGSize(width: width, height: width)
let emojiRect = CGRect(origin: .zero, size: size)
let emojiRenderer = UIGraphicsImageRenderer(size: size)
return SKTexture(image: emojiRenderer.image { context in
UIColor.clear.setFill()
context.fill(emojiRect)
let text = text
let attributes = [
NSAttributedString.Key.font: UIFont.systemFont(ofSize: width - 5)
]
text.draw(in: emojiRect, withAttributes: attributes)
})
}
let goldNode = SKSpriteNode(texture: texture(for: "🥇"))
goldNode.physicsBody = physicsBody
self.goldNode = goldNode
let silverNode = SKSpriteNode(texture: texture(for: "🥈"))
silverNode.physicsBody = physicsBody
self.silverNode = silverNode
let bronzeNode = SKSpriteNode(texture: texture(for: "🥉"))
bronzeNode.physicsBody = physicsBody
self.bronzeNode = bronzeNode
let dnfNode = SKSpriteNode(texture: texture(for: "❌", width: 20))
dnfNode.physicsBody = physicsBody
self.dnfNode = dnfNode
super.init(size: size)
anchorPoint = CGPoint(x: 0, y: 0)
backgroundColor = .clear
physicsWorld.gravity = CGVector(dx: 0, dy: -7)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
// MARK: - Update -
override func update(_ currentTime: TimeInterval) {
for node in children where node.position.y < -50 {
node.removeFromParent()
}
DispatchQueue.main.asyncAfter(deadline: .now() + 1) {
self.isPaused = self.children.isEmpty
}
}
// MARK: - Other -
func showMedals(gold: Int, silver: Int, bronze: Int, dnf: Int) {
func createMedal(place: Int) {
let node: SKNode
if place == 1, let copy = goldNode.copy() as? SKNode {
node = copy
} else if place == 2, let copy = silverNode.copy() as? SKNode {
node = copy
} else if place == 3, let copy = bronzeNode.copy() as? SKNode {
node = copy
} else if place == 4, let copy = dnfNode.copy() as? SKNode {
node = copy
} else {
return
}
let padding: CGFloat = 40
let maxX = size.width - padding
node.position = CGPoint(x: CGFloat.random(in: padding..<maxX),
y: size.height + 50)
node.zRotation = CGFloat.random(in: (-CGFloat.pi / 4)..<(CGFloat.pi / 4))
addChild(node)
var range: CGFloat = 0.5
let impulse = CGVector(dx: CGFloat.random(in: 0..<range) - range / 2,
dy: CGFloat.random(in: 0..<range) - range / 2)
node.physicsBody?.applyImpulse(impulse)
range = 0.001
node.physicsBody?.applyTorque(CGFloat.random(in: 0..<range) - range / 2)
}
var places = [Int]()
(0..<gold).forEach { _ in places.append(1) }
(0..<silver).forEach {_ in places.append(2)}
(0..<bronze).forEach { _ in places.append(3)}
(0..<dnf).forEach { _ in places.append(4)}
for (index, place) in places.shuffled().enumerated() {
scene?.run(.sequence([
.wait(forDuration: Double(index) * 0.075),
.run {
createMedal(place: place)
}]))
}
}
}
| mit | 88660bfc900e5e2056ba5fde431216bb | 34.609756 | 85 | 0.541324 | 4.469388 | false | false | false | false |
wdkk/CAIM | Metal/caimmetal04/CAIM/UIVIew+CAIM.swift | 29 | 2140 | //
// UIView+CAIM.swift
// CAIM Project
// https://kengolab.net/CreApp/wiki/
//
// Copyright (c) Watanabe-DENKI Inc.
// https://wdkk.co.jp/
//
// This software is released under the MIT License.
// https://opensource.org/licenses/mit-license.php
//
import UIKit
public extension UIView
{
var pixelX:CGFloat {
get { return self.frame.origin.x * UIScreen.main.scale }
set { self.frame.origin.x = newValue / UIScreen.main.scale }
}
var pixelY:CGFloat {
get { return self.frame.origin.y * UIScreen.main.scale }
set { self.frame.origin.y = newValue / UIScreen.main.scale }
}
var pixelWidth:CGFloat {
get { return self.frame.size.width * UIScreen.main.scale }
set { self.frame.size.width = newValue / UIScreen.main.scale }
}
var pixelHeight:CGFloat {
get { return self.frame.size.height * UIScreen.main.scale }
set { self.frame.size.height = newValue / UIScreen.main.scale }
}
var pixelFrame:CGRect {
get { return CGRect(x: pixelX, y: pixelY, width: pixelWidth, height: pixelHeight) }
set {
self.frame = CGRect( x: newValue.origin.x / UIScreen.main.scale,
y: newValue.origin.y / UIScreen.main.scale,
width: newValue.size.width / UIScreen.main.scale,
height: newValue.size.height / UIScreen.main.scale )
}
}
var pixelBounds:CGRect {
get { return CGRect(x: bounds.origin.x * UIScreen.main.scale,
y: bounds.origin.y * UIScreen.main.scale,
width: bounds.size.width * UIScreen.main.scale,
height: bounds.size.height * UIScreen.main.scale)
}
set {
self.bounds = CGRect( x: newValue.origin.x / UIScreen.main.scale,
y: newValue.origin.y / UIScreen.main.scale,
width: newValue.size.width / UIScreen.main.scale,
height: newValue.size.height / UIScreen.main.scale )
}
}
}
| mit | 99872e0c6d441f1178b99091e4fa5c2f | 37.909091 | 91 | 0.565888 | 4 | false | false | false | false |
OpenKitten/MongoKitten | Sources/MongoCore/MongoReplyDeserializer.swift | 2 | 2352 | import Foundation
import BSON
import NIO
import Logging
/// A type capable of deserializing messages from MongoDB
public struct MongoServerReplyDeserializer {
private var header: MongoMessageHeader?
private var reply: MongoServerReply?
let logger: Logger
public mutating func takeReply() -> MongoServerReply? {
if let reply = reply {
self.reply = nil
return reply
}
return nil
}
public init(logger: Logger) {
self.logger = logger
}
/// Parses a buffer into a server reply
///
/// Returns `.continue` if enough data was read for a single reply
///
/// Sets `reply` to a the found ServerReply when done parsing it.
/// It's replaced with a new reply the next successful iteration of the parser so needs to be extracted after each `parse` attempt
///
/// Any remaining data left in the `buffer` needs to be left until the next interation, which NIO does by default
public mutating func parse(from buffer: inout ByteBuffer) throws -> DecodingState {
let header: MongoMessageHeader
if let _header = self.header {
header = _header
} else {
if buffer.readableBytes < MongoMessageHeader.byteSize {
return .needMoreData
}
header = try buffer.assertReadMessageHeader()
}
guard header.messageLength - MongoMessageHeader.byteSize <= buffer.readableBytes else {
self.header = header
return .needMoreData
}
self.header = nil
switch header.opCode {
case .reply:
// <= Wire Version 5
self.reply = try .reply(OpReply(reading: &buffer, header: header))
case .message:
// >= Wire Version 6
self.reply = try .message(OpMessage(reading: &buffer, header: header))
default:
logger.error("Mongo Protocol error: OpCode \(header.opCode) in reply is not supported")
throw MongoProtocolParsingError(reason: .unsupportedOpCode)
}
self.header = nil
return .continue
}
}
fileprivate extension Optional {
func assert() throws -> Wrapped {
guard let `self` = self else {
throw MongoOptionalUnwrapFailure()
}
return self
}
}
| mit | 1a40bfb0d43e49aeee13a6e2f9e72cc6 | 29.153846 | 134 | 0.613095 | 4.951579 | false | false | false | false |
pusher-community/pusher-websocket-swift | Sources/Models/Constants.swift | 1 | 2178 | import Foundation
// swiftlint:disable nesting
enum Constants {
enum API {
static let defaultHost = "ws.pusherapp.com"
static let pusherDomain = "pusher.com"
}
enum ChannelTypes {
static let presence = "presence"
static let `private` = "private"
static let privateEncrypted = "private-encrypted"
}
enum Events {
enum Pusher {
static let connectionEstablished = "pusher:connection_established"
static let error = "pusher:error"
static let subscribe = "pusher:subscribe"
static let unsubscribe = "pusher:unsubscribe"
static let subscriptionError = "pusher:subscription_error"
static let subscriptionSucceeded = "pusher:subscription_succeeded"
}
enum PusherInternal {
static let memberAdded = "pusher_internal:member_added"
static let memberRemoved = "pusher_internal:member_removed"
static let subscriptionSucceeded = "pusher_internal:subscription_succeeded"
}
}
enum EventTypes {
static let client = "client"
static let pusher = "pusher"
static let pusherInternal = "pusher_internal"
}
enum JSONKeys {
static let activityTimeout = "activity_timeout"
static let auth = "auth"
static let channel = "channel"
static let channelData = "channel_data"
static let ciphertext = "ciphertext"
static let code = "code"
static let data = "data"
static let event = "event"
static let hash = "hash"
static let message = "message"
static let nonce = "nonce"
static let presence = "presence"
static let socketId = "socket_id"
static let sharedSecret = "shared_secret"
static let userId = "user_id"
static let userInfo = "user_info"
}
}
| mit | f4e64a30d4ce81ad757a552a6c377f43 | 35.915254 | 90 | 0.536272 | 5.030023 | false | false | false | false |
peihsendoyle/ZCPlayer | ZCPlayer/ZCPlayer/SecondViewController.swift | 1 | 5326 | //
// SecondViewController.swift
// ZCPlayer
//
// Created by Doyle Illusion on 7/8/17.
// Copyright © 2017 Zyncas Technologies. All rights reserved.
//
import UIKit
class SecondViewController: UIViewController {
var isInTransition = false
let urls = ["https://yosing.vn/master/files/records/records/record_record_59522512a7acd.mp4"]
let image = UIImage.init(named: "cover.jpg")
let tableView = UITableView.init(frame: CGRect.init(x: 0, y: 0, width: UIScreen.main.bounds.size.width, height: UIScreen.main.bounds.size.height), style: .plain)
override func viewDidLoad() {
super.viewDidLoad()
self.tableView.backgroundColor = .white
self.tableView.tableFooterView = UIView()
self.tableView.separatorStyle = .none
self.tableView.allowsSelection = false
self.tableView.delegate = self
self.tableView.dataSource = self
self.tableView.register(VideoTableViewCell.self, forCellReuseIdentifier: "videoCell")
self.view.addSubview(self.tableView)
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
self.isInTransition = true
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
self.isInTransition = false
let cells = self.tableView.visibleCells
for cell in cells {
guard let videoCell = cell as? VideoTableViewCell else { continue }
guard let indexPath = self.tableView.indexPath(for: videoCell) else { continue }
if self.isFullyVisible(cell: videoCell, scrollView: self.tableView) {
let url = self.urls[indexPath.row]
if let controller = PlayerControllerManager.shared.dict[url] {
controller.addPlayerViewToSuperview(view: videoCell.contentView)
}
}
}
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
self.isInTransition = true
let cells = self.tableView.visibleCells
for cell in cells {
guard let videoCell = cell as? VideoTableViewCell else { continue }
guard let indexPath = self.tableView.indexPath(for: videoCell) else { continue }
let url = self.urls[indexPath.row]
if let controller = PlayerControllerManager.shared.dict[url] {
controller.removePlayerViewFromSuperview()
}
}
}
override func viewDidDisappear(_ animated: Bool) {
super.viewDidDisappear(animated)
self.isInTransition = false
}
}
extension SecondViewController : UITableViewDataSource {
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "videoCell", for: indexPath) as! VideoTableViewCell
cell.coverImage = self.image
let url = self.urls[indexPath.row]
if let controller = PlayerControllerManager.shared.dict[url] {
controller.addPlayerViewToSuperview(view: cell.contentView)
} else {
let controller = PlayerController.init(url: URL.init(string: url)!)
controller.addPlayerViewToSuperview(view: cell.contentView)
}
return cell
}
func scrollViewDidScroll(_ scrollView: UIScrollView) {
guard self.isInTransition == false else { return }
let cells = self.tableView.visibleCells
for cell in cells {
guard let videoCell = cell as? VideoTableViewCell else { continue }
guard let indexPath = self.tableView.indexPath(for: videoCell) else { continue }
if self.isFullyVisible(cell: videoCell, scrollView: scrollView) {
let url = self.urls[indexPath.row]
if let controller = PlayerControllerManager.shared.dict[url] {
controller.addPlayerViewToSuperview(view: cell.contentView)
}
} else {
let url = self.urls[indexPath.row]
if let controller = PlayerControllerManager.shared.dict[url] {
controller.removePlayerViewFromSuperview()
}
}
}
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 1
}
fileprivate func isFullyVisible(cell: VideoTableViewCell, scrollView: UIScrollView) -> Bool {
let relativeToScrollViewRect = cell.convert(cell.bounds, to: scrollView)
let visibleScrollViewRect = CGRect(x: CGFloat(scrollView.contentOffset.x), y: CGFloat(scrollView.contentOffset.y), width: CGFloat(scrollView.bounds.size.width), height: CGFloat(scrollView.bounds.size.height))
return visibleScrollViewRect.contains(CGPoint.init(x: relativeToScrollViewRect.midX, y: relativeToScrollViewRect.midY))
}
}
extension SecondViewController: UITableViewDelegate {
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return 200.0
}
}
| apache-2.0 | 46b1a8fd8476738b788e094b5f379e45 | 36.5 | 216 | 0.635117 | 5.169903 | false | false | false | false |
exsortis/TenCenturiesKit | Sources/TenCenturiesKit/Models/Channel.swift | 1 | 2476 | //
// Channel.swift
// Yawp
//
// Created by Paul Schifferer on 21/5/17.
// Copyright © 2017 Pilgrimage Software. All rights reserved.
//
import Foundation
public struct Channel {
public var id : Int
public var guid : String
public var createdAt : Date
public var createdUnix : Int
public var updatedAt : Date
public var updatedUnix : Int
public var type : ChannelType
public var privacy : Privacy
public var ownerId : Int?
}
public enum ChannelType : String {
case global = "channel.global"
}
extension Channel : Serializable {
public init?(from json : JSONDictionary) {
guard let id = json["id"] as? Int,
let guid = json["guid"] as? String,
let c = json["created_at"] as? String,
let createdAt = DateUtilities.isoFormatter.date(from: c),
let createdUnix = json["created_unix"] as? Int,
let u = json["updated_at"] as? String,
let updatedAt = DateUtilities.isoFormatter.date(from: u),
let updatedUnix = json["updated_unix"] as? Int,
let t = json["type"] as? String,
let type = ChannelType(rawValue: t),
let p = json["privacy"] as? String,
let privacy = Privacy(rawValue: p)
else { return nil }
self.id = id
self.guid = guid
self.createdAt = createdAt
self.createdUnix = createdUnix
self.updatedAt = updatedAt
self.updatedUnix = updatedUnix
self.type = type
self.privacy = privacy
self.ownerId = json["owner_id"] as? Int
}
public func toDictionary() -> JSONDictionary {
var dict : JSONDictionary = [
"privacy": privacy.rawValue,
"created_at": DateUtilities.isoFormatter.string(from: createdAt),
"updated_unix": createdUnix,
"updated_at": DateUtilities.isoFormatter.string(from: updatedAt),
"created_unix": createdUnix,
"guid": guid,
"type": type.rawValue,
"id": id,
]
if let ownerId = ownerId {
dict["owner_id"] = ownerId
}
return dict
}
}
/*
{
"privacy": "visibility.public",
"created_at": "2015-08-01T00:00:00Z",
"updated_unix": 1438387200,
"updated_at": "2015-08-01T00:00:00Z",
"created_unix": 1438387200,
"guid": "d9ba5a8d768d0dbd9fc9c3ea4c8e183b2aa7336c",
"type": "channel.global",
"id": 1,
"owner_id": false
}
*/
| mit | 0a6f25bba3e81c12abdcd38214a5de6b | 26.5 | 77 | 0.589495 | 3.873239 | false | false | false | false |
ulrikdamm/Forbind | Forbind/Promise.swift | 1 | 2177 | //
// Promise.swift
// Forbind
//
// Created by Ulrik Damm on 06/06/15.
//
//
import Foundation
private enum PromiseState<T> {
case noValue
case value(T)
}
open class Promise<T> {
public init(value : T? = nil) {
value => setValue
}
public init(previousPromise : AnyObject) {
self.previousPromise = previousPromise
}
fileprivate var _value : PromiseState<T> = .noValue
var previousPromise : AnyObject?
open func setValue(_ value : T) {
_value = PromiseState.value(value)
notifyListeners()
}
open var value : T? {
get {
switch _value {
case .noValue: return nil
case .value(let value): return value
}
}
}
fileprivate var listeners : [(T) -> Void] = []
open func getValue(_ callback : @escaping (T) -> Void) {
getValueWeak { value in
let _ = self
callback(value)
}
}
open func getValueWeak(_ callback : @escaping (T) -> Void) {
if let value = value {
callback(value)
} else {
listeners.append(callback)
}
}
fileprivate func notifyListeners() {
switch _value {
case .noValue: break
case .value(let value):
for callback in listeners {
callback(value)
}
}
listeners = []
}
}
//public func ==<T : Equatable>(lhs : Promise<T>, rhs : Promise<T>) -> Promise<Bool> {
// return (lhs ++ rhs) => { $0 == $1 }
//}
//
//public func ==<T : Equatable>(lhs : Promise<T?>, rhs : Promise<T?>) -> Promise<Bool?> {
// return (lhs ++ rhs) => { $0 == $1 }
//}
//
//public func ==<T : Equatable>(lhs : Promise<Result<T>>, rhs : Promise<Result<T>>) -> Promise<Result<Bool>> {
// return (lhs ++ rhs) => { $0 == $1 }
//}
extension Promise : CustomStringConvertible {
public var description : String {
if let value = value {
return "Promise(\(value))"
} else {
return "Promise(\(T.self))"
}
}
}
//public func filterp<T>(_ source : [Promise<T>], includeElement : (T) -> Bool) -> Promise<[T]> {
// return reducep(source, initial: []) { all, this in includeElement(this) ? all + [this] : all }
//}
//
//public func reducep<T, U>(_ source : [Promise<T>], initial : U, combine : (U, T) -> U) -> Promise<U> {
// return source.reduce(Promise(value: initial)) { $0 ++ $1 => combine }
//}
| mit | 3d927ee896192a5af48f086ecd2d6b8e | 20.77 | 110 | 0.602664 | 3.066197 | false | false | false | false |
nodekit-io/nodekit-darwin | src/nodekit/NKElectro/NKEBrowser/platform-osx/NKEBrowserWindow_OSX.swift | 1 | 11920 | /*
* nodekit.io
*
* Copyright (c) 2016 OffGrid Networks. All Rights Reserved.
* Portions Copyright (c) 2013 GitHub, Inc. under MIT License
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#if os(OSX)
import Foundation
import Cocoa
extension NKE_BrowserWindow {
internal func createWindow(options: Dictionary<String, AnyObject>) -> AnyObject {
let isTaskBarPopup = (options[NKEBrowserOptions.kTaskBarPopup] as? Bool) ?? false ;
let TaskBarIcon = (options[NKEBrowserOptions.kTaskBarIcon] as? String) ?? "" ;
if !isTaskBarPopup {
let width: CGFloat = CGFloat((options[NKEBrowserOptions.kWidth] as? Int) ?? NKEBrowserDefaults.kWidth)
let height: CGFloat = CGFloat((options[NKEBrowserOptions.kHeight] as? Int) ?? NKEBrowserDefaults.kHeight)
let title: String = (options[NKEBrowserOptions.kTitle] as? String) ?? NKEBrowserDefaults.kTitle
let windowRect: NSRect = (NSScreen.mainScreen()!).frame
let frameRect: NSRect = NSMakeRect(
(NSWidth(windowRect) - width)/2,
(NSHeight(windowRect) - height)/2,
width, height)
let window = NSWindow(contentRect: frameRect, styleMask: [NSTitledWindowMask , NSClosableWindowMask , NSResizableWindowMask], backing: NSBackingStoreType.Buffered, defer: false, screen: NSScreen.mainScreen())
objc_setAssociatedObject(self, unsafeAddressOf(NSWindow), window, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN_NONATOMIC)
window.title = title
window.makeKeyAndOrderFront(nil)
return window
} else
{
let window = NSPopover()
window.contentViewController = NSViewController()
objc_setAssociatedObject(self, unsafeAddressOf(NSWindow), window, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN_NONATOMIC)
let nke_popover = NKE_Popover(Popover: window, imageName: TaskBarIcon)
objc_setAssociatedObject(self, unsafeAddressOf(NKE_Popover), nke_popover, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN_NONATOMIC)
return window
}
}
}
extension NKE_BrowserWindow: NKE_BrowserWindowProtocol {
func destroy() -> Void { NotImplemented(); }
func close() -> Void {
guard let window = self._window as? NSWindow else {return;}
window.close()
self._window = nil
NKE_BrowserWindow._windowArray[self._id] = nil
_context = nil
_webView = nil
}
func focus() -> Void { NotImplemented(); }
func isFocused() -> Bool { NotImplemented(); return false; }
func show() -> Void { NotImplemented(); }
func showInactive() -> Void { NotImplemented(); }
func hide() -> Void { NotImplemented(); }
func isVisible() -> Bool { NotImplemented(); return true; }
func maximize() -> Void { NotImplemented(); }
func unmaximize() -> Void { NotImplemented(); }
func isMaximized() -> Bool { NotImplemented(); return false; }
func minimize() -> Void { NotImplemented(); }
func isMinimized() -> Bool { NotImplemented(); return false; }
func setFullScreen(flag: Bool) -> Void { NotImplemented(); }
func isFullScreen() -> Bool { NotImplemented(); return false; }
func setAspectRatio(aspectRatio: NSNumber, extraSize: [Int]) -> Void { NotImplemented(); } //OS X
func setBounds(options: [NSObject : AnyObject]!) -> Void { NotImplemented(); }
func getBounds() -> [NSObject : AnyObject]! { NotImplemented(); return [NSObject : AnyObject](); }
func setSize(width: Int, height: Int) -> Void { NotImplemented(); }
func getSize() -> [NSObject : AnyObject]! { NotImplemented(); return [NSObject : AnyObject](); }
func setContentSize(width: Int, height: Int) -> Void { NotImplemented(); }
func getContentSize() -> [Int] { NotImplemented(); return [Int](); }
func setMinimumSize(width: Int, height: Int) -> Void { NotImplemented(); }
func getMinimumSize() -> [Int] { NotImplemented(); return [Int](); }
func setMaximumSize(width: Int, height: Int) -> Void { NotImplemented(); }
func getMaximumSize() -> [Int] { NotImplemented(); return [Int](); }
func setResizable(resizable: Bool) -> Void { NotImplemented(); }
func isResizable() -> Bool { NotImplemented(); return false; }
func setAlwaysOnTop(flag: Bool) -> Void { NotImplemented(); }
func isAlwaysOnTop() -> Bool { NotImplemented(); return false; }
func center() -> Void { NotImplemented(); }
func setPosition(x: Int, y: Int) -> Void { NotImplemented(); }
func getPosition() -> [Int] { NotImplemented(); return [Int]() }
func setTitle(title: String) -> Void { NotImplemented(); }
func getTitle() -> Void { NotImplemented(); }
func flashFrame(flag: Bool) -> Void { NotImplemented(); }
func setSkipTaskbar(skip: Bool) -> Void { NotImplemented(); }
func setKiosk(flag: Bool) -> Void { NotImplemented(); }
func isKiosk() -> Bool { NotImplemented(); return false; }
// func hookWindowMessage(message: Int,callback: AnyObject) -> Void //WINDOWS
// func isWindowMessageHooked(message: Int) -> Void //WINDOWS
// func unhookWindowMessage(message: Int) -> Void //WINDOWS
// func unhookAllWindowMessages() -> Void //WINDOWS
func setRepresentedFilename(filename: String) -> Void { NotImplemented(); } //OS X
func getRepresentedFilename() -> String { NotImplemented(); return "" } //OS X
func setDocumentEdited(edited: Bool) -> Void { NotImplemented(); } //OS X
func isDocumentEdited() -> Bool { NotImplemented(); return false; } //OS X
func focusOnWebView() -> Void { NotImplemented(); }
func blurWebView() -> Void { NotImplemented(); }
func capturePage(rect: [NSObject : AnyObject]!, callback: AnyObject) -> Void { NotImplemented(); }
func print(options: [NSObject : AnyObject]) -> Void { NotImplemented(); }
func printToPDF(options: [NSObject : AnyObject], callback: AnyObject) -> Void { NotImplemented(); }
func loadURL(url: String, options: [NSObject : AnyObject]) -> Void { NotImplemented(); }
func reload() -> Void { NotImplemented(); }
// func setMenu(menu) -> Void //LINUX WINDOWS
func setProgressBar(progress: Double) -> Void { NotImplemented(); }
// func setOverlayIcon(overlay, description) -> Void //WINDOWS 7+
// func setThumbarButtons(buttons) -> Void //WINDOWS 7+
func showDefinitionForSelection() -> Void { NotImplemented(); } //OS X
func setAutoHideMenuBar(hide: Bool) -> Void { NotImplemented(); }
func isMenuBarAutoHide() -> Bool { NotImplemented(); return false; }
func setMenuBarVisibility(visible: Bool) -> Void { NotImplemented(); }
func isMenuBarVisible() -> Bool { NotImplemented(); return false; }
func setVisibleOnAllWorkspaces(visible: Bool) -> Void { NotImplemented(); }
func isVisibleOnAllWorkspaces() -> Bool { NotImplemented(); return false; }
func setIgnoreMouseEvents(ignore: Bool) -> Void { NotImplemented(); } //OS X
private static func NotImplemented() -> Void {
NSException(name: "NotImplemented", reason: "This function is not implemented", userInfo: nil).raise()
}
private func NotImplemented() -> Void {
NSException(name: "NotImplemented", reason: "This function is not implemented", userInfo: nil).raise()
}
}
class NKE_Popover : NSObject {
let statusItem: NSStatusItem
let popover: NSPopover
var popoverMonitor: AnyObject?
init( Popover: NSPopover, imageName: String) {
popover = Popover
statusItem = NSStatusBar.systemStatusBar().statusItemWithLength(NSSquareStatusItemLength)
super.init()
setupStatusButton(imageName)
}
func setupStatusButton(imageName: String) {
if let statusButton = statusItem.button {
let mainBundle: NSBundle = NSBundle.mainBundle()
guard let image: NSImage = mainBundle.imageForResource(imageName) else { return }
statusButton.image = image
statusButton.target = self
statusButton.action = #selector(NKE_Popover.onPress(_:))
statusButton.sendActionOn(NSEventMask(rawValue: UInt64((NSEventMask.RightMouseDown).rawValue)))
let dummyControl = DummyControl()
dummyControl.frame = statusButton.bounds
statusButton.addSubview(dummyControl)
statusButton.superview!.subviews = [statusButton, dummyControl]
dummyControl.action = #selector(NKE_Popover.onPress(_:))
dummyControl.target = self
}
}
func quitApp(sender: AnyObject) {
NSApplication.sharedApplication().terminate(self)
}
func onPress(sender: AnyObject) {
let event:NSEvent! = NSApp.currentEvent!
if (event.type == NSEventType.RightMouseDown) {
let menu = NSMenu()
let quitMenuItem = NSMenuItem(title:"Quit", action:#selector(NKE_Popover.quitApp(_:)), keyEquivalent:"")
quitMenuItem.target = self
menu.addItem(quitMenuItem)
statusItem.popUpStatusItemMenu(menu)
}
else{
if popover.shown == false {
openPopover()
} else {
closePopover()
}
}
}
func openPopover() {
if let statusButton = statusItem.button {
statusButton.highlight(true)
popover.showRelativeToRect(NSZeroRect, ofView: statusButton, preferredEdge: NSRectEdge.MinY)
popoverMonitor = NSEvent.addGlobalMonitorForEventsMatchingMask(.LeftMouseDown, handler: {
(event: NSEvent) -> Void in
self.closePopover()
})
}
}
func closePopover() {
popover.close()
if let statusButton = statusItem.button {
statusButton.highlight(false)
}
if let monitor : AnyObject = popoverMonitor {
NSEvent.removeMonitor(monitor)
popoverMonitor = nil
}
}
}
class DummyControl : NSControl {
override func mouseDown(theEvent: NSEvent) {
superview!.mouseDown(theEvent)
sendAction(action, to: target)
}
}
#endif
| apache-2.0 | db28f0ea690e2ed417adcec69751362d | 29.642674 | 220 | 0.583221 | 5.255732 | false | false | false | false |
clwm01/RTKitDemo | RCToolsDemo/RTRC.swift | 2 | 742 | //
// RTRC.swift
// RCToolsDemo
//
// Created by Rex Tsao on 5/18/16.
// Copyright © 2016 rexcao. All rights reserved.
//
import Foundation
class RTRC {
private var stack: Dictionary<String, Int>
init(key: String) {
self.stack = [key: 0]
}
func add(key: String, count: Int) {
}
func increaseForKey(key: String) {
var value = self.stack[key]!
value += 1
self.stack[key] = value
}
func decreaseForKey(key: String) {
var value = self.stack[key]!
value -= 1
if value < 0 {
value = 0
}
self.stack[key] = value
}
func valueForKey(key: String) -> Int {
return self.stack[key]!
}
}
| mit | 56d9c9fc4c61d82faf4c2d01544ca67d | 18 | 49 | 0.522267 | 3.528571 | false | false | false | false |
IdrissPiard/UnikornTube_Client | UnikornTube/UploadVideoVC.swift | 1 | 5444 | //
// UploadVideoVC.swift
// UnikornTube
//
// Created by Damien Serin on 03/06/2015.
// Copyright (c) 2015 SimpleAndNew. All rights reserved.
//
import UIKit
class UploadVideoVC: UIViewController, UIImagePickerControllerDelegate, UINavigationControllerDelegate {
@IBOutlet weak var myActivityIndicator: UIActivityIndicatorView!
@IBOutlet weak var coverImage: UIImageView!
var videoPickerController = UIImagePickerController()
var coverPickerController = UIImagePickerController()
var moviePath : String!
var coverUrl : NSURL!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func uploadButtonTapped(sender: AnyObject) {
videoUploadRequest()
}
@IBAction func selectVideoButtonTapped(sender: AnyObject) {
videoPickerController.allowsEditing = false
videoPickerController.delegate = self;
videoPickerController.sourceType = UIImagePickerControllerSourceType.PhotoLibrary
videoPickerController.mediaTypes = [kUTTypeMovie as NSString]
self.presentViewController(videoPickerController, animated: true, completion: nil)
}
@IBAction func selectCoverButtonTapped(sender: AnyObject) {
coverPickerController.allowsEditing = false
coverPickerController.delegate = self;
coverPickerController.sourceType = UIImagePickerControllerSourceType.PhotoLibrary
coverPickerController.mediaTypes = [kUTTypeImage as NSString]
self.presentViewController(coverPickerController, animated: true, completion: nil)
}
func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [NSObject : AnyObject])
{
if picker == self.videoPickerController {
var mediaType = info[UIImagePickerControllerMediaType] as! CFString!
var compareResult = CFStringCompare(mediaType, kUTTypeMovie, CFStringCompareFlags.CompareCaseInsensitive)
if(compareResult == CFComparisonResult.CompareEqualTo){
var videoUrl = info[UIImagePickerControllerMediaURL] as! NSURL
var moviePath = videoUrl.path
if(UIVideoAtPathIsCompatibleWithSavedPhotosAlbum(moviePath)){
//UISaveVideoAtPathToSavedPhotosAlbum(moviePath, nil, nil, nil)
}
self.moviePath = moviePath
println(self.moviePath)
}
}
if picker == self.coverPickerController {
var coverUrl = info[UIImagePickerControllerReferenceURL] as! NSURL
var image = info[UIImagePickerControllerOriginalImage] as! UIImage
self.coverImage.image = image
var coverPath = coverUrl.path
self.coverUrl = coverUrl
println(self.coverUrl)
}
self.dismissViewControllerAnimated(true, completion: nil)
}
func imagePickerControllerDidCancel(picker: UIImagePickerController) {
dismissViewControllerAnimated(true, completion: nil)
}
func videoUploadRequest(){
//var json: JSON = ["meta_data": ["title":"titre", "idUser":"42", "description":"desc"]]
let manager = AFHTTPRequestOperationManager()
let url = "http://192.168.200.40:9000/upload"
manager.requestSerializer = AFJSONRequestSerializer(writingOptions: nil)
var videoURL = NSURL.fileURLWithPath(self.moviePath)
var imageData = UIImageJPEGRepresentation(self.coverImage.image, CGFloat(1))
println(videoURL)
var params = ["meta_data" : "{\"title\":\"titre\", \"idUser\":42, \"description\":\"ladesc\"}"]
var json : String = "{ \"meta_data\" : [{\"title\":\"titre\", \"idUser\":42, \"description\":\"ladesc\"}]}"
println(json)
AFNetworkActivityLogger.sharedLogger().level = AFHTTPRequestLoggerLevel.AFLoggerLevelDebug
manager.POST( url, parameters: params,
constructingBodyWithBlock: { (data: AFMultipartFormData!) in
var res = data.appendPartWithFileURL(videoURL, name: "video_data", error: nil)
data.appendPartWithFileData(imageData, name: "cover_data", fileName: "cover.jpg", mimeType: "image/jpeg")
println("was file added properly to the body? \(res)")
},
success: { (operation: AFHTTPRequestOperation!, responseObject: AnyObject!) in
println("Yes thies was a success")
},
failure: { (operation: AFHTTPRequestOperation!, error: NSError!) in
println("We got an error here.. \(error)")
println(operation.responseString)
})
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
| mit | 6e8b26021277bb6901cb68b6646293e2 | 38.737226 | 123 | 0.647686 | 5.791489 | false | false | false | false |
CSullivan102/LearnApp | LearnKit/CreateTopic/CreateTopicModel.swift | 1 | 1657 | //
// CreateTopicModel.swift
// Learn
//
// Created by Christopher Sullivan on 9/23/15.
// Copyright © 2015 Christopher Sullivan. All rights reserved.
//
import Foundation
public struct CreateTopicModel {
public init() {}
private let maxEmojiTextLength = 1
private let emojiRanges = [
0x0080...0x00FF,
0x2100...0x214F,
0x2190...0x21FF,
0x2300...0x23FF,
0x25A0...0x27BF,
0x2900...0x297F,
0x2B00...0x2BFF,
0x3001...0x303F,
0x3200...0x32FF,
0x1F000...0x1F02F,
0x1F110...0x1F251,
0x1F300...0x1F5FF,
0x1F600...0x1F64F,
0x1F680...0x1F6FF
]
public func isValidTopicName(name: String, andIcon icon: String) -> Bool {
return isValidTopicName(name) && isValidEmojiValue(icon)
}
public func canChangeTopicIconToString(string: String) -> Bool {
return string.lengthWithEmoji() == 0 || isValidEmojiValue(string)
}
public func isValidTopicName(name: String) -> Bool {
return name.lengthWithEmoji() > 0
}
public func isValidEmojiValue(string: String) -> Bool {
if string.lengthWithEmoji() == 0 || string.lengthWithEmoji() > maxEmojiTextLength {
return false
}
if let scalarVal = string.unicodeScalars.first?.value {
var found = false
for range in emojiRanges {
if range.contains(Int(scalarVal)) {
found = true
}
}
if !found {
return false
}
}
return true
}
} | mit | 97bb5332cd42312931e014667cd8b64a | 25.301587 | 91 | 0.557971 | 3.82448 | false | false | false | false |
daltoniam/Starscream | examples/AutobahnTest/Autobahn/ViewController.swift | 1 | 6021 | //
// ViewController.swift
// Autobahn
//
// Created by Dalton Cherry on 7/24/15.
// Copyright (c) 2015 vluxe. All rights reserved.
//
import UIKit
import Starscream
class ViewController: UIViewController {
let host = "localhost:9001"
var socketArray = [WebSocket]()
var caseCount = 300 //starting cases
override func viewDidLoad() {
super.viewDidLoad()
getCaseCount()
//getTestInfo(1)
//runTest(304)
}
func removeSocket(_ s: WebSocket?) {
guard let s = s else {return}
socketArray = socketArray.filter{$0 !== s}
}
func getCaseCount() {
let req = URLRequest(url: URL(string: "ws://\(host)/getCaseCount")!)
let s = WebSocket(request: req)
socketArray.append(s)
s.onEvent = { [weak self] event in
switch event {
case .text(let string):
if let c = Int(string) {
print("number of cases is: \(c)")
self?.caseCount = c
}
case .disconnected(_, _):
self?.runTest(1)
self?.removeSocket(s)
default:
break
}
}
s.connect()
}
func getTestInfo(_ caseNum: Int) {
let s = createSocket("getCaseInfo",caseNum)
socketArray.append(s)
// s.onText = { (text: String) in
// let data = text.dataUsingEncoding(NSUTF8StringEncoding)
// do {
// let resp: AnyObject? = try NSJSONSerialization.JSONObjectWithData(data!,
// options: NSJSONReadingOptions())
// if let dict = resp as? Dictionary<String,String> {
// let num = dict["id"]
// let summary = dict["description"]
// if let n = num, let sum = summary {
// print("running case:\(caseNum) id:\(n) summary: \(sum)")
// }
// }
// } catch {
// print("error parsing the json")
// }
// }
var once = false
s.onEvent = { [weak self] event in
switch event {
case .disconnected(_, _), .error(_):
if !once {
once = true
self?.runTest(caseNum)
}
self?.removeSocket(s)
default:
break
}
}
s.connect()
}
func runTest(_ caseNum: Int) {
let s = createSocket("runCase",caseNum)
self.socketArray.append(s)
var once = false
s.onEvent = { [weak self, weak s] event in
switch event {
case .disconnected(_, _), .error(_):
if !once {
once = true
print("case:\(caseNum) finished")
//self?.verifyTest(caseNum) //disabled since it slows down the tests
let nextCase = caseNum+1
if nextCase <= (self?.caseCount)! {
self?.runTest(nextCase)
//self?.getTestInfo(nextCase) //disabled since it slows down the tests
} else {
self?.finishReports()
}
self?.removeSocket(s)
}
self?.removeSocket(s)
case .text(let string):
s?.write(string: string)
case .binary(let data):
s?.write(data: data)
// case .error(let error):
// print("got an error: \(error)")
default:
break
}
}
s.connect()
}
// func verifyTest(_ caseNum: Int) {
// let s = createSocket("getCaseStatus",caseNum)
// self.socketArray.append(s)
// s.onText = { (text: String) in
// let data = text.data(using: String.Encoding.utf8)
// do {
// let resp: Any? = try JSONSerialization.jsonObject(with: data!,
// options: JSONSerialization.ReadingOptions())
// if let dict = resp as? Dictionary<String,String> {
// if let status = dict["behavior"] {
// if status == "OK" {
// print("SUCCESS: \(caseNum)")
// return
// }
// }
// print("FAILURE: \(caseNum)")
// }
// } catch {
// print("error parsing the json")
// }
// }
// var once = false
// s.onDisconnect = { [weak self, weak s] (error: Error?) in
// if !once {
// once = true
// let nextCase = caseNum+1
// print("next test is: \(nextCase)")
// if nextCase <= (self?.caseCount)! {
// self?.getTestInfo(nextCase)
// } else {
// self?.finishReports()
// }
// }
// self?.removeSocket(s)
// }
// s.connect()
// }
func finishReports() {
let s = createSocket("updateReports",0)
self.socketArray.append(s)
s.onEvent = { [weak self, weak s] event in
switch event {
case .disconnected(_, _):
print("finished all the tests!")
self?.removeSocket(s)
default:
break
}
}
s.connect()
}
func createSocket(_ cmd: String, _ caseNum: Int) -> WebSocket {
let req = URLRequest(url: URL(string: "ws://\(host)\(buildPath(cmd,caseNum))")!)
//return WebSocket(request: req, compressionHandler: WSCompression())
return WebSocket(request: req)
}
func buildPath(_ cmd: String, _ caseNum: Int) -> String {
return "/\(cmd)?case=\(caseNum)&agent=Starscream"
}
}
| apache-2.0 | 42b211b88419794c3807a0ceee33842a | 31.722826 | 94 | 0.449427 | 4.599694 | false | true | false | false |
kouky/MavlinkPrimaryFlightDisplay | Sources/iOS/BLE.swift | 1 | 10813 | /*
Copyright (c) 2015 Fernando Reynoso
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
import Foundation
import CoreBluetooth
enum BLEBaudRate {
case Bps9600
case Bps19200
case Bps38400
case Bps57600
case Bps115200
var data: NSData {
switch self {
case .Bps9600:
return NSData(bytes: [0x00] as [UInt8],length: 1)
case .Bps19200:
return NSData(bytes: [0x01] as [UInt8],length: 1)
case .Bps38400:
return NSData(bytes: [0x02] as [UInt8],length: 1)
case .Bps57600:
return NSData(bytes: [0x03] as [UInt8],length: 1)
case .Bps115200:
return NSData(bytes: [0x04] as [UInt8],length: 1)
}
}
}
protocol BLEDelegate {
func bleDidDiscoverPeripherals()
func bleDidConnectToPeripheral()
func bleDidDisconenctFromPeripheral()
func bleDidDicoverCharacateristics()
func bleDidReceiveData(data: NSData?)
}
class BLE: NSObject, CBCentralManagerDelegate, CBPeripheralDelegate {
let RBL_SERVICE_UUID = "713D0000-503E-4C75-BA94-3148F18D941E"
let RBL_CHAR_TX_UUID = "713D0002-503E-4C75-BA94-3148F18D941E"
let RBL_CHAR_RX_UUID = "713D0003-503E-4C75-BA94-3148F18D941E"
let RBL_CHAR_BAUD_UUID = "713D0004-503E-4C75-BA94-3148F18D941E"
var delegate: BLEDelegate?
private var centralManager: CBCentralManager!
private var activePeripheral: CBPeripheral?
private var characteristics = [String : CBCharacteristic]()
private var data: NSMutableData?
private(set) var peripherals = [CBPeripheral]()
private(set) var state = CBCentralManagerState.Unknown
private var RSSICompletionHandler: ((NSNumber?, NSError?) -> ())?
override init() {
super.init()
self.centralManager = CBCentralManager(delegate: self, queue: nil)
self.data = NSMutableData()
}
@objc private func scanTimeout() {
print("[DEBUG] Scanning stopped")
self.centralManager.stopScan()
}
// MARK: Public methods
func startScanning(timeout: Double) -> Bool {
if self.centralManager.state != .PoweredOn {
print("[ERROR] Couldn´t start scanning")
return false
}
print("[DEBUG] Scanning started")
// CBCentralManagerScanOptionAllowDuplicatesKey
NSTimer.scheduledTimerWithTimeInterval(timeout, target: self, selector: #selector(BLE.scanTimeout), userInfo: nil, repeats: false)
let services:[CBUUID] = [CBUUID(string: RBL_SERVICE_UUID)]
self.centralManager.scanForPeripheralsWithServices(services, options: nil)
return true
}
func connectToPeripheral(peripheral: CBPeripheral) -> Bool {
if self.centralManager.state != .PoweredOn {
print("[ERROR] Couldn´t connect to peripheral")
return false
}
print("[DEBUG] Connecting to peripheral: \(peripheral.identifier.UUIDString)")
self.centralManager.connectPeripheral(peripheral, options: [CBConnectPeripheralOptionNotifyOnDisconnectionKey : NSNumber(bool: true)])
return true
}
func disconnectFromPeripheral(peripheral: CBPeripheral) -> Bool {
if self.centralManager.state != .PoweredOn {
print("[ERROR] Couldn´t disconnect from peripheral")
return false
}
self.centralManager.cancelPeripheralConnection(peripheral)
return true
}
func disconnectActivePeripheral() {
if let peripheral = activePeripheral {
disconnectFromPeripheral(peripheral)
}
}
func read() {
guard let char = self.characteristics[RBL_CHAR_TX_UUID] else { return }
self.activePeripheral?.readValueForCharacteristic(char)
}
func write(data data: NSData) {
guard let char = self.characteristics[RBL_CHAR_RX_UUID] else { return }
self.activePeripheral?.writeValue(data, forCharacteristic: char, type: .WithoutResponse)
}
func enableNotifications(enable: Bool) {
guard let char = self.characteristics[RBL_CHAR_TX_UUID] else { return }
self.activePeripheral?.setNotifyValue(enable, forCharacteristic: char)
}
func readRSSI(completion: (RSSI: NSNumber?, error: NSError?) -> ()) {
self.RSSICompletionHandler = completion
self.activePeripheral?.readRSSI()
}
func setBaudRate(baudRate: BLEBaudRate) {
guard let characteristc = self.characteristics[RBL_CHAR_BAUD_UUID] else {
print("[DEBUG] Cannot get BAUD characterictic")
return
}
self.activePeripheral?.writeValue(baudRate.data, forCharacteristic: characteristc, type: .WithoutResponse)
}
// MARK: CBCentralManager delegate
func centralManagerDidUpdateState(central: CBCentralManager) {
switch central.state {
case .Unknown:
print("[DEBUG] Central manager state: Unknown")
break
case .Resetting:
print("[DEBUG] Central manager state: Resseting")
break
case .Unsupported:
print("[DEBUG] Central manager state: Unsopported")
break
case .Unauthorized:
print("[DEBUG] Central manager state: Unauthorized")
break
case .PoweredOff:
print("[DEBUG] Central manager state: Powered off")
break
case .PoweredOn:
print("[DEBUG] Central manager state: Powered on")
break
}
state = central.state
}
func centralManager(central: CBCentralManager, didDiscoverPeripheral peripheral: CBPeripheral, advertisementData: [String : AnyObject],RSSI: NSNumber) {
print("[DEBUG] Find peripheral: \(peripheral.identifier.UUIDString) RSSI: \(RSSI)")
let index = peripherals.indexOf { $0.identifier.UUIDString == peripheral.identifier.UUIDString }
if let index = index {
peripherals[index] = peripheral
} else {
peripherals.append(peripheral)
}
delegate?.bleDidDiscoverPeripherals()
}
func centralManager(central: CBCentralManager, didFailToConnectPeripheral peripheral: CBPeripheral, error: NSError?) {
print("[ERROR] Could not connecto to peripheral \(peripheral.identifier.UUIDString) error: \(error!.description)")
}
func centralManager(central: CBCentralManager, didConnectPeripheral peripheral: CBPeripheral) {
print("[DEBUG] Connected to peripheral \(peripheral.identifier.UUIDString)")
self.activePeripheral = peripheral
self.activePeripheral?.delegate = self
self.activePeripheral?.discoverServices([CBUUID(string: RBL_SERVICE_UUID)])
self.delegate?.bleDidConnectToPeripheral()
}
func centralManager(central: CBCentralManager, didDisconnectPeripheral peripheral: CBPeripheral, error: NSError?) {
var text = "[DEBUG] Disconnected from peripheral: \(peripheral.identifier.UUIDString)"
if error != nil {
text += ". Error: \(error!.description)"
}
print(text)
self.activePeripheral?.delegate = nil
self.activePeripheral = nil
self.characteristics.removeAll(keepCapacity: false)
self.delegate?.bleDidDisconenctFromPeripheral()
}
// MARK: CBPeripheral delegate
func peripheral(peripheral: CBPeripheral, didDiscoverServices error: NSError?) {
if error != nil {
print("[ERROR] Error discovering services. \(error!.description)")
return
}
print("[DEBUG] Found services for peripheral: \(peripheral.identifier.UUIDString)")
for service in peripheral.services! {
let theCharacteristics = [CBUUID(string: RBL_CHAR_RX_UUID), CBUUID(string: RBL_CHAR_TX_UUID),
CBUUID(string: RBL_CHAR_BAUD_UUID)]
peripheral.discoverCharacteristics(theCharacteristics, forService: service)
}
}
func peripheral(peripheral: CBPeripheral, didDiscoverCharacteristicsForService service: CBService, error: NSError?) {
if error != nil {
print("[ERROR] Error discovering characteristics. \(error!.description)")
return
}
print("[DEBUG] Found characteristics for peripheral: \(peripheral.identifier.UUIDString)")
for characteristic in service.characteristics! {
self.characteristics[characteristic.UUID.UUIDString] = characteristic
}
enableNotifications(true)
delegate?.bleDidDicoverCharacateristics()
}
func peripheral(peripheral: CBPeripheral, didUpdateValueForCharacteristic characteristic: CBCharacteristic, error: NSError?) {
if error != nil {
print("[ERROR] Error updating value. \(error!.description)")
return
}
if characteristic.UUID.UUIDString == RBL_CHAR_TX_UUID {
self.delegate?.bleDidReceiveData(characteristic.value)
}
}
func peripheral(peripheral: CBPeripheral, didReadRSSI RSSI: NSNumber, error: NSError?) {
self.RSSICompletionHandler?(RSSI, error)
self.RSSICompletionHandler = nil
}
}
| mit | bf17140e5c2bdd5d419b6cbf2033db3e | 35.033333 | 460 | 0.630342 | 5.204622 | false | false | false | false |
skylib/SnapPageableArray | SnapPageableArrayTests/InsertTests.swift | 1 | 3523 | import XCTest
import SnapPageableArray
class InsertTests: PageableArrayTests {
func testInsertElementsWithSubscript() {
let size = 10
let pageSize = 5
var array = createArrayWithSize(size, pageSize: pageSize)
for i in 0..<size {
let element = array[UInt(i)]
XCTAssertNotNil(element)
XCTAssertEqual(i, element!.data)
}
}
func testAppendElementShouldIncreaseCount() {
let size = 10
let pageSize = 5
var array = createArrayWithSize(size, pageSize: pageSize)
array.appendElement(TestElement(id: 11, data: 11))
XCTAssertEqual(UInt(size + 1), array.count)
}
func testAppendElementShouldAppendElelemt() {
let size = 10
let pageSize = 5
var array = createArrayWithSize(size, pageSize: pageSize)
let data = 100
array.appendElement(TestElement(id: data, data: data))
let element = array[UInt(array.count - 1)]
XCTAssertNotNil(element)
XCTAssertEqual(data, element!.data)
}
func testTopUpShouldInsertNewElementsFirst() {
let size = 10
let pageSize = 5
var array = createArrayWithSize(size, pageSize: pageSize)
var newElements = [TestElement]()
for i in size..<size * 2 {
newElements.append(TestElement(id: i, data: i))
}
array.topUpWithElements(newElements)
for i in 0..<size {
let element = array[UInt(i)]
XCTAssertNotNil(element)
XCTAssertEqual(i + size, element!.data)
}
}
func testTopUpWithNoNewItemsShouldReturnNoNewItems() {
let size = 10
let pageSize = 5
var array = PageableArray<TestElement>(capacity: UInt(size), pageSize: UInt(pageSize))
var elements = [TestElement]()
for i in 0..<size {
let element = TestElement(id: i, data: i)
array[UInt(i)] = element
elements.append(element)
}
let result = array.topUpWithElements(elements)
XCTAssertEqual(result, UpdateResult.noNewItems)
}
func testTopUpWithSomeNewItemsShouldReturnSomeNewItems() {
let size = 10
let pageSize = 5
var array = PageableArray<TestElement>(capacity: UInt(size), pageSize: UInt(pageSize))
var elements = [TestElement]()
for i in 0..<size {
var element = TestElement(id: i, data: i)
array[UInt(i)] = element
if i < size/2 {
element = TestElement(id: i + 10, data: i + 10)
}
elements.append(element)
}
let result = array.topUpWithElements(elements)
XCTAssertEqual(result, UpdateResult.someNewItems(newItems: size/2))
}
func testTopUpWithAllNewItemsShouldReturnAllNewItems() {
let size = 10
let pageSize = 5
var array = PageableArray<TestElement>(capacity: UInt(size), pageSize: UInt(pageSize))
var elements = [TestElement]()
for i in 0..<size {
var element = TestElement(id: i, data: i)
array[UInt(i)] = element
element = TestElement(id: i + 10, data: i + 10)
elements.append(element)
}
let result = array.topUpWithElements(elements)
XCTAssertEqual(result, UpdateResult.allNewItems)
}
}
| bsd-3-clause | 68fe6f94112c0bb5bf52d1361111fd4c | 30.738739 | 94 | 0.573659 | 4.812842 | false | true | false | false |
64characters/Telephone | Telephone/PresentationSoundIO.swift | 1 | 2182 | //
// PresentationSoundIO.swift
// Telephone
//
// Copyright © 2008-2016 Alexey Kuznetsov
// Copyright © 2016-2022 64 Characters
//
// Telephone 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.
//
// Telephone 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.
//
import Domain
import Foundation
import UseCases
final class PresentationSoundIO: NSObject {
@objc let input: PresentationAudioDevice
@objc let output: PresentationAudioDevice
@objc let ringtoneOutput: PresentationAudioDevice
@objc init(input: PresentationAudioDevice, output: PresentationAudioDevice, ringtoneOutput: PresentationAudioDevice) {
self.input = input
self.output = output
self.ringtoneOutput = ringtoneOutput
}
}
extension PresentationSoundIO {
convenience init(soundIO: SystemDefaultingSoundIO, systemDefaultDeviceName name: String) {
self.init(
input: PresentationAudioDevice(item: soundIO.input, systemDefaultDeviceName: name),
output: PresentationAudioDevice(item: soundIO.output, systemDefaultDeviceName: name),
ringtoneOutput: PresentationAudioDevice(item: soundIO.ringtoneOutput, systemDefaultDeviceName: name)
)
}
}
extension PresentationSoundIO {
override func isEqual(_ object: Any?) -> Bool {
guard let soundIO = object as? PresentationSoundIO else { return false }
return isEqual(to: soundIO)
}
override var hash: Int {
var hasher = Hasher()
hasher.combine(input)
hasher.combine(output)
hasher.combine(ringtoneOutput)
return hasher.finalize()
}
private func isEqual(to soundIO: PresentationSoundIO) -> Bool {
return input == soundIO.input && output == soundIO.output && ringtoneOutput == soundIO.ringtoneOutput
}
}
| gpl-3.0 | 3de16a08254c90c6d42fd5f225b69cd7 | 34.16129 | 122 | 0.716055 | 5.105386 | false | false | false | false |
C453/Force-Touch-Command-Center | Force Touch Command Center/AppDelegate.swift | 1 | 2742 | //
// AppDelegate.swift
// Force Touch Command Center
//
// Created by Case Wright on 9/24/15.
// Copyright © 2015 C453. All rights reserved.
//
import Cocoa
import MASShortcut
@NSApplicationMain
class AppDelegate: NSObject, NSApplicationDelegate {
let StatusItem = NSStatusBar.systemStatusBar().statusItemWithLength(NSVariableStatusItemLength)
let settings = NSUserDefaults.standardUserDefaults()
func applicationDidFinishLaunching(aNotification: NSNotification) {
if settings.boolForKey("notFirstLaunch") == false {
//First Launch
settings.setBool(true, forKey: "notFirstLaunch")
settings.setFloat(Options.lowerLimit, forKey: "lowerLimit")
settings.setFloat(Options.upperLimit, forKey: "upperLimit")
settings.setBool(Options.showLevel, forKey: "showLevel")
settings.setBool(Options.showSlider, forKey: "showSlider")
settings.setFloat(Float(Options.Shape.rawValue), forKey: "shapeType")
settings.setInteger(Options.action.rawValue, forKey: "action")
}
Options.lowerLimit = settings.floatForKey("lowerLimit")
Options.upperLimit = settings.floatForKey("upperLimit")
Options.showLevel = settings.boolForKey("showLevel")
Options.showSlider = settings.boolForKey("showSlider")
Options.Shape = ShapeType(rawValue: CGFloat(settings.floatForKey("shapeType")))!
Options.action = ActionType(rawValue: settings.integerForKey("action"))!
StatusItem.button?.title = "Options"
StatusItem.button?.image = NSImage(named: "statusIcon")
Options.optionsWindowController = OptionsWindowController(
windowNibName: "OptionsWindowController")
Options.popupWindowController = PopupWindowController(
windowNibName: "PopupWindowController")
let menu = NSMenu()
menu.addItem(NSMenuItem(title: "Options", action: Selector(
"openOptions"), keyEquivalent: ""))
menu.addItem(NSMenuItem(title: "Quit", action: Selector("terminate:"), keyEquivalent: ""))
StatusItem.menu = menu
Options.getVolumeDevice()
MASShortcutBinder.sharedBinder().bindShortcutWithDefaultsKey("GlobalShortcut") { () -> Void in
self.openPopup()
self.centerCursor()
}
}
func applicationWillTerminate(aNotification: NSNotification) {
// Insert code here to tear down your application
}
func openOptions() {
Options.optionsWindowController?.showWindow(self)
}
func openPopup() {
Options.popupWindowController?.showWindow(self)
}
func centerCursor() {
CGDisplayMoveCursorToPoint(0, Options.center)
}
} | gpl-2.0 | cb6fb337ac7dbee5fde246113d238ad2 | 36.561644 | 102 | 0.682598 | 5.020147 | false | false | false | false |
iachievedit/swiftysockets | Source/IP.swift | 1 | 2419 | // IP.swift
//
// The MIT License (MIT)
//
// Copyright (c) 2015 Zewo
//
// 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 Tide
import Glibc
public enum IPMode {
case IPV4
case IPV6
case IPV4Prefered
case IPV6Prefered
}
extension IPMode {
var code: Int32 {
switch self {
case .IPV4: return 1
case .IPV6: return 2
case .IPV4Prefered: return 3
case .IPV6Prefered: return 4
}
}
}
public struct IP {
let address: ipaddr
public init(port: Int, mode: IPMode = .IPV4) throws {
self.address = iplocal(nil, Int32(port), mode.code)
if errno != 0 {
let description = IPError.lastSystemErrorDescription
throw IPError(description: description)
}
}
public init(networkInterface: String, port: Int, mode: IPMode = .IPV4) throws {
self.address = iplocal(networkInterface, Int32(port), mode.code)
if errno != 0 {
let description = IPError.lastSystemErrorDescription
throw IPError(description: description)
}
}
public init(address: String, port: Int, mode: IPMode = .IPV4) throws {
self.address = ipremote(address, Int32(port), mode.code)
if errno != 0 {
let description = IPError.lastSystemErrorDescription
throw IPError(description: description)
}
}
}
| mit | e7ac3c30d6ceead1a6814f15a7640e50 | 31.253333 | 83 | 0.677966 | 4.335125 | false | false | false | false |
mozilla-mobile/firefox-ios | Extensions/ShareTo/ShareTheme.swift | 2 | 1546 | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
import UIKit
private enum ColorScheme {
case dark
case light
}
public struct ModernColor {
var darkColor: UIColor
var lightColor: UIColor
public init(dark: UIColor, light: UIColor) {
self.darkColor = dark
self.lightColor = light
}
public var color: UIColor {
return UIColor { (traitCollection: UITraitCollection) -> UIColor in
if traitCollection.userInterfaceStyle == .dark {
return self.color(for: .dark)
} else {
return self.color(for: .light)
}
}
}
private func color(for scheme: ColorScheme) -> UIColor {
return scheme == .dark ? darkColor : lightColor
}
}
struct ShareTheme {
static let defaultBackground = ModernColor(dark: UIColor.Photon.Grey80, light: .white)
static let doneLabelBackground = ModernColor(dark: UIColor.Photon.Blue40, light: UIColor.Photon.Blue40)
static let separator = ModernColor(dark: UIColor.Photon.Grey10, light: UIColor.Photon.Grey30)
static let actionRowTextAndIcon = ModernColor(dark: .white, light: UIColor.Photon.Grey80)
static let textColor = ModernColor(dark: UIColor.Photon.LightGrey05, light: UIColor.Photon.DarkGrey90)
static let iconColor = ModernColor(dark: UIColor.Photon.LightGrey05, light: UIColor.Photon.DarkGrey90)
}
| mpl-2.0 | 0de26e19a8a4ec901ce2cf1755d298e5 | 34.953488 | 107 | 0.684347 | 4.247253 | false | false | false | false |
LinkRober/RBRefresh | custom/RBBallScaleHeader.swift | 1 | 2452 | //
// RBBallScaleHeader.swift
// RBRefresh
//
// Created by 夏敏 on 08/02/2017.
// Copyright © 2017 夏敏. All rights reserved.
//
import UIKit
class RBBallScaleHeader: UIView ,RBPullDownToRefreshViewDelegate{
override init(frame: CGRect) {
super.init(frame: frame)
backgroundColor = UIColor(red: CGFloat(237 / 255.0), green: CGFloat(85 / 255.0), blue: CGFloat(101 / 255.0), alpha: 1)
let layer = CAShapeLayer()
let path = UIBezierPath()
path.addArc(withCenter: CGPoint.init(x: 15, y: 15), radius: 15, startAngle: 0, endAngle: 2*CGFloat(M_PI), clockwise: false)
layer.path = path.cgPath
layer.fillColor = UIColor.white.cgColor
layer.frame = CGRect.init(x: (frame.size.width - 30)/2, y: (frame.size.height - 30)/2, width: 30, height: 30)
let animtaion = getAnimation()
layer.add(animtaion, forKey: "animation")
self.layer.addSublayer(layer)
}
func getAnimation() -> CAAnimationGroup {
let duration:CFTimeInterval = 1
//scale
let scaleAnimation = CABasicAnimation.init(keyPath: "transform.scale")
scaleAnimation.fromValue = 0
scaleAnimation.toValue = 1
scaleAnimation.duration = duration
//opacity
let opacityAnimation = CABasicAnimation.init(keyPath: "opacity")
opacityAnimation.fromValue = 1
opacityAnimation.toValue = 0
opacityAnimation.duration = duration
//group
let animationGroup = CAAnimationGroup()
animationGroup.animations = [scaleAnimation,opacityAnimation]
animationGroup.timingFunction = CAMediaTimingFunction.init(name: kCAMediaTimingFunctionEaseInEaseOut)
animationGroup.duration = duration
animationGroup.repeatCount = HUGE
animationGroup.isRemovedOnCompletion = false
return animationGroup
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func pullDownToRefreshAnimationDidEnd(_ view: RBHeader) {
}
func pullDownToRefreshAnimationDidStart(_ view: RBHeader) {
}
func pullDownToRefresh(_ view: RBHeader, progressDidChange progress: CGFloat) {
}
func pullDownToRefresh(_ view: RBHeader, stateDidChange state: RBPullDownToRefreshViewState) {
}
}
| mit | 40faa998e0a1ff335541e0d2dc9a3307 | 31.144737 | 131 | 0.641424 | 4.809055 | false | false | false | false |
youknowone/Say | macOS/ViewController.swift | 1 | 5842 | //
// ViewController.swift
// Say
//
// Created by Jeong YunWon on 2015. 4. 10..
// Copyright (c) 2015년 youknowone.org. All rights reserved.
//
import Cocoa
// import SayKit
/// Main window of the application
class MainWindow: NSWindow {
@IBOutlet var speechToolbarItem: NSToolbarItem! = nil
@IBOutlet var pauseToolbarItem: NSToolbarItem! = nil
@IBOutlet var exportToolbarItem: NSToolbarItem! = nil
@IBOutlet var openToolbarItem: NSToolbarItem! = nil
@IBOutlet var stopToolbarItem: NSToolbarItem! = nil
override func awakeFromNib() {
/** Load data from cache in NSUserDefaults or from URL.
*
* Load data from cache in NSUserDefaults. If cache data doesn't exist
* in NSUserDefaults with given tag, download data from URL and save
* it to the given tag before loading.
*/
func syncronizedData(_ tag: String, URL: Foundation.URL) -> Data? {
let standardUserDefaults = UserDefaults.standard
guard let iconData = standardUserDefaults.object(forKey: tag) as? Data else {
if let downloadedData = try? Data(contentsOf: URL) {
standardUserDefaults.set(downloadedData, forKey: tag)
standardUserDefaults.synchronize()
return downloadedData
} else {
//print("Icon is not loadable!")
return nil
}
}
return iconData
}
super.awakeFromNib()
if let imageData = syncronizedData("icon_speech", URL: URL(string: "https://upload.wikimedia.org/wikipedia/commons/1/10/Exquisite-microphone.png")!) {
self.speechToolbarItem.image = NSImage(data: imageData)
}
if let imageData = syncronizedData("icon_pause", URL: URL(string: "https://upload.wikimedia.org/wikipedia/commons/5/57/Pause_icon_status.png")!) {
self.pauseToolbarItem.image = NSImage(data: imageData)
}
if let imageData = syncronizedData("icon_export", URL: URL(string: "https://upload.wikimedia.org/wikipedia/commons/thumb/3/38/Gnome-generic-empty.svg/500px-Gnome-generic-empty.svg.png?uselang=ko")!) {
self.exportToolbarItem.image = NSImage(data: imageData)
}
if let imageData = syncronizedData("icon_open", URL: URL(string: "https://upload.wikimedia.org/wikipedia/commons/thumb/9/98/Inkscape_icons_document_import.svg/500px-Inkscape_icons_document_import.svg.png?uselang=ko")!) {
self.openToolbarItem.image = NSImage(data: imageData)
}
if let imageData = syncronizedData("icon_stop_", URL: URL(string: "https://upload.wikimedia.org/wikipedia/commons/b/bf/Stop_icon_status.png")!) {
self.stopToolbarItem.image = NSImage(data: imageData)
}
}
}
/// The controller for main view in main window
class ViewController: NSViewController {
/// Text view to speech
@IBOutlet var textView: NSTextView! = nil
/// Combo box for voices. Default is decided by system locale
@IBOutlet var voiceComboBox: NSComboBox! = nil
/// Save panel for "Export" menu
@IBOutlet var URLField: NSTextField! = nil;
let voiceSavePanel = NSSavePanel()
/// Open panel for "Open" menu
let textOpenPanel = NSOpenPanel()
var api: SayAPI! = SayAPI(text: " ", voice: nil)
var pause: Bool = false
@available(OSX 10.10, *)
override func viewDidLoad() {
super.viewDidLoad()
assert(self.textView != nil)
assert(self.voiceComboBox != nil)
self.voiceSavePanel.allowedFileTypes = ["aiff"] // default output format is aiff. See `man say`
self.voiceComboBox.addItems(withObjectValues: VoiceAPI.voices.map({ "\($0.name)(\($0.locale)): \($0.comment)"; }))
}
override var representedObject: Any? {
didSet {
// Update the view, if already loaded.
}
}
var textForSpeech: String {
var selectedText = self.textView.string
let selectedRange = self.textView.selectedRange()
if selectedRange.length > 0 {
selectedText = (selectedText as NSString).substring(with: selectedRange)
}
return selectedText
}
var selectedVoice: VoiceAPI? {
get {
let index = self.voiceComboBox.indexOfSelectedItem
guard index >= 0 && index != NSNotFound else {
return nil
}
return VoiceAPI.voices[index - 1]
}
}
@IBAction func say(_ sender: NSToolbarItem) {
guard api.isplaying() else {
return
}
if self.pause {
self.pause = false
api.continueSpeaking()
} else {
api = SayAPI(text: self.textForSpeech, voice: self.selectedVoice)
api.play(false)
}
}
@IBAction func pause(_ sender: NSControl) {
self.pause = true
api.pause()
}
@IBAction func stop(_ sender: NSControl) {
self.pause = false
api.stop()
}
@IBAction func saveDocumentAs(_ sender: NSControl) {
self.voiceSavePanel.runModal()
guard let fileURL = self.voiceSavePanel.url else {
return
}
let say = SayAPI(text: self.textForSpeech, voice: self.selectedVoice)
say.writeToURL(fileURL, atomically: true)
}
@IBAction func openTextFile(_ sender: NSControl) {
self.textOpenPanel.runModal()
guard let textURL = self.textOpenPanel.url else {
// No given URL
return
}
guard let text = try? String(contentsOf: textURL, encoding: .utf8) else {
// No utf-8 data in the URL
return
}
self.textView.string = text
}
}
| gpl-3.0 | 8c77b9932a1a2b265985f8a96529cf29 | 34.828221 | 228 | 0.608562 | 4.488855 | false | false | false | false |
takamashiro/XDYZB | XDYZB/XDYZB/Classes/LiveMySelf/LiveMySelfViewController.swift | 1 | 8198 | //
// LiveMySelfViewController.swift
// XLiveDemo
//
// Created by takamashiro on 2016/11/11.
// Copyright © 2016年 com.takamashiro. All rights reserved.
//
import UIKit
import LFLiveKit
class LiveMySelfViewController: UIViewController {
//MARK: - Getters and Setters
// 默认分辨率368 * 640 音频:44.1 iphone6以上48 双声道 方向竖屏
var session: LFLiveSession = {
let audioConfiguration = LFLiveAudioConfiguration.defaultConfiguration(for: LFLiveAudioQuality.high)
let videoConfiguration = LFLiveVideoConfiguration.defaultConfiguration(for: LFLiveVideoQuality.low3)
let session = LFLiveSession(audioConfiguration: audioConfiguration, videoConfiguration: videoConfiguration)
return session!
}()
// 视图
var containerView: UIView = {
let containerView = UIView(frame: CGRect(x: 0, y: 0, width: UIScreen.main.bounds.width, height: UIScreen.main.bounds.height))
containerView.backgroundColor = UIColor.clear
containerView.autoresizingMask = [UIViewAutoresizing.flexibleHeight, UIViewAutoresizing.flexibleHeight]
return containerView
}()
// 状态Label
var stateLabel: UILabel = {
let stateLabel = UILabel(frame: CGRect(x: 20, y: 20, width: 80, height: 40))
stateLabel.text = "未连接"
stateLabel.textColor = UIColor.white
stateLabel.font = UIFont.systemFont(ofSize: 14)
return stateLabel
}()
// 关闭按钮
var closeButton: UIButton = {
let closeButton = UIButton(frame: CGRect(x: UIScreen.main.bounds.width - 10 - 44, y: 20, width: 44, height: 44))
closeButton.setImage(UIImage(named: "close_preview"), for: UIControlState())
return closeButton
}()
// 摄像头
var cameraButton: UIButton = {
let cameraButton = UIButton(frame: CGRect(x: UIScreen.main.bounds.width - 54 * 2, y: 20, width: 44, height: 44))
cameraButton.setImage(UIImage(named: "camra_preview"), for: UIControlState())
return cameraButton
}()
// 摄像头
var beautyButton: UIButton = {
let beautyButton = UIButton(frame: CGRect(x: UIScreen.main.bounds.width - 54 * 3, y: 20, width: 44, height: 44))
beautyButton.setImage(UIImage(named: "camra_beauty"), for: UIControlState.selected)
beautyButton.setImage(UIImage(named: "camra_beauty_close"), for: UIControlState())
return beautyButton
}()
// 开始直播按钮
var startLiveButton: UIButton = {
let startLiveButton = UIButton(frame: CGRect(x: 30, y: UIScreen.main.bounds.height - 60, width: UIScreen.main.bounds.width - 10 - 44, height: 44))
startLiveButton.layer.cornerRadius = 22
startLiveButton.setTitleColor(UIColor.black, for:UIControlState())
startLiveButton.setTitle("开始直播", for: UIControlState())
startLiveButton.titleLabel!.font = UIFont.systemFont(ofSize: 14)
startLiveButton.backgroundColor = UIColor(colorLiteralRed: 50, green: 32, blue: 245, alpha: 1)
return startLiveButton
}()
override func viewDidLoad() {
super.viewDidLoad()
session.delegate = self
session.preView = self.view
self.requestAccessForVideo()
self.requestAccessForAudio()
self.view.backgroundColor = UIColor.clear
self.view.addSubview(containerView)
containerView.addSubview(stateLabel)
containerView.addSubview(closeButton)
containerView.addSubview(beautyButton)
containerView.addSubview(cameraButton)
containerView.addSubview(startLiveButton)
cameraButton.addTarget(self, action: #selector(didTappedCameraButton(_:)), for:.touchUpInside)
beautyButton.addTarget(self, action: #selector(didTappedBeautyButton(_:)), for: .touchUpInside)
startLiveButton.addTarget(self, action: #selector(didTappedStartLiveButton(_:)), for: .touchUpInside)
closeButton.addTarget(self, action: #selector(didTappedCloseButton(_:)), for: .touchUpInside)
}
deinit {
print(#function)
}
//MARK: - Events
// 开始直播
func didTappedStartLiveButton(_ button: UIButton) -> Void {
startLiveButton.isSelected = !startLiveButton.isSelected;
if (startLiveButton.isSelected) {
startLiveButton.setTitle("结束直播", for: UIControlState())
let stream = LFLiveStreamInfo()
stream.url = "rtmp://172.20.10.2:1935/rtmplive/room"
session.startLive(stream)
} else {
startLiveButton.setTitle("开始直播", for: UIControlState())
session.stopLive()
}
}
// 美颜
func didTappedBeautyButton(_ button: UIButton) -> Void {
session.beautyFace = !session.beautyFace;
beautyButton.isSelected = !session.beautyFace
}
// 摄像头
func didTappedCameraButton(_ button: UIButton) -> Void {
let devicePositon = session.captureDevicePosition;
session.captureDevicePosition = (devicePositon == AVCaptureDevicePosition.back) ? AVCaptureDevicePosition.front : AVCaptureDevicePosition.back;
}
// 关闭
func didTappedCloseButton(_ button: UIButton) -> Void {
dismiss(animated: true, completion: nil)
}
}
extension LiveMySelfViewController {
//MARK: AccessAuth
func requestAccessForVideo() -> Void {
let status = AVCaptureDevice.authorizationStatus(forMediaType: AVMediaTypeVideo);
switch status {
// 许可对话没有出现,发起授权许可
case AVAuthorizationStatus.notDetermined:
AVCaptureDevice.requestAccess(forMediaType: AVMediaTypeVideo, completionHandler: { (granted) in
if(granted){
DispatchQueue.main.async {
self.session.running = true
}
}
})
break;
// 已经开启授权,可继续
case AVAuthorizationStatus.authorized:
session.running = true;
break;
// 用户明确地拒绝授权,或者相机设备无法访问
case AVAuthorizationStatus.denied: break
case AVAuthorizationStatus.restricted:break;
}
}
func requestAccessForAudio() -> Void {
let status = AVCaptureDevice.authorizationStatus(forMediaType:AVMediaTypeAudio)
switch status {
// 许可对话没有出现,发起授权许可
case AVAuthorizationStatus.notDetermined:
AVCaptureDevice.requestAccess(forMediaType: AVMediaTypeAudio, completionHandler: { (granted) in
})
break;
// 已经开启授权,可继续
case AVAuthorizationStatus.authorized:
break;
// 用户明确地拒绝授权,或者相机设备无法访问
case AVAuthorizationStatus.denied: break
case AVAuthorizationStatus.restricted:break;
}
}
} //相机,麦克风授权
extension LiveMySelfViewController : LFLiveSessionDelegate {
/** live status changed will callback */
func liveSession(_ session: LFLiveSession?, liveStateDidChange state: LFLiveState) {
print("liveStateDidChange: \(state.rawValue)")
switch state {
case LFLiveState.ready:
stateLabel.text = "未连接"
break;
case LFLiveState.pending:
stateLabel.text = "连接中"
break;
case LFLiveState.start:
stateLabel.text = "已连接"
break;
case LFLiveState.error:
stateLabel.text = "连接错误"
break;
case LFLiveState.stop:
stateLabel.text = "未连接"
break;
}
}
/** live debug info callback */
func liveSession(_ session: LFLiveSession?, debugInfo: LFLiveDebug?) {
print("debugInfo: \(debugInfo?.currentBandwidth)")
}
/** callback socket errorcode */
func liveSession(_ session: LFLiveSession?, errorCode: LFLiveSocketErrorCode) {
print("errorCode: \(errorCode.rawValue)")
}
}
| mit | bb35248c787959b400f5a137c2f522b9 | 36.502392 | 154 | 0.642894 | 4.811541 | false | false | false | false |
mohssenfathi/MTLImage | MTLImage/Sources/Filters/DepthToGrayscale.swift | 1 | 1525 | //
// DepthToGrayscale.swift
// Pods
//
// Created by Mohssen Fathi on 6/8/17.
//
struct DepthToGrayscaleUniforms: Uniforms {
var offset: Float = 0.5
var range: Float = 0.5
}
public
class DepthToGrayscale: Filter {
var uniforms = DepthToGrayscaleUniforms()
@objc public var offset: Float = 0.5 {
didSet {
// clamp(&offset, low: 0, high: 1)
needsUpdate = true
}
}
@objc public var range: Float = 0.5 {
didSet {
// clamp(&range, low: 0, high: 1)
needsUpdate = true
}
}
public init() {
super.init(functionName: "depthToGrayscale")
title = "Depth To Grayscale"
properties = [
Property(key: "offset", title: "Offset"),
Property(key: "range", title: "Range")
]
}
required public init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
override func update() {
if self.input == nil { return }
uniforms.offset = offset
uniforms.range = range
updateUniforms(uniforms: uniforms)
}
override func configureCommandEncoder(_ commandEncoder: MTLComputeCommandEncoder) {
super.configureCommandEncoder(commandEncoder)
if let context = (source as? Camera)?.depthContext {
if context.minDepth < offset { offset = context.minDepth }
if context.maxDepth < range { range = context.maxDepth }
}
}
}
| mit | e5c347f32efa4e75b99267c9aa23f428 | 24 | 87 | 0.562623 | 4.30791 | false | false | false | false |
ekranac/FoodPin | FoodPin/ReviewViewController.swift | 1 | 2028 | //
// ReviewViewController.swift
// FoodPin
//
// Created by Ziga Besal on 09/01/2017.
// Copyright © 2017 Ziga Besal. All rights reserved.
//
import UIKit
class ReviewViewController: UIViewController {
@IBOutlet var backgroundImageView: UIImageView!
@IBOutlet var containerView: UIView!
@IBOutlet var containerImage: UIImageView!
@IBOutlet var btnClose: UIButton!
var restaurant: RestaurantMO!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
containerImage.image = UIImage(data: restaurant.image as! Data)
let blurEffect = UIBlurEffect(style: .dark)
let blurEffectView = UIVisualEffectView(effect: blurEffect)
blurEffectView.frame = view.bounds
backgroundImageView.addSubview(blurEffectView)
let scaleTransform = CGAffineTransform.init(scaleX: 0, y: 0)
let translateTransform = CGAffineTransform.init(translationX: 0, y: -1000)
let combineTransform = scaleTransform.concatenating(translateTransform)
containerView.transform = combineTransform
btnClose.transform = CGAffineTransform.init(translationX: 1000, y: 0)
}
override func viewDidAppear(_ animated: Bool) {
UIView.animate(withDuration: 0.7, animations: {
self.containerView.transform = CGAffineTransform.identity
self.btnClose.transform = CGAffineTransform.identity
})
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
| gpl-3.0 | b6826d738976f2bfe9edfd0d8a8379ce | 32.229508 | 106 | 0.683276 | 5.157761 | false | false | false | false |
sbcmadn1/swift | swiftweibo05/GZWeibo05/Class/Module/Compose/Controller/CZComposeViewController.swift | 2 | 16221 | //
// CZComposeViewController.swift
// GZWeibo05
//
// Created by zhangping on 15/11/3.
// Copyright © 2015年 zhangping. All rights reserved.
//
import UIKit
import SVProgressHUD
class CZComposeViewController: UIViewController {
// MARK: - 属性
/// toolBar底部约束
private var toolBarBottomCon: NSLayoutConstraint?
/// 照片选择器控制器view的底部约束
private var photoSelectorViewBottomCon: NSLayoutConstraint?
/// 微博内容的最大长度
private let statusMaxLength = 20
override func viewDidLoad() {
super.viewDidLoad()
// 需要设置背景颜色,不然弹出时动画有问题
view.backgroundColor = UIColor.whiteColor()
prepareUI()
// 添加键盘frame改变的通知
NSNotificationCenter.defaultCenter().addObserver(self, selector: "willChangeFrame:", name: UIKeyboardWillChangeFrameNotification, object: nil)
}
deinit {
NSNotificationCenter.defaultCenter().removeObserver(self)
}
/*
notification:NSConcreteNotification 0x7f8fea5a4e20 {name = UIKeyboardDidChangeFrameNotification; userInfo = {
UIKeyboardAnimationCurveUserInfoKey = 7;
UIKeyboardAnimationDurationUserInfoKey = "0.25"; // 动画时间
UIKeyboardBoundsUserInfoKey = "NSRect: {{0, 0}, {375, 258}}";
UIKeyboardCenterBeginUserInfoKey = "NSPoint: {187.5, 796}";
UIKeyboardCenterEndUserInfoKey = "NSPoint: {187.5, 538}";
UIKeyboardFrameBeginUserInfoKey = "NSRect: {{0, 667}, {375, 258}}";
UIKeyboardFrameEndUserInfoKey = "NSRect: {{0, 409}, {375, 258}}"; // 键盘最终的位置
UIKeyboardIsLocalUserInfoKey = 1;
}}
*/
/// 键盘frame改变
func willChangeFrame(notification: NSNotification) {
// print("notification:\(notification)")
// 获取键盘最终位置
let endFrame = notification.userInfo![UIKeyboardFrameEndUserInfoKey]!.CGRectValue
// 动画时间
let duration = notification.userInfo![UIKeyboardAnimationDurationUserInfoKey] as! NSTimeInterval
toolBarBottomCon?.constant = -(UIScreen.height() - endFrame.origin.y)
UIView.animateWithDuration(duration) { () -> Void in
// 不能直接更新toolBar的约束
// self.toolBar.layoutIfNeeded()
self.view.layoutIfNeeded()
}
}
// MARK: - 准备UI
private func prepareUI() {
// 添加子控件
view.addSubview(textView)
view.addSubview(photoSelectorVC.view)
view.addSubview(toolBar)
view.addSubview(lengthTipLabel)
setupNavigationBar()
setupTextView()
preparePhotoSelectorView()
setupToolBar()
prepareLengthTipLabel()
}
// override func viewWillAppear(animated: Bool) {
// super.viewWillAppear(animated)
//
// // 弹出键盘
// textView.becomeFirstResponder()
// }
override func viewDidAppear(animated: Bool) {
super.viewDidAppear(animated)
// let view = UIView(frame: CGRect(x: 0, y: 0, width: 200, height: 10))
// view.backgroundColor = UIColor.redColor()
// textView.inputView = view
// 自定义键盘其实就是给 textView.inputView 赋值
// 如果照片选择器的view没有显示就弹出键盘
if photoSelectorViewBottomCon?.constant != 0 {
textView.becomeFirstResponder()
}
}
/// 设置导航栏
private func setupNavigationBar() {
// 设置按钮, 左边
navigationItem.leftBarButtonItem = UIBarButtonItem(title: "取消", style: UIBarButtonItemStyle.Plain, target: self, action: "close")
// 右边
navigationItem.rightBarButtonItem = UIBarButtonItem(title: "发送", style: UIBarButtonItemStyle.Plain, target: self, action: "sendStatus")
navigationItem.rightBarButtonItem?.enabled = false
setupTitleView()
}
/// 设置toolBar
private func setupToolBar() {
// 添加约束
let cons = toolBar.ff_AlignInner(type: ff_AlignType.BottomLeft, referView: view, size: CGSize(width: UIScreen.width(), height: 44))
// 获取底部约束
toolBarBottomCon = toolBar.ff_Constraint(cons, attribute: NSLayoutAttribute.Bottom)
// 创建toolBar item
var items = [UIBarButtonItem]()
// 每个item对应的图片名称
let itemSettings = [["imageName": "compose_toolbar_picture", "action": "picture"],
["imageName": "compose_trendbutton_background", "action": "trend"],
["imageName": "compose_mentionbutton_background", "action": "mention"],
["imageName": "compose_emoticonbutton_background", "action": "emoticon"],
["imageName": "compose_addbutton_background", "action": "add"]]
var index = 0
// 遍历 itemSettings 获取图片名称,创建items
for dict in itemSettings {
// 获取图片的名称
let imageName = dict["imageName"]!
// 获取图片对应点点击方法名称
let action = dict["action"]!
let item = UIBarButtonItem(imageName: imageName)
// 获取item里面的按钮
let button = item.customView as! UIButton
button.addTarget(self, action: Selector(action), forControlEvents: UIControlEvents.TouchUpInside)
items.append(item)
// 添加弹簧
items.append(UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.FlexibleSpace, target: nil, action: nil))
index++
}
// 移除最后一个弹簧
items.removeLast()
toolBar.items = items
}
/// 设置导航栏标题
private func setupTitleView() {
let prefix = "发微博"
// 获取用户的名称
if let name = CZUserAccount.loadAccount()?.name {
// 有用户名
let titleName = prefix + "\n" + name
// 创建可变的属性文本
let attrString = NSMutableAttributedString(string: titleName)
// 创建label
let label = UILabel()
// 设置属性文本
label.numberOfLines = 0
label.textAlignment = NSTextAlignment.Center
label.font = UIFont.systemFontOfSize(14)
// 获取NSRange
let nameRange = (titleName as NSString).rangeOfString(name)
// 设置属性文本的属性
attrString.addAttribute(NSFontAttributeName, value: UIFont.systemFontOfSize(12), range: nameRange)
attrString.addAttribute(NSForegroundColorAttributeName, value: UIColor.lightGrayColor(), range: nameRange)
// 顺序不要搞错
label.attributedText = attrString
label.sizeToFit()
navigationItem.titleView = label
} else {
// 没有用户名
navigationItem.title = prefix
}
}
/// 设置textView
private func setupTextView() {
/*
前提:
1.scrollView所在的控制器属于某个导航控制器
2.scrollView控制器的view或者控制器的view的第一个子view
*/
// scrollView会自动设置Insets, 比如scrollView所在的控制器属于某个导航控制器contentInset.top = 64
// automaticallyAdjustsScrollViewInsets = true
// 添加约束
// 相对控制器的view的内部左上角
textView.ff_AlignInner(type: ff_AlignType.TopLeft, referView: view, size: nil)
// 相对toolBar顶部右上角
textView.ff_AlignVertical(type: ff_AlignType.TopRight, referView: toolBar, size: nil)
}
/// 准备 显示微博剩余长度 label
func prepareLengthTipLabel() {
// 添加约束
lengthTipLabel.ff_AlignVertical(type: ff_AlignType.TopRight, referView: toolBar, size: nil, offset: CGPoint(x: -8, y: -8))
}
/// 准备 照片选择器
func preparePhotoSelectorView() {
// 照片选择器控制器的view
let photoSelectorView = photoSelectorVC.view
photoSelectorView.translatesAutoresizingMaskIntoConstraints = false
let views = ["psv": photoSelectorView]
// 添加约束
// 水平
view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|-0-[psv]-0-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: views))
// 高度
view.addConstraint(NSLayoutConstraint(item: photoSelectorView, attribute: NSLayoutAttribute.Height, relatedBy: NSLayoutRelation.Equal, toItem: view, attribute: NSLayoutAttribute.Height, multiplier: 0.6, constant: 0))
// 底部重合,偏移photoSelectorView的高度
photoSelectorViewBottomCon = NSLayoutConstraint(item: photoSelectorView, attribute: NSLayoutAttribute.Bottom, relatedBy: NSLayoutRelation.Equal, toItem: view, attribute: NSLayoutAttribute.Bottom, multiplier: 1, constant: view.frame.height * 0.6)
view.addConstraint(photoSelectorViewBottomCon!)
}
// MARK: - 按钮点击事件
func picture() {
print("图片")
// 让照片选择器的view移动上来
photoSelectorViewBottomCon?.constant = 0
// 退下键盘
textView.resignFirstResponder()
UIView.animateWithDuration(0.25) { () -> Void in
self.view.layoutIfNeeded()
}
}
func trend() {
print("#")
}
func mention() {
print("@")
}
/*
1.textView.inputView == nil 弹出的是系统的键盘
2.正在显示的时候设置 textView.inputView 不会立马起效果
3.在弹出来之前判断使用什么键盘
*/
/// 切换表情键盘
func emoticon() {
print("切换前表情键盘:\(textView.inputView)")
// 先让键盘退回去
textView.resignFirstResponder()
// 延时0.25
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (Int64)(250 * USEC_PER_SEC)), dispatch_get_main_queue()) { () -> Void in
// 如果inputView == nil 使用的是系统的键盘,切换到自定的键盘
// 如果inputView != nil 使用的是自定义键盘,切换到系统的键盘
self.textView.inputView = self.textView.inputView == nil ? self.emoticonVC.view : nil
// 弹出键盘
self.textView.becomeFirstResponder()
print("切换后表情键盘:\(self.textView.inputView)")
}
}
func add() {
print("加号")
}
/// toolBar item点击事件
// func itemClick(button: UIButton) {
// print(button.tag)
// switch button.tag {
// case 0:
// print("图片")
// case 1:
// print("#")
// case 2:
// print("@")
// case 3:
// print("表情")
// case 4:
// print("加号")
// default:
// print("没有这个按钮")
// }
// }
/// 关闭控制器
@objc private func close() {
// 关闭键盘
textView.resignFirstResponder()
// 关闭sv提示
SVProgressHUD.dismiss()
dismissViewControllerAnimated(true, completion: nil)
}
/// 发微博
func sendStatus() {
// 获取textView的文本内容发送给服务器
let text = textView.emoticonText()
// 判断微博内容的长度 < 0 不发送
let statusLength = text.characters.count
if statusMaxLength - statusLength < 0 {
// 微博内容超出,提示用户
SVProgressHUD.showErrorWithStatus("微博长度超出", maskType: SVProgressHUDMaskType.Black)
return
}
// 获取图片选择器中的图片
let image = photoSelectorVC.photos.first
// 显示正在发送
SVProgressHUD.showWithStatus("正在发布微博...", maskType: SVProgressHUDMaskType.Black)
// 发送微博
CZNetworkTools.sharedInstance.sendStatus(image, status: text) { (result, error) -> () in
if error != nil {
print("error:\(error)")
SVProgressHUD.showErrorWithStatus("网络不给力...", maskType: SVProgressHUDMaskType.Black)
return
}
// 发送成功, 直接关闭界面
self.close()
}
}
// MARK: - 懒加载
/// toolBar
private lazy var toolBar: UIToolbar = {
let toolBar = UIToolbar()
toolBar.backgroundColor = UIColor(white: 0.8, alpha: 1)
return toolBar
}()
/*
iOS中可以让用户输入的控件:
1.UITextField:
1.只能显示一行
2.可以有占位符
3.不能滚动
2.UITextView:
1.可以显示多行
2.没有占位符
3.继承UIScrollView,可以滚动
*/
/// textView
private lazy var textView: CZPlaceholderTextView = {
let textView = CZPlaceholderTextView()
// 当textView被拖动的时候就会将键盘退回,textView能拖动
textView.keyboardDismissMode = UIScrollViewKeyboardDismissMode.OnDrag
textView.font = UIFont.systemFontOfSize(18)
textView.backgroundColor = UIColor.brownColor()
textView.textColor = UIColor.blackColor()
textView.bounces = true
textView.alwaysBounceVertical = true
// 设置占位文本
textView.placeholder = "分享新鲜事..."
// 设置顶部的偏移
// textView.contentInset = UIEdgeInsets(top: 64, left: 0, bottom: 0, right: 0)
// 设置控制器作为textView的代理来监听textView文本的改变
textView.delegate = self
return textView
}()
/// 表情键盘控制器
private lazy var emoticonVC: CZEmoticonViewController = {
let controller = CZEmoticonViewController()
// 设置textView
controller.textView = self.textView
return controller
}()
/// 显示微博剩余长度
private lazy var lengthTipLabel: UILabel = {
let label = UILabel(fonsize: 12, textColor: UIColor.lightGrayColor())
// 设置默认的长度
label.text = String(self.statusMaxLength)
return label
}()
/// 照片选择器的控制器
private lazy var photoSelectorVC: CZPhotoSelectorViewController = {
let controller = CZPhotoSelectorViewController()
// 让照片选择控制器被被人管理
self.addChildViewController(controller)
return controller
}()
}
extension CZComposeViewController: UITextViewDelegate {
/// textView文本改变的时候调用
func textViewDidChange(textView: UITextView) {
// 当textView 有文本的时候,发送按钮可用,
// 当textView 没有文本的时候,发送按钮不可用
navigationItem.rightBarButtonItem?.enabled = textView.hasText()
// 计算剩余微博的长度
let statusLength = textView.emoticonText().characters.count
// 剩余长度
let length = statusMaxLength - statusLength
lengthTipLabel.text = String(length)
// 判断 length 大于等于0显示灰色, 小于0显示红色
lengthTipLabel.textColor = length < 0 ? UIColor.redColor() : UIColor.lightGrayColor()
}
}
| mit | 16021d998538bac2a475fe8c5947a9cf | 30.409978 | 253 | 0.576865 | 5.012115 | false | false | false | false |
eoger/firefox-ios | Shared/AsyncReducer.swift | 3 | 4364 | /* 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 Deferred
public let DefaultDispatchQueue = DispatchQueue.global(qos: DispatchQoS.default.qosClass)
public func asyncReducer<T, U>(_ initialValue: T, combine: @escaping (T, U) -> Deferred<Maybe<T>>) -> AsyncReducer<T, U> {
return AsyncReducer(initialValue: initialValue, combine: combine)
}
/**
* A appendable, async `reduce`.
*
* The reducer starts empty. New items need to be `append`ed.
*
* The constructor takes an `initialValue`, a `dispatch_queue_t`, and a `combine` function.
*
* The reduced value can be accessed via the `reducer.terminal` `Deferred<Maybe<T>>`, which is
* run once all items have been combined.
*
* The terminal will never be filled if no items have been appended.
*
* Once the terminal has been filled, no more items can be appended, and `append` methods will error.
*/
open class AsyncReducer<T, U> {
// T is the accumulator. U is the input value. The returned T is the new accumulated value.
public typealias Combine = (T, U) -> Deferred<Maybe<T>>
fileprivate let lock = NSRecursiveLock()
private let dispatchQueue: DispatchQueue
private let combine: Combine
private let initialValueDeferred: Deferred<Maybe<T>>
open let terminal: Deferred<Maybe<T>> = Deferred()
private var queuedItems: [U] = []
private var isStarted: Bool = false
/**
* Has this task queue finished?
* Once the task queue has finished, it cannot have more tasks appended.
*/
open var isFilled: Bool {
lock.lock()
defer { lock.unlock() }
return terminal.isFilled
}
public convenience init(initialValue: T, queue: DispatchQueue = DefaultDispatchQueue, combine: @escaping Combine) {
self.init(initialValue: deferMaybe(initialValue), queue: queue, combine: combine)
}
public init(initialValue: Deferred<Maybe<T>>, queue: DispatchQueue = DefaultDispatchQueue, combine: @escaping Combine) {
self.dispatchQueue = queue
self.combine = combine
self.initialValueDeferred = initialValue
}
// This is always protected by a lock, so we don't need to
// take another one.
fileprivate func ensureStarted() {
if self.isStarted {
return
}
func queueNext(_ deferredValue: Deferred<Maybe<T>>) {
deferredValue.uponQueue(dispatchQueue, block: continueMaybe)
}
func nextItem() -> U? {
// Because popFirst is only available on array slices.
// removeFirst is fine for range-replaceable collections.
return queuedItems.isEmpty ? nil : queuedItems.removeFirst()
}
func continueMaybe(_ res: Maybe<T>) {
lock.lock()
defer { lock.unlock() }
if res.isFailure {
self.queuedItems.removeAll()
self.terminal.fill(Maybe(failure: res.failureValue!))
return
}
let accumulator = res.successValue!
guard let item = nextItem() else {
self.terminal.fill(Maybe(success: accumulator))
return
}
let combineItem = deferDispatchAsync(dispatchQueue) {
return self.combine(accumulator, item)
}
queueNext(combineItem)
}
queueNext(self.initialValueDeferred)
self.isStarted = true
}
/**
* Append one or more tasks onto the end of the queue.
*
* @throws AlreadyFilled if the queue has finished already.
*/
open func append(_ items: U...) throws -> Deferred<Maybe<T>> {
return try append(items)
}
/**
* Append a list of tasks onto the end of the queue.
*
* @throws AlreadyFilled if the queue has already finished.
*/
open func append(_ items: [U]) throws -> Deferred<Maybe<T>> {
lock.lock()
defer { lock.unlock() }
if terminal.isFilled {
throw ReducerError.alreadyFilled
}
queuedItems.append(contentsOf: items)
ensureStarted()
return terminal
}
}
enum ReducerError: Error {
case alreadyFilled
}
| mpl-2.0 | 60ab51daf5fa06cd22b8664a66e152dd | 30.395683 | 124 | 0.631531 | 4.560084 | false | false | false | false |
SAP/IssieBoard | ConfigurableKeyboard/KeyboardViewController.swift | 1 | 17771 |
import UIKit
import AudioToolbox
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 settingsView: ExtraView?
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 keyboardHeight: CGFloat {
get {
if let constraint = self.heightConstraint {
return constraint.constant
}
else {
return 0
}
}
set {
self.setHeight(newValue)
}
}
convenience init() {
self.init(nibName: nil, bundle: nil)
}
override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: NSBundle?) {
self.keyboard = standardKeyboard()
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("defaultsChanged:"), name: NSUserDefaultsDidChangeNotification, object: nil)
}
required init?(coder: NSCoder) {
fatalError("NSCoding not supported")
}
deinit {
backspaceDelayTimer?.invalidate()
backspaceRepeatTimer?.invalidate()
NSNotificationCenter.defaultCenter().removeObserver(self)
}
func defaultsChanged(notification: NSNotification) {
var defaults = notification.object as! NSUserDefaults
defaults.synchronize()
defaults = NSUserDefaults.standardUserDefaults()
var i : Int = defaults.integerForKey("defaultBackgroundColor")
defaults.synchronize()
}
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
}
}
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)
self.layout?.initialize()
self.setMode(0)
self.setupKludge()
self.addInputTraitsObservers()
self.constraintsAdded = true
}
}
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) {
}
else {
self.forwardingView.frame = orientationSavvyBounds
self.layout?.layoutKeys(self.currentMode)
self.lastLayoutBounds = orientationSavvyBounds
self.setupKeys()
}
let newOrigin = CGPointMake(0, self.view.bounds.height - self.forwardingView.bounds.height)
self.forwardingView.frame.origin = newOrigin
}
override func loadView() {
super.loadView()
}
override func viewWillAppear(animated: Bool) {
self.keyboardHeight = self.heightForOrientation(self.interfaceOrientation, withTopBanner: true)
}
override func willRotateToInterfaceOrientation(toInterfaceOrientation: UIInterfaceOrientation, duration: NSTimeInterval) {
self.forwardingView.resetTrackedViews()
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)
{
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
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))
return CGFloat(orientation.isPortrait ? canonicalPortraitHeight : canonicalLandscapeHeight )
}
func setupKeys() {
if self.layout == nil {
return
}
for page in keyboard.pages {
for rowKeys in page.rows {
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: "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: "backspaceDown:", forControlEvents: .TouchDown)
keyView.addTarget(self, action: "backspaceUp:", forControlEvents: cancelEvents)
case Key.KeyType.ModeChange:
keyView.addTarget(self, action: Selector("modeChangeTapped:"), forControlEvents: .TouchDown)
case Key.KeyType.DismissKeyboard :
keyView.addTarget(self, action: Selector("dismissKeyboardTapped:"), forControlEvents: .TouchDown)
default:
break
}
if key.isCharacter && key.type != Key.KeyType.HiddenKey {
if UIDevice.currentDevice().userInterfaceIdiom != UIUserInterfaceIdiom.Pad {
keyView.addTarget(self, action: Selector("showPopup:"), forControlEvents: [.TouchDown, .TouchDragInside, .TouchDragEnter])
keyView.addTarget(keyView, action: Selector("hidePopup"), forControlEvents: [.TouchDragExit, .TouchCancel])
keyView.addTarget(self, action: Selector("hidePopupDelay:"), forControlEvents: [.TouchUpInside, .TouchUpOutside, .TouchDragOutside])
}
}
if key.type == Key.KeyType.Undo {
keyView.addTarget(self, action: "undoTapped:", forControlEvents: .TouchUpInside)
}
if key.hasOutput && key.type != Key.KeyType.HiddenKey {
keyView.addTarget(self, action: "keyPressedHelper:", forControlEvents: .TouchUpInside)
}
if key.type != Key.KeyType.ModeChange {
keyView.addTarget(self, action: Selector("highlightKey:"), forControlEvents: [.TouchDown, .TouchDragInside, .TouchDragEnter])
keyView.addTarget(self, action: Selector("unHighlightKey:"), forControlEvents: [.TouchUpInside, .TouchUpOutside, .TouchDragOutside, .TouchDragExit, .TouchCancel])
}
if key.type != Key.KeyType.HiddenKey {
keyView.addTarget(self, action: Selector("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("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
}
override func textDidChange(textInput: UITextInput?) {
self.contextChanged()
}
override func textWillChange(textInput: UITextInput?) {
self.contextChanged()
}
func contextChanged() {
self.autoPeriodState = .NoSpace
}
func setHeight(height: CGFloat) {
self.heightConstraint?.constant = height
}
func updateAppearances(appearanceIsDark: Bool) {
self.layout?.updateKeyAppearance()
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)
if model.type == Key.KeyType.Return {
self.currentMode = 0
}
var lastCharCountInBeforeContext: Int = 0
var readyForDoubleSpacePeriod: Bool = true
self.handleAutoPeriod(model)
}
}
func handleAutoPeriod(key: Key) {
if self.autoPeriodState == .FirstSpace {
if key.type != Key.KeyType.Space {
self.autoPeriodState = .NoSpace
return
}
let charactersAreInCorrectState = { () -> Bool in
let previousContext = (self.textDocumentProxy as? UITextDocumentProxy)?.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 as? UITextDocumentProxy)?.deleteBackward()
(self.textDocumentProxy as? UITextDocumentProxy)?.deleteBackward()
(self.textDocumentProxy as? UITextDocumentProxy)?.insertText(".")
(self.textDocumentProxy as? UITextDocumentProxy)?.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()
if let textDocumentProxy = self.textDocumentProxy as? UIKeyInput {
textDocumentProxy.deleteBackward()
}
self.backspaceDelayTimer = NSTimer.scheduledTimerWithTimeInterval(backspaceDelay - backspaceRepeat, target: self, selector: Selector("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("backspaceRepeatCallback"), userInfo: nil, repeats: true)
}
func backspaceRepeatCallback() {
self.playKeySound()
if let textDocumentProxy = self.textDocumentProxy as? UIKeyInput {
textDocumentProxy.deleteBackward()
}
}
func dismissKeyboardTapped (sender : KeyboardKey) {
self.dismissKeyboard()
}
func undoTapped (sender : KeyboardKey) {
}
func modeChangeTapped(sender: KeyboardKey) {
if let toMode = self.layout?.viewToModel[sender]?.toMode {
self.currentMode = toMode
}
}
func setMode(mode: Int) {
self.forwardingView.resetTrackedViews()
self.layout?.layoutKeys(mode)
self.setupKeys()
}
func advanceTapped(sender: KeyboardKey) {
self.forwardingView.resetTrackedViews()
self.advanceToNextInputMode()
}
func characterIsPunctuation(character: Character) -> Bool {
return (character == ".") || (character == "!") || (character == "?")
}
func characterIsNewline(character: Character) -> Bool {
return (character == "\n") || (character == "\r")
}
func characterIsWhitespace(character: Character) -> Bool {
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 playKeySound() {
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) {
if let proxy = (self.textDocumentProxy as? UIKeyInput) {
proxy.insertText(key.getKeyOutput())
}
}
}
| apache-2.0 | 1f889adf46d71e6a6596ed0a23434142 | 36.412632 | 252 | 0.583816 | 6.083875 | false | false | false | false |
haskellswift/swift-package-manager | Sources/PackageGraph/RepositoryPackageContainerProvider.swift | 1 | 5642 | /*
This source file is part of the Swift.org open source project
Copyright 2016 Apple Inc. and the Swift project authors
Licensed under Apache License v2.0 with Runtime Library Exception
See http://swift.org/LICENSE.txt for license information
See http://swift.org/CONTRIBUTORS.txt for Swift project authors
*/
import Basic
import PackageLoading
import SourceControl
import Utility
import struct PackageDescription.Version
/// Adaptor for exposing repositories as PackageContainerProvider instances.
///
/// This is the root class for bridging the manifest & SCM systems into the
/// interfaces used by the `DependencyResolver` algorithm.
public class RepositoryPackageContainerProvider: PackageContainerProvider {
public typealias Container = RepositoryPackageContainer
let repositoryManager: RepositoryManager
let manifestLoader: ManifestLoaderProtocol
/// Create a repository-based package provider.
///
/// - Parameters:
/// - repositoryManager: The repository manager responsible for providing repositories.
/// - manifestLoader: The manifest loader instance.
public init(repositoryManager: RepositoryManager, manifestLoader: ManifestLoaderProtocol) {
self.repositoryManager = repositoryManager
self.manifestLoader = manifestLoader
}
public func getContainer(for identifier: RepositorySpecifier) throws -> Container {
// Resolve the container using the repository manager.
//
// FIXME: We need to move this to an async interface, or document the interface as thread safe.
let handle = repositoryManager.lookup(repository: identifier)
// Wait for the repository to be fetched.
let wasAvailableCondition = Condition()
var wasAvailableOpt: Bool? = nil
handle.addObserver { handle in
wasAvailableCondition.whileLocked{
wasAvailableOpt = handle.isAvailable
wasAvailableCondition.signal()
}
}
while wasAvailableCondition.whileLocked({ wasAvailableOpt == nil}) {
wasAvailableCondition.wait()
}
let wasAvailable = wasAvailableOpt!
if !wasAvailable {
throw RepositoryPackageResolutionError.unavailableRepository
}
// Open the repository.
//
// FIXME: Do we care about holding this open for the lifetime of the container.
let repository = try handle.open()
// Create the container wrapper.
return RepositoryPackageContainer(identifier: identifier, repository: repository, manifestLoader: manifestLoader)
}
}
enum RepositoryPackageResolutionError: Swift.Error {
/// A requested repository could not be cloned.
case unavailableRepository
}
/// Abstract repository identifier.
extension RepositorySpecifier: PackageContainerIdentifier {}
public typealias RepositoryPackageConstraint = PackageContainerConstraint<RepositorySpecifier>
/// Adaptor to expose an individual repository as a package container.
public class RepositoryPackageContainer: PackageContainer, CustomStringConvertible {
public typealias Identifier = RepositorySpecifier
/// The identifier of the repository.
public let identifier: RepositorySpecifier
/// The available version list (in order).
public let versions: [Version]
/// The opened repository.
let repository: Repository
/// The manifest loader.
let manifestLoader: ManifestLoaderProtocol
/// The versions in the repository and their corresponding tags.
let knownVersions: [Version: String]
/// The cached dependency information.
private var dependenciesCache: [Version: [RepositoryPackageConstraint]] = [:]
private var dependenciesCacheLock = Lock()
init(identifier: RepositorySpecifier, repository: Repository, manifestLoader: ManifestLoaderProtocol) {
self.identifier = identifier
self.repository = repository
self.manifestLoader = manifestLoader
// Compute the map of known versions and sorted version set.
//
// FIXME: Move this utility to a more stable location.
self.knownVersions = Git.convertTagsToVersionMap(repository.tags)
self.versions = [Version](knownVersions.keys).sorted()
}
public var description: String {
return "RepositoryPackageContainer(\(identifier.url.debugDescription))"
}
public func getTag(for version: Version) -> String? {
return knownVersions[version]
}
public func getRevision(for tag: String) throws -> Revision {
return try repository.resolveRevision(tag: tag)
}
public func getDependencies(at version: Version) throws -> [RepositoryPackageConstraint] {
// FIXME: Get a caching helper for this.
return try dependenciesCacheLock.withLock{
if let result = dependenciesCache[version] {
return result
}
// FIXME: We should have a persistent cache for these.
let tag = knownVersions[version]!
let revision = try repository.resolveRevision(tag: tag)
let fs = try repository.openFileView(revision: revision)
let manifest = try manifestLoader.load(packagePath: AbsolutePath.root, baseURL: identifier.url, version: version, fileSystem: fs)
let result = manifest.package.dependencies.map{
RepositoryPackageConstraint(container: RepositorySpecifier(url: $0.url), versionRequirement: .range($0.versionRange))
}
dependenciesCache[version] = result
return result
}
}
}
| apache-2.0 | e4acf97693e664b093c17b09ffee2fd5 | 37.121622 | 141 | 0.704715 | 5.73374 | false | false | false | false |
mlilback/rc2SwiftClient | ClientCore/editing/DocumentManager.swift | 1 | 11269 | //
// DocumentManager.swift
//
// Copyright ©2017 Mark Lilback. This file is licensed under the ISC license.
//
import Foundation
import Rc2Common
import ReactiveSwift
import Networking
import SwiftyUserDefaults
import MJLLogger
import iosMath
public extension Notification.Name {
/// sent before the currentDocument will be saved. object will be the EditorContext/DocummentManager
static let willSaveDocument = Notification.Name(rawValue: "DocumentWillSaveNotification")
}
/// Manages open documents and the current document. Provides common properties to editor components via the EditorContext protocol.
public class DocumentManager: EditorContext {
let minTimeBetweenAutoSaves: TimeInterval = 2
// MARK: properties
public let id = UUID()
// when changed, should use .updateProgress() while loading file contents
// use the double property paradigm to prevent any edits from publc property
private let _currentDocument = MutableProperty<EditorDocument?>(nil)
public let currentDocument: Property<EditorDocument?>
public let editorFont: MutableProperty<PlatformFont>
public var errorHandler: Rc2ErrorHandler { return self }
private var openDocuments: [Int: EditorDocument] = [:]
public var notificationCenter: NotificationCenter
public var workspaceNotificationCenter: NotificationCenter
public let lifetime: Lifetime
var defaults: UserDefaults
private var lastParsed: TimeInterval = 0
private var equationLabel: MTMathUILabel?
/// object that actually saves the file to disk, has a workspace reference
let fileSaver: FileSaver
let fileCache: FileCache
let loading = Atomic<Bool>(false)
let saving = Atomic<Bool>(false)
public var busy: Bool { return loading.value || saving.value }
// MARK: methods
/// Creates a new DocumentManager. Should only be a need for one.
/// - Parameter fileSaver: The object that will do the actually saving of contents to disk
/// - Parameter fileCache: Used to load files
/// - Parameter lifetime: A lifetime to use when binding to a property via ReactiveSwift
/// - Parameter notificationCenter: The notification center to use. Defaults to NotificationCenter.default
/// - Parameter wspaceCenter: The notification to use for NSWorkspace notifications. Defaults to NSWorkspace.shared.notificationCenter
/// - Parameter defaults: The UserDefaults to use. Defualts to NSNotifcationCenter.default
public init(fileSaver: FileSaver,
fileCache: FileCache,
lifetime: Lifetime,
notificationCenter: NotificationCenter = .default,
wspaceCenter: NotificationCenter = NSWorkspace.shared.notificationCenter,
defaults: UserDefaults = .standard)
{
currentDocument = Property<EditorDocument?>(_currentDocument)
self.fileSaver = fileSaver
self.fileCache = fileCache
self.lifetime = lifetime
self.notificationCenter = notificationCenter
self.workspaceNotificationCenter = wspaceCenter
self.defaults = defaults
let defaultSize = CGFloat(defaults[.defaultFontSize])
// font defaults to user-fixed pitch font
var initialFont = PlatformFont.userFixedPitchFont(ofSize: defaultSize)!
// try loading a saved font, or if there isn't one, Menlo
if let fontDesc = defaults[.editorFont], let font = PlatformFont(descriptor: fontDesc, size: fontDesc.pointSize) {
initialFont = font
} else if let menlo = PlatformFont(name: "Menlo-Regular", size: defaultSize) {
initialFont = menlo
}
editorFont = MutableProperty<PlatformFont>(initialFont)
fileSaver.workspace.fileChangeSignal.observe(on: UIScheduler()).observeValues { [weak self] changes in
self?.process(changes: changes)
}
}
func process(changes: [AppWorkspace.FileChange]) {
guard !busy else { Log.info("skipping filechange message", .app); return }
// only care about change if it is our current document
guard let document = currentDocument.value,
let change = changes.first(where: { $0.file.fileId == document.file.fileId })
else { return }
if change.type == .modify {
guard document.file.fileId == change.file.fileId else { return }
document.fileUpdated()
switchTo(document: document)
} else if change.type == .remove {
//document being editied was removed
switchTo(document: nil)
}
}
/// returns a SP that will save the current document and then load the document for file
public func load(file: AppFile?) -> SignalProducer<String?, Rc2Error> {
if loading.value {
Log.warn("load called while already loading", .app)
}
// get a producer to save the old document
let saveProducer: SignalProducer<(), Rc2Error>
if let curDoc = currentDocument.value {
saveProducer = save(document: curDoc)
} else { // make a producer that does nothing
saveProducer = SignalProducer<(), Rc2Error>(value: ())
}
// if file is nil, nil out current document (saving current first)
guard let theFile = file else {
return saveProducer
.on(starting: { self.loading.value = true })
.map { _ in () }
.flatMap(.concat, nilOutCurrentDocument)
.on(terminated: { self.loading.value = false })
}
// save current document, get the document to load, and load it
return saveProducer
.map { _ in theFile }
.flatMap(.concat, getDocumentFor)
.flatMap(.concat, load)
.on(starting: { self.loading.value = true }, completed: { self.loading.value = false })
}
/// discards all changes to the current document
public func revertCurrentDocument() {
guard let doc = currentDocument.value else { return }
// clear autosave document if exists
let tmpUrl = autosaveUrl(document: doc)
if tmpUrl.fileExists() {
try? fileCache.fileManager.removeItem(at: tmpUrl)
}
switchTo(document: doc)
}
/// saves to server, fileCache, and memory cache
public func save(document: EditorDocument, isAutoSave: Bool = false) -> SignalProducer<(), Rc2Error> {
if isAutoSave {
return autosave(document: document)
}
notificationCenter.post(name: .willSaveDocument, object: self)
guard document.isDirty else { return SignalProducer<(), Rc2Error>(value: ()) }
guard let contents = document.currentContents else {
return SignalProducer<(), Rc2Error>(error: Rc2Error(type: .invalidArgument))
}
return self.fileSaver.save(file: document.file, contents: contents)
.on(starting: { self.saving.value = true })
.map { _ in (document.file, contents) }
.flatMap(.concat, fileCache.save)
.on(completed: {
document.contentsSaved()
},
terminated: {
self.saving.value = false
})
}
/// Generates an image to use for the passed in latex, size based on the editor font's size
///
/// - Parameter latex: The latex to use as an inline equation
/// - Returns: an image of the latex as an inline equation
public func inlineImageFor(latex: String) -> PlatformImage? {
if nil == equationLabel {
equationLabel = MTMathUILabel(frame: CGRect(x: 0, y: 0, width: 1000, height: 20)) // default max size for equation image
equationLabel?.labelMode = .text
}
equationLabel?.fontSize = editorFont.value.pointSize
equationLabel?.latex = latex
equationLabel?.layout()
guard let dlist = equationLabel?.displayList else {
print("error with list no list")
return nil
}
let size = equationLabel!.intrinsicContentSize
#if os(macOS)
let rep = NSBitmapImageRep(bitmapDataPlanes: nil, pixelsWide: Int(size.width), pixelsHigh: Int(size.height), bitsPerSample: 8, samplesPerPixel: 4, hasAlpha: true, isPlanar: false, colorSpaceName: .calibratedRGB, bytesPerRow: 0, bitsPerPixel: 0)!
let nscontext = NSGraphicsContext(bitmapImageRep: rep)!
NSGraphicsContext.saveGraphicsState()
NSGraphicsContext.current = nscontext
dlist.draw(nscontext.cgContext)
NSGraphicsContext.restoreGraphicsState()
let image = NSImage(size: size)
image.addRepresentation(rep)
return image
#else
#error("inlineImageFor not implemented for non-macOS platforms")
#endif
}
// MARK: - private methods
/// actually autosaves a file
private func autosave(document: EditorDocument) -> SignalProducer<(), Rc2Error> {
guard defaults[.autosaveEnabled] else {
Log.info("skipping autosave", .app)
return SignalProducer<(), Rc2Error>(value: ())
}
Log.info("autosaving \(document.file.name)", .core)
let tmpUrl = autosaveUrl(document: document)
return SignalProducer<(), Rc2Error> { [weak self] observer, _ in
var err: Rc2Error?
defer {
if let err = err {
observer.send(error: err)
} else {
observer.send(value: ())
observer.sendCompleted()
}
}
guard let me = self else { return }
me.notificationCenter.post(name: .willSaveDocument, object: self)
if let content = document.savedContents {
do {
try Data(content.utf8).write(to: tmpUrl)
document.file.writeXAttributes(tmpUrl)
Log.info("autosaved \(tmpUrl.lastPathComponent)", .core)
} catch {
err = Rc2Error(type: .file, nested: error, explanation: "failed to autosave \(tmpUrl.lastPathComponent)")
}
}
}
}
private func autosaveUrl(document: EditorDocument) -> URL {
return fileCache.fileCacheUrl.appendingPathComponent("~\(document.file.fileId).\(document.file.fileType.fileExtension)")
}
private func nilOutCurrentDocument() -> SignalProducer<String?, Rc2Error> {
return SignalProducer<String?, Rc2Error>(value: nil)
.on(started: { self.switchTo(document: nil) })
}
// the only function that should change _currentDocument
private func switchTo(document: EditorDocument?) {
_currentDocument.value = document
}
// returns SP to return the specified document, creating and inserting into openDocuments if necessary
private func getDocumentFor(file: AppFile) -> SignalProducer<EditorDocument, Rc2Error> {
let doc = openDocuments[file.fileId] ?? EditorDocument(file: file)
openDocuments[file.fileId] = doc
guard doc.isLoaded else {
return fileCache.contents(of: file)
.map { String(data: $0, encoding: .utf8)! }
.on(value: { doc.contentsLoaded(contents: $0) })
.map { _ in doc }
}
return SignalProducer<EditorDocument, Rc2Error>(value: doc)
}
private func load(document: EditorDocument) -> SignalProducer<String?, Rc2Error> {
precondition(openDocuments[document.file.fileId] == document)
if loading.value || document.isLoaded {
switchTo(document: document)
return SignalProducer<String?, Rc2Error>(value: document.currentContents)
}
// see if there is autosave data to use
let tmpUrl = autosaveUrl(document: document)
if tmpUrl.fileExists(),
document.file.versionXAttributesMatch(url: tmpUrl),
let contents = try? String(contentsOf: tmpUrl, encoding: .utf8)
{
Log.info("using contents from autosave file (\(document.file.fileId))", .core)
return SignalProducer<String?, Rc2Error>(value: contents)
}
// read cache
if fileCache.isFileCached(document.file) {
return fileCache.contents(of: document.file)
.on(value: { _ in self.switchTo(document: document) })
.map( { String(data: $0, encoding: .utf8) })
}
// load from network
return fileCache.validUrl(for: document.file)
.map({ _ in return document.file })
.flatMap(.concat, fileCache.contents)
.on(value: { _ in self.switchTo(document: document) })
.map( { String(data: $0, encoding: .utf8) })
}
}
extension DocumentManager: Rc2ErrorHandler {
public func handle(error: Rc2Error) {
}
}
| isc | e8fe8b32b4a0f9aff8b4db92f5da1964 | 38.125 | 247 | 0.730032 | 3.868177 | false | false | false | false |
emilstahl/swift | validation-test/compiler_crashers_fixed/1255-getselftypeforcontainer.swift | 12 | 2030 | // RUN: not %target-swift-frontend %s -parse
// Distributed under the terms of the MIT license
// Test case submitted to project by https://github.com/practicalswift (practicalswift)
// Test case found by fuzzing
import Foundation
class m<j>: NSObject {
var h: j
g -> k = l $n
}
b f: _ = j() {
}
}
func k<g {
enum k {
func l
var _ = l
c
j)
func c<k>() -> (k, > k) -> k {
d h d.f 1, k(j, i)))
class k {
typealias h = h
protocol A {
typealias B
}
class C<D> {
init <A: A where A.B == D>(e: A.B) {
}
}
protocol a {
typealias d
typealias e = d
typealias f = d
}
class b<h : c, i : c where h.g == i> : a {
}
class b<h, i> {
}
protocol c {
typealias g
}
class l {
func f((k, l() -> f
}
class d
}
class i: d, g {
l func d() -> f {
m ""
}
}
}
func m<j n j: g, j: d
let l = h
l()
f
protocol l : f { func f
protocol g
import Foundation
class m<j>k i<g : g, e : f k(f: l) {
}
i(())
class h {
typealias g = g
struct c<d : SequenceType> {
var b: [c<d>] {
return []
}
protocol a {
class func c()
}
class b: a {
class func c() { }
}
(b() as a).dynamicType.c()
func f<T : BooleanType>(b: T) {
}
f(true as BooleanType)
func a(x: Any, y: Any) -> (((Any, Any) -> Any) -> A var d: b.Type
func e() {
d.e()
}
}
b
protocol c : b { func b
otocol A {
E == F>(f: B<T>)
}
struct }
}
struct l<e : SequenceType> {
l g: e
}
func h<e>() -> [l<e>] {
f []
}
func i(e: g) -> <j>(() -> j) -> k
func b(c) -> <d>(() -> d) {
}
func k<q>() -> [n<q>] {
r []
}
func k(l: Int = 0) {
}
n n = k
n()
func n<q {
l n {
func o
o _ = o
}
}
func ^(k: m, q) -> q {
r !(k)
}
protocol k {
j q
j o = q
j f = q
}
class l<r : n, l : n p r.q == l> : k {
}
class l<r, l> {
}
protocol n {
j q
}
protocol k : k {
}
class k<f : l, q : l p f.q == q> {
}
protocol l {
j q
j o
}
struct n<r : l>
struct c<d: SequenceType, b where Optional<b> == d.Generator.Element>
}
class p {
u _ = q() {
}
}
u l = r
u s: k -> k = {
n $h: m.j) {
}
}
o l() {
({})
}
struct m<t> {
let p: [(t, () -> ())] = []
}
protocol p : p {
}
protocol m {
o u() -> String
}
class j {
o m() -> String {
n ""
}
}
class h
| apache-2.0 | f73a61b4473d50a00c64985790accf26 | 11.228916 | 87 | 0.5133 | 2.175777 | false | false | false | false |
magi82/MGRelativeKit | Sources/RelativeLayout+center.swift | 1 | 2044 | // The MIT License (MIT)
//
// Copyright (c) 2017 ByungKook Hwang (https://magi82.github.io)
//
// 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
extension RelativeLayout {
public func centerHorizontalSuper() -> Self {
guard let myView = self.myView, let superView = myView.superview else { return self }
myView.frame.origin.x = (superView.frame.size.width - myView.frame.size.width) * 0.5
return self
}
public func centerVerticalSuper() -> Self {
guard let myView = self.myView, let superView = myView.superview else { return self }
myView.frame.origin.y = (superView.frame.size.height - myView.frame.size.height) * 0.5
return self
}
public func centerInSuper() -> Self {
guard let myView = self.myView, let superView = myView.superview else { return self }
myView.frame.origin.x = (superView.frame.size.width - myView.frame.size.width) * 0.5
myView.frame.origin.y = (superView.frame.size.height - myView.frame.size.height) * 0.5
return self
}
}
| mit | d63805a4010a1733cb5c44b89483b73c | 39.88 | 90 | 0.733366 | 4.112676 | false | false | false | false |
josve05a/wikipedia-ios | Wikipedia/Code/DiffController.swift | 2 | 10850 |
import Foundation
enum DiffError: Error {
case generateUrlFailure
case missingDiffResponseFailure
case missingUrlResponseFailure
case fetchRevisionConstructTitleFailure
case unrecognizedHardcodedIdsForIntermediateCounts
case failureToPopulateModelsFromDeepLink
case failureToVerifyRevisionIDs
var localizedDescription: String {
return CommonStrings.genericErrorDescription
}
}
class DiffController {
enum RevisionDirection {
case next
case previous
}
let diffFetcher: DiffFetcher
let pageHistoryFetcher: PageHistoryFetcher?
let globalUserInfoFetcher: GlobalUserInfoFetcher
let diffThanker: DiffThanker
let siteURL: URL
let type: DiffContainerViewModel.DiffType
private weak var revisionRetrievingDelegate: DiffRevisionRetrieving?
let transformer: DiffTransformer
init(siteURL: URL, diffFetcher: DiffFetcher = DiffFetcher(), pageHistoryFetcher: PageHistoryFetcher?, revisionRetrievingDelegate: DiffRevisionRetrieving?, type: DiffContainerViewModel.DiffType) {
self.diffFetcher = diffFetcher
self.pageHistoryFetcher = pageHistoryFetcher
self.globalUserInfoFetcher = GlobalUserInfoFetcher()
self.diffThanker = DiffThanker()
self.siteURL = siteURL
self.revisionRetrievingDelegate = revisionRetrievingDelegate
self.type = type
self.transformer = DiffTransformer(type: type, siteURL: siteURL)
}
func fetchEditCount(guiUser: String, completion: @escaping ((Result<Int, Error>) -> Void)) {
globalUserInfoFetcher.fetchEditCount(guiUser: guiUser, siteURL: siteURL, completion: completion)
}
func fetchIntermediateCounts(for pageTitle: String, pageURL: URL, from fromRevisionID: Int , to toRevisionID: Int, completion: @escaping (Result<EditCountsGroupedByType, Error>) -> Void) {
pageHistoryFetcher?.fetchEditCounts(.edits, .editors, for: pageTitle, pageURL: pageURL, from: fromRevisionID, to: toRevisionID, completion: completion)
}
func thankRevisionAuthor(toRevisionId: Int, completion: @escaping ((Result<DiffThankerResult, Error>) -> Void)) {
diffThanker.thank(siteURL: siteURL, rev: toRevisionId, completion: completion)
}
func fetchFirstRevisionModel(articleTitle: String, completion: @escaping ((Result<WMFPageHistoryRevision, Error>) -> Void)) {
guard let articleTitle = (articleTitle as NSString).wmf_normalizedPageTitle() else {
completion(.failure(DiffError.fetchRevisionConstructTitleFailure))
return
}
diffFetcher.fetchFirstRevisionModel(siteURL: siteURL, articleTitle: articleTitle, completion: completion)
}
struct DeepLinkModelsResponse {
let from: WMFPageHistoryRevision?
let to: WMFPageHistoryRevision?
let first: WMFPageHistoryRevision
let articleTitle: String
}
func populateModelsFromDeepLink(fromRevisionID: Int?, toRevisionID: Int?, articleTitle: String?, completion: @escaping ((Result<DeepLinkModelsResponse, Error>) -> Void)) {
if let articleTitle = articleTitle {
populateModelsFromDeepLink(fromRevisionID: fromRevisionID, toRevisionID: toRevisionID, articleTitle: articleTitle, completion: completion)
return
}
let maybeRevisionID = toRevisionID ?? fromRevisionID
guard let revisionID = maybeRevisionID else {
completion(.failure(DiffError.failureToVerifyRevisionIDs))
return
}
diffFetcher.fetchArticleTitle(siteURL: siteURL, revisionID: revisionID) { (result) in
switch result {
case .success(let title):
self.populateModelsFromDeepLink(fromRevisionID: fromRevisionID, toRevisionID: toRevisionID, articleTitle: title, completion: completion)
case .failure(let error):
completion(.failure(error))
}
}
}
private func populateModelsFromDeepLink(fromRevisionID: Int?, toRevisionID: Int?, articleTitle: String, completion: @escaping ((Result<DeepLinkModelsResponse, Error>) -> Void)) {
guard let articleTitle = (articleTitle as NSString).wmf_normalizedPageTitle() else {
completion(.failure(DiffError.fetchRevisionConstructTitleFailure))
return
}
var fromResponse: WMFPageHistoryRevision?
var toResponse: WMFPageHistoryRevision?
var firstResponse: WMFPageHistoryRevision?
let group = DispatchGroup()
if let fromRevisionID = fromRevisionID {
group.enter()
let fromRequest = DiffFetcher.FetchRevisionModelRequest.populateModel(revisionID: fromRevisionID)
diffFetcher.fetchRevisionModel(siteURL, articleTitle: articleTitle, request: fromRequest) { (result) in
switch result {
case .success(let fetchResponse):
fromResponse = fetchResponse
case .failure:
break
}
group.leave()
}
}
if let toRevisionID = toRevisionID {
group.enter()
let toRequest = DiffFetcher.FetchRevisionModelRequest.populateModel(revisionID: toRevisionID)
diffFetcher.fetchRevisionModel(siteURL, articleTitle: articleTitle, request: toRequest) { (result) in
switch result {
case .success(let fetchResponse):
toResponse = fetchResponse
case .failure:
break
}
group.leave()
}
}
group.enter()
diffFetcher.fetchFirstRevisionModel(siteURL: siteURL, articleTitle: articleTitle) { (result) in
switch result {
case .success(let fetchResponse):
firstResponse = fetchResponse
case .failure:
break
}
group.leave()
}
group.notify(queue: DispatchQueue.global(qos: .userInitiated)) {
guard let firstResponse = firstResponse,
(fromResponse != nil || toResponse != nil) else {
completion(.failure(DiffError.failureToPopulateModelsFromDeepLink))
return
}
let response = DeepLinkModelsResponse(from: fromResponse, to: toResponse, first: firstResponse, articleTitle: articleTitle)
completion(.success(response))
}
}
func fetchAdjacentRevisionModel(sourceRevision: WMFPageHistoryRevision, direction: RevisionDirection, articleTitle: String, completion: @escaping ((Result<WMFPageHistoryRevision, Error>) -> Void)) {
if let revisionRetrievingDelegate = revisionRetrievingDelegate {
//optimization - first try to grab a revision we might already have in memory from the revisionRetrievingDelegate
switch direction {
case .next:
if let nextRevision = revisionRetrievingDelegate.retrieveNextRevision(with: sourceRevision) {
completion(.success(nextRevision))
return
}
case .previous:
if let previousRevision = revisionRetrievingDelegate.retrievePreviousRevision(with: sourceRevision) {
completion(.success(previousRevision))
return
}
}
}
let direction: DiffFetcher.FetchRevisionModelRequestDirection = direction == .previous ? .older : .newer
let request = DiffFetcher.FetchRevisionModelRequest.adjacent(sourceRevision: sourceRevision, direction: direction)
diffFetcher.fetchRevisionModel(siteURL, articleTitle: articleTitle, request: request) { (result) in
switch result {
case .success(let response):
completion(.success(response))
case .failure(let error):
completion(.failure(error))
}
}
}
func fetchFirstRevisionDiff(revisionId: Int, siteURL: URL, theme: Theme, traitCollection: UITraitCollection, completion: @escaping ((Result<[DiffListGroupViewModel], Error>) -> Void)) {
diffFetcher.fetchWikitext(siteURL: siteURL, revisionId: revisionId) { (result) in
switch result {
case .success(let wikitext):
do {
let viewModels = try self.transformer.firstRevisionViewModels(from: wikitext, theme: theme, traitCollection: traitCollection)
completion(.success(viewModels))
} catch (let error) {
completion(.failure(error))
}
case .failure(let error):
completion(.failure(error))
}
}
}
func fetchDiff(fromRevisionId: Int, toRevisionId: Int, theme: Theme, traitCollection: UITraitCollection, completion: @escaping ((Result<[DiffListGroupViewModel], Error>) -> Void)) {
// let queue = DispatchQueue.global(qos: .userInitiated)
//
// queue.async { [weak self] in
//
// guard let self = self else { return }
//
// do {
//
// let url = Bundle.main.url(forResource: "DiffResponse", withExtension: "json")!
// let data = try Data(contentsOf: url)
// let diffResponse = try JSONDecoder().decode(DiffResponse.self, from: data)
//
//
// do {
// let viewModels = try self.transformer.viewModels(from: diffResponse, theme: theme, traitCollection: traitCollection)
//
// completion(.success(viewModels))
// } catch (let error) {
// completion(.failure(error))
// }
//
//
// } catch (let error) {
// completion(.failure(error))
// }
// }
diffFetcher.fetchDiff(fromRevisionId: fromRevisionId, toRevisionId: toRevisionId, siteURL: siteURL) { [weak self] (result) in
guard let self = self else { return }
switch result {
case .success(let diffResponse):
do {
let viewModels = try self.transformer.viewModels(from: diffResponse, theme: theme, traitCollection: traitCollection)
completion(.success(viewModels))
} catch (let error) {
completion(.failure(error))
}
case .failure(let error):
completion(.failure(error))
}
}
}
}
| mit | 594db7cab5248dd13151d2de467f8e51 | 39.485075 | 202 | 0.618065 | 5.925724 | false | false | false | false |
Edovia/SwiftPasscodeLock | PasscodeLock/Views/PasscodeSignPlaceholderView.swift | 1 | 2164 | //
// PasscodeSignPlaceholderView.swift
// PasscodeLock
//
// Created by Yanko Dimitrov on 8/28/15.
// Copyright © 2015 Yanko Dimitrov. All rights reserved.
//
import UIKit
@IBDesignable
public class PasscodeSignPlaceholderView: UIView {
public enum State {
case inactive
case active
case error
}
@IBInspectable
public var inactiveColor: UIColor = UIColor.white {
didSet {
setupView()
}
}
@IBInspectable
public var activeColor: UIColor = UIColor.gray {
didSet {
setupView()
}
}
@IBInspectable
public var errorColor: UIColor = UIColor.red {
didSet {
setupView()
}
}
public override init(frame: CGRect) {
super.init(frame: frame)
setupView()
}
public required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
public override var intrinsicContentSize: CGSize {
return CGSize(width: 16, height: 16)
}
private func setupView() {
layer.cornerRadius = 8
layer.borderWidth = 1
layer.borderColor = activeColor.cgColor
backgroundColor = inactiveColor
}
private func colorsForState(_ state: State) -> (backgroundColor: UIColor, borderColor: UIColor) {
switch state {
case .inactive: return (inactiveColor, activeColor)
case .active: return (activeColor, activeColor)
case .error: return (errorColor, errorColor)
}
}
public func animateState(_ state: State) {
let colors = colorsForState(state)
UIView.animate(
withDuration: 0.5,
delay: 0,
usingSpringWithDamping: 1,
initialSpringVelocity: 0,
options: [],
animations: {
self.backgroundColor = colors.backgroundColor
self.layer.borderColor = colors.borderColor.cgColor
},
completion: nil
)
}
}
| mit | 878cea7426371a9d14f82eeeea9ea883 | 22.010638 | 101 | 0.54785 | 5.4075 | false | false | false | false |
combes/audio-weather | AudioWeather/AudioWeather/WeatherViewModel.swift | 1 | 4370 | //
// WeatherViewModel.swift
// AudioWeather
//
// Created by Christopher Combes on 6/25/17.
// Copyright © 2017 Christopher Combes. All rights reserved.
//
import UIKit
class WeatherViewModel: WeatherModelProtocol {
// Protocol proprerties
var city: String {
get {
return (cityText.characters.count == 0 ? "--" : cityText)
}
}
var conditionText: String {
get {
return (conditionaryText.characters.count == 0 ? "--" : conditionaryText)
}
}
var temperature: String {
get {
return UnitsViewModel.formattedTemperature(temperatureText)
}
}
var windDirection: String {
get {
return windDirectionText.compassDirection()
}
}
var windChill: String {
get {
return (windChillText.characters.count == 0 ? UnitsViewModel.formattedTemperature("-") : UnitsViewModel.formattedTemperature(windChillText))
}
}
var windSpeed: String {
get {
return UnitsViewModel.formattedSpeed(windSpeedText)
}
}
var sunrise: String {
get {
return sunriseText.characters.count == 0 ? "-- am" : sunriseText
}
}
var sunset: String {
get {
return sunsetText.characters.count == 0 ? "-- pm" : sunsetText
}
}
var date: String
// Private properties
private var cityText: String
private var temperatureText: String
private var conditionaryText: String
private var windDirectionText: String
private var windChillText: String
private var windSpeedText: String
private var sunriseText: String
private var sunsetText: String
init(model: WeatherModel) {
cityText = model.city
conditionaryText = model.conditionText
temperatureText = model.temperature
windDirectionText = model.windDirection
windChillText = model.windChill
windSpeedText = model.windSpeed
sunriseText = model.sunrise
sunsetText = model.sunset
date = model.date
}
func backgroundImage() -> UIImage {
return backgroundImage(sunriseHour: hourUsingTimeFormat(timeText: sunrise),
sunsetHour: hourUsingTimeFormat(timeText: sunset),
currentHour: hourUsingWeatherFormat(dateText: date))
}
/// Derive background image based on sunrise, day, sunset, night
///
/// - Returns: Image name based on current time
func backgroundImage(sunriseHour: Int, sunsetHour: Int, currentHour: Int) -> UIImage {
if (abs(sunriseHour - currentHour) <= 1) {
return #imageLiteral(resourceName: "background-sunrise")
}
if (abs(sunsetHour - currentHour) <= 1) {
return #imageLiteral(resourceName: "background-sunset")
}
if (currentHour > sunriseHour && currentHour < sunsetHour) {
return #imageLiteral(resourceName: "background-day")
}
return #imageLiteral(resourceName: "background-evening")
}
// MARK: Helper methods
func hourUsingWeatherFormat(dateText: String) -> Int {
var hour = 0
var textComponents = dateText.components(separatedBy: " ")
textComponents.removeLast()
let newText = textComponents.joined(separator: " ")
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "EEE, d MMM yyyy hh:mm a"
if let checkDate = dateFormatter.date(from: newText) {
let calendar = NSCalendar(calendarIdentifier: NSCalendar.Identifier.gregorian)
let components = calendar?.components(NSCalendar.Unit.hour, from: checkDate)
hour = components?.hour ?? 0
}
return hour
}
func hourUsingTimeFormat(timeText: String) -> Int {
var hour = 0
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "hh:mm a"
if let checkDate = dateFormatter.date(from: timeText) {
let calendar = NSCalendar(calendarIdentifier: NSCalendar.Identifier.gregorian)
let components = calendar?.components(NSCalendar.Unit.hour, from: checkDate)
hour = components?.hour ?? 0
}
return hour
}
}
| mit | 1d85780cbb9149a7c3c682bb5bf6d45a | 31.604478 | 152 | 0.610437 | 4.942308 | false | false | false | false |
JackLearning/Weibo | Weibo/Weibo/Classes/Module/Home/StatusCell/StatusPictureView.swift | 1 | 5937 | //
// StatusPictureView.swift
// Weibo
//
// Created by apple on 15/12/21.
// Copyright © 2015年 apple. All rights reserved.
//
import UIKit
private let pictureCellID = "pictureCellID"
private let pictureCellMargin:CGFloat = 5
class StatusPictureView: UICollectionView {
// MARK:定义外部模型属性
var imageURLs: [NSURL]? {
didSet {
//修改配图视图的大小
let pSize = caclePictureViewSize()
//更新配图视图的大小
self.snp_updateConstraints { (make) -> Void in
make.size.equalTo(pSize)
}
//修改测试的文案
testLabel.text = "\(imageURLs?.count ?? 0)"
// 刷新列表
reloadData()
}
}
// MARK:重写构造方法
override init(frame: CGRect, collectionViewLayout layout: UICollectionViewLayout) {
//实例化一个 流水布局
let flowLayout = UICollectionViewFlowLayout()
// 设置间距
flowLayout.minimumInteritemSpacing = pictureCellMargin
flowLayout.minimumLineSpacing = pictureCellMargin
super.init(frame: frame, collectionViewLayout: flowLayout)
backgroundColor = UIColor.whiteColor()
self.registerClass(PictureCell.self, forCellWithReuseIdentifier:pictureCellID)
// 设置数据源
self.dataSource = self
//设置视图
setupUI()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
/*
单图会按照图片等比例显示
多图的图片大小固定
多图如果是4张,会按照 2 * 2 显示
多图其他数量,按照 3 * 3 九宫格显示
*/
//计算配图视图的大小
private func caclePictureViewSize() -> CGSize {
//计算配图的大小
//1.获取配图的数量
let imageCount = imageURLs?.count ?? 0
//获取配图视图的最大宽度
let maxWidth = screenW - 2 * StatusCellMarigin
let itemWidth = (maxWidth - 2 * pictureCellMargin) / 3
// 1,取出collectionView的流水布局
let layout = self.collectionViewLayout as! UICollectionViewFlowLayout
// 设置itemSize
layout.itemSize = CGSize(width: itemWidth, height: itemWidth)
//没有图片
if imageCount == 0 {
return CGSizeZero
}
//单张图片
if imageCount == 1 {
//TODO: 单图会按照图片等比例显示
//先给定固定尺寸
let imageSize = CGSize(width: 180, height: 120)
// 设置单张图片的 itemSize
layout.itemSize = imageSize
return imageSize
}
if imageCount == 4 {
//多图如果是4张,会按照 2 * 2 显示
let w = itemWidth * 2 + pictureCellMargin
return CGSize(width: w, height: w)
}
//如果程序走到这里 就是其他的多张图片
//1. 确定有多少行
/*
1,2,3 -> 1
4,5,6 -> 2
7,8,9 -> 3
先 整体 + 1 -> 修正 分子 -1
*/
let row = CGFloat((imageCount - 1) / 3 + 1)
return CGSize(width: maxWidth, height: row * itemWidth + (row - 1) * pictureCellMargin )
}
// MARK:设置页面 和 布局
private func setupUI() {
self.addSubview(testLabel)
testLabel.snp_makeConstraints { (make) -> Void in
make.center.equalTo(self.snp_center)
}
}
// MARK:懒加载所有的子视图
private lazy var testLabel: UILabel = UILabel(title: "", color: UIColor.redColor(), fontSize: 30)
}
// 数据源方法
//MARK: 数据源方法
extension StatusPictureView: UICollectionViewDataSource {
func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return imageURLs?.count ?? 0
}
func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
//使用这个方法 一定要注册cell
let cell = collectionView.dequeueReusableCellWithReuseIdentifier(pictureCellID, forIndexPath: indexPath) as! PictureCell
// cell.backgroundColor = UIColor.randomColor()
cell.imageURL = imageURLs![indexPath.item]
return cell
}
}
class PictureCell: UICollectionViewCell {
// MARK:定义外部模型属性
var imageURL: NSURL? {
didSet {
iconView.sd_setImageWithURL(imageURL)
}
}
// MARK:重写构造方法
override init(frame: CGRect) {
super.init(frame: frame)
setupUI()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
// MARK:设置页面 和 布局
private func setupUI() {
contentView.addSubview(iconView)
//设置布局
iconView.snp_makeConstraints { (make) -> Void in
make.edges.equalTo(snp_edges)
}
}
// MARK:懒加载所有的子视图
private lazy var iconView: UIImageView = {
let iv = UIImageView()
//ScaleAspectFill 显示图片的原比例 但是 图片会被裁减 一般采用这种方式
//ScaleToFill 图片默认的显示样式 但是 图片 会被压缩 或者拉伸 一般不推荐使用这种方式来显示
iv.contentMode = UIViewContentMode.ScaleAspectFill
//在手码开发中 图片的默认的剪裁 是没有开启的 需要手动设置
iv.clipsToBounds = true
return iv
}()
}
| mit | de4ec135bf48ddcd8810c93363a6d0f0 | 24.805 | 130 | 0.563566 | 4.640288 | false | false | false | false |
mollywoodnini/ImageViewer | ImageViewer/ImageViewer.swift | 1 | 13232 | //
// ImageViewer.swift
// ImageViewer
//
// Created by Tan Nghia La on 30.04.15.
// Copyright (c) 2015 Tan Nghia La. All rights reserved.
//
import UIKit
final class ImageViewer: UIViewController {
// MARK: - Properties
fileprivate let kMinMaskViewAlpha: CGFloat = 0.3
fileprivate let kMaxImageScale: CGFloat = 2.5
fileprivate let kMinImageScale: CGFloat = 1.0
fileprivate let senderView: UIImageView
fileprivate var originalFrameRelativeToScreen: CGRect!
fileprivate var rootViewController: UIViewController!
fileprivate let imageView = UIImageView()
fileprivate var panGesture: UIPanGestureRecognizer!
fileprivate var panOrigin: CGPoint!
fileprivate var isAnimating = false
fileprivate var isLoaded = false
fileprivate var closeButton = UIButton()
fileprivate let windowBounds = UIScreen.main.bounds
fileprivate let scrollView = UIScrollView()
fileprivate let maskView = UIView()
// MARK: - Lifecycle methods
init(senderView: UIImageView, backgroundColor: UIColor) {
self.senderView = senderView
rootViewController = UIApplication.shared.keyWindow!.rootViewController!
maskView.backgroundColor = backgroundColor
super.init(nibName: nil, bundle: nil)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func viewDidLoad() {
super.viewDidLoad()
configureView()
configureMaskView()
configureScrollView()
configureCloseButton()
configureImageView()
configureConstraints()
}
// MARK: - View configuration
fileprivate func configureScrollView() {
scrollView.frame = windowBounds
scrollView.delegate = self
scrollView.minimumZoomScale = kMinImageScale
scrollView.maximumZoomScale = kMaxImageScale
scrollView.zoomScale = 1
view.addSubview(scrollView)
}
fileprivate func configureMaskView() {
maskView.frame = windowBounds
maskView.alpha = 0.0
view.insertSubview(maskView, at: 0)
}
fileprivate func configureCloseButton() {
closeButton.alpha = 0.0
let image = UIImage(named: "Close", in: Bundle(for: ImageViewer.self), compatibleWith: nil)
closeButton.setImage(image, for: UIControlState())
closeButton.translatesAutoresizingMaskIntoConstraints = false
closeButton.addTarget(self, action: #selector(ImageViewer.closeButtonTapped(_:)), for: UIControlEvents.touchUpInside)
view.addSubview(closeButton)
view.setNeedsUpdateConstraints()
}
fileprivate func configureView() {
var originalFrame = senderView.convert(windowBounds, to: nil)
originalFrame.origin = CGPoint(x: originalFrame.origin.x, y: originalFrame.origin.y)
originalFrame.size = senderView.frame.size
originalFrameRelativeToScreen = originalFrame
UIApplication.shared.setStatusBarHidden(true, with: UIStatusBarAnimation.slide)
}
fileprivate func configureImageView() {
senderView.alpha = 0.0
imageView.frame = originalFrameRelativeToScreen
imageView.isUserInteractionEnabled = true
imageView.contentMode = UIViewContentMode.scaleAspectFit
imageView.image = senderView.image
scrollView.addSubview(imageView)
animateEntry()
addPanGestureToView()
addGestures()
centerScrollViewContents()
}
fileprivate func configureConstraints() {
var constraints: [NSLayoutConstraint] = []
let views: [String: UIView] = [
"closeButton": closeButton
]
constraints.append(NSLayoutConstraint(item: closeButton, attribute: .centerX, relatedBy: .equal, toItem: closeButton.superview, attribute: .centerX, multiplier: 1.0, constant: 0))
constraints.append(contentsOf: NSLayoutConstraint.constraints(withVisualFormat: "V:[closeButton(==64)]-40-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: views))
constraints.append(contentsOf: NSLayoutConstraint.constraints(withVisualFormat: "H:[closeButton(==64)]", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: views))
NSLayoutConstraint.activate(constraints)
}
// MARK: - Gestures
fileprivate func addPanGestureToView() {
panGesture = UIPanGestureRecognizer(target: self, action: #selector(ImageViewer.gestureRecognizerDidPan(_:)))
panGesture.cancelsTouchesInView = false
panGesture.delegate = self
imageView.addGestureRecognizer(panGesture)
}
fileprivate func addGestures() {
let singleTapRecognizer = UITapGestureRecognizer(target: self, action: #selector(ImageViewer.didSingleTap(_:)))
singleTapRecognizer.numberOfTapsRequired = 1
singleTapRecognizer.numberOfTouchesRequired = 1
scrollView.addGestureRecognizer(singleTapRecognizer)
let doubleTapRecognizer = UITapGestureRecognizer(target: self, action: #selector(ImageViewer.didDoubleTap(_:)))
doubleTapRecognizer.numberOfTapsRequired = 2
doubleTapRecognizer.numberOfTouchesRequired = 1
scrollView.addGestureRecognizer(doubleTapRecognizer)
singleTapRecognizer.require(toFail: doubleTapRecognizer)
}
fileprivate func zoomInZoomOut(_ point: CGPoint) {
let newZoomScale = scrollView.zoomScale > (scrollView.maximumZoomScale / 2) ? scrollView.minimumZoomScale : scrollView.maximumZoomScale
let scrollViewSize = scrollView.bounds.size
let w = scrollViewSize.width / newZoomScale
let h = scrollViewSize.height / newZoomScale
let x = point.x - (w / 2.0)
let y = point.y - (h / 2.0)
let rectToZoomTo = CGRect(x: x, y: y, width: w, height: h)
scrollView.zoom(to: rectToZoomTo, animated: true)
}
// MARK: - Animation
fileprivate func animateEntry() {
guard let image = imageView.image else {
fatalError("no image provided")
}
UIView.animate(withDuration: 0.8, delay: 0.0, usingSpringWithDamping: 0.7, initialSpringVelocity: 0.6, options: UIViewAnimationOptions.beginFromCurrentState, animations: {() -> Void in
self.imageView.frame = self.centerFrameFromImage(image)
}, completion: nil)
UIView.animate(withDuration: 0.4, delay: 0.03, options: UIViewAnimationOptions.beginFromCurrentState, animations: {() -> Void in
self.closeButton.alpha = 1.0
self.maskView.alpha = 1.0
}, completion: nil)
UIView.animate(withDuration: 0.4, delay: 0.1, options: UIViewAnimationOptions.beginFromCurrentState, animations: {() -> Void in
self.view.transform = CGAffineTransform.identity.scaledBy(x: 1.1, y: 1.1)
self.rootViewController.view.transform = CGAffineTransform.identity.scaledBy(x: 0.95, y: 0.95)
}, completion: nil)
}
fileprivate func centerFrameFromImage(_ image: UIImage) -> CGRect {
var newImageSize = imageResizeBaseOnWidth(windowBounds.size.width, oldWidth: image.size.width, oldHeight: image.size.height)
newImageSize.height = min(windowBounds.size.height, newImageSize.height)
return CGRect(x: 0, y: windowBounds.size.height / 2 - newImageSize.height / 2, width: newImageSize.width, height: newImageSize.height)
}
fileprivate func imageResizeBaseOnWidth(_ newWidth: CGFloat, oldWidth: CGFloat, oldHeight: CGFloat) -> CGSize {
let scaleFactor = newWidth / oldWidth
let newHeight = oldHeight * scaleFactor
return CGSize(width: newWidth, height: newHeight)
}
// MARK: - Actions
func gestureRecognizerDidPan(_ recognizer: UIPanGestureRecognizer) {
if scrollView.zoomScale != 1.0 || isAnimating {
return
}
senderView.alpha = 0.0
scrollView.bounces = false
let windowSize = maskView.bounds.size
let currentPoint = panGesture.translation(in: scrollView)
let y = currentPoint.y + panOrigin.y
imageView.frame.origin = CGPoint(x: currentPoint.x + panOrigin.x, y: y)
let yDiff = abs((y + imageView.frame.size.height / 2) - windowSize.height / 2)
maskView.alpha = max(1 - yDiff / (windowSize.height / 0.95), kMinMaskViewAlpha)
closeButton.alpha = max(1 - yDiff / (windowSize.height / 0.95), kMinMaskViewAlpha) / 2
if (panGesture.state == UIGestureRecognizerState.ended || panGesture.state == UIGestureRecognizerState.cancelled)
&& scrollView.zoomScale == 1.0 {
maskView.alpha < 0.85 ? dismissViewController() : rollbackViewController()
}
}
func didSingleTap(_ recognizer: UITapGestureRecognizer) {
scrollView.zoomScale == 1.0 ? dismissViewController() : scrollView.setZoomScale(1.0, animated: true)
}
func didDoubleTap(_ recognizer: UITapGestureRecognizer) {
let pointInView = recognizer.location(in: imageView)
zoomInZoomOut(pointInView)
}
func closeButtonTapped(_ sender: UIButton) {
if scrollView.zoomScale != 1.0 {
scrollView.setZoomScale(1.0, animated: true)
}
dismissViewController()
}
// MARK: - Misc.
fileprivate func centerScrollViewContents() {
let boundsSize = rootViewController.view.bounds.size
var contentsFrame = imageView.frame
if contentsFrame.size.width < boundsSize.width {
contentsFrame.origin.x = (boundsSize.width - contentsFrame.size.width) / 2.0
} else {
contentsFrame.origin.x = 0.0
}
if contentsFrame.size.height < boundsSize.height {
contentsFrame.origin.y = (boundsSize.height - contentsFrame.size.height) / 2.0
} else {
contentsFrame.origin.y = 0.0
}
imageView.frame = contentsFrame
}
fileprivate func rollbackViewController() {
guard let image = imageView.image else {
fatalError("no image provided")
}
isAnimating = true
UIView.animate(withDuration: 0.8, delay: 0, usingSpringWithDamping: 0.7, initialSpringVelocity: 0.6, options: UIViewAnimationOptions.beginFromCurrentState, animations: {() in
self.imageView.frame = self.centerFrameFromImage(image)
self.maskView.alpha = 1.0
self.closeButton.alpha = 1.0
}, completion: {(finished) in
self.isAnimating = false
})
}
fileprivate func dismissViewController() {
isAnimating = true
DispatchQueue.main.async(execute: {
self.imageView.clipsToBounds = true
UIView.animate(withDuration: 0.2, animations: {() in
self.closeButton.alpha = 0.0
})
UIView.animate(withDuration: 0.8, delay: 0, usingSpringWithDamping: 0.7, initialSpringVelocity: 0.6, options: UIViewAnimationOptions.beginFromCurrentState, animations: {() in
self.imageView.frame = self.originalFrameRelativeToScreen
self.rootViewController.view.transform = CGAffineTransform.identity.scaledBy(x: 1.0, y: 1.0)
self.view.transform = CGAffineTransform.identity.scaledBy(x: 1.0, y: 1.0)
self.maskView.alpha = 0.0
UIApplication.shared.setStatusBarHidden(false, with: UIStatusBarAnimation.none)
}, completion: {(finished) in
self.willMove(toParentViewController: nil)
self.view.removeFromSuperview()
self.removeFromParentViewController()
self.senderView.alpha = 1.0
self.isAnimating = false
})
})
}
func presentFromRootViewController() {
willMove(toParentViewController: rootViewController)
rootViewController.view.addSubview(view)
rootViewController.addChildViewController(self)
didMove(toParentViewController: rootViewController)
}
}
// MARK: - GestureRecognizer delegate
extension ImageViewer: UIGestureRecognizerDelegate {
func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldReceive touch: UITouch) -> Bool {
panOrigin = imageView.frame.origin
gestureRecognizer.isEnabled = true
return !isAnimating
}
}
// MARK: - ScrollView delegate
extension ImageViewer: UIScrollViewDelegate {
func viewForZooming(in scrollView: UIScrollView) -> UIView? {
return imageView
}
func scrollViewDidZoom(_ scrollView: UIScrollView) {
isAnimating = true
centerScrollViewContents()
}
func scrollViewDidEndZooming(_ scrollView: UIScrollView, with view: UIView?, atScale scale: CGFloat) {
isAnimating = false
}
}
| mit | 10e51ce52151923ba5cd9e4a1abc22a2 | 38.616766 | 192 | 0.653189 | 5.389817 | false | false | false | false |
joerocca/GitHawk | Classes/Utility/DeleteSwipeAction.swift | 2 | 508 | //
// DeleteSwipeAction.swift
// Freetime
//
// Created by Hesham Salman on 10/24/17.
// Copyright © 2017 Ryan Nystrom. All rights reserved.
//
import SwipeCellKit
func DeleteSwipeAction(callback: ((SwipeAction, IndexPath) -> Void)? = nil) -> SwipeAction {
let action = SwipeAction(style: .destructive, title: Constants.Strings.delete, handler: callback)
action.backgroundColor = Styles.Colors.Red.medium.color
action.textColor = .white
action.tintColor = .white
return action
}
| mit | 2fae659e543836ab97bb88ff613dcf37 | 25.684211 | 101 | 0.714004 | 3.930233 | false | false | false | false |
prebid/prebid-mobile-ios | Example/PrebidDemo/PrebidDemoSwift/Examples/MAX/MAXNativeViewController.swift | 1 | 5347 | /* Copyright 2019-2022 Prebid.org, Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
import UIKit
import PrebidMobile
import PrebidMobileMAXAdapters
import AppLovinSDK
fileprivate let nativeStoredImpression = "imp-prebid-banner-native-styles"
fileprivate let nativeStoredResponse = "response-prebid-banner-native-styles"
fileprivate let maxRenderingNativeAdUnitId = "e4375fdcc7c5e56c"
class MAXNativeViewController: BannerBaseViewController, MANativeAdDelegate {
// Prebid
private var maxMediationNativeAdUnit: MediationNativeAdUnit!
private var maxMediationDelegate: MAXMediationNativeUtils!
private var nativeRequestAssets: [NativeAsset] {
let image = NativeAssetImage(minimumWidth: 200, minimumHeight: 50, required: true)
image.type = ImageAsset.Main
let icon = NativeAssetImage(minimumWidth: 20, minimumHeight: 20, required: true)
icon.type = ImageAsset.Icon
let title = NativeAssetTitle(length: 90, required: true)
let body = NativeAssetData(type: DataAsset.description, required: true)
let cta = NativeAssetData(type: DataAsset.ctatext, required: true)
let sponsored = NativeAssetData(type: DataAsset.sponsored, required: true)
return [title, icon, image, sponsored, body, cta]
}
private var eventTrackers: [NativeEventTracker] {
[NativeEventTracker(event: EventType.Impression, methods: [EventTracking.Image,EventTracking.js])]
}
// MAX
private var maxNativeAdLoader: MANativeAdLoader!
private weak var maxLoadedNativeAd: MAAd!
override func loadView() {
super.loadView()
Prebid.shared.storedAuctionResponse = nativeStoredResponse
createAd()
}
deinit {
if let maxLoadedNativeAd = maxLoadedNativeAd {
maxNativeAdLoader?.destroy(maxLoadedNativeAd)
}
}
func createAd() {
// 1. Create a MANativeAdLoader
maxNativeAdLoader = MANativeAdLoader(adUnitIdentifier: maxRenderingNativeAdUnitId)
maxNativeAdLoader.nativeAdDelegate = self
// 2. Create the MAXMediationNativeUtils
maxMediationDelegate = MAXMediationNativeUtils(nativeAdLoader: maxNativeAdLoader)
// 3. Create the MediationNativeAdUnit
maxMediationNativeAdUnit = MediationNativeAdUnit(configId: nativeStoredImpression, mediationDelegate: maxMediationDelegate)
// 4. Configure the MediationNativeAdUnit
maxMediationNativeAdUnit.addNativeAssets(nativeRequestAssets)
maxMediationNativeAdUnit.setContextType(.Social)
maxMediationNativeAdUnit.setPlacementType(.FeedContent)
maxMediationNativeAdUnit.setContextSubType(.Social)
maxMediationNativeAdUnit.addEventTracker(eventTrackers)
// 5. Create a MAXNativeAdView
let nativeAdViewNib = UINib(nibName: "MAXNativeAdView", bundle: Bundle.main)
let maNativeAdView = nativeAdViewNib.instantiate(withOwner: nil, options: nil).first! as! MANativeAdView?
// 6. Create a MANativeAdViewBinder
let adViewBinder = MANativeAdViewBinder.init(builderBlock: { (builder) in
builder.iconImageViewTag = 1
builder.titleLabelTag = 2
builder.bodyLabelTag = 3
builder.advertiserLabelTag = 4
builder.callToActionButtonTag = 5
builder.mediaContentViewTag = 123
})
// 7. Bind views
maNativeAdView!.bindViews(with: adViewBinder)
// 7. Make a bid request to Prebid Server
maxMediationNativeAdUnit.fetchDemand { [weak self] result in
// 8. Load the native ad
self?.maxNativeAdLoader.loadAd(into: maNativeAdView!)
}
}
// MARK: - MANativeAdDelegate
func didLoadNativeAd(_ nativeAdView: MANativeAdView?, for ad: MAAd) {
if let nativeAd = maxLoadedNativeAd {
maxNativeAdLoader?.destroy(nativeAd)
}
maxLoadedNativeAd = ad
bannerView.backgroundColor = .clear
nativeAdView?.translatesAutoresizingMaskIntoConstraints = false
bannerView.addSubview(nativeAdView!)
bannerView.heightAnchor.constraint(equalTo: nativeAdView!.heightAnchor).isActive = true
bannerView.topAnchor.constraint(equalTo: nativeAdView!.topAnchor).isActive = true
bannerView.leftAnchor.constraint(equalTo: nativeAdView!.leftAnchor).isActive = true
bannerView.rightAnchor.constraint(equalTo: nativeAdView!.rightAnchor).isActive = true
}
func didFailToLoadNativeAd(forAdUnitIdentifier adUnitIdentifier: String, withError error: MAError) {
PrebidDemoLogger.shared.error("\(error.message)")
}
func didClickNativeAd(_ ad: MAAd) {}
}
| apache-2.0 | dbada77fd34500f32d3942eda29971c3 | 39.203008 | 131 | 0.699271 | 5.216585 | false | false | false | false |
ihomway/RayWenderlichCourses | Beginning Swift 3/Beginning Swift 3.playground/Pages/Tuples.xcplaygroundpage/Contents.swift | 1 | 435 | //: [Previous](@previous)
import Foundation
var str = "Hello, playground"
var monster = ("Reaper", 100, true)
monster.0
monster.1
monster.2
var anotherMonster: (String, Int, Bool)
anotherMonster = ("Savager", 100, false)
var yetAnotherMonster = (name: "Blobby", hitPoints: 200, isAggroed: true)
yetAnotherMonster.hitPoints
yetAnotherMonster.name
yetAnotherMonster.isAggroed
var (name, hp, _) = monster
name
hp
//: [Next](@next)
| mit | 86b7970c7559d9328697885936984e2b | 17.125 | 73 | 0.728736 | 3.085106 | false | false | false | false |
SVKorosteleva/heartRateMonitor | HeartMonitor/HeartMonitor/TrainingsListViewController.swift | 1 | 2402 | //
// TrainingsListViewController.swift
// HeartMonitor
//
// Created by Светлана Коростелёва on 9/22/17.
// Copyright © 2017 home. All rights reserved.
//
import UIKit
class TrainingsListViewController: UIViewController {
@IBOutlet private weak var tableView: UITableView!
private var trainings: [Training] = []
override func viewDidLoad() {
super.viewDidLoad()
title = "Trainings"
trainings = DataStorageManager.shared.trainingsManager?.trainings() ?? []
trainings = trainings.filter { $0.duration > 0 }
tableView.reloadData()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: - Navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
guard let cell = sender as? UITableViewCell,
let indexPath = tableView.indexPath(for: cell),
let trainingDataVC = segue.destination as? TrainingDataViewController else {
return
}
tableView.deselectRow(at: indexPath, animated: true)
trainingDataVC.training = trainings[indexPath.row]
}
}
extension TrainingsListViewController: UITableViewDataSource {
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return trainings.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell =
tableView.dequeueReusableCell(withIdentifier: "TrainingCell", for: indexPath)
cell.textLabel?.textColor = UIColor(red: 107.0 / 255.0,
green: 160.0 / 255.0,
blue: 232.0 / 255.0,
alpha: 1.0)
let training = trainings[indexPath.row]
cell.textLabel?.text =
"\(TrainingDataSource.text(forDate: training.dateTimeStart ?? Date())), " +
"\(TrainingDataSource.text(forTimeInSeconds: UInt32(training.duration)))"
return cell
}
}
extension TrainingsListViewController: UITableViewDelegate {
func tableView(_ tableView: UITableView,
heightForHeaderInSection section: Int) -> CGFloat {
return CGFloat.leastNormalMagnitude
}
}
| mit | ef6ac826b3a88b09a8aeefd55ce1f21c | 30.76 | 100 | 0.631822 | 5.089744 | false | false | false | false |
pixelmaid/DynamicBrushes | swift/Palette-Knife/models/behavior/State.swift | 1 | 4944 | //
// State.swift
// PaletteKnife
//
// Created by JENNIFER MARY JACOBS on 7/20/16.
// Copyright © 2016 pixelmaid. All rights reserved.
//
import Foundation
class State {
var transitions = [String:StateTransition]()
var constraint_mappings = [String:Constraint]()
let name: String
let id: String
init(id:String,name:String){
self.id = id;
self.name = name;
}
func addConstraintMapping(key:String, reference:Observable<Float>, relativeProperty:Observable<Float>, type:String){
let mapping = Constraint(id:key,reference: reference, relativeProperty:relativeProperty,type:type)
constraint_mappings[key] = mapping;
}
func removeAllConstraintMappings(brush:Brush){
for (key,_) in constraint_mappings{
_ = removeConstraintMapping(key:key,brush:brush);
}
}
func removeAllTransitions()->[StateTransition]{
var removed = [StateTransition]();
for (key,_) in transitions{
removed.append(removeTransitionMapping(key:key)!);
}
return removed;
}
func removeConstraintMapping(key:String, brush:Brush)->Constraint?{
constraint_mappings[key]!.relativeProperty.constrained = false;
constraint_mappings[key]!.reference.unsubscribe(id:brush.id);
constraint_mappings[key]!.reference.didChange.removeHandler(key:key)
constraint_mappings[key]!.relativeProperty.constraintTarget = nil;
return constraint_mappings.removeValue(forKey: key)
}
func addStateTransitionMapping(id:String, name:String, reference:Emitter,toStateId:String)->StateTransition{
let mapping = StateTransition(id:id, name:name, reference:reference,toStateId:toStateId)
transitions[id] = mapping;
return mapping;
}
func removeTransitionMapping(key:String)->StateTransition?{
return transitions.removeValue(forKey: key)
}
func getConstraintMapping(key:String)->Constraint?{
if let _ = constraint_mappings[key] {
return constraint_mappings[key]
}
else {
return nil
}
}
func getTransitionMapping(key:String)->StateTransition?{
if let _ = transitions[key] {
return transitions[key]
}
else {
return nil
}
}
func hasTransitionKey(key:String)->Bool{
if(transitions[key] != nil){
return true
}
return false
}
func hasConstraintKey(key:String)->Bool{
if(constraint_mappings[key] != nil){
return true
}
return false
}
func toJSON()->String{
var data = "{\"id\":\""+(self.id)+"\","
data += "\"name\":\""+self.name+"\","
data += "\"mappings\":[";
var count = 0;
for (_, mapping) in constraint_mappings{
if(count>0){
data += ","
}
data += mapping.toJSON();
count += 1;
}
data += "]"
data += "}"
return data;
}
}
struct Constraint{
var reference:Observable<Float>
var relativeProperty:Observable<Float>
var id:String
var type:String
init(id:String, reference:Observable<Float>, relativeProperty:Observable<Float>,type:String){
self.reference = reference
self.relativeProperty = relativeProperty
self.id = id;
self.type = type; //should be active or passive
}
func toJSON()->String{
let data = "{\"id\":\""+(self.id)+"\"}"
return data;
}
}
class Method{
var name: String;
var id: String;
var arguments: [Any]?
init(id:String,name:String,arguments:[Any]?){
self.name = name;
self.id = id;
self.arguments = arguments;
}
func toJSON()->String{
var data = "{\"id\":\""+(self.id)+"\","
data += "\"name\":\""+(self.name)+"\"}"
return data;
}
}
class StateTransition{
var reference:Emitter
var toStateId: String
var methods = [Method]()
let name: String
let id: String
init(id:String, name:String, reference:Emitter, toStateId:String){
self.reference = reference
self.toStateId = toStateId
self.name = name
self.id = id;
}
func addMethod(id:String, name:String, arguments:[Any]?){
methods.append(Method(id:id, name:name,arguments:arguments));
}
func toJSON()->String{
var data = "{\"id\":\""+(self.id)+"\","
data += "\"name\":\""+self.name+"\","
data += "\"methods\":[";
for i in 0..<methods.count{
if(i>0){
data += ","
}
data += methods[i].toJSON();
}
data += "]"
data += "}"
return data;
}
}
| mit | 5fb9b2935c342ab0d0c71fee6a3cd96a | 24.479381 | 120 | 0.558163 | 4.505925 | false | false | false | false |
tingting-anne/WebEditor | WebEditor/Classes/WebEditorToolBar.swift | 1 | 2138 | //
// WebEditorToolBar.swift
// WebEditor
//
// Created by liutingting on 16/7/12.
// Copyright (c) 2016 liutingting. All rights reserved.
//
import Foundation
import SnapKit
public class WebEditorToolBar: UIView {
public var leading: CGFloat = 15
public var trailing: CGFloat = 15
public var itemSpacing: CGFloat = 15
public var items: [WebEditorToolItem] = [] {
didSet {
for value in oldValue {
value.removeFromSuperview()
}
updateItems()
}
}
private let containerView = UIScrollView()
override init(frame: CGRect) {
super.init(frame: frame)
containerView.bounces = false
containerView.showsHorizontalScrollIndicator = false
self.addSubview(containerView)
containerView.snp.makeConstraints() {make in
make.edges.equalTo(self)
}
let lineView = UIView()
lineView.backgroundColor = UIColor(red: 230/255.0, green: 230/255.0, blue: 230/255.0, alpha: 1)
self.addSubview(lineView)
lineView.snp.makeConstraints() {make in
make.height.equalTo(0.5)
make.leading.equalTo(self)
make.trailing.equalTo(self)
make.top.equalTo(self)
}
}
required public init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
private func updateItems() {
let width: CGFloat = items.reduce(0) {sum, new in
return sum + new.itemSize.width + itemSpacing
}
containerView.contentSize.width = width - itemSpacing + leading + trailing
var leadingOffset = leading
for value in items {
containerView.addSubview(value)
value.snp.makeConstraints() {make in
make.leading.equalTo(containerView).offset(leadingOffset)
make.size.equalTo(value.itemSize)
make.centerY.equalTo(containerView)
}
leadingOffset += value.itemSize.width + itemSpacing
}
}
}
| mit | d9921dd0391a398c1b1c9113c5428d77 | 28.694444 | 103 | 0.591207 | 4.761693 | false | false | false | false |
PopcornTimeTV/PopcornTimeTV | PopcornTime/UI/tvOS/Views/LoadExternalTorrentViewController.swift | 1 | 6397 |
import Foundation
import GCDWebServer
import PopcornKit
class LoadExternalTorrentViewController:UIViewController,GCDWebServerDelegate,PCTPlayerViewControllerDelegate,UIViewControllerTransitioningDelegate{
@IBOutlet var infoLabel:UITextView!
var webserver:GCDWebServer!
override func viewWillAppear(_ animated: Bool) {
self.navigationController?.tabBarController?.tabBar.isHidden = true
if webserver == nil {
webserver=GCDWebServer()
webserver?.addGETHandler(forBasePath: "/", directoryPath: Bundle.main.path(forResource: "torrent_upload", ofType: "")!, indexFilename: "index.html", cacheAge: 3600, allowRangeRequests: false) // serve the website located in Supporting Files/torrent_upload when we receive a GET request for /
webserver?.addHandler(forMethod: "GET", path: "/torrent", request: GCDWebServerRequest.self, processBlock: {request in
let magnetLink = request.query?["link"]!.removingPercentEncoding ?? ""// get magnet link that is inserted as a link tag from the website
DispatchQueue.main.async {
let userTorrent = Torrent.init(health: .excellent, url: magnetLink, quality: "1080p", seeds: 100, peers: 100, size: nil)
var title = magnetLink
if let startIndex = title.range(of: "dn="){
title = String(title[startIndex.upperBound...])
title = String(title[title.startIndex ... title.range(of: "&tr")!.lowerBound])
}
let magnetTorrentMedia = Movie.init(title: title, id: "34", tmdbId: nil, slug: "magnet-link", summary: "", torrents: [userTorrent], subtitles: [:], largeBackgroundImage: nil, largeCoverImage: nil)
let storyboard = UIStoryboard.main
let loadingViewController = storyboard.instantiateViewController(withIdentifier: "PreloadTorrentViewController") as! PreloadTorrentViewController
loadingViewController.transitioningDelegate = self
loadingViewController.loadView()
loadingViewController.titleLabel.text = magnetLink
self.present(loadingViewController, animated: true)
//Movie completion Blocks
let error: (String) -> Void = { (errorMessage) in
if self.presentedViewController != nil {
self.dismiss(animated: false)
}
let vc = UIAlertController(title: "Error".localized, message: errorMessage, preferredStyle: .alert)
vc.addAction(UIAlertAction(title: "OK".localized, style: .cancel, handler: nil))
self.present(vc, animated: true)
}
let finishedLoading: (PreloadTorrentViewController, UIViewController) -> Void = { (loadingVc, playerVc) in
let flag = UIDevice.current.userInterfaceIdiom != .tv
self.dismiss(animated: flag)
self.present(playerVc, animated: flag)
}
let selectTorrent: (Array<String>) -> Int32 = { (torrents) in
var selected = -1
let torrentSelection = UIAlertController(title: "Select file to play".localized, message: nil, preferredStyle: .alert)
for torrent in torrents{
torrentSelection.addAction(UIAlertAction(title: torrent, style: .default, handler: { _ in
selected = torrents.firstIndex(of: torrent) ?? -1
}))
}
DispatchQueue.main.sync{
torrentSelection.show(animated: true)
}
while selected == -1{ print("hold") }
return Int32(selected)
}
//Movie player view controller calls
let playViewController = storyboard.instantiateViewController(withIdentifier: "PCTPlayerViewController") as! PCTPlayerViewController
playViewController.delegate = self
magnetTorrentMedia.play(fromFileOrMagnetLink: magnetLink, nextEpisodeInSeries: nil, loadingViewController: loadingViewController, playViewController: playViewController, progress: 0, errorBlock: error, finishedLoadingBlock: finishedLoading, selectingTorrentBlock: selectTorrent)
}// start to stream the new movie asynchronously as we do not want to mess the web server response
return GCDWebServerDataResponse(statusCode:200)
})//handle the request that returns the magnet link
}
super.viewWillAppear(true)
webserver?.start(withPort: 54320, bonjourName: "popcorn")
infoLabel.text = .localizedStringWithFormat("Please navigate to the webpage %@ and insert the magnet link of the torrent you would like to play".localized, webserver?.serverURL?.absoluteString ?? "")
}
@IBAction func exitView(_ sender: Any) {
self.navigationController?.pop(animated: true)
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(true)
if webserver != nil {
webserver.stop()
webserver = nil
}
}
// MARK: - Presentation
dynamic func animationController(forPresented presented: UIViewController, presenting: UIViewController, source: UIViewController) -> UIViewControllerAnimatedTransitioning? {
if presented is PreloadTorrentViewController {
return PreloadTorrentViewControllerAnimatedTransitioning(isPresenting: true)
}
return nil
}
dynamic func animationController(forDismissed dismissed: UIViewController) -> UIViewControllerAnimatedTransitioning? {
if dismissed is PreloadTorrentViewController {
return PreloadTorrentViewControllerAnimatedTransitioning(isPresenting: false)
}
return nil
}
}
| gpl-3.0 | 012caee16ad4d1d88c13abde45abba9c | 55.114035 | 303 | 0.599812 | 6.186654 | false | false | false | false |
SusanDoggie/Doggie | Sources/DoggieGraphics/ColorPixel/RGB/BGRA32ColorPixel.swift | 1 | 1590 | //
// BGRA32ColorPixel.swift
//
// The MIT License
// Copyright (c) 2015 - 2022 Susan Cheng. All rights reserved.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
@frozen
public struct BGRA32ColorPixel: _RGBColorPixel {
public var b: UInt8
public var g: UInt8
public var r: UInt8
public var a: UInt8
@inlinable
@inline(__always)
public init(red: UInt8, green: UInt8, blue: UInt8, opacity: UInt8 = 0xFF) {
self.r = red
self.g = green
self.b = blue
self.a = opacity
}
}
| mit | 795a90f77131d755c224aa6c44cf571d | 36.857143 | 81 | 0.707547 | 4.087404 | false | false | false | false |
taufikobet/Fusuma | Sources/FSVideoCameraView.swift | 1 | 19287 | //
// FSVideoCameraView.swift
// Fusuma
//
// Created by Brendan Kirchner on 3/18/16.
// Copyright © 2016 CocoaPods. All rights reserved.
//
import UIKit
import AVFoundation
import MZTimerLabel
import CoreMotion
@objc protocol FSVideoCameraViewDelegate: class {
func videoFinished(withFileURL fileURL: URL)
}
final class FSVideoCameraView: UIView {
@IBOutlet weak var previewViewContainer: UIView!
@IBOutlet weak var shotButton: CameraButton!
@IBOutlet weak var flashButton: UIButton!
@IBOutlet weak var flipButton: UIButton!
@IBOutlet weak var timerLabel: UILabel!
@IBOutlet weak var recordIndicator: UIView!
@IBOutlet weak var placeholderTopConstraint: NSLayoutConstraint!
@IBOutlet weak var timerLabelTopConstraint: NSLayoutConstraint!
lazy var mzTimerLabel:MZTimerLabel = MZTimerLabel(label: self.timerLabel, andTimerType: MZTimerLabelTypeStopWatch)
weak var delegate: FSVideoCameraViewDelegate? = nil
var session: AVCaptureSession?
var device: AVCaptureDevice?
var audioDevice: AVCaptureDevice?
var videoInput: AVCaptureDeviceInput?
var audioInput: AVCaptureDeviceInput?
var videoOutput: AVCaptureMovieFileOutput?
var focusView: UIView?
var flashOffImage: UIImage?
var flashOnImage: UIImage?
var videoStartImage: UIImage?
var videoStopImage: UIImage?
let motionManager: CMMotionManager = CMMotionManager()
var videoOrientation:UIInterfaceOrientation = .portrait
fileprivate var isRecording = false
static func instance() -> FSVideoCameraView {
return UINib(nibName: "FSVideoCameraView", bundle: Bundle(for: self.classForCoder())).instantiate(withOwner: self, options: nil)[0] as! FSVideoCameraView
}
func initialize() {
if session != nil {
return
}
self.backgroundColor = fusumaBackgroundColor
self.isHidden = false
// AVCapture
session = AVCaptureSession()
session?.sessionPreset = AVCaptureSessionPreset640x480
for device in AVCaptureDevice.devices() {
if let device = device as? AVCaptureDevice , device.position == AVCaptureDevicePosition.back {
self.device = device
}
}
for device in AVCaptureDevice.devices(withMediaType: AVMediaTypeAudio) {
if let device = device as? AVCaptureDevice {
self.audioDevice = device
}
}
do {
if let session = session {
videoInput = try AVCaptureDeviceInput(device: device)
audioInput = try AVCaptureDeviceInput(device: audioDevice)
session.addInput(videoInput)
session.addInput(audioInput)
videoOutput = AVCaptureMovieFileOutput()
let totalSeconds = 60.0 //Total Seconds of capture time
let timeScale: Int32 = 30 //FPS
let maxDuration = CMTimeMakeWithSeconds(totalSeconds, timeScale)
videoOutput?.maxRecordedDuration = maxDuration
videoOutput?.minFreeDiskSpaceLimit = 1024 * 1024 //SET MIN FREE SPACE IN BYTES FOR RECORDING TO CONTINUE ON A VOLUME
if session.canAddOutput(videoOutput) {
session.addOutput(videoOutput)
}
let videoLayer = AVCaptureVideoPreviewLayer(session: session)
videoLayer?.frame = self.previewViewContainer.bounds
videoLayer?.videoGravity = AVLayerVideoGravityResizeAspectFill
self.previewViewContainer.layer.addSublayer(videoLayer!)
session.startRunning()
}
// Focus View
self.focusView = UIView(frame: CGRect(x: 0, y: 0, width: 90, height: 90))
let tapRecognizer = UITapGestureRecognizer(target: self, action: #selector(FSVideoCameraView.focus(_:)))
self.previewViewContainer.addGestureRecognizer(tapRecognizer)
} catch {
}
let bundle = Bundle(for: self.classForCoder)
flashOnImage = fusumaFlashOnImage != nil ? fusumaFlashOnImage : UIImage(named: "ic_flash_on", in: bundle, compatibleWith: nil)
flashOffImage = fusumaFlashOffImage != nil ? fusumaFlashOffImage : UIImage(named: "ic_flash_off", in: bundle, compatibleWith: nil)
let flipImage = fusumaFlipImage != nil ? fusumaFlipImage : UIImage(named: "ic_loop", in: bundle, compatibleWith: nil)
videoStartImage = fusumaVideoStartImage != nil ? fusumaVideoStartImage : UIImage(named: "video_button", in: bundle, compatibleWith: nil)
videoStopImage = fusumaVideoStopImage != nil ? fusumaVideoStopImage : UIImage(named: "video_button_rec", in: bundle, compatibleWith: nil)
if(fusumaTintIcons) {
flashButton.tintColor = fusumaBaseTintColor
flipButton.tintColor = fusumaBaseTintColor
flashButton.setImage(flashOffImage?.withRenderingMode(.alwaysTemplate), for: UIControlState())
flipButton.setImage(flipImage?.withRenderingMode(.alwaysTemplate), for: UIControlState())
} else {
flashButton.setImage(flashOffImage, for: UIControlState())
flipButton.setImage(flipImage, for: UIControlState())
}
flashConfiguration()
}
public override func safeAreaInsetsDidChange() {
if #available(iOS 11.0, *) {
super.safeAreaInsetsDidChange()
let topInset = self.safeAreaInsets.top
if topInset > 0 {
placeholderTopConstraint.constant += topInset
timerLabelTopConstraint.constant += topInset
}
}
}
func setupMotionManager() {
motionManager.deviceMotionUpdateInterval = 5.0
if motionManager.isAccelerometerAvailable {
let queue = OperationQueue.main
motionManager.startAccelerometerUpdates(to: queue, withHandler: {
[weak self] data, error in
guard let data = data else {
return
}
let angle = (atan2(data.acceleration.y,data.acceleration.x))*180/M_PI
//print(angle)
if (fabs(angle)<=45) {
self?.videoOrientation = .landscapeLeft
}
else if ((fabs(angle)>45)&&(fabs(angle)<135)) {
if(angle>0){
self?.videoOrientation = .portraitUpsideDown
} else {
self?.videoOrientation = .portrait
}
} else {
self?.videoOrientation = .landscapeRight
}
})
}
}
deinit {
NotificationCenter.default.removeObserver(self)
}
func startCamera() {
let status = AVCaptureDevice.authorizationStatus(forMediaType: AVMediaTypeVideo)
if status == AVAuthorizationStatus.authorized {
session?.startRunning()
setupMotionManager()
} else if status == AVAuthorizationStatus.denied || status == AVAuthorizationStatus.restricted {
session?.stopRunning()
stopMotionManager()
}
}
func stopCamera() {
if self.isRecording {
self.toggleRecording()
}
session?.stopRunning()
stopMotionManager()
}
@IBAction func shotButtonPressed(_ sender: UIButton) {
self.toggleRecording()
if self.isRecording {
stopMotionManager()
}
}
func stopMotionManager() {
motionManager.stopDeviceMotionUpdates()
motionManager.stopAccelerometerUpdates()
}
func startAnimatingRecordIndicator() {
recordIndicator.isHidden = false
UIView.animate(withDuration: 0.75, delay: 0.0, options: .repeat, animations: {
self.recordIndicator.alpha = 0.0
}, completion: nil)
}
func stopAnimatingRecordIndicator() {
recordIndicator.layer.removeAllAnimations()
recordIndicator.isHidden = true
}
fileprivate func toggleRecording() {
guard let videoOutput = videoOutput else {
return
}
self.isRecording = !self.isRecording
let shotImage: UIImage?
if self.isRecording {
shotImage = videoStopImage
mzTimerLabel.start()
startAnimatingRecordIndicator()
} else {
shotImage = videoStartImage
mzTimerLabel.pause()
mzTimerLabel.reset()
stopAnimatingRecordIndicator()
}
if self.isRecording {
let outputPath = "\(NSTemporaryDirectory())output.mov"
let outputURL = URL(fileURLWithPath: outputPath)
let fileManager = FileManager.default
if fileManager.fileExists(atPath: outputPath) {
do {
try fileManager.removeItem(atPath: outputPath)
} catch {
print("error removing item at path: \(outputPath)")
self.isRecording = false
return
}
}
self.flipButton.isEnabled = false
self.flashButton.isEnabled = false
videoOutput.startRecording(toOutputFileURL: outputURL, recordingDelegate: self)
} else {
videoOutput.stopRecording()
self.flipButton.isEnabled = true
self.flashButton.isEnabled = true
}
return
}
@IBAction func flipButtonPressed(_ sender: UIButton) {
session?.stopRunning()
do {
session?.beginConfiguration()
if let session = session {
for input in session.inputs {
session.removeInput(input as! AVCaptureInput)
}
let position = (videoInput?.device.position == AVCaptureDevicePosition.front) ? AVCaptureDevicePosition.back : AVCaptureDevicePosition.front
for device in AVCaptureDevice.devices(withMediaType: AVMediaTypeVideo) {
if let device = device as? AVCaptureDevice , device.position == position {
videoInput = try AVCaptureDeviceInput(device: device)
session.addInput(videoInput)
}
}
for device in AVCaptureDevice.devices(withMediaType: AVMediaTypeAudio) {
if let device = device as? AVCaptureDevice {
audioInput = try AVCaptureDeviceInput(device: device)
session.addInput(audioInput)
}
}
}
session?.commitConfiguration()
} catch {
}
session?.startRunning()
}
@IBAction func flashButtonPressed(_ sender: UIButton) {
do {
if let device = device {
try device.lockForConfiguration()
if device.hasFlash {
let mode = device.flashMode
if mode == AVCaptureFlashMode.off {
device.flashMode = AVCaptureFlashMode.on
flashButton.setImage(flashOnImage, for: UIControlState())
} else if mode == AVCaptureFlashMode.on {
device.flashMode = AVCaptureFlashMode.off
flashButton.setImage(flashOffImage, for: UIControlState())
}
}
device.unlockForConfiguration()
}
} catch _ {
flashButton.setImage(flashOffImage, for: UIControlState())
return
}
}
}
extension FSVideoCameraView: AVCaptureFileOutputRecordingDelegate {
func capture(_ captureOutput: AVCaptureFileOutput!, didStartRecordingToOutputFileAt fileURL: URL!, fromConnections connections: [Any]!) {
print("started recording to: \(fileURL)")
}
func capture(_ captureOutput: AVCaptureFileOutput!, didFinishRecordingToOutputFileAt outputFileURL: URL!, fromConnections connections: [Any]!, error: Error!) {
print("finished recording to: \(outputFileURL)")
exportVideo(withURL: outputFileURL, orientation: videoOrientation) { (url) in
if let url = url {
self.delegate?.videoFinished(withFileURL: url)
}
}
}
}
extension FSVideoCameraView {
func focus(_ recognizer: UITapGestureRecognizer) {
let point = recognizer.location(in: self)
let viewsize = self.bounds.size
let newPoint = CGPoint(x: point.y/viewsize.height, y: 1.0-point.x/viewsize.width)
let device = AVCaptureDevice.defaultDevice(withMediaType: AVMediaTypeVideo)
do {
try device?.lockForConfiguration()
} catch _ {
return
}
if device?.isFocusModeSupported(AVCaptureFocusMode.autoFocus) == true {
device?.focusMode = AVCaptureFocusMode.autoFocus
device?.focusPointOfInterest = newPoint
}
if device?.isExposureModeSupported(AVCaptureExposureMode.continuousAutoExposure) == true {
device?.exposureMode = AVCaptureExposureMode.continuousAutoExposure
device?.exposurePointOfInterest = newPoint
}
device?.unlockForConfiguration()
self.focusView?.alpha = 0.0
self.focusView?.center = point
self.focusView?.backgroundColor = UIColor.clear
self.focusView?.layer.borderColor = UIColor.white.cgColor
self.focusView?.layer.borderWidth = 1.0
self.focusView!.transform = CGAffineTransform(scaleX: 1.0, y: 1.0)
self.addSubview(self.focusView!)
UIView.animate(withDuration: 0.8, delay: 0.0, usingSpringWithDamping: 0.8,
initialSpringVelocity: 3.0, options: UIViewAnimationOptions.curveEaseIn, // UIViewAnimationOptions.BeginFromCurrentState
animations: {
self.focusView!.alpha = 1.0
self.focusView!.transform = CGAffineTransform(scaleX: 0.7, y: 0.7)
}, completion: {(finished) in
self.focusView!.transform = CGAffineTransform(scaleX: 1.0, y: 1.0)
self.focusView!.removeFromSuperview()
})
}
func flashConfiguration() {
do {
if let device = device {
try device.lockForConfiguration()
if device.hasFlash {
device.flashMode = AVCaptureFlashMode.off
flashButton.setImage(flashOffImage, for: UIControlState())
}
device.unlockForConfiguration()
}
} catch _ {
return
}
}
}
extension FSVideoCameraView {
func exportVideo(withURL url: URL, orientation:UIInterfaceOrientation, completionHandler:@escaping (URL?)->()) {
let asset = AVURLAsset(url: url)
let exportSession = SDAVAssetExportSession(asset: asset)!
let outputPath = NSTemporaryDirectory().appending("temp.mov")
if FileManager.default.fileExists(atPath: outputPath) {
try! FileManager.default.removeItem(atPath: outputPath)
}
exportSession.outputURL = URL(fileURLWithPath: outputPath)
exportSession.outputFileType = AVFileTypeQuickTimeMovie
// exportSession.shouldOptimizeForNetworkUse = true
var size:CGSize = CGSize.zero
if let naturalSize = asset.tracks(withMediaType: AVMediaTypeVideo).first?.naturalSize,
let preferredTransform = asset.tracks(withMediaType: AVMediaTypeVideo).first?.preferredTransform
{
size = naturalSize
if isVideoRotated90_270(preferredTransform: preferredTransform) {
let flippedSize:CGSize = size
size.width = flippedSize.height
size.height = flippedSize.width
}
}
exportSession.videoSettings = [
AVVideoCodecKey: AVVideoCodecH264,
AVVideoWidthKey: size.width,
AVVideoHeightKey: size.height,
AVVideoCompressionPropertiesKey: [
AVVideoAverageBitRateKey: 1216000,
AVVideoProfileLevelKey: AVVideoProfileLevelH264High41,
],
]
exportSession.audioSettings = [
AVFormatIDKey: NSNumber(value: Int32(kAudioFormatMPEG4AAC)),
AVNumberOfChannelsKey: 1,
AVSampleRateKey: 44100,
AVEncoderBitRateKey: 64000,
]
exportSession.exportAsynchronously(with: orientation, completionHandler: {
DispatchQueue.main.async {
print(exportSession.status)
switch exportSession.status {
case .cancelled:
print("cancelled")
case .failed:
print("failed")
completionHandler(nil)
case .unknown:
print("unknown")
case .completed:
if let outputURL = exportSession.outputURL {
completionHandler(outputURL)
}
default: break
}
}
})
}
func isVideoRotated90_270(preferredTransform: CGAffineTransform) -> Bool {
var isRotated90_270 = false
let t: CGAffineTransform = preferredTransform
if t.a == 0 && t.b == 1.0 && t.c == -1.0 && t.d == 0 {
isRotated90_270 = true
}
if t.a == 0 && t.b == -1.0 && t.c == 1.0 && t.d == 0 {
isRotated90_270 = true
}
if t.a == 1.0 && t.b == 0 && t.c == 0 && t.d == 1.0 {
isRotated90_270 = false
}
if t.a == -1.0 && t.b == 0 && t.c == 0 && t.d == -1.0 {
isRotated90_270 = false
}
return isRotated90_270
}
}
| mit | 4752751050adb275ca837a8bf3cf6d0c | 33.377897 | 163 | 0.555584 | 6.116714 | false | false | false | false |
SusanDoggie/Doggie | Sources/DoggieGraphics/ImageCodec/RawBitmap/SlowDecode/_aligned_channel.swift | 1 | 4574 | //
// _aligned_channel.swift
//
// The MIT License
// Copyright (c) 2015 - 2022 Susan Cheng. All rights reserved.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
extension Image {
@inlinable
@inline(__always)
mutating func _decode_aligned_channel<T: FixedWidthInteger, R: BinaryFloatingPoint>(_ bitmap: RawBitmap, _ channel_idx: Int, _ is_opaque: Bool, _: T.Type, _ : R.Type) {
let width = self.width
let height = self.height
guard bitmap.startsRow < height else { return }
let bytesPerPixel = bitmap.bitsPerPixel >> 3
let channel = bitmap.channels[channel_idx]
let channel_max: R = scalbn(1, T.bitWidth) - 1
let byteOffset = channel.bitRange.lowerBound >> 3
self.withUnsafeMutableTypePunnedBufferPointer(to: R.self) {
guard var dest = $0.baseAddress else { return }
let row = Pixel.numberOfComponents * width
dest += bitmap.startsRow * row
var data = bitmap.data
for _ in bitmap.startsRow..<height {
let _length = min(bitmap.bytesPerRow, data.count)
guard _length != 0 else { return }
data.popFirst(bitmap.bytesPerRow).withUnsafeBytes { (bytes: UnsafeRawBufferPointer) in
guard var source = bytes.baseAddress else { return }
var destination = dest
let source_end = source + _length
var predictor_record: T = 0
for _ in 0..<width {
guard source + bytesPerPixel <= source_end else { return }
let _destination = destination + channel.index
let _source = source + byteOffset
let _s: T
let _d: T
switch channel.endianness {
case .big: _s = T(bigEndian: _source.bindMemory(to: T.self, capacity: 1).pointee)
case .little: _s = T(littleEndian: _source.bindMemory(to: T.self, capacity: 1).pointee)
}
switch bitmap.predictor {
case .none: _d = _s
case .subtract: _d = _s &+ predictor_record
}
if T.isSigned {
_destination.pointee = Image._denormalized(channel.index, R(UInt64(bitPattern: Int64(_d) &- Int64(T.min))) / channel_max)
} else {
_destination.pointee = Image._denormalized(channel.index, R(_d) / channel_max)
}
predictor_record = _d
source += bytesPerPixel
if is_opaque {
destination[Pixel.numberOfComponents - 1] = 1
}
destination += Pixel.numberOfComponents
}
dest += row
}
}
}
}
}
| mit | d3a82e653cccb38afcae8b0e9b653700 | 40.963303 | 172 | 0.503279 | 5.419431 | false | false | false | false |
garynewby/GLNPianoView | Example/Example/FasciaView.swift | 1 | 807 | //
// FasciaView.swift
// Example
//
// Created by Gary Newby on 14/08/2020.
//
import UIKit
class FasciaView: UIView {
private lazy var fasciaLayer: CAGradientLayer = {
let layer = CAGradientLayer()
layer.frame = bounds
layer.colors = [UIColor.darkGray.cgColor, UIColor.lightGray.cgColor, UIColor.black.cgColor]
layer.startPoint = CGPoint(x: 0.0, y: 0.92)
layer.endPoint = CGPoint(x: 0.0, y: 1.0)
return layer
}()
override init(frame: CGRect) {
super.init(frame: frame)
layer.insertSublayer(fasciaLayer, at: 0)
}
required init?(coder: NSCoder) {
super.init(coder: coder)
layer.insertSublayer(fasciaLayer, at: 0)
}
override func layoutSubviews() {
fasciaLayer.frame = bounds
}
}
| mit | 66053ef8469f7e6274899f938491790e | 23.454545 | 99 | 0.620818 | 3.668182 | false | false | false | false |
cweatureapps/SwiftScraper | Pods/Observable-Swift/Observable-Swift/OwningEventReference.swift | 2 | 1674 | //
// OwningEventReference.swift
// Observable-Swift
//
// Created by Leszek Ślażyński on 28/06/14.
// Copyright (c) 2014 Leszek Ślażyński. All rights reserved.
//
/// A subclass of event reference allowing it to own other object[s].
/// Additionally, the reference makes added events own itself.
/// This retain cycle allows owned objects to live as long as valid subscriptions exist.
public class OwningEventReference<T>: EventReference<T> {
internal var owned: AnyObject? = nil
public override func add(_ subscription: SubscriptionType) -> SubscriptionType {
let subscr = super.add(subscription)
if owned != nil {
subscr.addOwnedObject(self)
}
return subscr
}
public override func add(_ handler: @escaping (T) -> ()) -> EventSubscription<T> {
let subscr = super.add(handler)
if owned != nil {
subscr.addOwnedObject(self)
}
return subscr
}
public override func remove(_ subscription: SubscriptionType) {
subscription.removeOwnedObject(self)
super.remove(subscription)
}
public override func removeAll() {
for subscription in event.subscriptions {
subscription.removeOwnedObject(self)
}
super.removeAll()
}
public override func add(owner: AnyObject, _ handler: @escaping HandlerType) -> SubscriptionType {
let subscr = super.add(owner: owner, handler)
if owned != nil {
subscr.addOwnedObject(self)
}
return subscr
}
public override init(event: Event<T>) {
super.init(event: event)
}
}
| mit | 26f9af14d8e7b31e5cae21ca1539dfec | 28.785714 | 103 | 0.630096 | 4.582418 | false | false | false | false |
CaiMiao/CGSSGuide | DereGuide/Extension/UIColorExtension.swift | 1 | 3064 | //
// UIColorExtension.swift
// DereGuide
//
// Created by zzk on 2017/1/4.
// Copyright © 2017年 zzk. All rights reserved.
//
import UIKit
import DynamicColor
extension UIColor {
static let border = UIColor.lightGray
static let background = UIColor(hexString: "E2E2E2")
static let vocal = UIColor(red: 1.0 * 236 / 255, green: 1.0 * 87 / 255, blue: 1.0 * 105 / 255, alpha: 1)
static let dance = UIColor(red: 1.0 * 89 / 255, green: 1.0 * 187 / 255, blue: 1.0 * 219 / 255, alpha: 1)
static let visual = UIColor(red: 1.0 * 254 / 255, green: 1.0 * 154 / 255, blue: 1.0 * 66 / 255, alpha: 1)
static let life = UIColor(red: 1.0 * 75 / 255, green: 1.0 * 202 / 255, blue: 1.0 * 137 / 255, alpha: 1)
static let debut = UIColor(red: 1.0 * 138 / 255, green: 1.0 * 206 / 255, blue: 1.0 * 233 / 255, alpha: 1)
static let regular = UIColor(red: 1.0 * 253 / 255, green: 1.0 * 164 / 255, blue: 1.0 * 40 / 255, alpha: 1)
static let pro = UIColor(red: 1.0 * 254 / 255, green: 1.0 * 183 / 255, blue: 1.0 * 194 / 255, alpha: 1)
static let master = UIColor.init(red: 1.0 * 147 / 255, green: 1.0 * 236 / 255, blue: 1.0 * 148 / 255, alpha: 1)
static let masterPlus = UIColor(red: 1.0 * 255 / 255, green: 1.0 * 253 / 255, blue: 1.0 * 114 / 255, alpha: 1)
static let legacyMasterPlus = UIColor.masterPlus.lighter()
static let light = UIColor(hexString: "E1F3A6")
static let trick = UIColor(hexString: "E1B9F7")
static let cute = UIColor(red: 1.0 * 248 / 255, green: 1.0 * 24 / 255, blue: 1.0 * 117 / 255, alpha: 1)
static let cool = UIColor(red: 1.0 * 42 / 255, green: 1.0 * 113 / 255, blue: 1.0 * 247 / 255, alpha: 1)
static let passion = UIColor(red: 1.0 * 250 / 255, green: 1.0 * 168 / 255, blue: 1.0 * 57 / 255, alpha: 1)
static let parade = UIColor(red: 1.0 * 22 / 255, green: 1.0 * 87 / 255, blue: 1.0 * 250 / 255, alpha: 1)
static let kyalapon = UIColor(red: 1.0 * 252 / 255, green: 1.0 * 60 / 255, blue: 1.0 * 169 / 255, alpha: 1)
static let groove = UIColor(red: 1.0 * 238 / 255, green: 1.0 * 175 / 255, blue: 1.0 * 50 / 255, alpha: 1)
static let party = UIColor(red: 1.0 * 89 / 255, green: 1.0 * 192 / 255, blue: 1.0 * 50 / 255, alpha: 1)
static let tradition = UIColor(red: 1.0 * 113 / 255, green: 1.0 * 80 / 255, blue: 1.0 * 69 / 255, alpha: 1)
static let rail = UIColor(hexString: "81CD46")
static let normal = UIColor(red: 1.0 * 253 / 255, green: 1.0 * 186 / 255, blue: 1.0 * 80 / 255, alpha: 1)
static let limited = UIColor(red: 1.0 * 236 / 255, green: 1.0 * 103 / 255, blue: 1.0 * 105 / 255, alpha: 1)
static let cinfes = UIColor(red: 1.0 * 25 / 255, green: 1.0 * 154 / 255, blue: 1.0 * 218 / 255, alpha: 1)
static let flick4 = UIColor(hexString: "3568D5")
static let flick3 = UIColor(hexString: "7CD8AA")
static let slide = UIColor(hexString: "A544D9")
static let tap = UIColor(hexString: "EC6279")
static let hold = UIColor(hexString: "F7CD72")
static let allType = UIColor.darkGray
}
| mit | b6576dc9bc1d5d82b0835d7ed6726e40 | 53.660714 | 115 | 0.598497 | 2.885014 | false | false | false | false |
LeeCenY/iRent | Sources/iRent/Model/Room.swift | 1 | 2009 | //
// Room.swift
// iRentPackageDescription
//
// Created by nil on 2018/3/3.
//
import Foundation
struct Room: Codable {
let id: UUID
let state: Bool //是否退房
let room_no: String? //房间号
let rent_money: Int? //租金
let deposit: Int? //押金
let lease_term: Int? //租期
let rent_date: String? //收租日期
let network: Int? //网络
let trash_fee: Int? //垃圾费
let water_max: Int? //水表阈值
let electricity_max: Int? //电表阈值
let create_at: String //创建时间
let updated_at: String //更新时间
let payments: [Payment]?
let tenants: [Tenant]?
public init(state: Bool, room_no: String?, rent_money: Int?, deposit: Int?, lease_term: Int?, rent_date: String?, network: Int?, trash_fee: Int?) {
self.init(state: state, room_no: room_no, rent_money: rent_money, deposit: deposit, lease_term: lease_term, rent_date: rent_date, network: network, trash_fee: trash_fee, water_max: nil, electricity_max: nil)
}
public init(state: Bool, room_no: String?, rent_money: Int?, deposit: Int?, lease_term: Int?, rent_date: String?, network: Int?, trash_fee: Int?, water_max: Int?, electricity_max: Int?) {
self.id = UUID()
self.state = state
self.room_no = room_no
self.rent_money = rent_money
self.deposit = deposit
self.lease_term = lease_term
self.rent_date = rent_date
self.network = network
self.trash_fee = trash_fee
self.water_max = water_max
self.electricity_max = electricity_max
self.create_at = Date().iso8601()
self.updated_at = Date().iso8601()
self.payments = nil
self.tenants = nil
}
}
| mit | f558ae81543b0d997d47159ae730ad77 | 36.901961 | 215 | 0.52716 | 3.746124 | false | false | false | false |
iosyoujian/Swift-DeviceType | DeviceTypeSample/DeviceTypeSample/ViewController.swift | 2 | 867 | //
// ViewController.swift
// DeviceTypeSample
//
// Created by Ian Hirschfeld on 3/6/15.
// Copyright (c) 2015 Ian Hirschfeld. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
println("UIDevice.currentDevice().deviceType: \(UIDevice.currentDevice().deviceType)")
println("UIDevice.currentDevice().isIPhone: \(UIDevice.currentDevice().isIPhone)")
println("UIDevice.currentDevice().isIPad: \(UIDevice.currentDevice().isIPad)")
println("UIDevice.currentDevice().isSimulator: \(UIDevice.currentDevice().isSimulator)")
println("==========")
println("self.isIPhone6PlusSize: \(self.isIPhone6PlusSize)")
println("self.isIPhone6Size: \(self.isIPhone6Size)")
println("self.isIPhone5sSize: \(self.isIPhone5sSize)")
}
}
| mit | a4e431d59dc8919d586e6183f180f78f | 31.111111 | 92 | 0.719723 | 4.25 | false | false | false | false |
samwyndham/DictateSRS | DictateSRS/Shared/Attributes.swift | 1 | 2025 | //
// Attributes.swift
// DictateSRS
//
// Created by Sam Wyndham on 23/02/2017.
// Copyright © 2017 Sam Wyndham. All rights reserved.
//
import UIKit
/// A container of `Character Attributes` that can be applied to an
/// `NSAttributedString`.
struct Attributes {
private var textStyle: UIFontTextStyle?
private var _dictionary: [String: Any] = [
NSFontAttributeName: UIFont.systemFont(ofSize: 12),
NSForegroundColorAttributeName: UIColor.black
]
/// Returns a copy of `self` with `NSFontAttributeName` set to `font`.
@discardableResult func settingFont(_ font: UIFont) -> Attributes {
var attributes = self
attributes.textStyle = nil
attributes._dictionary[NSFontAttributeName] = font
return attributes
}
/// Returns a copy of `self` with `NSFontAttributeName` set to the preferred
/// font for `style`.
@discardableResult func settingFont(style: UIFontTextStyle) -> Attributes {
var attributes = self
attributes.textStyle = style
return attributes
}
/// Returns a copy of `self` with `NSForegroundColorAttributeName` set to
/// `color`.
@discardableResult func settingColor(_ color: UIColor) -> Attributes {
var attributes = self
attributes._dictionary[NSForegroundColorAttributeName] = color
return attributes
}
/// A `Dictionary` of all `Character Attributes`.
var dictionary: [String: Any] {
if let textStyle = textStyle {
var attributes = _dictionary
attributes[NSFontAttributeName] = UIFont.preferredFont(forTextStyle: textStyle)
return attributes
} else {
return _dictionary
}
}
/// The font for `NSFontAttributeName`.
var font: UIFont {
if let textStyle = textStyle {
return UIFont.preferredFont(forTextStyle: textStyle)
} else {
return _dictionary[NSFontAttributeName] as! UIFont
}
}
}
| mit | ed598a2bec5063804a4d9191fae71551 | 31.126984 | 91 | 0.641304 | 5.163265 | false | false | false | false |
StYaphet/firefox-ios | Client/Frontend/Settings/AppSettingsTableViewController.swift | 2 | 7466 | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
import UIKit
import Shared
import Account
/// App Settings Screen (triggered by tapping the 'Gear' in the Tab Tray Controller)
class AppSettingsTableViewController: SettingsTableViewController {
var showContentBlockerSetting = false
override func viewDidLoad() {
super.viewDidLoad()
navigationItem.title = NSLocalizedString("Settings", comment: "Title in the settings view controller title bar")
navigationItem.rightBarButtonItem = UIBarButtonItem(
title: NSLocalizedString("Done", comment: "Done button on left side of the Settings view controller title bar"),
style: .done,
target: navigationController, action: #selector((navigationController as! ThemedNavigationController).done))
navigationItem.rightBarButtonItem?.accessibilityIdentifier = "AppSettingsTableViewController.navigationItem.leftBarButtonItem"
tableView.accessibilityIdentifier = "AppSettingsTableViewController.tableView"
// Refresh the user's FxA profile upon viewing settings. This will update their avatar,
// display name, etc.
////profile.rustAccount.refreshProfile()
if showContentBlockerSetting {
let viewController = ContentBlockerSettingViewController(prefs: profile.prefs)
viewController.profile = profile
viewController.tabManager = tabManager
navigationController?.pushViewController(viewController, animated: false)
// Add a done button from this view
viewController.navigationItem.rightBarButtonItem = navigationItem.rightBarButtonItem
}
}
override func generateSettings() -> [SettingSection] {
var settings = [SettingSection]()
let privacyTitle = NSLocalizedString("Privacy", comment: "Privacy section title")
let prefs = profile.prefs
var generalSettings: [Setting] = [
SearchSetting(settings: self),
NewTabPageSetting(settings: self),
HomeSetting(settings: self),
OpenWithSetting(settings: self),
ThemeSetting(settings: self),
BoolSetting(prefs: prefs, prefKey: PrefsKeys.KeyBlockPopups, defaultValue: true,
titleText: NSLocalizedString("Block Pop-up Windows", comment: "Block pop-up windows setting")),
]
if #available(iOS 12.0, *) {
generalSettings.insert(SiriPageSetting(settings: self), at: 5)
}
if AppConstants.MOZ_DOCUMENT_SERVICES {
generalSettings.insert(TranslationSetting(settings: self), at: 6)
}
let accountChinaSyncSetting: [Setting]
if !AppInfo.isChinaEdition {
accountChinaSyncSetting = []
} else {
accountChinaSyncSetting = [
// Show China sync service setting:
ChinaSyncServiceSetting(settings: self)
]
}
// There is nothing to show in the Customize section if we don't include the compact tab layout
// setting on iPad. When more options are added that work on both device types, this logic can
// be changed.
generalSettings += [
BoolSetting(prefs: prefs, prefKey: "showClipboardBar", defaultValue: false,
titleText: Strings.SettingsOfferClipboardBarTitle,
statusText: Strings.SettingsOfferClipboardBarStatus),
BoolSetting(prefs: prefs, prefKey: PrefsKeys.ContextMenuShowLinkPreviews, defaultValue: true,
titleText: Strings.SettingsShowLinkPreviewsTitle,
statusText: Strings.SettingsShowLinkPreviewsStatus)
]
let accountSectionTitle = NSAttributedString(string: Strings.FxAFirefoxAccount)
let footerText = !profile.hasAccount() ? NSAttributedString(string: Strings.FxASyncUsageDetails) : nil
settings += [
SettingSection(title: accountSectionTitle, footerTitle: footerText, children: [
// Without a Firefox Account:
ConnectSetting(settings: self),
AdvancedAccountSetting(settings: self),
// With a Firefox Account:
AccountStatusSetting(settings: self),
SyncNowSetting(settings: self)
] + accountChinaSyncSetting )]
settings += [ SettingSection(title: NSAttributedString(string: Strings.SettingsGeneralSectionTitle), children: generalSettings)]
var privacySettings = [Setting]()
privacySettings.append(LoginsSetting(settings: self, delegate: settingsDelegate))
privacySettings.append(TouchIDPasscodeSetting(settings: self))
privacySettings.append(ClearPrivateDataSetting(settings: self))
privacySettings += [
BoolSetting(prefs: prefs,
prefKey: "settings.closePrivateTabs",
defaultValue: false,
titleText: NSLocalizedString("Close Private Tabs", tableName: "PrivateBrowsing", comment: "Setting for closing private tabs"),
statusText: NSLocalizedString("When Leaving Private Browsing", tableName: "PrivateBrowsing", comment: "Will be displayed in Settings under 'Close Private Tabs'"))
]
privacySettings.append(ContentBlockerSetting(settings: self))
privacySettings += [
PrivacyPolicySetting()
]
settings += [
SettingSection(title: NSAttributedString(string: privacyTitle), children: privacySettings),
SettingSection(title: NSAttributedString(string: NSLocalizedString("Support", comment: "Support section title")), children: [
ShowIntroductionSetting(settings: self),
SendFeedbackSetting(),
SendAnonymousUsageDataSetting(prefs: prefs, delegate: settingsDelegate),
OpenSupportPageSetting(delegate: settingsDelegate),
]),
SettingSection(title: NSAttributedString(string: NSLocalizedString("About", comment: "About settings section title")), children: [
VersionSetting(settings: self),
LicenseAndAcknowledgementsSetting(),
YourRightsSetting(),
ExportBrowserDataSetting(settings: self),
ExportLogDataSetting(settings: self),
DeleteExportedDataSetting(settings: self),
ForceCrashSetting(settings: self),
SlowTheDatabase(settings: self),
ForgetSyncAuthStateDebugSetting(settings: self),
SentryIDSetting(settings: self),
ChangeToChinaSetting(settings: self),
ToggleOnboarding(settings: self),
LeanplumStatus(settings: self),
ShowEtpCoverSheet(settings: self),
ToggleOnboarding(settings: self),
LeanplumStatus(settings: self),
ClearOnboardingABVariables(settings: self)
])]
return settings
}
override func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
let headerView = super.tableView(tableView, viewForHeaderInSection: section) as! ThemedTableSectionHeaderFooterView
return headerView
}
}
| mpl-2.0 | 16975bec58b3a1b3dc03d64b24ae286e | 47.167742 | 178 | 0.657648 | 6.139803 | false | false | false | false |
linkedin/LayoutKit | ExampleLayouts/CircleImagePileLayout.swift | 1 | 2090 | // Copyright 2016 LinkedIn Corp.
// 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.
import UIKit
import LayoutKit
/// Displays a pile of overlapping circular images.
open class CircleImagePileLayout: StackLayout<CircleImagePileView> {
public enum Mode {
case leadingOnTop, trailingOnTop
}
public let mode: Mode
public init(imageNames: [String], mode: Mode = .trailingOnTop, alignment: Alignment = .topLeading, viewReuseId: String? = nil) {
self.mode = mode
let sublayouts: [Layout] = imageNames.map { imageName in
return SizeLayout<UIImageView>(width: 50, height: 50, config: { imageView in
imageView.image = UIImage(named: imageName)
imageView.layer.cornerRadius = 25
imageView.layer.masksToBounds = true
imageView.layer.borderColor = UIColor.white.cgColor
imageView.layer.borderWidth = 2
})
}
super.init(
axis: .horizontal,
spacing: -25,
distribution: .leading,
alignment: alignment,
flexibility: .inflexible,
viewReuseId: viewReuseId,
sublayouts: sublayouts)
}
open override var needsView: Bool {
return super.needsView || mode == .leadingOnTop
}
}
open class CircleImagePileView: UIView {
open override func addSubview(_ view: UIView) {
// Make sure views are inserted below existing views so that the first image in the face pile is on top.
if let lastSubview = subviews.last {
insertSubview(view, belowSubview: lastSubview)
} else {
super.addSubview(view)
}
}
}
| apache-2.0 | e0cb1ad93ebe526081314f80b75dd76f | 35.666667 | 132 | 0.647847 | 4.739229 | false | false | false | false |
Trevi-Swift/Trevi | Sources/OutgoingMessage.swift | 1 | 810 | //
// HttpStream.swift
// Trevi
//
// Created by LeeYoseob on 2016. 3. 3..
// Copyright © 2016 Trevi Community. All rights reserved.
//
import Foundation
// To be class parents who have the data for processing of response.
public class OutgoingMessage {
public var socket: Socket!
public var connection: Socket!
public var header: [String: String]!
public var shouldKeepAlive = false
public var chunkEncoding = false
public init(socket: AnyObject){
header = [String: String]()
}
deinit{
socket = nil
connection = nil
}
public func _end(data: NSData, encoding: Any! = nil){
self.socket.write(data, handle: self.socket.handle)
if shouldKeepAlive == false {
self.socket.close()
}
}
}
| apache-2.0 | 1deaa8f6caadecbb5d4f0f7fc26e82c4 | 21.472222 | 68 | 0.618047 | 4.170103 | false | false | false | false |
a2/Simon | Simon WatchKit App Extension/HighScoresInterfaceController.swift | 1 | 1205 | import Foundation
import WatchKit
class HighScoresInterfaceController: WKInterfaceController {
let dateFormatter: NSDateFormatter = {
let dateFormatter = NSDateFormatter()
dateFormatter.dateStyle = .ShortStyle
dateFormatter.locale = NSLocale.currentLocale()
dateFormatter.timeStyle = .NoStyle
return dateFormatter
}()
var scores: [HighScore]!
// MARK: - IBOutlets
@IBOutlet weak var table: WKInterfaceTable!
// MARK: View Life Cycle
override func awakeWithContext(context: AnyObject?) {
super.awakeWithContext(context)
let box = context as! Box<[HighScore]>
scores = box.value
table.setNumberOfRows(scores.count, withRowType: "highScore")
for (i, highScore) in scores.enumerate() {
let rowController = table.rowControllerAtIndex(i) as! HighScoreController
rowController.scoreLabel.setText(String.localizedStringWithFormat(NSLocalizedString("%d pts.", comment: "Score in points; {score} is replaced with the number of completed rounds"), highScore.score))
rowController.dateLabel.setText(dateFormatter.stringFromDate(highScore.date))
}
}
}
| mit | f112a0274eb3e5307b4a67cf55862f20 | 32.472222 | 210 | 0.695436 | 5.452489 | false | false | false | false |
bitboylabs/selluv-ios | selluv-ios/selluv-ios/Classes/Base/BBConstants.swift | 1 | 6464 | //
// BBConstants.swift
// bitboylabs-ios-base
//
// Created by 조백근 on 2016. 10. 18..
// Copyright © 2016년 BitBoy Labs. All rights reserved.
//
import Foundation
import UIKit
import XCGLogger
import SwiftyUserDefaults
import AlamofireImage
import SwiftHEXColors
//for log
let log = XCGLogger.default
/// for test !!!
let itunes_api_url: String = "https://itunes.apple.com/search"
let itunes_param_base: [String: AnyObject] = [
"country": "US" as AnyObject,
"lang": "en_us" as AnyObject,
"media": "music" as AnyObject,
"entity": "album" as AnyObject,
"limit": 100 as AnyObject
]
let empty: AnyObject = [:] as AnyObject
//잘은 모르지만 BBNetworkManager에서 사용하는 상수
let BBProjectName = "bitboylabs.project"
let SLV_URL = "http://api.selluv.com:3000"
//let SLV_URL = "http://52.79.81.3:3000"
//
let dnHost = "http://image.selluv.com:80/"
let dnAvatar = "\(dnHost)avatars/" //사용자 프로필 사진 및 배경 이미지, SNS 공유
let dnProduct = "\(dnHost)photos/" //상품 사진
let dnStyle = "\(dnHost)styles/" //스타일 사진
let dnDamage = "\(dnHost)damages/" //상품 하지 사진
let dnAccessory = "\(dnHost)accessories/" //상품 부속품 사진
let dnSign = "\(dnHost)signatures/" //서명 사진
let dnImage = "\(dnHost)images/" // Admin에서 업로드한 사진(배너, 이벤트 등)
let POST_REQUEST_KEY = "9815915a42c227fdc1483404447777"//우체국 open api 키
let KEY_IAMPORT_RESTAPI = "3966461868589664"
let KEY_IAMPORT_RESTAPI_SECRET = "mZaECL4VHGAajM1WEBKydn2pKNi5TjmfjwTViYR0ErbYecUTOEs22urMiJSc3frmMli5j95YBgWPtRJi"
public extension DefaultsKeys {
// App Token
static let isRegisterRemoteTokenKey = DefaultsKey<Bool?>("isRegisterRemoteTokenKey")
static let remoteTokenKey = DefaultsKey<String?>("remoteTokenKey")
static let permissionForCameraKey = DefaultsKey<Bool?>("permissionForCameraKey")
// 사이즈표 세팅여부
static let isClothingSizeConvetingInfoSetupKey = DefaultsKey<Bool?>("isClothingSizeConvetingInfoSetupKey")
//API서버와 통신에 사용
static let appTokenKey = DefaultsKey<String?>("appTokenKey")
static let appUserNameKey = DefaultsKey<String?>("appUserNameKey")
static let isAppAccessedServerKey = DefaultsKey<Bool?>("isAppAccessedServerKey")
//임시저장목록
static let inputDataSaveListKey = DefaultsKey<String?>("inputDataSaveListKey")
}
//MARK : 화면제어에 필요한 수치상수
internal let Noti = NotificationCenter.default
internal let App = UIApplication.shared
let appDelegate = App.delegate as! AppDelegate
let tabController = appDelegate.window?.rootViewController as! SLVTabBarController
let tabHeight = tabController.tabBar.frame.size.height //하단 공통 탭바 높이(아마도 49?)
//MARK : 컨텐츠 제어에 필요한 상수
var categoryTree: TreeNode<Category>?
let SIZE_KR = "KR"
let SIZE_EU = "EU"
let SIZE_US_UK = "US/UK"
let SIZE_ROMAN_123 = "I/II/III"
let SIZE_IT = "IT"
let SIZE_INCH = "Inch"
let SIZE_US = "US"
let SIZE_UK = "UK"
let SIZE_KOR = "KOR"
let SIZE_AGE = "연령"
let SIZE_MM = "mm"
//MARK : 사진관련
let SLV_SELL_PHOTO_DIR = "SelluvSellItemPhoto"
let DEFAULT_PHOTO_SIZE = CGSize(width: 720, height: 1280)
//MARK: 행정자치부 도로명주소 안내 오픈 api 키
let JUSO_API_SEARCH_ADDRESS_KEY = "U01TX0FVVEgyMDE3MDEwMzE3NDkyNDE3OTMz"
//MARK: NAVER 로그인
let NaverClientId = "Khgw7OI4mtNP47Hv9Jwq"
let NaverClientSecret = "K94EMljc5Q"
let NaverScheme = "com.selluv.ios"
//MARK: 텍스트 컬러
let text_color_bl51 = UIColor(colorLiteralRed: 51/255, green: 51/255, blue: 51/255, alpha: 1.0)
let text_color_g85 = UIColor(colorLiteralRed: 85/255, green: 85/255, blue: 85/255, alpha: 1.0)
let text_color_g204 = UIColor(colorLiteralRed: 204/255, green: 204/255, blue: 204/255, alpha: 1.0)
let text_color_g153 = UIColor(colorLiteralRed: 153/255, green: 153/255, blue: 153/255, alpha: 1.0)
let text_color_blue = UIColor(colorLiteralRed: 57/255, green: 90/255, blue: 128/255, alpha: 1.0)
let text_color_gold = UIColor(colorLiteralRed: 204/255, green: 177/255, blue: 119/255, alpha: 1.0)
let text_color_g181 = UIColor(colorLiteralRed: 181/255, green: 181/255, blue: 185/255, alpha: 1.0)
//MARK: 배경색
let bg_color_g245 = UIColor(colorLiteralRed: 245/255, green: 245/255, blue: 250/255, alpha: 1.0)
let bg_color_brass = UIColor(colorLiteralRed: 204/255, green: 177/255, blue: 119/255, alpha: 1.0)
let bg_color_step = UIColor(colorLiteralRed: 194/255, green: 233/255, blue: 254/255, alpha: 1.0)
let bg_color_blue = UIColor(colorLiteralRed: 45/255, green: 129/255, blue: 255/255, alpha: 1.0)
let bg_color_gline = UIColor(colorLiteralRed: 183/255, green: 188/255, blue: 203/255, alpha: 1.0)
let bg_color_pink = UIColor(colorLiteralRed: 236/255, green: 95/255, blue: 120/255, alpha: 1.0)//핑크
//MARK: Degree for rotate Animation
let d90 = CGFloat(0)
let d180 = CGFloat(M_PI)
let d360 = CGFloat(M_PI * 2)
//MARK: 판매 단계 스텝 값
//0.03, 0.12, 0.25, 0.36, 0.48
let sell_step_1_value = 0.03
let sell_step_2_value = 0.13
let sell_step_3_value = 0.25
let sell_step_4_value = 0.36
let sell_step_5_value = 0.48
//MARK: 판매 추가입력 컬러값
let additional_select_color_black = UIColor(hexString:"000000")//블랙
let additional_select_color_gray = UIColor(hexString:"c2c2c2")//그레이
let additional_select_color_white = UIColor(hexString:"ffffff")//화이트
let additional_select_color_white_border = UIColor(hexString:"555555")//화이트 보더라인
let additional_select_color_beige = UIColor(hexString:"ece7b7")//베이지
let additional_select_color_red = UIColor(hexString:"ed1232")//레드
let additional_select_color_pink = UIColor(hexString:"ff6ba3")//핑크
let additional_select_color_blue = UIColor(hexString:"4e92e0")//블루
let additional_select_color_green = UIColor(hexString:"81d235")//그린
let additional_select_color_yellow = UIColor(hexString:"f8e73b")//-- 옐로우
let additional_select_color_orange = UIColor(hexString:"f4a536")// 오렌지
let additional_select_color_purple = UIColor(hexString:"ba55d3")//퍼플
let additional_select_color_brown = UIColor(hexString:"87532b")//브라운
let additional_select_color_gold = UIColor(hexString:"e5ce61")// 골드
//MARK: JPEG 압축시 손실율.
let CompressionQuality: CGFloat = 1.0
//MARK
public enum GenderType {
case men
case women
case kid
}
| mit | 979d900a9c8532df24a9b88985d9e1fb | 35.393939 | 115 | 0.720733 | 2.851377 | false | false | false | false |
KlubJagiellonski/pola-ios | BuyPolish/PolaUITests/PageObjects/BasePage.swift | 1 | 1097 | import XCTest
class BasePage {
let app: XCUIApplication
var waitForExistanceTimeout = TimeInterval(10)
var pasteboard: String? {
get {
UIPasteboard.general.strings?.first
}
set {
UIPasteboard.general.strings = newValue != nil ? [newValue!] : []
}
}
init(app: XCUIApplication) {
self.app = app
}
func done() {}
func setPasteboard(_ pasteboard: String?) -> Self {
self.pasteboard = pasteboard
return self
}
func waitForPasteboardInfoDissappear(file: StaticString = #file, line: UInt = #line) -> Self {
let elements = [
"Pola pasted from PolaUITests-Runner",
"CoreSimulatorBridge pasted from Pola",
].map { app.staticTexts[$0] }
if !elements.waitForDisappear(timeout: waitForExistanceTimeout) {
XCTFail("Pasteboard info still visible", file: file, line: line)
}
return self
}
func wait(time: TimeInterval) -> Self {
Thread.sleep(forTimeInterval: time)
return self
}
}
| gpl-2.0 | 1b408d639128aa92045565b5123961db | 24.511628 | 98 | 0.587967 | 4.589958 | false | false | false | false |
brave/browser-ios | AlertPopupView.swift | 1 | 3734 | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
import UIKit
class AlertPopupView: PopupView {
fileprivate var dialogImage: UIImageView?
fileprivate var titleLabel: UILabel!
fileprivate var messageLabel: UILabel!
fileprivate var containerView: UIView!
fileprivate let kAlertPopupScreenFraction: CGFloat = 0.8
fileprivate let kPadding: CGFloat = 20.0
init(image: UIImage?, title: String, message: String) {
super.init(frame: CGRect.zero)
overlayDismisses = false
defaultShowType = .normal
defaultDismissType = .noAnimation
presentsOverWindow = true
containerView = UIView(frame: CGRect.zero)
containerView.autoresizingMask = [.flexibleWidth]
if let image = image {
let di = UIImageView(image: image)
containerView.addSubview(di)
dialogImage = di
}
titleLabel = UILabel(frame: CGRect.zero)
titleLabel.textColor = UIColor.black
titleLabel.textAlignment = .center
titleLabel.font = UIFont.systemFont(ofSize: 24, weight: UIFont.Weight.bold)
titleLabel.text = title
titleLabel.numberOfLines = 0
containerView.addSubview(titleLabel)
messageLabel = UILabel(frame: CGRect.zero)
messageLabel.textColor = UIColor(rgb: 0x696969)
messageLabel.textAlignment = .center
messageLabel.font = UIFont.systemFont(ofSize: 15, weight: UIFont.Weight.regular)
messageLabel.text = message
messageLabel.numberOfLines = 0
containerView.addSubview(messageLabel)
updateSubviews()
setPopupContentView(view: containerView)
setStyle(popupStyle: .dialog)
setDialogColor(color: BraveUX.PopupDialogColorLight)
}
func updateSubviews() {
let width: CGFloat = dialogWidth
var imageFrame: CGRect = dialogImage?.frame ?? CGRect.zero
if let dialogImage = dialogImage {
imageFrame.origin.x = (width - imageFrame.width) / 2.0
imageFrame.origin.y = kPadding * 2.0
dialogImage.frame = imageFrame
}
let titleLabelSize: CGSize = titleLabel.sizeThatFits(CGSize(width: width - kPadding * 4.0, height: CGFloat.greatestFiniteMagnitude))
var titleLabelFrame: CGRect = titleLabel.frame
titleLabelFrame.size = titleLabelSize
titleLabelFrame.origin.x = rint((width - titleLabelSize.width) / 2.0)
titleLabelFrame.origin.y = imageFrame.maxY + kPadding
titleLabel.frame = titleLabelFrame
let messageLabelSize: CGSize = messageLabel.sizeThatFits(CGSize(width: width - kPadding * 4.0, height: CGFloat.greatestFiniteMagnitude))
var messageLabelFrame: CGRect = messageLabel.frame
messageLabelFrame.size = messageLabelSize
messageLabelFrame.origin.x = rint((width - messageLabelSize.width) / 2.0)
messageLabelFrame.origin.y = rint(titleLabelFrame.maxY + kPadding / 2.0)
messageLabel.frame = messageLabelFrame
var containerViewFrame: CGRect = containerView.frame
containerViewFrame.size.width = width
containerViewFrame.size.height = messageLabelFrame.maxY + kPadding
containerView.frame = containerViewFrame
}
override func layoutSubviews() {
super.layoutSubviews()
updateSubviews()
}
required init(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
| mpl-2.0 | 672665fb4c62b73a00e11bb3f4adb9cb | 37.895833 | 144 | 0.657472 | 5.171745 | false | false | false | false |
brave/browser-ios | ThirdParty/SQLiteSwift/Sources/SQLite/Typed/Query.swift | 9 | 36689 | //
// SQLite.swift
// https://github.com/stephencelis/SQLite.swift
// Copyright © 2014-2015 Stephen Celis.
//
// 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 protocol QueryType : Expressible {
var clauses: QueryClauses { get set }
init(_ name: String, database: String?)
}
public protocol SchemaType : QueryType {
static var identifier: String { get }
}
extension SchemaType {
/// Builds a copy of the query with the `SELECT` clause applied.
///
/// let users = Table("users")
/// let id = Expression<Int64>("id")
/// let email = Expression<String>("email")
///
/// users.select(id, email)
/// // SELECT "id", "email" FROM "users"
///
/// - Parameter all: A list of expressions to select.
///
/// - Returns: A query with the given `SELECT` clause applied.
public func select(_ column1: Expressible, _ more: Expressible...) -> Self {
return select(false, [column1] + more)
}
/// Builds a copy of the query with the `SELECT DISTINCT` clause applied.
///
/// let users = Table("users")
/// let email = Expression<String>("email")
///
/// users.select(distinct: email)
/// // SELECT DISTINCT "email" FROM "users"
///
/// - Parameter columns: A list of expressions to select.
///
/// - Returns: A query with the given `SELECT DISTINCT` clause applied.
public func select(distinct column1: Expressible, _ more: Expressible...) -> Self {
return select(true, [column1] + more)
}
/// Builds a copy of the query with the `SELECT` clause applied.
///
/// let users = Table("users")
/// let id = Expression<Int64>("id")
/// let email = Expression<String>("email")
///
/// users.select([id, email])
/// // SELECT "id", "email" FROM "users"
///
/// - Parameter all: A list of expressions to select.
///
/// - Returns: A query with the given `SELECT` clause applied.
public func select(_ all: [Expressible]) -> Self {
return select(false, all)
}
/// Builds a copy of the query with the `SELECT DISTINCT` clause applied.
///
/// let users = Table("users")
/// let email = Expression<String>("email")
///
/// users.select(distinct: [email])
/// // SELECT DISTINCT "email" FROM "users"
///
/// - Parameter columns: A list of expressions to select.
///
/// - Returns: A query with the given `SELECT DISTINCT` clause applied.
public func select(distinct columns: [Expressible]) -> Self {
return select(true, columns)
}
/// Builds a copy of the query with the `SELECT *` clause applied.
///
/// let users = Table("users")
///
/// users.select(*)
/// // SELECT * FROM "users"
///
/// - Parameter star: A star literal.
///
/// - Returns: A query with the given `SELECT *` clause applied.
public func select(_ star: Star) -> Self {
return select([star(nil, nil)])
}
/// Builds a copy of the query with the `SELECT DISTINCT *` clause applied.
///
/// let users = Table("users")
///
/// users.select(distinct: *)
/// // SELECT DISTINCT * FROM "users"
///
/// - Parameter star: A star literal.
///
/// - Returns: A query with the given `SELECT DISTINCT *` clause applied.
public func select(distinct star: Star) -> Self {
return select(distinct: [star(nil, nil)])
}
/// Builds a scalar copy of the query with the `SELECT` clause applied.
///
/// let users = Table("users")
/// let id = Expression<Int64>("id")
///
/// users.select(id)
/// // SELECT "id" FROM "users"
///
/// - Parameter all: A list of expressions to select.
///
/// - Returns: A query with the given `SELECT` clause applied.
public func select<V : Value>(_ column: Expression<V>) -> ScalarQuery<V> {
return select(false, [column])
}
public func select<V : Value>(_ column: Expression<V?>) -> ScalarQuery<V?> {
return select(false, [column])
}
/// Builds a scalar copy of the query with the `SELECT DISTINCT` clause
/// applied.
///
/// let users = Table("users")
/// let email = Expression<String>("email")
///
/// users.select(distinct: email)
/// // SELECT DISTINCT "email" FROM "users"
///
/// - Parameter column: A list of expressions to select.
///
/// - Returns: A query with the given `SELECT DISTINCT` clause applied.
public func select<V : Value>(distinct column: Expression<V>) -> ScalarQuery<V> {
return select(true, [column])
}
public func select<V : Value>(distinct column: Expression<V?>) -> ScalarQuery<V?> {
return select(true, [column])
}
public var count: ScalarQuery<Int> {
return select(Expression.count(*))
}
}
extension QueryType {
fileprivate func select<Q : QueryType>(_ distinct: Bool, _ columns: [Expressible]) -> Q {
var query = Q.init(clauses.from.name, database: clauses.from.database)
query.clauses = clauses
query.clauses.select = (distinct, columns)
return query
}
// MARK: UNION
/// Adds a `UNION` clause to the query.
///
/// let users = Table("users")
/// let email = Expression<String>("email")
///
/// users.filter(email == "[email protected]").union(users.filter(email == "[email protected]"))
/// // SELECT * FROM "users" WHERE email = '[email protected]' UNION SELECT * FROM "users" WHERE email = '[email protected]'
///
/// - Parameters:
///
/// - table: A query representing the other table.
///
/// - Returns: A query with the given `UNION` clause applied.
public func union(_ table: QueryType) -> Self {
var query = self
query.clauses.union.append(table)
return query
}
// MARK: JOIN
/// Adds a `JOIN` clause to the query.
///
/// let users = Table("users")
/// let id = Expression<Int64>("id")
/// let posts = Table("posts")
/// let userId = Expression<Int64>("user_id")
///
/// users.join(posts, on: posts[userId] == users[id])
/// // SELECT * FROM "users" INNER JOIN "posts" ON ("posts"."user_id" = "users"."id")
///
/// - Parameters:
///
/// - table: A query representing the other table.
///
/// - condition: A boolean expression describing the join condition.
///
/// - Returns: A query with the given `JOIN` clause applied.
public func join(_ table: QueryType, on condition: Expression<Bool>) -> Self {
return join(table, on: Expression<Bool?>(condition))
}
/// Adds a `JOIN` clause to the query.
///
/// let users = Table("users")
/// let id = Expression<Int64>("id")
/// let posts = Table("posts")
/// let userId = Expression<Int64?>("user_id")
///
/// users.join(posts, on: posts[userId] == users[id])
/// // SELECT * FROM "users" INNER JOIN "posts" ON ("posts"."user_id" = "users"."id")
///
/// - Parameters:
///
/// - table: A query representing the other table.
///
/// - condition: A boolean expression describing the join condition.
///
/// - Returns: A query with the given `JOIN` clause applied.
public func join(_ table: QueryType, on condition: Expression<Bool?>) -> Self {
return join(.inner, table, on: condition)
}
/// Adds a `JOIN` clause to the query.
///
/// let users = Table("users")
/// let id = Expression<Int64>("id")
/// let posts = Table("posts")
/// let userId = Expression<Int64>("user_id")
///
/// users.join(.LeftOuter, posts, on: posts[userId] == users[id])
/// // SELECT * FROM "users" LEFT OUTER JOIN "posts" ON ("posts"."user_id" = "users"."id")
///
/// - Parameters:
///
/// - type: The `JOIN` operator.
///
/// - table: A query representing the other table.
///
/// - condition: A boolean expression describing the join condition.
///
/// - Returns: A query with the given `JOIN` clause applied.
public func join(_ type: JoinType, _ table: QueryType, on condition: Expression<Bool>) -> Self {
return join(type, table, on: Expression<Bool?>(condition))
}
/// Adds a `JOIN` clause to the query.
///
/// let users = Table("users")
/// let id = Expression<Int64>("id")
/// let posts = Table("posts")
/// let userId = Expression<Int64?>("user_id")
///
/// users.join(.LeftOuter, posts, on: posts[userId] == users[id])
/// // SELECT * FROM "users" LEFT OUTER JOIN "posts" ON ("posts"."user_id" = "users"."id")
///
/// - Parameters:
///
/// - type: The `JOIN` operator.
///
/// - table: A query representing the other table.
///
/// - condition: A boolean expression describing the join condition.
///
/// - Returns: A query with the given `JOIN` clause applied.
public func join(_ type: JoinType, _ table: QueryType, on condition: Expression<Bool?>) -> Self {
var query = self
query.clauses.join.append((type: type, query: table, condition: table.clauses.filters.map { condition && $0 } ?? condition as Expressible))
return query
}
// MARK: WHERE
/// Adds a condition to the query’s `WHERE` clause.
///
/// let users = Table("users")
/// let id = Expression<Int64>("id")
///
/// users.filter(id == 1)
/// // SELECT * FROM "users" WHERE ("id" = 1)
///
/// - Parameter condition: A boolean expression to filter on.
///
/// - Returns: A query with the given `WHERE` clause applied.
public func filter(_ predicate: Expression<Bool>) -> Self {
return filter(Expression<Bool?>(predicate))
}
/// Adds a condition to the query’s `WHERE` clause.
///
/// let users = Table("users")
/// let age = Expression<Int?>("age")
///
/// users.filter(age >= 35)
/// // SELECT * FROM "users" WHERE ("age" >= 35)
///
/// - Parameter condition: A boolean expression to filter on.
///
/// - Returns: A query with the given `WHERE` clause applied.
public func filter(_ predicate: Expression<Bool?>) -> Self {
var query = self
query.clauses.filters = query.clauses.filters.map { $0 && predicate } ?? predicate
return query
}
/// Adds a condition to the query’s `WHERE` clause.
/// This is an alias for `filter(predicate)`
public func `where`(_ predicate: Expression<Bool>) -> Self {
return `where`(Expression<Bool?>(predicate))
}
/// Adds a condition to the query’s `WHERE` clause.
/// This is an alias for `filter(predicate)`
public func `where`(_ predicate: Expression<Bool?>) -> Self {
return filter(predicate)
}
// MARK: GROUP BY
/// Sets a `GROUP BY` clause on the query.
///
/// - Parameter by: A list of columns to group by.
///
/// - Returns: A query with the given `GROUP BY` clause applied.
public func group(_ by: Expressible...) -> Self {
return group(by)
}
/// Sets a `GROUP BY` clause on the query.
///
/// - Parameter by: A list of columns to group by.
///
/// - Returns: A query with the given `GROUP BY` clause applied.
public func group(_ by: [Expressible]) -> Self {
return group(by, nil)
}
/// Sets a `GROUP BY`-`HAVING` clause on the query.
///
/// - Parameters:
///
/// - by: A column to group by.
///
/// - having: A condition determining which groups are returned.
///
/// - Returns: A query with the given `GROUP BY`–`HAVING` clause applied.
public func group(_ by: Expressible, having: Expression<Bool>) -> Self {
return group([by], having: having)
}
/// Sets a `GROUP BY`-`HAVING` clause on the query.
///
/// - Parameters:
///
/// - by: A column to group by.
///
/// - having: A condition determining which groups are returned.
///
/// - Returns: A query with the given `GROUP BY`–`HAVING` clause applied.
public func group(_ by: Expressible, having: Expression<Bool?>) -> Self {
return group([by], having: having)
}
/// Sets a `GROUP BY`-`HAVING` clause on the query.
///
/// - Parameters:
///
/// - by: A list of columns to group by.
///
/// - having: A condition determining which groups are returned.
///
/// - Returns: A query with the given `GROUP BY`–`HAVING` clause applied.
public func group(_ by: [Expressible], having: Expression<Bool>) -> Self {
return group(by, Expression<Bool?>(having))
}
/// Sets a `GROUP BY`-`HAVING` clause on the query.
///
/// - Parameters:
///
/// - by: A list of columns to group by.
///
/// - having: A condition determining which groups are returned.
///
/// - Returns: A query with the given `GROUP BY`–`HAVING` clause applied.
public func group(_ by: [Expressible], having: Expression<Bool?>) -> Self {
return group(by, having)
}
fileprivate func group(_ by: [Expressible], _ having: Expression<Bool?>?) -> Self {
var query = self
query.clauses.group = (by, having)
return query
}
// MARK: ORDER BY
/// Sets an `ORDER BY` clause on the query.
///
/// let users = Table("users")
/// let email = Expression<String>("email")
/// let name = Expression<String?>("name")
///
/// users.order(email.desc, name.asc)
/// // SELECT * FROM "users" ORDER BY "email" DESC, "name" ASC
///
/// - Parameter by: An ordered list of columns and directions to sort by.
///
/// - Returns: A query with the given `ORDER BY` clause applied.
public func order(_ by: Expressible...) -> Self {
return order(by)
}
/// Sets an `ORDER BY` clause on the query.
///
/// let users = Table("users")
/// let email = Expression<String>("email")
/// let name = Expression<String?>("name")
///
/// users.order([email.desc, name.asc])
/// // SELECT * FROM "users" ORDER BY "email" DESC, "name" ASC
///
/// - Parameter by: An ordered list of columns and directions to sort by.
///
/// - Returns: A query with the given `ORDER BY` clause applied.
public func order(_ by: [Expressible]) -> Self {
var query = self
query.clauses.order = by
return query
}
// MARK: LIMIT/OFFSET
/// Sets the LIMIT clause (and resets any OFFSET clause) on the query.
///
/// let users = Table("users")
///
/// users.limit(20)
/// // SELECT * FROM "users" LIMIT 20
///
/// - Parameter length: The maximum number of rows to return (or `nil` to
/// return unlimited rows).
///
/// - Returns: A query with the given LIMIT clause applied.
public func limit(_ length: Int?) -> Self {
return limit(length, nil)
}
/// Sets LIMIT and OFFSET clauses on the query.
///
/// let users = Table("users")
///
/// users.limit(20, offset: 20)
/// // SELECT * FROM "users" LIMIT 20 OFFSET 20
///
/// - Parameters:
///
/// - length: The maximum number of rows to return.
///
/// - offset: The number of rows to skip.
///
/// - Returns: A query with the given LIMIT and OFFSET clauses applied.
public func limit(_ length: Int, offset: Int) -> Self {
return limit(length, offset)
}
// prevents limit(nil, offset: 5)
fileprivate func limit(_ length: Int?, _ offset: Int?) -> Self {
var query = self
query.clauses.limit = length.map { ($0, offset) }
return query
}
// MARK: - Clauses
//
// MARK: SELECT
// MARK: -
fileprivate var selectClause: Expressible {
return " ".join([
Expression<Void>(literal: clauses.select.distinct ? "SELECT DISTINCT" : "SELECT"),
", ".join(clauses.select.columns),
Expression<Void>(literal: "FROM"),
tableName(alias: true)
])
}
fileprivate var joinClause: Expressible? {
guard !clauses.join.isEmpty else {
return nil
}
return " ".join(clauses.join.map { arg in
let (type, query, condition) = arg
return " ".join([
Expression<Void>(literal: "\(type.rawValue) JOIN"),
query.tableName(alias: true),
Expression<Void>(literal: "ON"),
condition
])
})
}
fileprivate var whereClause: Expressible? {
guard let filters = clauses.filters else {
return nil
}
return " ".join([
Expression<Void>(literal: "WHERE"),
filters
])
}
fileprivate var groupByClause: Expressible? {
guard let group = clauses.group else {
return nil
}
let groupByClause = " ".join([
Expression<Void>(literal: "GROUP BY"),
", ".join(group.by)
])
guard let having = group.having else {
return groupByClause
}
return " ".join([
groupByClause,
" ".join([
Expression<Void>(literal: "HAVING"),
having
])
])
}
fileprivate var orderClause: Expressible? {
guard !clauses.order.isEmpty else {
return nil
}
return " ".join([
Expression<Void>(literal: "ORDER BY"),
", ".join(clauses.order)
])
}
fileprivate var limitOffsetClause: Expressible? {
guard let limit = clauses.limit else {
return nil
}
let limitClause = Expression<Void>(literal: "LIMIT \(limit.length)")
guard let offset = limit.offset else {
return limitClause
}
return " ".join([
limitClause,
Expression<Void>(literal: "OFFSET \(offset)")
])
}
fileprivate var unionClause: Expressible? {
guard !clauses.union.isEmpty else {
return nil
}
return " ".join(clauses.union.map { query in
" ".join([
Expression<Void>(literal: "UNION"),
query
])
})
}
// MARK: -
public func alias(_ aliasName: String) -> Self {
var query = self
query.clauses.from = (clauses.from.name, aliasName, clauses.from.database)
return query
}
// MARK: - Operations
//
// MARK: INSERT
public func insert(_ value: Setter, _ more: Setter...) -> Insert {
return insert([value] + more)
}
public func insert(_ values: [Setter]) -> Insert {
return insert(nil, values)
}
public func insert(or onConflict: OnConflict, _ values: Setter...) -> Insert {
return insert(or: onConflict, values)
}
public func insert(or onConflict: OnConflict, _ values: [Setter]) -> Insert {
return insert(onConflict, values)
}
fileprivate func insert(_ or: OnConflict?, _ values: [Setter]) -> Insert {
let insert = values.reduce((columns: [Expressible](), values: [Expressible]())) { insert, setter in
(insert.columns + [setter.column], insert.values + [setter.value])
}
let clauses: [Expressible?] = [
Expression<Void>(literal: "INSERT"),
or.map { Expression<Void>(literal: "OR \($0.rawValue)") },
Expression<Void>(literal: "INTO"),
tableName(),
"".wrap(insert.columns) as Expression<Void>,
Expression<Void>(literal: "VALUES"),
"".wrap(insert.values) as Expression<Void>,
whereClause
]
return Insert(" ".join(clauses.compactMap { $0 }).expression)
}
/// Runs an `INSERT` statement against the query with `DEFAULT VALUES`.
public func insert() -> Insert {
return Insert(" ".join([
Expression<Void>(literal: "INSERT INTO"),
tableName(),
Expression<Void>(literal: "DEFAULT VALUES")
]).expression)
}
/// Runs an `INSERT` statement against the query with the results of another
/// query.
///
/// - Parameter query: A query to `SELECT` results from.
///
/// - Returns: The number of updated rows and statement.
public func insert(_ query: QueryType) -> Update {
return Update(" ".join([
Expression<Void>(literal: "INSERT INTO"),
tableName(),
query.expression
]).expression)
}
// MARK: UPDATE
public func update(_ values: Setter...) -> Update {
return update(values)
}
public func update(_ values: [Setter]) -> Update {
let clauses: [Expressible?] = [
Expression<Void>(literal: "UPDATE"),
tableName(),
Expression<Void>(literal: "SET"),
", ".join(values.map { " = ".join([$0.column, $0.value]) }),
whereClause,
orderClause,
limitOffsetClause
]
return Update(" ".join(clauses.compactMap { $0 }).expression)
}
// MARK: DELETE
public func delete() -> Delete {
let clauses: [Expressible?] = [
Expression<Void>(literal: "DELETE FROM"),
tableName(),
whereClause,
orderClause,
limitOffsetClause
]
return Delete(" ".join(clauses.compactMap { $0 }).expression)
}
// MARK: EXISTS
public var exists: Select<Bool> {
return Select(" ".join([
Expression<Void>(literal: "SELECT EXISTS"),
"".wrap(expression) as Expression<Void>
]).expression)
}
// MARK: -
/// Prefixes a column expression with the query’s table name or alias.
///
/// - Parameter column: A column expression.
///
/// - Returns: A column expression namespaced with the query’s table name or
/// alias.
public func namespace<V>(_ column: Expression<V>) -> Expression<V> {
return Expression(".".join([tableName(), column]).expression)
}
public subscript<T>(column: Expression<T>) -> Expression<T> {
return namespace(column)
}
public subscript<T>(column: Expression<T?>) -> Expression<T?> {
return namespace(column)
}
/// Prefixes a star with the query’s table name or alias.
///
/// - Parameter star: A literal `*`.
///
/// - Returns: A `*` expression namespaced with the query’s table name or
/// alias.
public subscript(star: Star) -> Expression<Void> {
return namespace(star(nil, nil))
}
// MARK: -
// TODO: alias support
func tableName(alias aliased: Bool = false) -> Expressible {
guard let alias = clauses.from.alias , aliased else {
return database(namespace: clauses.from.alias ?? clauses.from.name)
}
return " ".join([
database(namespace: clauses.from.name),
Expression<Void>(literal: "AS"),
Expression<Void>(alias)
])
}
func tableName(qualified: Bool) -> Expressible {
if qualified {
return tableName()
}
return Expression<Void>(clauses.from.alias ?? clauses.from.name)
}
func database(namespace name: String) -> Expressible {
let name = Expression<Void>(name)
guard let database = clauses.from.database else {
return name
}
return ".".join([Expression<Void>(database), name])
}
public var expression: Expression<Void> {
let clauses: [Expressible?] = [
selectClause,
joinClause,
whereClause,
groupByClause,
unionClause,
orderClause,
limitOffsetClause
]
return " ".join(clauses.compactMap { $0 }).expression
}
}
// TODO: decide: simplify the below with a boxed type instead
/// Queries a collection of chainable helper functions and expressions to build
/// executable SQL statements.
public struct Table : SchemaType {
public static let identifier = "TABLE"
public var clauses: QueryClauses
public init(_ name: String, database: String? = nil) {
clauses = QueryClauses(name, alias: nil, database: database)
}
}
public struct View : SchemaType {
public static let identifier = "VIEW"
public var clauses: QueryClauses
public init(_ name: String, database: String? = nil) {
clauses = QueryClauses(name, alias: nil, database: database)
}
}
public struct VirtualTable : SchemaType {
public static let identifier = "VIRTUAL TABLE"
public var clauses: QueryClauses
public init(_ name: String, database: String? = nil) {
clauses = QueryClauses(name, alias: nil, database: database)
}
}
// TODO: make `ScalarQuery` work in `QueryType.select()`, `.filter()`, etc.
public struct ScalarQuery<V> : QueryType {
public var clauses: QueryClauses
public init(_ name: String, database: String? = nil) {
clauses = QueryClauses(name, alias: nil, database: database)
}
}
// TODO: decide: simplify the below with a boxed type instead
public struct Select<T> : ExpressionType {
public var template: String
public var bindings: [Binding?]
public init(_ template: String, _ bindings: [Binding?]) {
self.template = template
self.bindings = bindings
}
}
public struct Insert : ExpressionType {
public var template: String
public var bindings: [Binding?]
public init(_ template: String, _ bindings: [Binding?]) {
self.template = template
self.bindings = bindings
}
}
public struct Update : ExpressionType {
public var template: String
public var bindings: [Binding?]
public init(_ template: String, _ bindings: [Binding?]) {
self.template = template
self.bindings = bindings
}
}
public struct Delete : ExpressionType {
public var template: String
public var bindings: [Binding?]
public init(_ template: String, _ bindings: [Binding?]) {
self.template = template
self.bindings = bindings
}
}
public struct RowIterator: FailableIterator {
public typealias Element = Row
let statement: Statement
let columnNames: [String: Int]
public func failableNext() throws -> Row? {
return try statement.failableNext().flatMap { Row(columnNames, $0) }
}
public func map<T>(_ transform: (Element) throws -> T) throws -> [T] {
var elements = [T]()
while let row = try failableNext() {
elements.append(try transform(row))
}
return elements
}
}
extension Connection {
public func prepare(_ query: QueryType) throws -> AnySequence<Row> {
let expression = query.expression
let statement = try prepare(expression.template, expression.bindings)
let columnNames = try columnNamesForQuery(query)
return AnySequence {
AnyIterator { statement.next().map { Row(columnNames, $0) } }
}
}
public func prepareRowIterator(_ query: QueryType) throws -> RowIterator {
let expression = query.expression
let statement = try prepare(expression.template, expression.bindings)
return RowIterator(statement: statement, columnNames: try columnNamesForQuery(query))
}
private func columnNamesForQuery(_ query: QueryType) throws -> [String: Int] {
var (columnNames, idx) = ([String: Int](), 0)
column: for each in query.clauses.select.columns {
var names = each.expression.template.split { $0 == "." }.map(String.init)
let column = names.removeLast()
let namespace = names.joined(separator: ".")
func expandGlob(_ namespace: Bool) -> ((QueryType) throws -> Void) {
return { (query: QueryType) throws -> (Void) in
var q = type(of: query).init(query.clauses.from.name, database: query.clauses.from.database)
q.clauses.select = query.clauses.select
let e = q.expression
var names = try self.prepare(e.template, e.bindings).columnNames.map { $0.quote() }
if namespace { names = names.map { "\(query.tableName().expression.template).\($0)" } }
for name in names { columnNames[name] = idx; idx += 1 }
}
}
if column == "*" {
var select = query
select.clauses.select = (false, [Expression<Void>(literal: "*") as Expressible])
let queries = [select] + query.clauses.join.map { $0.query }
if !namespace.isEmpty {
for q in queries {
if q.tableName().expression.template == namespace {
try expandGlob(true)(q)
continue column
}
throw QueryError.noSuchTable(name: namespace)
}
throw QueryError.noSuchTable(name: namespace)
}
for q in queries {
try expandGlob(query.clauses.join.count > 0)(q)
}
continue
}
columnNames[each.expression.template] = idx
idx += 1
}
return columnNames
}
public func scalar<V : Value>(_ query: ScalarQuery<V>) throws -> V {
let expression = query.expression
return value(try scalar(expression.template, expression.bindings))
}
public func scalar<V : Value>(_ query: ScalarQuery<V?>) throws -> V.ValueType? {
let expression = query.expression
guard let value = try scalar(expression.template, expression.bindings) as? V.Datatype else { return nil }
return V.fromDatatypeValue(value)
}
public func scalar<V : Value>(_ query: Select<V>) throws -> V {
let expression = query.expression
return value(try scalar(expression.template, expression.bindings))
}
public func scalar<V : Value>(_ query: Select<V?>) throws -> V.ValueType? {
let expression = query.expression
guard let value = try scalar(expression.template, expression.bindings) as? V.Datatype else { return nil }
return V.fromDatatypeValue(value)
}
public func pluck(_ query: QueryType) throws -> Row? {
return try prepareRowIterator(query.limit(1, query.clauses.limit?.offset)).failableNext()
}
/// Runs an `Insert` query.
///
/// - SeeAlso: `QueryType.insert(value:_:)`
/// - SeeAlso: `QueryType.insert(values:)`
/// - SeeAlso: `QueryType.insert(or:_:)`
/// - SeeAlso: `QueryType.insert()`
///
/// - Parameter query: An insert query.
///
/// - Returns: The insert’s rowid.
@discardableResult public func run(_ query: Insert) throws -> Int64 {
let expression = query.expression
return try sync {
try self.run(expression.template, expression.bindings)
return self.lastInsertRowid
}
}
/// Runs an `Update` query.
///
/// - SeeAlso: `QueryType.insert(query:)`
/// - SeeAlso: `QueryType.update(values:)`
///
/// - Parameter query: An update query.
///
/// - Returns: The number of updated rows.
@discardableResult public func run(_ query: Update) throws -> Int {
let expression = query.expression
return try sync {
try self.run(expression.template, expression.bindings)
return self.changes
}
}
/// Runs a `Delete` query.
///
/// - SeeAlso: `QueryType.delete()`
///
/// - Parameter query: A delete query.
///
/// - Returns: The number of deleted rows.
@discardableResult public func run(_ query: Delete) throws -> Int {
let expression = query.expression
return try sync {
try self.run(expression.template, expression.bindings)
return self.changes
}
}
}
public struct Row {
let columnNames: [String: Int]
fileprivate let values: [Binding?]
internal init(_ columnNames: [String: Int], _ values: [Binding?]) {
self.columnNames = columnNames
self.values = values
}
func hasValue(for column: String) -> Bool {
guard let idx = columnNames[column.quote()] else {
return false
}
return values[idx] != nil
}
/// Returns a row’s value for the given column.
///
/// - Parameter column: An expression representing a column selected in a Query.
///
/// - Returns: The value for the given column.
public func get<V: Value>(_ column: Expression<V>) throws -> V {
if let value = try get(Expression<V?>(column)) {
return value
} else {
throw QueryError.unexpectedNullValue(name: column.template)
}
}
public func get<V: Value>(_ column: Expression<V?>) throws -> V? {
func valueAtIndex(_ idx: Int) -> V? {
guard let value = values[idx] as? V.Datatype else { return nil }
return V.fromDatatypeValue(value) as? V
}
guard let idx = columnNames[column.template] else {
let similar = Array(columnNames.keys).filter { $0.hasSuffix(".\(column.template)") }
switch similar.count {
case 0:
throw QueryError.noSuchColumn(name: column.template, columns: columnNames.keys.sorted())
case 1:
return valueAtIndex(columnNames[similar[0]]!)
default:
throw QueryError.ambiguousColumn(name: column.template, similar: similar)
}
}
return valueAtIndex(idx)
}
public subscript<T : Value>(column: Expression<T>) -> T {
return try! get(column)
}
public subscript<T : Value>(column: Expression<T?>) -> T? {
return try! get(column)
}
}
/// Determines the join operator for a query’s `JOIN` clause.
public enum JoinType : String {
/// A `CROSS` join.
case cross = "CROSS"
/// An `INNER` join.
case inner = "INNER"
/// A `LEFT OUTER` join.
case leftOuter = "LEFT OUTER"
}
/// ON CONFLICT resolutions.
public enum OnConflict: String {
case replace = "REPLACE"
case rollback = "ROLLBACK"
case abort = "ABORT"
case fail = "FAIL"
case ignore = "IGNORE"
}
// MARK: - Private
public struct QueryClauses {
var select = (distinct: false, columns: [Expression<Void>(literal: "*") as Expressible])
var from: (name: String, alias: String?, database: String?)
var join = [(type: JoinType, query: QueryType, condition: Expressible)]()
var filters: Expression<Bool?>?
var group: (by: [Expressible], having: Expression<Bool?>?)?
var order = [Expressible]()
var limit: (length: Int, offset: Int?)?
var union = [QueryType]()
fileprivate init(_ name: String, alias: String?, database: String?) {
self.from = (name, alias, database)
}
}
| mpl-2.0 | f86723270ad6bc7123c7fdd8146b3c85 | 30.198298 | 147 | 0.57109 | 4.344394 | false | false | false | false |
bordplate/sociabl | Sources/App/Models/User.swift | 1 | 9619 | //
// User.swift
// sociabl
//
// Created by Vetle Økland on 16/03/2017.
//
//
import Foundation
import Vapor
import Fluent
import Auth
import Random
/// Social network user.
final class User: Model {
enum Error: Swift.Error {
case invalidCredentials
case usernameTaken
case emailUsed
case postExceedsMaxLength
case alreadyFollowing
case notFollowing
case cantFollowSelf
}
var id: Node?
var email: String
var username: String
var password: String
var salt: String
var displayName: String
var profileDescription: String
var profileImgUrl: String
var joinDate: Date
var exists: Bool = false
init(email: String, username: String, password: String, salt: String, displayName: String, profileDescription: String, profileImgUrl: String, joinDate: Date) {
self.email = email
self.username = username
self.password = password
self.salt = salt
self.displayName = displayName
self.profileDescription = profileDescription
self.profileImgUrl = profileImgUrl
self.joinDate = joinDate
}
init(node: Node, in context: Context) throws {
id = try node.extract("id")
email = try node.extract("email")
username = try node.extract("username")
password = try node.extract("password")
salt = try node.extract("salt")
displayName = try node.extract("display_name")
profileDescription = try node.extract("profile_description")
profileImgUrl = try node.extract("profile_img_url")
// Database stores the date as Unix-style timestamp, so we convert that to a `Date`
joinDate = try node.extract("join_date") { (timestamp: Int) throws -> Date in
return Date(timeIntervalSince1970: TimeInterval(timestamp))
}
}
/**
## Discussion
It feels dangerous to return the password here,
even though it's hashed.
*/
func makeNode(context: Context) throws -> Node {
return try Node(node: [
"id": id,
"email": email,
"username": username,
"password": password,
"salt": salt,
"display_name": displayName,
"profile_description": profileDescription,
"profile_img_url": profileImgUrl,
"join_date": joinDate.timeIntervalSince1970 // Convert Date to Unix timestamp
])
}
/// Use this for when making a Node that should be displayed as a profile.
func makeProfileNode() throws -> Node {
return try Node(node: [
"id": id,
"username": username,
"display_name": displayName,
"profile_description": profileDescription,
"profile_img_url": profileImgUrl,
"join_date": joinDate.timeIntervalSince1970,
"post_count": try self.postCount(),
"like_count": try self.likeCount(),
"following_count": try self.followingCount(),
"follower_count": try self.followerCount(),
"posts": try self.posts().makeNode(context: ["public": true])
])
}
/// For when a user should be embedded in e.g. a post.
func makeEmbedNode() throws -> Node {
return try Node(node: [
"id": id,
"username": username,
"display_name": displayName,
"profile_img_url": profileImgUrl
])
}
/// Returns the timeline for the user.
func timeline() throws -> Node? {
if let id = self.id {
if var subjects = try Follower.subjects(for: id)?.nodeArray {
if let id = self.id { subjects += id } // To see your own posts in the timeline as well.
return try Post.posts(for: subjects).makeNode(context: ["public": true])
}
}
return nil
}
}
// - Interactions with other users
extension User {
/**
Follows provided subject given valid credentials.
## Discusion
This probably should have some sort of check to see that the subject
does not have a private profile, if that ever becomes a thing.
- parameters:
- subject: The user of the user to follow.
*/
public func follow(user subject: User) throws {
if subject.id == self.id {
throw Error.cantFollowSelf
}
if try self.isFollowing(user: subject) {
throw Error.alreadyFollowing
}
var followerRelationship = Follower(owner: self.id, subject: subject.id)
try followerRelationship.save()
}
public func unfollow(user subject: User) throws {
if subject.id == self.id {
throw Error.cantFollowSelf
}
guard let subjectId = subject.id else {
throw Abort.badRequest
}
if let relation = try self.children("owner", Follower.self).filter("subject", subjectId).first() {
try relation.delete()
} else {
throw Error.notFollowing
}
}
public func submit(post content: String) throws {
if content.count > Configuration.maxPostLength {
throw Error.postExceedsMaxLength
}
var post = Post(content: content, date: Date(), user: self)
try post.save()
}
public func isFollowing(user subject: User) throws -> Bool {
guard let subjectId = subject.id else {
throw Abort.badRequest
}
if try self.children("owner", Follower.self).filter("subject", subjectId).count() > 0 {
return true
}
return false
}
}
extension User {
public func postCount() throws -> Int {
return try self.children(nil, Post.self).count()
}
public func likeCount() throws -> Int {
return 0
}
public func followingCount() throws -> Int {
return try self.children("owner", Follower.self).count()
}
public func followerCount() throws -> Int {
return try self.children("subject", Follower.self).count()
}
public func posts() throws -> [Post] {
return try self.children(nil, Post.self).sort("date", .descending).all()
}
}
extension User: Preparation {
/// Mostly useful when setting up app on new system
public static func prepare(_ database: Database) throws {
try database.create("users") { user in
user.id()
user.string("email")
user.string("username")
user.string("password")
user.string("salt")
user.string("display_name")
user.string("profile_description")
user.string("profile_img_url")
user.int("join_date")
}
}
/// Called when you do a `vapor <something> revert` from a terminal.
public static func revert(_ database: Database) throws {
try database.delete("users");
}
}
extension User: Auth.User {
// TODO: Erh... Should salt and pepper passwords...
static func authenticate(credentials: Credentials) throws -> Auth.User {
var user: User?
switch credentials {
case let creds as UserPassword:
let passwordHash = try drop.hash.make(creds.password)
user = try User.query().filter("username", creds.username).filter("password", passwordHash).first()
case let id as Identifier:
user = try User.find(id.id)
default:
throw Abort.custom(status: .badRequest, message: "Malformed request")
}
guard let u = user else {
throw Error.invalidCredentials
}
return u
}
static func register(credentials: Credentials) throws -> Auth.User {
guard let registration = credentials as? RegistrationCredentials else {
throw Error.invalidCredentials
}
if try User.query().filter("username", registration.username.value).count() > 0 {
throw Error.usernameTaken
}
if try User.query().filter("email", registration.email.value).count() > 0 {
throw Error.emailUsed
}
let password = try drop.hash.make(registration.password)
let salt = "Totally random salt" //try URandom.bytes(count: 24).string()
var user = User(email: registration.email.value,
username: registration.username.value,
password: password,
salt: salt,
displayName: registration.username.value,
profileDescription: "",
profileImgUrl: "",
joinDate: Date())
try user.save()
return user
}
}
class UserPassword: Credentials {
public let username: String
public let password: String
public init(username: String, password: String) {
self.username = username
self.password = password
}
}
// TODO: Validation for password as well.
class RegistrationCredentials: Credentials {
public let email: Valid<Email>
public let username: Valid<OnlyAlphanumeric>
public let password: String
public init(email: Valid<Email>, username: Valid<OnlyAlphanumeric>, password: String) {
self.email = email
self.username = username
self.password = password
}
}
| mit | c41a00ffb674ed67783dc3f10ee9f6ca | 30.227273 | 163 | 0.580266 | 4.792227 | false | false | false | false |
Carthage/Commandant | Sources/Commandant/Argument.swift | 2 | 3858 | //
// Argument.swift
// Commandant
//
// Created by Syo Ikeda on 12/14/15.
// Copyright (c) 2015 Carthage. All rights reserved.
//
/// Describes an argument that can be provided on the command line.
public struct Argument<T> {
/// The default value for this argument. This is the value that will be used
/// if the argument is never explicitly specified on the command line.
///
/// If this is nil, this argument is always required.
public let defaultValue: T?
/// A human-readable string describing the purpose of this argument. This will
/// be shown in help messages.
public let usage: String
/// A human-readable string that describes this argument as a paramater shown
/// in the list of possible parameters in help messages (e.g. for "paths", the
/// user would see <paths…>).
public let usageParameter: String?
public init(defaultValue: T? = nil, usage: String, usageParameter: String? = nil) {
self.defaultValue = defaultValue
self.usage = usage
self.usageParameter = usageParameter
}
fileprivate func invalidUsageError<ClientError>(_ value: String) -> CommandantError<ClientError> {
let description = "Invalid value for '\(self.usageParameterDescription)': \(value)"
return .usageError(description: description)
}
}
extension Argument {
/// A string describing this argument as a parameter in help messages. This falls back
/// to `"\(self)"` if `usageParameter` is `nil`
internal var usageParameterDescription: String {
return self.usageParameter.map { "<\($0)>" } ?? "\(self)"
}
}
extension Argument where T: Sequence {
/// A string describing this argument as a parameter in help messages. This falls back
/// to `"\(self)"` if `usageParameter` is `nil`
internal var usageParameterDescription: String {
return self.usageParameter.map { "<\($0)…>" } ?? "\(self)"
}
}
// MARK: - Operators
extension CommandMode {
/// Evaluates the given argument in the given mode.
///
/// If parsing command line arguments, and no value was specified on the command
/// line, the argument's `defaultValue` is used.
public static func <| <T: ArgumentProtocol, ClientError>(mode: CommandMode, argument: Argument<T>) -> Result<T, CommandantError<ClientError>> {
switch mode {
case let .arguments(arguments):
guard let stringValue = arguments.consumePositionalArgument() else {
if let defaultValue = argument.defaultValue {
return .success(defaultValue)
} else {
return .failure(missingArgumentError(argument.usage))
}
}
if let value = T.from(string: stringValue) {
return .success(value)
} else {
return .failure(argument.invalidUsageError(stringValue))
}
case .usage:
return .failure(informativeUsageError(argument))
}
}
/// Evaluates the given argument list in the given mode.
///
/// If parsing command line arguments, and no value was specified on the command
/// line, the argument's `defaultValue` is used.
public static func <| <T: ArgumentProtocol, ClientError>(mode: CommandMode, argument: Argument<[T]>) -> Result<[T], CommandantError<ClientError>> {
switch mode {
case let .arguments(arguments):
guard let firstValue = arguments.consumePositionalArgument() else {
if let defaultValue = argument.defaultValue {
return .success(defaultValue)
} else {
return .failure(missingArgumentError(argument.usage))
}
}
var values = [T]()
guard let value = T.from(string: firstValue) else {
return .failure(argument.invalidUsageError(firstValue))
}
values.append(value)
while let nextValue = arguments.consumePositionalArgument() {
guard let value = T.from(string: nextValue) else {
return .failure(argument.invalidUsageError(nextValue))
}
values.append(value)
}
return .success(values)
case .usage:
return .failure(informativeUsageError(argument))
}
}
}
| mit | b8a21e2ffee5071b3bdc8aa73651bf6a | 31.116667 | 148 | 0.707058 | 3.928644 | false | false | false | false |
fgulan/letter-ml | project/LetterML/Frameworks/framework/Source/Operations/FalseColor.swift | 9 | 518 | public class FalseColor: BasicOperation {
public var firstColor:Color = Color(red:0.0, green:0.0, blue:0.5, alpha:1.0) { didSet { uniformSettings["firstColor"] = firstColor } }
public var secondColor:Color = Color.red { didSet { uniformSettings["secondColor"] = secondColor } }
public init() {
super.init(fragmentShader:FalseColorFragmentShader, numberOfInputs:1)
({firstColor = Color(red:0.0, green:0.0, blue:0.5, alpha:1.0)})()
({secondColor = Color.red})()
}
}
| mit | 58ce8687c48d9595e4d4e4544fae7480 | 46.090909 | 138 | 0.650579 | 3.808824 | false | false | false | false |
FengDeng/RXGitHub | RxGitHubAPI/YYCommitAPI.swift | 1 | 1564 | //
// YYCommitAPI.swift
// RxGitHub
//
// Created by 邓锋 on 16/1/26.
// Copyright © 2016年 fengdeng. All rights reserved.
//
import Foundation
import RxSwift
import Moya
enum YYCommitAPI{
//List commits on a repository
case Commits(owner:String,repo:String,page:Int,sha:String,path:String,author:String,since:String,until:String)
//Get a single commit
case Commit(owner:String,repo:String,sha:String)
//Compare two commits
case CompareTwoCommits(owner:String,repo:String,base:String,head:String)
}
extension YYCommitAPI : TargetType{
var baseURL: NSURL {
return NSURL(string: "https://api.github.com")!
}
var path: String {
switch self {
case .Commits(let owner,let repo,let page,let sha,let path,let author,let since,let until):
return "/repos/\(owner)/\(repo)/commits?sha=\(sha)&path=\(path)&author=\(author)&since=\(since)&until=\(until)&page=\(page)"
case .Commit(let owner,let repo,let sha):
return "/repos/\(owner)/\(repo)/commits/\(sha)"
case .CompareTwoCommits(let owner,let repo,let base,let head):
return "/repos/\(owner)/\(repo)/compare/\(base)...\(head)"
}
}
var method: Moya.Method {
switch self {
default:
return .GET
}
}
var parameters: [String: AnyObject]? {
switch self {
default:
return nil
}
}
var sampleData: NSData {
return "No response".dataUsingEncoding(NSUTF8StringEncoding)!
}
}
| mit | 576d63fcfeadbbfa8202fc6d19e59791 | 27.309091 | 136 | 0.614644 | 3.921914 | false | false | false | false |
kenwilcox/Petitions | Petitions/AppDelegate.swift | 1 | 3637 | //
// AppDelegate.swift
// Petitions
//
// Created by Kenneth Wilcox on 11/11/15.
// Copyright © 2015 Kenneth Wilcox. All rights reserved.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate, UISplitViewControllerDelegate {
var window: UIWindow?
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
// Override point for customization after application launch.
let splitViewController = self.window!.rootViewController as! UISplitViewController
let navigationController = splitViewController.viewControllers[splitViewController.viewControllers.count-1] as! UINavigationController
navigationController.topViewController!.navigationItem.leftBarButtonItem = splitViewController.displayModeButtonItem()
splitViewController.delegate = self
let tabBarController = splitViewController.viewControllers[0] as! UITabBarController
let storyboard = UIStoryboard(name: "Main", bundle: nil)
let vc = storyboard.instantiateViewControllerWithIdentifier("NavController") as! UINavigationController
vc.tabBarItem = UITabBarItem(tabBarSystemItem: .TopRated, tag: 1)
tabBarController.viewControllers?.append(vc)
return true
}
func applicationWillResignActive(application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}
func applicationDidEnterBackground(application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(application: UIApplication) {
// Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}
// MARK: - Split view
func splitViewController(splitViewController: UISplitViewController, collapseSecondaryViewController secondaryViewController:UIViewController, ontoPrimaryViewController primaryViewController:UIViewController) -> Bool {
guard let secondaryAsNavController = secondaryViewController as? UINavigationController else { return false }
guard let topAsDetailController = secondaryAsNavController.topViewController as? DetailViewController else { return false }
if topAsDetailController.detailItem == nil {
// Return true to indicate that we have handled the collapse by doing nothing; the secondary controller will be discarded.
return true
}
return false
}
}
| mit | 36f61379ebcf3d55d089410abdfa91b0 | 51.695652 | 281 | 0.784103 | 6.009917 | false | false | false | false |
ahmetkgunay/AKGPushAnimator | Examples/AKGPushAnimatorDemo/AKGPushAnimator/BaseViewController.swift | 2 | 1284 | //
// BaseViewController.swift
// AKGPushAnimator
//
// Created by AHMET KAZIM GUNAY on 30/04/2017.
// Copyright © 2017 AHMET KAZIM GUNAY. All rights reserved.
//
import UIKit
class BaseViewController: UIViewController, UINavigationControllerDelegate {
let pushAnimator = AKGPushAnimator()
let interactionAnimator = AKGInteractionAnimator()
override func viewDidLoad() {
super.viewDidLoad()
}
func navigationController(_ navigationController: UINavigationController, animationControllerFor operation: UINavigationControllerOperation, from fromVC: UIViewController, to toVC: UIViewController) -> UIViewControllerAnimatedTransitioning? {
if operation == .push {
interactionAnimator.attachToViewController(toVC)
}
pushAnimator.isReverseTransition = operation == .pop
return pushAnimator
}
func navigationController(_ navigationController: UINavigationController, interactionControllerFor animationController: UIViewControllerAnimatedTransitioning) -> UIViewControllerInteractiveTransitioning? {
return interactionAnimator.transitionInProgress ? interactionAnimator : nil
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
}
| mit | 27ad479aa46f066155908ddfbda70abf | 35.657143 | 246 | 0.748246 | 6.051887 | false | false | false | false |
cdmx/MiniMancera | miniMancera/Model/Option/ReformaCrossing/Node/MOptionReformaCrossingHud.swift | 1 | 1871 | import SpriteKit
class MOptionReformaCrossingHud:MGameUpdate<MOptionReformaCrossing>
{
weak var view:VOptionReformaCrossingHud?
private var elapsedTime:TimeInterval?
private let kMaxTime:TimeInterval = 32
private let kTimeDelta:TimeInterval = 0.1
override func update(
elapsedTime:TimeInterval,
scene:ViewGameScene<MOptionReformaCrossing>)
{
if let lastElapsedTime:TimeInterval = self.elapsedTime
{
let deltaTime:TimeInterval = abs(elapsedTime - lastElapsedTime)
if deltaTime > kTimeDelta
{
self.elapsedTime = elapsedTime
let score:Int = scene.controller.model.score
updateStrings(scene:scene, score:score)
}
}
else
{
self.elapsedTime = elapsedTime
}
}
//MARK: private
private func timeOut(scene:ViewGameScene<MOptionReformaCrossing>)
{
let model:MOptionReformaCrossing = scene.controller.model
model.timeOut()
let soundFail:SKAction = model.sounds.soundFail
scene.controller.playSound(actionSound:soundFail)
}
private func updateStrings(scene:ViewGameScene<MOptionReformaCrossing>, score:Int)
{
guard
let elapsedTime:TimeInterval = self.elapsedTime
else
{
return
}
let remainTime:TimeInterval = kMaxTime - elapsedTime
let scoreString:String = "\(score)"
let time:Int
if remainTime < 0
{
timeOut(scene:scene)
time = 0
}
else
{
time = Int(remainTime)
}
let timeString:String = "\(time)"
view?.update(time:timeString, score:scoreString)
}
}
| mit | 0f247f545e71eb89363cbffc66f82fb6 | 25.728571 | 86 | 0.577766 | 5.45481 | false | false | false | false |
Lordxen/MagistralSwift | Carthage/Checkouts/CryptoSwift/CryptoSwiftTests/HashTests.swift | 2 | 7591 | //
// CryptoSwiftTests.swift
// CryptoSwiftTests
//
// Created by Marcin Krzyzanowski on 06/07/14.
// Copyright (c) 2014 Marcin Krzyzanowski. All rights reserved.
//
import XCTest
@testable import CryptoSwift
final class CryptoSwiftTests: XCTestCase {
override func setUp() {
super.setUp()
}
override func tearDown() {
super.tearDown()
}
func testMD5_data() {
let data = [0x31, 0x32, 0x33] as Array<UInt8> // "1", "2", "3"
XCTAssertEqual(Hash.md5(data).calculate(), [0x20,0x2c,0xb9,0x62,0xac,0x59,0x07,0x5b,0x96,0x4b,0x07,0x15,0x2d,0x23,0x4b,0x70], "MD5 calculation failed");
}
func testMD5_emptyString() {
let data:NSData = "".dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)!
XCTAssertEqual(Hash.md5(data.arrayOfBytes()).calculate(), [0xd4,0x1d,0x8c,0xd9,0x8f,0x00,0xb2,0x04,0xe9,0x80,0x09,0x98,0xec,0xf8,0x42,0x7e], "MD5 calculation failed")
}
func testMD5_string() {
XCTAssertEqual("123".md5(), "202cb962ac59075b964b07152d234b70", "MD5 calculation failed");
XCTAssertEqual("".md5(), "d41d8cd98f00b204e9800998ecf8427e", "MD5 calculation failed")
XCTAssertEqual("a".md5(), "0cc175b9c0f1b6a831c399e269772661", "MD5 calculation failed")
XCTAssertEqual("abc".md5(), "900150983cd24fb0d6963f7d28e17f72", "MD5 calculation failed")
XCTAssertEqual("message digest".md5(), "f96b697d7cb7938d525a2f31aaf161d0", "MD5 calculation failed")
XCTAssertEqual("abcdefghijklmnopqrstuvwxyz".md5(), "c3fcd3d76192e4007dfb496cca67e13b", "MD5 calculation failed")
XCTAssertEqual("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789".md5(), "d174ab98d277d9f5a5611c2c9f419d9f", "MD5 calculation failed")
XCTAssertEqual("12345678901234567890123456789012345678901234567890123456789012345678901234567890".md5(), "57edf4a22be3c955ac49da2e2107b67a", "MD5 calculation failed")
}
func testMD5PerformanceSwift() {
self.measureMetrics([XCTPerformanceMetric_WallClockTime], automaticallyStartMeasuring: false, forBlock: { () -> Void in
let buf = UnsafeMutablePointer<UInt8>(calloc(1024 * 1024, sizeof(UInt8)))
let data = NSData(bytes: buf, length: 1024 * 1024)
let arr = data.arrayOfBytes()
self.startMeasuring()
Hash.md5(arr).calculate()
self.stopMeasuring()
buf.dealloc(1024 * 1024)
buf.destroy()
})
}
func testMD5PerformanceCommonCrypto() {
self.measureMetrics([XCTPerformanceMetric_WallClockTime], automaticallyStartMeasuring: false, forBlock: { () -> Void in
let buf = UnsafeMutablePointer<UInt8>(calloc(1024 * 1024, sizeof(UInt8)))
let data = NSData(bytes: buf, length: 1024 * 1024)
let outbuf = UnsafeMutablePointer<UInt8>.alloc(Int(CC_MD5_DIGEST_LENGTH))
self.startMeasuring()
CC_MD5(data.bytes, CC_LONG(data.length), outbuf)
//let output = NSData(bytes: outbuf, length: Int(CC_MD5_DIGEST_LENGTH));
self.stopMeasuring()
outbuf.dealloc(Int(CC_MD5_DIGEST_LENGTH))
outbuf.destroy()
buf.dealloc(1024 * 1024)
buf.destroy()
})
}
func testSHA1() {
let data:NSData = NSData(bytes: [0x31, 0x32, 0x33] as Array<UInt8>, length: 3)
if let hash = data.sha1() {
XCTAssertEqual(hash.toHexString(), "40bd001563085fc35165329ea1ff5c5ecbdbbeef", "SHA1 calculation failed");
}
XCTAssertEqual("abc".sha1(), "a9993e364706816aba3e25717850c26c9cd0d89d", "SHA1 calculation failed")
XCTAssertEqual("abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq".sha1(), "84983e441c3bd26ebaae4aa1f95129e5e54670f1", "SHA1 calculation failed")
XCTAssertEqual("".sha1(), "da39a3ee5e6b4b0d3255bfef95601890afd80709", "SHA1 calculation failed")
}
func testSHA224() {
let data:NSData = NSData(bytes: [0x31, 0x32, 0x33] as Array<UInt8>, length: 3)
if let hash = data.sha224() {
XCTAssertEqual(hash.toHexString(), "78d8045d684abd2eece923758f3cd781489df3a48e1278982466017f", "SHA224 calculation failed");
}
}
func testSHA256() {
let data:NSData = NSData(bytes: [0x31, 0x32, 0x33] as Array<UInt8>, length: 3)
if let hash = data.sha256() {
XCTAssertEqual(hash.toHexString(), "a665a45920422f9d417e4867efdc4fb8a04a1f3fff1fa07e998e86f7f7a27ae3", "SHA256 calculation failed");
}
XCTAssertEqual("Rosetta code".sha256(), "764faf5c61ac315f1497f9dfa542713965b785e5cc2f707d6468d7d1124cdfcf", "SHA256 calculation failed")
XCTAssertEqual("".sha256(), "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", "SHA256 calculation failed")
}
func testSHA384() {
let data:NSData = NSData(bytes: [49, 50, 51] as Array<UInt8>, length: 3)
if let hash = data.sha384() {
XCTAssertEqual(hash.toHexString(), "9a0a82f0c0cf31470d7affede3406cc9aa8410671520b727044eda15b4c25532a9b5cd8aaf9cec4919d76255b6bfb00f", "SHA384 calculation failed");
}
XCTAssertEqual("The quick brown fox jumps over the lazy dog.".sha384(), "ed892481d8272ca6df370bf706e4d7bc1b5739fa2177aae6c50e946678718fc67a7af2819a021c2fc34e91bdb63409d7", "SHA384 calculation failed");
XCTAssertEqual("".sha384(), "38b060a751ac96384cd9327eb1b1e36a21fdb71114be07434c0cc7bf63f6e1da274edebfe76f65fbd51ad2f14898b95b", "SHA384 calculation failed")
}
func testSHA512() {
let data:NSData = NSData(bytes: [49, 50, 51] as Array<UInt8>, length: 3)
if let hash = data.sha512() {
XCTAssertEqual(hash.toHexString(), "3c9909afec25354d551dae21590bb26e38d53f2173b8d3dc3eee4c047e7ab1c1eb8b85103e3be7ba613b31bb5c9c36214dc9f14a42fd7a2fdb84856bca5c44c2", "SHA512 calculation failed");
}
XCTAssertEqual("The quick brown fox jumps over the lazy dog.".sha512(), "91ea1245f20d46ae9a037a989f54f1f790f0a47607eeb8a14d12890cea77a1bbc6c7ed9cf205e67b7f2b8fd4c7dfd3a7a8617e45f3c463d481c7e586c39ac1ed", "SHA512 calculation failed");
XCTAssertEqual("".sha512(), "cf83e1357eefb8bdf1542850d66d8007d620e4050b5715dc83f4a921d36ce9ce47d0d13c5d85f2b0ff8318d2877eec2f63b931bd47417a81a538327af927da3e", "SHA512 calculation failed")
}
func testCRC32() {
let data:NSData = NSData(bytes: [49, 50, 51] as Array<UInt8>, length: 3)
if let crc = data.crc32(nil) {
XCTAssertEqual(crc.toHexString(), "884863d2", "CRC32 calculation failed");
}
XCTAssertEqual("".crc32(nil), "00000000", "CRC32 calculation failed");
}
func testCRC32NotReflected() {
let bytes : Array<UInt8> = [0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x38, 0x39]
let data:NSData = NSData(bytes: bytes, length: bytes.count)
if let crc = data.crc32(nil, reflect: false) {
XCTAssertEqual(crc.toHexString(), "fc891918", "CRC32 (with reflection) calculation failed");
}
XCTAssertEqual("".crc32(nil, reflect: false), "00000000", "CRC32 (with reflection) calculation failed");
}
func testCRC16() {
let result = CRC().crc16([49,50,51,52,53,54,55,56,57] as Array<UInt8>)
XCTAssert(result == 0xBB3D, "CRC16 failed")
}
func testChecksum() {
let data:NSData = NSData(bytes: [49, 50, 51] as Array<UInt8>, length: 3)
XCTAssert(data.checksum() == 0x96, "Invalid checksum")
}
}
| mit | b8de1c7e5c52a9543236b55d692e34a1 | 49.946309 | 241 | 0.681597 | 3.186818 | false | true | false | false |
realm/SwiftLint | Source/SwiftLintFramework/Rules/Idiomatic/DiscouragedNoneNameRule.swift | 1 | 6682 | import SwiftSyntax
struct DiscouragedNoneNameRule: SwiftSyntaxRule, OptInRule, ConfigurationProviderRule {
var configuration = SeverityConfiguration(.warning)
init() {}
static var description = RuleDescription(
identifier: "discouraged_none_name",
name: "Discouraged None Name",
description: "Discourages name cases/static members `none`, which can conflict with `Optional<T>.none`.",
kind: .idiomatic,
nonTriggeringExamples: [
// Should not trigger unless exactly matches "none"
Example("""
enum MyEnum {
case nOne
}
"""),
Example("""
enum MyEnum {
case _none
}
"""),
Example("""
enum MyEnum {
case none_
}
"""),
Example("""
enum MyEnum {
case none(Any)
}
"""),
Example("""
enum MyEnum {
case nonenone
}
"""),
Example("""
class MyClass {
class var nonenone: MyClass { MyClass() }
}
"""),
Example("""
class MyClass {
static var nonenone = MyClass()
}
"""),
Example("""
class MyClass {
static let nonenone = MyClass()
}
"""),
Example("""
struct MyStruct {
static var nonenone = MyStruct()
}
"""),
Example("""
struct MyStruct {
static let nonenone = MyStruct()
}
"""),
// Should not trigger if not an enum case or static/class member
Example("""
struct MyStruct {
let none = MyStruct()
}
"""),
Example("""
struct MyStruct {
var none = MyStruct()
}
"""),
Example("""
class MyClass {
let none = MyClass()
}
"""),
Example("""
class MyClass {
var none = MyClass()
}
""")
],
triggeringExamples: [
Example("""
enum MyEnum {
case ↓none
}
"""),
Example("""
enum MyEnum {
case a, ↓none
}
"""),
Example("""
enum MyEnum {
case ↓none, b
}
"""),
Example("""
enum MyEnum {
case a, ↓none, b
}
"""),
Example("""
enum MyEnum {
case a
case ↓none
}
"""),
Example("""
enum MyEnum {
case ↓none
case b
}
"""),
Example("""
enum MyEnum {
case a
case ↓none
case b
}
"""),
Example("""
class MyClass {
↓static let none = MyClass()
}
"""),
Example("""
class MyClass {
↓static let none: MyClass = MyClass()
}
"""),
Example("""
class MyClass {
↓static var none: MyClass = MyClass()
}
"""),
Example("""
class MyClass {
↓class var none: MyClass { MyClass() }
}
"""),
Example("""
struct MyStruct {
↓static var none = MyStruct()
}
"""),
Example("""
struct MyStruct {
↓static var none: MyStruct = MyStruct()
}
"""),
Example("""
struct MyStruct {
↓static var none = MyStruct()
}
"""),
Example("""
struct MyStruct {
↓static var none: MyStruct = MyStruct()
}
"""),
Example("""
struct MyStruct {
↓static var a = MyStruct(), none = MyStruct()
}
"""),
Example("""
struct MyStruct {
↓static var none = MyStruct(), a = MyStruct()
}
""")
]
)
func makeVisitor(file: SwiftLintFile) -> ViolationsSyntaxVisitor {
Visitor(viewMode: .sourceAccurate)
}
}
private extension DiscouragedNoneNameRule {
final class Visitor: ViolationsSyntaxVisitor {
override func visitPost(_ node: EnumCaseElementSyntax) {
let emptyParams = node.associatedValue?.parameterList.isEmpty ?? true
if emptyParams, node.identifier.isNone {
violations.append(ReasonedRuleViolation(
position: node.positionAfterSkippingLeadingTrivia,
reason: reason(type: "`case`")
))
}
}
override func visitPost(_ node: VariableDeclSyntax) {
let type: String? = {
if node.modifiers.isClass {
return "`class` member"
} else if node.modifiers.isStatic {
return "`static` member"
} else {
return nil
}
}()
guard let type = type else {
return
}
for binding in node.bindings {
guard let pattern = binding.pattern.as(IdentifierPatternSyntax.self), pattern.identifier.isNone else {
continue
}
violations.append(ReasonedRuleViolation(
position: node.positionAfterSkippingLeadingTrivia,
reason: reason(type: type)
))
return
}
}
private func reason(type: String) -> String {
let reason = "Avoid naming \(type) `none` as the compiler can think you mean `Optional<T>.none`."
let recommendation = "Consider using an Optional value instead."
return "\(reason) \(recommendation)"
}
}
}
private extension TokenSyntax {
var isNone: Bool {
tokenKind == .identifier("none") || tokenKind == .identifier("`none`")
}
}
| mit | 807b3f596bf2d71670b4fc23474c00bc | 26.932773 | 118 | 0.40373 | 6.31339 | false | false | false | false |
wireapp/wire-ios | Wire-iOS Tests/SearchGroup/SearchGroupSelectorSnapshotTests.swift | 1 | 1807 | //
// Wire
// Copyright (C) 2021 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 SnapshotTesting
import XCTest
@testable import Wire
final class SearchGroupSelectorSnapshotTests: XCTestCase {
var sut: SearchGroupSelector!
override func setUp() {
super.setUp()
}
override func tearDown() {
sut = nil
super.tearDown()
}
private func createSut() {
sut = SearchGroupSelector(style: .light)
sut.frame = CGRect(origin: .zero, size: CGSize(width: 320, height: 320))
}
func testForInitState_WhenSelfUserCanNotCreateService() {
// GIVEN
let mockSelfUser = MockUserType.createSelfUser(name: "selfUser")
SelfUser.provider = SelfProvider(selfUser: mockSelfUser)
createSut()
// WHEN & THEN
verify(matching: sut)
}
func testThatServiceTabExists_WhenSelfUserCanCreateService() {
// GIVEN
let mockSelfUser = MockUserType.createSelfUser(name: "selfUser")
mockSelfUser.canCreateService = true
SelfUser.provider = SelfProvider(selfUser: mockSelfUser)
createSut()
// WHEN & THEN
verify(matching: sut)
}
}
| gpl-3.0 | af98d4c2c52ddc87fe70887b188649d1 | 28.145161 | 80 | 0.682346 | 4.621483 | false | true | false | false |
benlangmuir/swift | test/SILGen/stored_property_init_reabstraction.swift | 9 | 2471 | // RUN: %target-swift-emit-silgen %s | %FileCheck %s
// rdar://problem/67419937
class Class<T> {
var fn: ((T) -> ())? = nil
init(_: T) where T == Int {}
}
// CHECK-LABEL: sil hidden [ossa] @$s34stored_property_init_reabstraction5ClassCyACySiGSicSiRszlufc : $@convention(method) (Int, @owned Class<Int>) -> @owned Class<Int> {
// CHECK: [[SELF:%.*]] = mark_uninitialized [rootself] %1 : $Class<Int>
// CHECK: [[BORROW:%.*]] = begin_borrow [[SELF]] : $Class<Int>
// CHECK: [[ADDR:%.*]] = ref_element_addr [[BORROW]] : $Class<Int>, #Class.fn
// CHECK: [[INIT:%.*]] = function_ref @$s34stored_property_init_reabstraction5ClassC2fnyxcSgvpfi : $@convention(thin) <τ_0_0> () -> @owned Optional<@callee_guaranteed @substituted <τ_0_0> (@in_guaranteed τ_0_0) -> () for <τ_0_0>>
// CHECK: [[VALUE:%.*]] = apply [[INIT]]<Int>() : $@convention(thin) <τ_0_0> () -> @owned Optional<@callee_guaranteed @substituted <τ_0_0> (@in_guaranteed τ_0_0) -> () for <τ_0_0>>
// CHECK: store [[VALUE]] to [init] [[ADDR]] : $*Optional<@callee_guaranteed @substituted <τ_0_0> (@in_guaranteed τ_0_0) -> () for <Int>>
// CHECK: end_borrow [[BORROW]] : $Class<Int>
struct Struct<T> {
var fn: ((T) -> ())? = nil
init(_: T) where T == Int {}
}
// CHECK-LABEL: sil hidden [ossa] @$s34stored_property_init_reabstraction6StructVyACySiGSicSiRszlufC : $@convention(method) (Int, @thin Struct<Int>.Type) -> @owned Struct<Int> {
// CHECK: [[SELF_BOX:%.*]] = mark_uninitialized [rootself] {{%.*}} : ${ var Struct<Int> }
// CHECK: [[SELF_LIFETIME:%[^,]+]] = begin_borrow [lexical] [[SELF_BOX]]
// CHECK: [[SELF:%.*]] = project_box [[SELF_LIFETIME]] : ${ var Struct<Int> }, 0
// CHECK: [[ADDR:%.*]] = struct_element_addr [[SELF]] : $*Struct<Int>, #Struct.fn
// CHECK: [[INIT:%.*]] = function_ref @$s34stored_property_init_reabstraction6StructV2fnyxcSgvpfi : $@convention(thin) <τ_0_0> () -> @owned Optional<@callee_guaranteed @substituted <τ_0_0> (@in_guaranteed τ_0_0) -> () for <τ_0_0>>
// CHECK: [[VALUE:%.*]] = apply [[INIT]]<Int>() : $@convention(thin) <τ_0_0> () -> @owned Optional<@callee_guaranteed @substituted <τ_0_0> (@in_guaranteed τ_0_0) -> () for <τ_0_0>>
// CHECK: store [[VALUE]] to [init] [[ADDR]] : $*Optional<@callee_guaranteed @substituted <τ_0_0> (@in_guaranteed τ_0_0) -> () for <Int>>
struct ComplexExample<T, U> {
var (fn, value): (((T) -> ())?, U?) = (nil, nil)
var anotherValue: (((T) -> ())?, U?) = (nil, nil)
init(_: T) where T == String {}
}
| apache-2.0 | b3f8b3026ef8a3aeeb552b82798cf0fd | 60.275 | 230 | 0.603835 | 2.960145 | false | false | false | false |
seandavidmcgee/HumanKontactBeta | src/keyboardTest/SyncAddressBookOperation.swift | 1 | 6706 | //
// SyncAddressBookOperation.swift
// keyboardTest
//
// Created by Sean McGee on 10/20/15.
// Copyright © 2015 Kannuu. All rights reserved.
//
import UIKit
import AddressBook
import AddressBookUI
import RealmSwift
class SyncAddressBookContactsOperation: NSOperation {
var adbk: ABAddressBook!
override func main() {
if self.cancelled {
return
}
if !self.determineStatus() {
print("not authorized")
return
}
importContacts()
if self.cancelled {
return
}
}
var lastSyncDate:NSDate?{
get{
return NSUserDefaults.standardUserDefaults().objectForKey("modifiedDate") as? NSDate
}
set{
NSUserDefaults.standardUserDefaults().setObject(newValue, forKey:"modifiedDate")
NSUserDefaults.standardUserDefaults().synchronize()
}
}
func importContacts(){
do {
let realm = try Realm()
realm.beginWrite()
let allPeople = ABAddressBookCopyArrayOfAllPeople(
adbk).takeRetainedValue() as NSArray
if let _ = lastSyncDate {
//Not first sync
let deleted = findDeletedPersons(inRealm: realm)
print("Deleted: \(deleted.count)")
for person in deleted{
person.deleteWithChildren(inRealm: realm)
}
for personRec: ABRecordRef in allPeople{
let recordId = ABRecordGetRecordID(personRec)
let queryRecordID = realm.objects(HKPerson).filter("record == \(recordId)")
let foundRecID = queryRecordID.first
if let foundRecID = foundRecID{
if Int(recordId) == foundRecID.record{
print("Existing person in AB.")
foundRecID.updateIfNeeded(fromRecord: personRec, inRealm: realm)
}
}else{
print("New person was created in AB, let's add it too.")
let newPerson = HKPerson()
newPerson.update(fromRecord: personRec, inRealm: realm)
realm.add(newPerson)
}
}
}else{
print("First sync with AB. Add all contacts.")
for personRec: ABRecordRef in allPeople{
//First sync
let newPerson = HKPerson()
newPerson.update(fromRecord: personRec, inRealm: realm)
realm.add(newPerson)
}
}
let index = HKPerson()
index.createIndex(false)
try realm.commitWrite()
lastSyncDate = NSDate()
} catch {
print("Something went wrong!")
}
}
func findDeletedPersons(inRealm realm:Realm) -> [HKPerson]{
let realm = try! Realm()
var allRecordsIds = [Int]()
let allPeople = ABAddressBookCopyArrayOfAllPeople(
adbk).takeRetainedValue() as NSArray
for personRec: ABRecordRef in allPeople{
let recordId = ABRecordGetRecordID(personRec)
allRecordsIds.append(Int(recordId))
}
let allPersons = realm.objects(HKPerson)
var missingPersons = [HKPerson]()
for person in allPersons{
let isPersonFound = allRecordsIds.filter { $0 == person.record }.count > 0
if !isPersonFound{
let foundPerson: ABRecord? = lookup(person: person) as ABRecord?
if foundPerson == nil{
missingPersons.append(person)
}
}
}
print("Missing Persons in AB sync: \(missingPersons)")
return missingPersons
}
func lookup(person person:HKPerson!) -> ABRecord?{
var rec : ABRecord! = nil
let people = ABAddressBookCopyPeopleWithName(self.adbk, person.fullName).takeRetainedValue() as NSArray
for personRec in people {
if let createdDate = ABRecordCopyValue(personRec, kABPersonCreationDateProperty).takeRetainedValue() as? NSDate {
if createdDate == person.createdDate {
let recordId = ABRecordGetRecordID(personRec)
person.record == Int(recordId)
rec = personRec
break
}
}
}
if rec != nil {
print("found person and updated recordID")
}
return rec
}
func createAddressBook() -> Bool {
if self.adbk != nil {
return true
}
var err : Unmanaged<CFError>? = nil
let adbk : ABAddressBook? = ABAddressBookCreateWithOptions(nil, &err).takeRetainedValue()
if adbk == nil {
print(err)
self.adbk = nil
return false
}
self.adbk = adbk
return true
}
func determineStatus() -> Bool {
let status = ABAddressBookGetAuthorizationStatus()
switch status {
case .Authorized:
return self.createAddressBook()
case .NotDetermined:
var ok = false
ABAddressBookRequestAccessWithCompletion(nil) {
(granted:Bool, err:CFError!) in
dispatch_async(dispatch_get_main_queue()) {
if granted {
ok = self.createAddressBook()
}
}
}
if ok == true {
return true
}
adbk = nil
return false
case .Restricted:
adbk = nil
return false
case .Denied:
let alert = UIAlertController(title: "Need Authorization", message: "Wouldn't you like to authorize this app to use your Contacts?", preferredStyle: .Alert)
alert.addAction(UIAlertAction(title: "No", style: .Cancel, handler: nil))
alert.addAction(UIAlertAction(title: "OK", style: .Default, handler: {
_ in
let url = NSURL(string:UIApplicationOpenSettingsURLString)!
UIApplication.sharedApplication().openURL(url)
}))
UIApplication.sharedApplication().keyWindow?.rootViewController!.presentViewController(alert, animated:true, completion:nil)
adbk = nil
return false
}
}
}
| mit | c082640730647e028e73c814f4ae5bd8 | 33.384615 | 168 | 0.524087 | 5.667794 | false | false | false | false |
RLovelett/VHS | VHSTests/Helpers/ExpectResponseFromDelegate.swift | 1 | 1111 | //
// ExpectResponseFromDelegate.swift
// VHS
//
// Created by Ryan Lovelett on 7/19/16.
// Copyright © 2016 Ryan Lovelett. All rights reserved.
//
import Foundation
import XCTest
final class ExpectResponseFromDelegate: NSObject, URLSessionDataDelegate {
enum QueueType {
case `default`, main
}
private let type: QueueType
private let expectation: XCTestExpectation
private let file: StaticString
private let line: UInt
init(on type: QueueType, fulfill: XCTestExpectation, file: StaticString = #file, line: UInt = #line) {
self.type = type
self.expectation = fulfill
self.file = file
self.line = line
super.init()
}
func urlSession(
_ session: URLSession,
task: URLSessionTask,
didCompleteWithError error: Error?
) {
switch self.type {
case .default:
XCTAssertFalse(Thread.isMainThread, file: file, line: line)
case .main:
XCTAssertTrue(Thread.isMainThread, file: file, line: line)
}
self.expectation.fulfill()
}
}
| mit | b64b08b5fc2e50a0d538ce2f1b9c0938 | 21.653061 | 106 | 0.632432 | 4.54918 | false | true | false | false |
qvik/qvik-swift-ios | QvikSwift/StringExtensions.swift | 1 | 5599 | // The MIT License (MIT)
//
// Copyright (c) 2015-2016 Qvik (www.qvik.fi)
//
// 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
/// Extensions to the String class.
public extension String {
/**
Trims all the whitespace-y / newline characters off the begin/end of the string.
- returns: a new string with all the newline/whitespace characters removed from the ends of the original string
*/
func trim() -> String {
return self.trimmingCharacters(in: CharacterSet.whitespacesAndNewlines)
}
/**
Returns an URL encoded string of this string.
- returns: String that is an URL-encoded representation of this string.
*/
var urlEncoded: String? {
return self.addingPercentEncoding(withAllowedCharacters: CharacterSet.urlQueryAllowed)
}
/**
Convenience method for a more familiar name for string splitting.
- parameter separator: string to split the original string by
- returns: the original string split into parts
*/
func split(_ separator: String) -> [String] {
return components(separatedBy: separator)
}
/**
Checks whether the string contains a given substring.
- parameter s: substring to check for
- returns: true if this string contained the given substring, false otherwise.
*/
func contains(_ s: String) -> Bool {
return (self.range(of: s) != nil)
}
/**
Returns a substring of this string from a given index up the given length.
- parameter startIndex: index of the first character to include in the substring
- parameter length: number of characters to include in the substring
- returns: the substring
*/
func substring(startIndex: Int, length: Int) -> String {
let start = self.index(self.startIndex, offsetBy: startIndex)
let end = self.index(self.startIndex, offsetBy: startIndex + length)
return String(self[start..<end])
}
/**
Returns a substring of this string from a given index to the end of the string.
- parameter startIndex: index of the first character to include in the substring
- returns: the substring from startIndex to the end of this string
*/
func substring(startIndex: Int) -> String {
let start = self.index(self.startIndex, offsetBy: startIndex)
return String(self[start...])
}
/**
Returns the i:th character in the string.
- parameter i: index of the character to return
- returns: i:th character in the string
*/
subscript (i: Int) -> Character {
return self[self.index(self.startIndex, offsetBy: i)]
}
/**
Returns a substring matching the given range.
- parameter r: range for substring to return
- returns: substring matching the range r
*/
subscript (r: Range<Int>) -> String {
let start = index(startIndex, offsetBy: r.lowerBound)
let end = index(start, offsetBy: r.upperBound - r.lowerBound)
return String(self[start..<end])
}
/**
Splits the string into substring of equal 'lengths'; any remainder string
will be shorter than 'length' in case the original string length was not multiple of 'length'.
- parameter length: (max) length of each substring
- returns: the substrings array
*/
func splitEqually(length: Int) -> [String] {
var index = 0
let len = self.count
var strings: [String] = []
while index < len {
let numChars = min(length, (len - index))
strings.append(self.substring(startIndex: index, length: numChars))
index += numChars
}
return strings
}
/**
Returns the bounding rectangle that drawing required for drawing this string using
the given font. By default the string is drawn on a single line, but it can be
constrained to a specific width with the optional parameter constrainedToSize.
- parameter font: font used
- parameter constrainedToSize: the constraints for drawing
- returns: the bounding rectangle required to draw the string
*/
func boundingRect(font: UIFont, constrainedToSize size: CGSize = CGSize(width: CGFloat.greatestFiniteMagnitude, height: CGFloat.greatestFiniteMagnitude)) -> CGRect {
let attributedString = NSAttributedString(string: self, attributes: [NSAttributedString.Key.font: font])
return attributedString.boundingRect(with: size, options: NSStringDrawingOptions.usesLineFragmentOrigin, context: nil)
}
}
| mit | 575ab774c52ba9a5b1dfbf8cfcb0c522 | 36.831081 | 169 | 0.685837 | 4.789564 | false | false | false | false |
StachkaConf/ios-app | StachkaIOS/StachkaIOS/Classes/User Stories/Talks/FiltersMain/ViewModel/FiltersMainViewModelImplementation.swift | 1 | 2363 | //
// FiltersViewModelImplementation.swift
// StachkaIOS
//
// Created by m.rakhmanov on 27.03.17.
// Copyright © 2017 m.rakhmanov. All rights reserved.
//
import RxSwift
import RealmSwift
class FiltersMainViewModelImplementation: FiltersMainViewModel {
var filters: Observable<[FilterCellViewModel]> {
return _filters.asObservable()
}
var _filters: Variable<[FilterCellViewModel]> = Variable([])
var parentFilters: [ParentFilter] = []
var parentFilterPublisher = PublishSubject<ParentFilter>()
let disposeBag = DisposeBag()
fileprivate let filterFactory: FilterFactory
fileprivate let filterCellViewModelFactory: FilterCellViewModelFactory
fileprivate let filterService: FilterService
fileprivate weak var view: FiltersMainView?
init(view: FiltersMainView,
filterService: FilterService,
filterFactory: FilterFactory,
filterCellViewModelFactory: FilterCellViewModelFactory) {
self.view = view
self.filterService = filterService
self.filterFactory = filterFactory
self.filterCellViewModelFactory = filterCellViewModelFactory
filterService
.updateFilters()
.do(onNext: { [weak self] filters in
guard let strongSelf = self else { return }
strongSelf.parentFilters = filters as? [ParentFilter] ?? []
})
.map { [weak self] filters -> [FilterCellViewModel] in
guard let strongSelf = self else { return [] }
return strongSelf.filterCellViewModelFactory.navigationViewModels(from: filters)
}
.subscribe(onNext: { [weak self] filterModels in
guard let strongSelf = self else { return }
strongSelf._filters.value = filterModels
})
.disposed(by: disposeBag)
view.indexSelected
.subscribe(onNext: { [weak self] indexPath in
guard let strongSelf = self else { return }
strongSelf.parentFilterPublisher.onNext(strongSelf.parentFilters[indexPath.row])
})
.disposed(by: disposeBag)
}
}
extension FiltersMainViewModelImplementation: FiltersMainModuleOutput {
var parentFilterSelected: Observable<ParentFilter> {
return parentFilterPublisher.asObservable()
}
}
| mit | 8158bc255e2b1f91a282fa2c9a036e60 | 35.338462 | 96 | 0.663421 | 5.583924 | false | false | false | false |
vulgur/WeeklyFoodPlan | WeeklyFoodPlan/WeeklyFoodPlan/Views/PlanList/PlanMealListViewController.swift | 1 | 4756 | //
// WeeklyFoodListViewController.swift
// WeeklyFoodPlan
//
// Created by vulgur on 2017/1/3.
// Copyright © 2017年 MAD. All rights reserved.
//
import UIKit
import RealmSwift
class PlanMealListViewController: UIViewController {
@IBOutlet var collectionView: UICollectionView!
let cellIdentifier = "PlanCell"
var plans = [DailyPlan]()
override func viewDidLoad() {
super.viewDidLoad()
collectionView.dataSource = self
collectionView.delegate = self
loadPlans()
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
self.automaticallyAdjustsScrollViewInsets = false
navigationItem.title = "美食计划".localized()
collectionView.reloadData()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
private func loadPlans() {
plans = WeeklyPlanManager.shared.nextWeeklyPlan()
}
@IBAction func barButtonTapped(sender: UIBarButtonItem) {
let oldPlans = plans
for plan in oldPlans {
BaseManager.shared.transaction {
plan.reduceIngredients()
}
}
let newPlans = WeeklyPlanManager.shared.fakeWeeklyPlan()
plans = newPlans
BaseManager.shared.delete(objects: oldPlans)
BaseManager.shared.save(objects: plans)
collectionView.reloadData()
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
let backItem = UIBarButtonItem()
backItem.title = ""
navigationItem.backBarButtonItem = backItem
if segue.identifier == "ShowMeals",
let button = sender as? UIButton{
let destinationVC = segue.destination as! MealViewController
destinationVC.dailyPlan = plans[button.tag]
}
}
}
extension PlanMealListViewController: UICollectionViewDataSource {
func numberOfSections(in collectionView: UICollectionView) -> Int {
return plans.count
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return 1
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: cellIdentifier, for: indexPath) as! PlanCell
let plan = plans[indexPath.section]
cell.plan = plan
cell.dateLabel.text = plan.date.dateAndWeekday()
cell.section = indexPath.section
cell.delegate = self
cell.tableView.reloadData()
return cell
}
}
extension PlanMealListViewController: UICollectionViewDelegateFlowLayout {
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat {
return 0
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumInteritemSpacingForSectionAt section: Int) -> CGFloat {
return 0
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
let headerHeight: CGFloat = navigationController!.navigationBar.bounds.height + UIApplication.shared.statusBarFrame.height
let footerHeight: CGFloat = tabBarController!.tabBar.bounds.height
return CGSize(width: self.view.bounds.width, height: self.view.bounds.height - headerHeight - footerHeight)
// return self.view.bounds.size
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets {
return UIEdgeInsets.zero
}
}
extension PlanMealListViewController: PlanCellDelegate {
func pickButtonTapped(section: Int) {
let plan = plans[section]
for meal in plan.meals {
BaseManager.shared.transaction {
meal.mealFoods.removeAll()
let when = Food.When(rawValue: meal.name)
for _ in 0..<defaultNumbersOfFoodInAMeal {
let mealFood = FoodManager.shared.randomMealFood(of: when!)
meal.mealFoods.append(mealFood)
}
}
}
collectionView.reloadItems(at: [IndexPath(row: 0, section: section)])
}
func editButtonTapped(section: Int) {
// nothing
}
}
| mit | 6a43bfff953243a84cedd56797c0c0cf | 31.951389 | 175 | 0.6647 | 5.608747 | false | false | false | false |
Sajjon/Zeus | Pods/SwiftyBeaver/sources/BaseDestination.swift | 1 | 11867 | //
// BaseDestination.swift
// SwiftyBeaver
//
// Created by Sebastian Kreutzberger (Twitter @skreutzb) on 05.12.15.
// Copyright © 2015 Sebastian Kreutzberger
// Some rights reserved: http://opensource.org/licenses/MIT
//
import Foundation
// store operating system / platform
#if os(iOS)
let OS = "iOS"
#elseif os(OSX)
let OS = "OSX"
#elseif os(watchOS)
let OS = "watchOS"
#elseif os(tvOS)
let OS = "tvOS"
#elseif os(Linux)
let OS = "Linux"
#elseif os(FreeBSD)
let OS = "FreeBSD"
#elseif os(Windows)
let OS = "Windows"
#elseif os(Android)
let OS = "Android"
#else
let OS = "Unknown"
#endif
@available(*, deprecated:0.5.5)
struct MinLevelFilter {
var minLevel = SwiftyBeaver.Level.Verbose
var path = ""
var function = ""
}
/// destination which all others inherit from. do not directly use
public class BaseDestination: Hashable, Equatable {
/// if true additionally logs file, function & line
public var detailOutput = true
/// adds colored log levels where possible
public var colored = true
/// colors entire log
public var coloredLines = false
/// runs in own serial background thread for better performance
public var asynchronously = true
/// do not log any message which has a lower level than this one
public var minLevel = SwiftyBeaver.Level.Verbose {
didSet {
// Craft a new level filter and add it
self.addFilter(filter: Filters.Level.atLeast(level: minLevel))
}
}
/// standard log format; set to "" to not log date at all
public var dateFormat = "yyyy-MM-dd HH:mm:ss.SSS"
/// set custom log level words for each level
public var levelString = LevelString()
/// set custom log level colors for each level
public var levelColor = LevelColor()
public struct LevelString {
public var Verbose = "VERBOSE"
public var Debug = "DEBUG"
public var Info = "INFO"
public var Warning = "WARNING"
public var Error = "ERROR"
}
// For a colored log level word in a logged line
// XCode RGB colors
public struct LevelColor {
public var Verbose = "fg150,178,193;" // silver
public var Debug = "fg32,155,124;" // green
public var Info = "fg70,204,221;" // blue
public var Warning = "fg253,202,78;" // yellow
public var Error = "fg243,36,73;" // red
}
var filters = [FilterType]()
let formatter = DateFormatter()
var reset = "\u{001b}[;"
var escape = "\u{001b}["
// each destination class must have an own hashValue Int
lazy public var hashValue: Int = self.defaultHashValue
public var defaultHashValue: Int {return 0}
// each destination instance must have an own serial queue to ensure serial output
// GCD gives it a prioritization between User Initiated and Utility
var queue: DispatchQueue? //dispatch_queue_t?
public init() {
let uuid = NSUUID().uuidString
let queueLabel = "swiftybeaver-queue-" + uuid
queue = DispatchQueue(label: queueLabel, target: queue)
addFilter(filter: Filters.Level.atLeast(level: minLevel))
}
/// Add a filter that determines whether or not a particular message will be logged to this destination
public func addFilter(filter: FilterType) {
// There can only be a maximum of one level filter in the filters collection.
// When one is set, remove any others if there are any and then add
let isNewLevelFilter = self.getFiltersTargeting(target: Filter.TargetType.LogLevel(minLevel),
fromFilters: [filter]).count == 1
if isNewLevelFilter {
let levelFilters = self.getFiltersTargeting(target: Filter.TargetType.LogLevel(minLevel),
fromFilters: self.filters)
levelFilters.forEach {
filter in
self.removeFilter(filter: filter)
}
}
filters.append(filter)
}
/// Remove a filter from the list of filters
public func removeFilter(filter: FilterType) {
let index = filters.index {
return ObjectIdentifier($0) == ObjectIdentifier(filter)
}
guard let filterIndex = index else {
return
}
filters.remove(at: filterIndex)
}
/// send / store the formatted log message to the destination
/// returns the formatted log message for processing by inheriting method
/// and for unit tests (nil if error)
public func send(_ level: SwiftyBeaver.Level, msg: String, thread: String,
path: String, function: String, line: Int) -> String? {
var dateStr = ""
var str = ""
let levelStr = formattedLevel(level)
let formattedMsg = coloredMessage(msg, forLevel: level)
dateStr = formattedDate(dateFormat)
str = formattedMessage(dateStr, levelString: levelStr, msg: formattedMsg, thread: thread, path: path,
function: function, line: line, detailOutput: detailOutput)
return str
}
/// returns a formatted date string
func formattedDate(_ dateFormat: String) -> String {
//formatter.timeZone = NSTimeZone(abbreviation: "UTC")
formatter.dateFormat = dateFormat
let dateStr = formatter.string(from: NSDate() as Date)
return dateStr
}
/// returns the log message entirely colored
func coloredMessage(_ msg: String, forLevel level: SwiftyBeaver.Level) -> String {
if !(colored && coloredLines) {
return msg
}
let color = colorForLevel(level: level)
let coloredMsg = escape + color + msg + reset
return coloredMsg
}
/// returns color string for level
func colorForLevel(level: SwiftyBeaver.Level) -> String {
var color = ""
switch level {
case SwiftyBeaver.Level.Debug:
color = levelColor.Debug
case SwiftyBeaver.Level.Info:
color = levelColor.Info
case SwiftyBeaver.Level.Warning:
color = levelColor.Warning
case SwiftyBeaver.Level.Error:
color = levelColor.Error
default:
color = levelColor.Verbose
}
return color
}
/// returns an optionally colored level noun (like INFO, etc.)
func formattedLevel(_ level: SwiftyBeaver.Level) -> String {
// optionally wrap the level string in color
let color = colorForLevel(level: level)
var levelStr = ""
switch level {
case SwiftyBeaver.Level.Debug:
levelStr = levelString.Debug
case SwiftyBeaver.Level.Info:
levelStr = levelString.Info
case SwiftyBeaver.Level.Warning:
levelStr = levelString.Warning
case SwiftyBeaver.Level.Error:
levelStr = levelString.Error
default:
// Verbose is default
levelStr = levelString.Verbose
}
if colored {
levelStr = escape + color + levelStr + reset
}
return levelStr
}
/// returns the formatted log message
func formattedMessage(_ dateString: String, levelString: String, msg: String,
thread: String, path: String, function: String, line: Int, detailOutput: Bool) -> String {
var str = ""
if dateString != "" {
str += "[\(dateString)] "
}
if detailOutput {
if thread != "main" && thread != "" {
str += "|\(thread)| "
}
// just use the file name of the path and remove suffix
//let file = path.components(separatedBy: "/").last!.components(".").first!
let pathComponents = path.components(separatedBy: "/")
if let lastComponent = pathComponents.last {
if let file = lastComponent.components(separatedBy: ".").first {
str += "\(file).\(function):\(String(line)) \(levelString): \(msg)"
}
}
} else {
str += "\(levelString): \(msg)"
}
return str
}
/// Answer whether the destination has any message filters
/// returns boolean and is used to decide whether to resolve the message before invoking shouldLevelBeLogged
func hasMessageFilters() -> Bool {
return !getFiltersTargeting(target: Filter.TargetType.Message(.Equals([], true)),
fromFilters: self.filters).isEmpty
}
/// checks if level is at least minLevel or if a minLevel filter for that path does exist
/// returns boolean and can be used to decide if a message should be logged or not
func shouldLevelBeLogged(level: SwiftyBeaver.Level, path: String, function: String, message: String? = nil) -> Bool {
return passesAllRequiredFilters(level: level, path: path, function: function, message: message) &&
passesAtLeastOneNonRequiredFilter(level: level, path: path, function: function, message: message)
}
func getFiltersTargeting(target: Filter.TargetType, fromFilters: [FilterType]) -> [FilterType] {
return fromFilters.filter {
filter in
return filter.getTarget() == target
}
}
func passesAllRequiredFilters(level: SwiftyBeaver.Level, path: String, function: String, message: String?) -> Bool {
let requiredFilters = self.filters.filter {
filter in
return filter.isRequired()
}
return applyFilters(targetFilters: requiredFilters, level: level, path: path,
function: function, message: message) == requiredFilters.count
}
func passesAtLeastOneNonRequiredFilter(level: SwiftyBeaver.Level,
path: String, function: String, message: String?) -> Bool {
let nonRequiredFilters = self.filters.filter {
filter in
return !filter.isRequired()
}
return nonRequiredFilters.isEmpty ||
applyFilters(targetFilters: nonRequiredFilters, level: level, path: path,
function: function, message: message) > 0
}
func passesLogLevelFilters(level: SwiftyBeaver.Level) -> Bool {
let logLevelFilters = getFiltersTargeting(target: Filter.TargetType.LogLevel(level), fromFilters: self.filters)
return logLevelFilters.filter {
filter in
return filter.apply(value: level.rawValue)
}.count == logLevelFilters.count
}
func applyFilters(targetFilters: [FilterType], level: SwiftyBeaver.Level,
path: String, function: String, message: String?) -> Int {
return targetFilters.filter {
filter in
let passes: Bool
switch filter.getTarget() {
case .LogLevel(_):
passes = filter.apply(value: level.rawValue)
case .Path(_):
passes = filter.apply(value: path)
case .Function(_):
passes = filter.apply(value: function)
case .Message(_):
guard let message = message else {
return false
}
passes = filter.apply(value: message)
}
return passes
}.count
}
/**
Triggered by main flush() method on each destination. Runs in background thread.
Use for destinations that buffer log items, implement this function to flush those
buffers to their final destination (web server...)
*/
func flush() {
// no implementation in base destination needed
}
}
public func == (lhs: BaseDestination, rhs: BaseDestination) -> Bool {
return ObjectIdentifier(lhs) == ObjectIdentifier(rhs)
}
| apache-2.0 | 64c944c419984ed66a8384040406efe7 | 33.695906 | 121 | 0.611916 | 4.861122 | false | false | false | false |
CPRTeam/CCIP-iOS | OPass/Tabs/MoreTab/MoreTableViewController.swift | 1 | 12580 | //
// MoreTableViewController.swift
// OPass
//
// Created by 腹黒い茶 on 2019/2/9.
// 2019 OPass.
//
import Foundation
import UIKit
import SwiftUI
import AudioToolbox
import AFNetworking
import FontAwesome_swift
import Nuke
let ACKNOWLEDGEMENTS = "Acknowledgements"
let INTERNAL_CONFIG = "InternalConfig"
class MoreTableViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
@IBOutlet var moreTableView: UITableView?
var shimmeringLogoView: FBShimmeringView = FBShimmeringView.init(frame: CGRect(x: 0, y: 0, width: 500, height: 50))
var userInfo: ScenarioStatus?
var moreItems: NSArray?
var switchEventButton: UIBarButtonItem?
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
let destination = segue.destination
guard let cell = sender as? UITableViewCell else { return }
let title = cell.textLabel?.text
Constants.SendFib("MoreTableView", WithEvents: [ "MoreTitle": title ])
destination.title = title
cell.setSelected(false, animated: true)
}
override func viewDidLoad() {
super.viewDidLoad()
// set logo on nav title
self.shimmeringLogoView.isUserInteractionEnabled = true
let tapGesture = UITapGestureRecognizer.init(target: self, action: #selector(navSingleTap))
tapGesture.numberOfTapsRequired = 1
self.shimmeringLogoView.addGestureRecognizer(tapGesture)
self.navigationItem.titleView = self.shimmeringLogoView
guard let navController = self.navigationController else { return }
let nvBar = navController.navigationBar
nvBar.setBackgroundImage(UIImage.init(), for: .default)
nvBar.shadowImage = UIImage.init()
nvBar.backgroundColor = UIColor.clear
nvBar.isTranslucent = false
let frame = CGRect.init(x: 0, y: 0, width: self.view.frame.size.width, height: (self.view.window?.windowScene?.statusBarManager?.statusBarFrame.height ?? 0) + navController.navigationBar.frame.size.height)
let headView = UIView.init(frame: frame)
headView.setGradientColor(from: Constants.appConfigColor.MoreTitleLeftColor, to: Constants.appConfigColor.MoreTitleRightColor, startPoint: CGPoint(x: -0.4, y: 0.5), toPoint: CGPoint(x: 1, y: 0.5))
let naviBackImg = headView.layer.sublayers?.last?.toImage()
nvBar.setBackgroundImage(naviBackImg, for: .default)
Constants.SendFib("MoreTableViewController")
if self.switchEventButton == nil {
let attribute = [
NSAttributedString.Key.font: UIFont.fontAwesome(ofSize: 20, style: .solid)
]
self.switchEventButton = UIBarButtonItem.init(title: "", style: .plain, target: self, action: #selector(CallSwitchEventView))
self.switchEventButton?.setTitleTextAttributes(attribute, for: .normal)
self.switchEventButton?.title = String.fontAwesomeIcon(code: "fa-sign-out-alt")
}
self.navigationItem.rightBarButtonItem = self.switchEventButton
let emptyButton = UIBarButtonItem.init(title: " ", style: .plain, target: nil, action: nil)
self.navigationItem.leftBarButtonItem = emptyButton;
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
Constants.LoadDevLogoTo(view: self.shimmeringLogoView)
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
if Constants.haveAccessToken {
checkNickName()
}
let features = OPassAPI.eventInfo?.Features.map { feature -> [Any?] in
switch OPassKnownFeatures(rawValue: feature.Feature) {
case Optional(.Puzzle):
return ["Puzzle", feature]
case Optional(.Ticket):
return ["Ticket", feature]
case Optional(.Telegram):
return ["Telegram", feature]
case Optional(.WiFiConnect):
return ["WiFiConnect", feature]
case Optional(.Venue):
return ["VenueWeb", feature]
case Optional(.Staffs):
return ["StaffsWeb", feature]
case Optional(.Sponsors):
return ["SponsorsWeb", feature]
case Optional(.Partners):
return ["PartnersWeb", feature]
case Optional(.WebView):
return ["MoreWeb", feature]
default:
return ["", nil]
}
}
self.moreItems = ((features ?? [["", nil]]) + [
[ACKNOWLEDGEMENTS, nil]
] + (
Constants.isDevMode ? [[INTERNAL_CONFIG, nil]] : []
)).filter {
guard let v = $0[0] else { return false }
guard let s = v as? String else { return false }
return s.count > 0
} as NSArray
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@objc func CallSwitchEventView() {
// clear last event id
OPassAPI.lastEventId = ""
self.dismiss(animated: true, completion: nil)
}
@objc func navSingleTap() {
//NSLog(@"navSingleTap");
self.handleNavTapTimes()
}
func checkNickName(max: Int = 10, current: Int = 1, _ milliseconds: Int = 500) {
NSLog("Check Nick Name \(current)/\(max)")
self.userInfo = OPassAPI.userInfo
if (self.userInfo != nil) {
self.moreTableView?.reloadSections([0], with: .automatic)
} else if (current < max) {
let delayMSec: DispatchTimeInterval = .milliseconds(milliseconds)
DispatchQueue.main.asyncAfter(deadline: .now() + delayMSec) {
self.checkNickName(max: max, current: current + 1, milliseconds)
}
}
}
func handleNavTapTimes() {
struct tap {
static var tapTimes: Int = 0
static var oldTapTime: Date?
static var newTapTime: Date?
}
tap.newTapTime = Date.init()
if (tap.oldTapTime == nil) {
tap.oldTapTime = tap.newTapTime
}
if let newTapTime = tap.newTapTime {
if let oldTapTime = tap.oldTapTime {
if (newTapTime.timeIntervalSince(oldTapTime) <= 0.25) {
tap.tapTimes += 1
if (tap.tapTimes >= 10) {
NSLog("-- Success tap 10 times --")
AudioServicesPlaySystemSound(kSystemSoundID_Vibrate)
if !Constants.isDevMode {
NSLog("-- Enable DEV_MODE --")
Constants.isDevMode = true
} else {
NSLog("-- Disable DEV_MODE --")
Constants.isDevMode = false
}
Constants.LoadDevLogoTo(view: self.shimmeringLogoView)
tap.tapTimes = 1
}
} else {
NSLog("-- Failed, just tap %2d times --", tap.tapTimes)
NSLog("-- Failed to trigger DEV_MODE --")
tap.tapTimes = 1
}
tap.oldTapTime = tap.newTapTime
}
}
}
// MARK: - Table view data source
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
guard let moreTableView = self.moreTableView else { return CGFloat(0) }
guard let moreItems = self.moreItems else { return moreTableView.frame.size.height }
return moreTableView.frame.size.height / CGFloat(moreItems.count + 1)
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
guard let moreItems = self.moreItems else { return 0 }
return moreItems.count
}
func tableView(_ tableView: UITableView, titleForHeaderInSection section: NSInteger) -> String? {
return (self.userInfo?.UserId.count ?? 0) > 0 ? String(format: NSLocalizedString("Hi", comment: ""), self.userInfo?.UserId ?? "") : nil;
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
if let moreItems = self.moreItems {
if let item = moreItems.object(at: indexPath.row) as? NSArray {
let feature = item[1] as? EventFeatures
if let cellId = item[0] as? String {
if let cell = tableView.dequeueReusableCell(withIdentifier: cellId, for: indexPath) as? MoreCell {
cell.Feature = feature
cell.backgroundColor = .clear
let cellIconId = NSLocalizedString("icon-\(cellId)", comment: "");
// FontAwesome Icon
if let classId = cellIconId.split(separator: " ").first {
var fontStyle: FontAwesomeStyle {
switch String(classId) {
case "fas":
return FontAwesomeStyle.solid
case "fab":
return FontAwesomeStyle.brands
default:
return FontAwesomeStyle.solid
}
}
if let fontName = FontAwesome(rawValue: String(cellIconId.split(separator: " ").last ?? "")) {
if let iV = cell.imageView {
iV.image = UIImage.fontAwesomeIcon(name: fontName, style: fontStyle, textColor: UIColor.black, size: CGSize(width: 24, height: 24))
}
}
}
// Custome Icon
if let customIconUrl = feature?.Icon {
ImagePipeline.shared.loadImage(
with: customIconUrl,
progress: { _, _, _ in
print("progress updated")
},
completion: { (result: Result<ImageResponse, ImagePipeline.Error>) in
print("task completed")
cell.imageView?.image = try? result.get().image.scaled(to: CGSize(width: 24, height: 24))
}
)
}
let cellText = [ACKNOWLEDGEMENTS, INTERNAL_CONFIG].contains(where: { $0 == cellId } ) ?
NSLocalizedString(cellId, comment: "") :
(feature?.DisplayText[Constants.shortLangUI] ?? "")
if ((OPassAPI.userInfo?.Role ?? "").count > 0 && !(feature?.VisibleRoles?.contains(OPassAPI.userInfo?.Role ?? "") ?? true)) {
cell.isUserInteractionEnabled = false
}
cell.textLabel?.text = cellText
return cell;
}
}
}
}
return tableView.dequeueReusableCell(withIdentifier: "", for: indexPath)
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
guard let cell = tableView.cellForRow(at: indexPath) as? MoreCell else { return }
switch (cell.Feature?.Feature) {
case OPassKnownFeatures.WebView.rawValue:
guard let url = cell.Feature?.Url else { break }
Constants.OpenInAppSafari(forURL: url)
break
case OPassKnownFeatures.WiFiConnect.rawValue:
guard let wifi = cell.Feature?.WiFi.first else { break }
NEHotspot.ConnectWiFi(SSID: wifi.SSID, withPass: wifi.Password)
break
default:
break
}
tableView.deselectRow(at: indexPath, animated: true)
}
@IBSegueAction func addInternalConfigView(_ coder: NSCoder) -> UIViewController? {
if let hostingController = UIHostingController(coder: coder, rootView: InternalConfigView()) {
hostingController.view.backgroundColor = UIColor.clear;
return hostingController
}
return nil
}
}
| gpl-3.0 | c979fe3622ea5ef4961d5b1922836048 | 41.610169 | 213 | 0.558154 | 5.233139 | false | false | false | false |
nRewik/swift-corelibs-foundation | Foundation/NSIndexSet.swift | 1 | 24241 | // This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2015 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
/* Class for managing set of indexes. The set of valid indexes are 0 .. NSNotFound - 1; trying to use indexes outside this range is an error. NSIndexSet uses NSNotFound as a return value in cases where the queried index doesn't exist in the set; for instance, when you ask firstIndex and there are no indexes; or when you ask for indexGreaterThanIndex: on the last index, and so on.
The following code snippets can be used to enumerate over the indexes in an NSIndexSet:
// Forward
var currentIndex = set.firstIndex
while currentIndex != NSNotFound {
...
currentIndex = set.indexGreaterThanIndex(currentIndex)
}
// Backward
var currentIndex = set.lastIndex
while currentIndex != NSNotFound {
...
currentIndex = set.indexLessThanIndex(currentIndex)
}
To enumerate without doing a call per index, you can use the method getIndexes:maxCount:inIndexRange:.
*/
public class NSIndexSet : NSObject, NSCopying, NSMutableCopying, NSSecureCoding {
// all instance variables are private
internal var _ranges = [NSRange]()
internal var _count = 0
override public init() {
_count = 0
_ranges = []
}
public init(indexesInRange range: NSRange) {
_count = range.length
_ranges = _count == 0 ? [] : [range]
}
public init(indexSet: NSIndexSet) {
_ranges = indexSet._ranges
_count = indexSet.count
}
public func copyWithZone(zone: NSZone) -> AnyObject { NSUnimplemented() }
public func mutableCopyWithZone(zone: NSZone) -> AnyObject { NSUnimplemented() }
public static func supportsSecureCoding() -> Bool { return true }
public required init?(coder aDecoder: NSCoder) { NSUnimplemented() }
public func encodeWithCoder(aCoder: NSCoder) {
NSUnimplemented()
}
public convenience init(index value: Int) {
self.init(indexesInRange: NSMakeRange(value, 1))
}
public func isEqualToIndexSet(indexSet: NSIndexSet) -> Bool {
guard indexSet !== self else {
return true
}
let otherRanges = indexSet._ranges
if _ranges.count != otherRanges.count {
return false
}
for (r1, r2) in zip(_ranges, otherRanges) {
if r1.length != r2.length || r1.location != r2.location {
return false
}
}
return true
}
public var count: Int {
return _count
}
/* The following six methods will return NSNotFound if there is no index in the set satisfying the query.
*/
public var firstIndex: Int {
return _ranges.first?.location ?? NSNotFound
}
public var lastIndex: Int {
guard _ranges.count > 0 else {
return NSNotFound
}
return NSMaxRange(_ranges.last!) - 1
}
internal func _indexAndRangeAdjacentToOrContainingIndex(idx : Int) -> (Int, NSRange)? {
let count = _ranges.count
guard count > 0 else {
return nil
}
var min = 0
var max = count - 1
while min < max {
let rIdx = (min + max) / 2
let range = _ranges[rIdx]
if range.location > idx {
max = rIdx
} else if NSMaxRange(range) - 1 < idx {
min = rIdx + 1
} else {
return (rIdx, range)
}
}
return (min, _ranges[min])
}
internal func _indexOfRangeContainingIndex (idx : Int) -> Int? {
if let (rIdx, range) = _indexAndRangeAdjacentToOrContainingIndex(idx) {
return NSLocationInRange(idx, range) ? rIdx : nil
} else {
return nil
}
}
internal func _indexOfRangeBeforeOrContainingIndex(idx : Int) -> Int? {
if let (rIdx, range) = _indexAndRangeAdjacentToOrContainingIndex(idx) {
if range.location <= idx {
return rIdx
} else if rIdx > 0 {
return rIdx - 1
} else {
return nil
}
} else {
return nil
}
}
internal func _indexOfRangeAfterOrContainingIndex(idx : Int) -> Int? {
if let (rIdx, range) = _indexAndRangeAdjacentToOrContainingIndex(idx) {
if NSMaxRange(range) - 1 >= idx {
return rIdx
} else if rIdx + 1 < _ranges.count {
return rIdx + 1
} else {
return nil
}
} else {
return nil
}
}
internal func _indexClosestToIndex(idx: Int, equalAllowed : Bool, following: Bool) -> Int? {
guard _count > 0 else {
return nil
}
if following {
var result = idx
if !equalAllowed {
guard idx < NSNotFound else {
return nil
}
result += 1
}
if let rangeIndex = _indexOfRangeAfterOrContainingIndex(result) {
let range = _ranges[rangeIndex]
return NSLocationInRange(result, range) ? result : range.location
}
} else {
var result = idx
if !equalAllowed {
guard idx > 0 else {
return nil
}
result -= 1
}
if let rangeIndex = _indexOfRangeBeforeOrContainingIndex(result) {
let range = _ranges[rangeIndex]
return NSLocationInRange(result, range) ? result : (NSMaxRange(range) - 1)
}
}
return nil
}
public func indexGreaterThanIndex(value: Int) -> Int {
return _indexClosestToIndex(value, equalAllowed: false, following: true) ?? NSNotFound
}
public func indexLessThanIndex(value: Int) -> Int {
return _indexClosestToIndex(value, equalAllowed: false, following: false) ?? NSNotFound
}
public func indexGreaterThanOrEqualToIndex(value: Int) -> Int {
return _indexClosestToIndex(value, equalAllowed: true, following: true) ?? NSNotFound
}
public func indexLessThanOrEqualToIndex(value: Int) -> Int {
return _indexClosestToIndex(value, equalAllowed: true, following: false) ?? NSNotFound
}
/* Fills up to bufferSize indexes in the specified range into the buffer and returns the number of indexes actually placed in the buffer; also modifies the optional range passed in by pointer to be "positioned" after the last index filled into the buffer.Example: if the index set contains the indexes 0, 2, 4, ..., 98, 100, for a buffer of size 10 and the range (20, 80) the buffer would contain 20, 22, ..., 38 and the range would be modified to (40, 60).
*/
public func getIndexes(indexBuffer: UnsafeMutablePointer<Int>, maxCount bufferSize: Int, inIndexRange range: NSRangePointer) -> Int {
let minIndex : Int
let maxIndex : Int
if range != nil {
minIndex = range.memory.location
maxIndex = NSMaxRange(range.memory) - 1
} else {
minIndex = firstIndex
maxIndex = lastIndex
}
guard minIndex <= maxIndex else {
return 0
}
if let initialRangeIndex = self._indexOfRangeAfterOrContainingIndex(minIndex) {
var rangeIndex = initialRangeIndex
let rangeCount = _ranges.count
var counter = 0
var idx = minIndex
var offset = 0
while rangeIndex < rangeCount && idx <= maxIndex && counter < bufferSize {
let currentRange = _ranges[rangeIndex]
if currentRange.location <= minIndex {
idx = minIndex
offset = minIndex - currentRange.location
} else {
idx = currentRange.location
}
while idx <= maxIndex && counter < bufferSize && offset < currentRange.length {
indexBuffer.advancedBy(counter).memory = idx
counter += 1
idx += 1
offset += 1
}
if offset >= currentRange.length {
rangeIndex += 1
offset = 0
}
}
if counter > 0 && range != nil {
let delta = indexBuffer.advancedBy(counter - 1).memory - minIndex + 1
range.memory.location += delta
range.memory.length -= delta
}
return counter
} else {
return 0
}
}
public func countOfIndexesInRange(range: NSRange) -> Int {
guard _count > 0 && range.length > 0 else {
return 0
}
if let initialRangeIndex = self._indexOfRangeAfterOrContainingIndex(range.location) {
var rangeIndex = initialRangeIndex
let maxRangeIndex = NSMaxRange(range) - 1
var result = 0
let firstRange = _ranges[rangeIndex]
if firstRange.location < range.location {
if NSMaxRange(firstRange) - 1 >= maxRangeIndex {
return range.length
}
result = NSMaxRange(firstRange) - range.location
rangeIndex += 1
}
for curRange in _ranges.suffixFrom(rangeIndex) {
if NSMaxRange(curRange) - 1 > maxRangeIndex {
if curRange.location <= maxRangeIndex {
result += maxRangeIndex + 1 - curRange.location
}
break
}
result += curRange.length
}
return result
} else {
return 0
}
}
public func containsIndex(value: Int) -> Bool {
return _indexOfRangeContainingIndex(value) != nil
}
public func containsIndexesInRange(range: NSRange) -> Bool {
guard range.length > 0 else {
return false
}
if let rIdx = self._indexOfRangeContainingIndex(range.location) {
return NSMaxRange(_ranges[rIdx]) >= NSMaxRange(range)
} else {
return false
}
}
public func containsIndexes(indexSet: NSIndexSet) -> Bool {
guard self !== indexSet else {
return true
}
var result = true
enumerateRangesUsingBlock { range, stop in
if !self.containsIndexesInRange(range) {
result = false
stop.memory = true
}
}
return result
}
public func intersectsIndexesInRange(range: NSRange) -> Bool {
guard range.length > 0 else {
return false
}
if let rIdx = _indexOfRangeBeforeOrContainingIndex(range.location) {
if NSMaxRange(_ranges[rIdx]) - 1 >= range.location {
return true
}
}
if let rIdx = _indexOfRangeAfterOrContainingIndex(range.location) {
if NSMaxRange(range) - 1 >= _ranges[rIdx].location {
return true
}
}
return false
}
internal func _enumerateWithOptions<P, R>(opts : NSEnumerationOptions, range: NSRange, paramType: P.Type, returnType: R.Type, block: (P, UnsafeMutablePointer<ObjCBool>) -> R) -> Int? {
guard !opts.contains(.Concurrent) else {
NSUnimplemented()
}
guard let startRangeIndex = self._indexOfRangeAfterOrContainingIndex(range.location), let endRangeIndex = _indexOfRangeBeforeOrContainingIndex(NSMaxRange(range) - 1) else {
return nil
}
var result : Int? = nil
let reverse = opts.contains(.Reverse)
let passRanges = paramType == NSRange.self
let findIndex = returnType == Bool.self
var stop = false
let ranges = _ranges[startRangeIndex...endRangeIndex]
let rangeSequence = (reverse ? AnySequence(ranges.reverse()) : AnySequence(ranges))
outer: for curRange in rangeSequence {
let intersection = NSIntersectionRange(curRange, range)
if passRanges {
if intersection.length > 0 {
block(intersection as! P, &stop)
}
if stop {
break outer
}
} else if intersection.length > 0 {
let maxIndex = NSMaxRange(intersection) - 1
let indexes = reverse ? maxIndex.stride(through: intersection.location, by: -1) : intersection.location.stride(through: maxIndex, by: 1)
for idx in indexes {
if findIndex {
let found : Bool = block(idx as! P, &stop) as! Bool
if found {
result = idx
stop = true
}
} else {
block(idx as! P, &stop)
}
if stop {
break outer
}
}
} // else, continue
}
return result
}
public func enumerateIndexesUsingBlock(block: (Int, UnsafeMutablePointer<ObjCBool>) -> Void) {
enumerateIndexesWithOptions([], usingBlock: block)
}
public func enumerateIndexesWithOptions(opts: NSEnumerationOptions, usingBlock block: (Int, UnsafeMutablePointer<ObjCBool>) -> Void) {
_enumerateWithOptions(opts, range: NSMakeRange(0, Int.max), paramType: Int.self, returnType: Void.self, block: block)
}
public func enumerateIndexesInRange(range: NSRange, options opts: NSEnumerationOptions, usingBlock block: (Int, UnsafeMutablePointer<ObjCBool>) -> Void) {
_enumerateWithOptions(opts, range: range, paramType: Int.self, returnType: Void.self, block: block)
}
public func indexPassingTest(predicate: (Int, UnsafeMutablePointer<ObjCBool>) -> Bool) -> Int {
return indexWithOptions([], passingTest: predicate)
}
public func indexWithOptions(opts: NSEnumerationOptions, passingTest predicate: (Int, UnsafeMutablePointer<ObjCBool>) -> Bool) -> Int {
return _enumerateWithOptions(opts, range: NSMakeRange(0, Int.max), paramType: Int.self, returnType: Bool.self, block: predicate) ?? NSNotFound
}
public func indexInRange(range: NSRange, options opts: NSEnumerationOptions, passingTest predicate: (Int, UnsafeMutablePointer<ObjCBool>) -> Bool) -> Int {
return _enumerateWithOptions(opts, range: range, paramType: Int.self, returnType: Bool.self, block: predicate) ?? NSNotFound
}
public func indexesPassingTest(predicate: (Int, UnsafeMutablePointer<ObjCBool>) -> Bool) -> NSIndexSet {
return indexesInRange(NSMakeRange(0, Int.max), options: [], passingTest: predicate)
}
public func indexesWithOptions(opts: NSEnumerationOptions, passingTest predicate: (Int, UnsafeMutablePointer<ObjCBool>) -> Bool) -> NSIndexSet {
return indexesInRange(NSMakeRange(0, Int.max), options: opts, passingTest: predicate)
}
public func indexesInRange(range: NSRange, options opts: NSEnumerationOptions, passingTest predicate: (Int, UnsafeMutablePointer<ObjCBool>) -> Bool) -> NSIndexSet {
let result = NSMutableIndexSet()
_enumerateWithOptions(opts, range: range, paramType: Int.self, returnType: Void.self) { idx, stop in
if predicate(idx, stop) {
result.addIndex(idx)
}
}
return result
}
/*
The following three convenience methods allow you to enumerate the indexes in the receiver by ranges of contiguous indexes. The performance of these methods is not guaranteed to be any better than if they were implemented with enumerateIndexesInRange:options:usingBlock:. However, depending on the receiver's implementation, they may perform better than that.
If the specified range for enumeration intersects a range of contiguous indexes in the receiver, then the block will be invoked with the intersection of those two ranges.
*/
public func enumerateRangesUsingBlock(block: (NSRange, UnsafeMutablePointer<ObjCBool>) -> Void) {
enumerateRangesWithOptions([], usingBlock: block)
}
public func enumerateRangesWithOptions(opts: NSEnumerationOptions, usingBlock block: (NSRange, UnsafeMutablePointer<ObjCBool>) -> Void) {
_enumerateWithOptions(opts, range: NSMakeRange(0, Int.max), paramType: NSRange.self, returnType: Void.self, block: block)
}
public func enumerateRangesInRange(range: NSRange, options opts: NSEnumerationOptions, usingBlock block: (NSRange, UnsafeMutablePointer<ObjCBool>) -> Void) {
_enumerateWithOptions(opts, range: range, paramType: NSRange.self, returnType: Void.self, block: block)
}
}
extension NSIndexSet : SequenceType {
public struct Generator : GeneratorType {
internal let _set: NSIndexSet
internal var _first: Bool = true
internal var _current: Int?
internal init(_ set: NSIndexSet) {
self._set = set
self._current = nil
}
public mutating func next() -> Int? {
if _first {
_current = _set.firstIndex
_first = false
} else if let c = _current {
_current = _set.indexGreaterThanIndex(c)
}
if _current == NSNotFound {
_current = nil
}
return _current
}
}
public func generate() -> Generator {
return Generator(self)
}
}
public class NSMutableIndexSet : NSIndexSet {
public func addIndexes(indexSet: NSIndexSet) {
indexSet.enumerateRangesUsingBlock { range, _ in
self.addIndexesInRange(range)
}
}
public func removeIndexes(indexSet: NSIndexSet) {
indexSet.enumerateRangesUsingBlock { range, _ in
self.removeIndexesInRange(range)
}
}
public func removeAllIndexes() {
_ranges = []
_count = 0
}
public func addIndex(value: Int) {
self.addIndexesInRange(NSMakeRange(value, 1))
}
public func removeIndex(value: Int) {
self.removeIndexesInRange(NSMakeRange(value, 1))
}
internal func _insertRange(range: NSRange, atIndex index: Int) {
_ranges.insert(range, atIndex: index)
_count += range.length
}
internal func _replaceRangeAtIndex(index: Int, withRange range: NSRange?) {
let oldRange = _ranges[index]
if let range = range {
_ranges[index] = range
_count += range.length - oldRange.length
} else {
_ranges.removeAtIndex(index)
_count -= oldRange.length
}
}
internal func _mergeOverlappingRangesStartingAtIndex(index: Int) {
var rangeIndex = index
while _ranges.count > 0 && rangeIndex < _ranges.count - 1 {
let curRange = _ranges[rangeIndex]
let nextRange = _ranges[rangeIndex + 1]
let curEnd = NSMaxRange(curRange)
let nextEnd = NSMaxRange(nextRange)
if curEnd >= nextRange.location {
// overlaps
if curEnd < nextEnd {
self._replaceRangeAtIndex(rangeIndex, withRange: NSMakeRange(nextEnd - curRange.location, curRange.length))
rangeIndex += 1
}
self._replaceRangeAtIndex(rangeIndex + 1, withRange: nil)
} else {
break
}
}
}
public func addIndexesInRange(range: NSRange) {
guard range.length > 0 else {
return
}
let addEnd = NSMaxRange(range)
let startRangeIndex = _indexOfRangeBeforeOrContainingIndex(range.location) ?? 0
var replacedRangeIndex : Int?
var rangeIndex = startRangeIndex
while rangeIndex < _ranges.count {
let curRange = _ranges[rangeIndex]
let curEnd = NSMaxRange(curRange)
if addEnd < curRange.location {
_insertRange(range, atIndex: rangeIndex)
// Done. No need to merge
return
} else if range.location < curRange.location && addEnd >= curRange.location {
if addEnd > curEnd {
_replaceRangeAtIndex(rangeIndex, withRange: range)
} else {
_replaceRangeAtIndex(rangeIndex, withRange: NSMakeRange(range.location, curEnd - range.location))
}
replacedRangeIndex = rangeIndex
// Proceed to merging
break
} else if range.location >= curRange.location && addEnd < curEnd {
// Nothing to add
return
} else if range.location >= curRange.location && range.location <= curEnd && addEnd > curEnd {
_replaceRangeAtIndex(rangeIndex, withRange: NSMakeRange(addEnd - curRange.location, curRange.location))
replacedRangeIndex = rangeIndex
// Proceed to merging
break
}
rangeIndex += 1
}
if let r = replacedRangeIndex {
_mergeOverlappingRangesStartingAtIndex(r)
} else {
_insertRange(range, atIndex: _ranges.count)
}
}
public func removeIndexesInRange(range: NSRange) {
guard range.length > 0 else {
return
}
guard let startRangeIndex = (range.location > 0) ? _indexOfRangeAfterOrContainingIndex(range.location) : 0 else {
return
}
let removeEnd = NSMaxRange(range)
var rangeIndex = startRangeIndex
while rangeIndex < _ranges.count {
let curRange = _ranges[rangeIndex]
let curEnd = NSMaxRange(curRange)
if removeEnd < curRange.location {
// Nothing to remove
return
} else if range.location <= curRange.location && removeEnd >= curRange.location {
if removeEnd >= curEnd {
_replaceRangeAtIndex(rangeIndex, withRange: nil)
// Don't increment rangeIndex
continue
} else {
self._replaceRangeAtIndex(rangeIndex, withRange: NSMakeRange(removeEnd, curEnd - removeEnd))
return
}
} else if range.location > curRange.location && removeEnd < curEnd {
let firstPiece = NSMakeRange(curRange.location, range.location - curRange.location)
let secondPiece = NSMakeRange(removeEnd, curEnd - removeEnd)
_replaceRangeAtIndex(rangeIndex, withRange: secondPiece)
_insertRange(firstPiece, atIndex: rangeIndex)
} else if range.location > curRange.location && range.location < curEnd && removeEnd >= curEnd {
_replaceRangeAtIndex(rangeIndex, withRange: NSMakeRange(curRange.location, range.location - curRange.location))
}
rangeIndex += 1
}
}
/* For a positive delta, shifts the indexes in [index, INT_MAX] to the right, thereby inserting an "empty space" [index, delta], for a negative delta, shifts the indexes in [index, INT_MAX] to the left, thereby deleting the indexes in the range [index - delta, delta].
*/
public func shiftIndexesStartingAtIndex(index: Int, by delta: Int) { NSUnimplemented() }
}
| apache-2.0 | 9da136796cc0e1d5a1cdd78abe2e9308 | 38.41626 | 461 | 0.575306 | 5.348853 | false | false | false | false |
1457792186/JWSwift | SwiftLearn/SwiftDemo/SwiftDemo/Home/JWHomeViewController.swift | 1 | 3897 | //
// JWHomeViewController.swift
// SwiftDemo
//
// Created by apple on 17/5/4.
// Copyright © 2017年 UgoMedia. All rights reserved.
//
import UIKit
class JWHomeViewController: JWBasicViewController,UITableViewDelegate,UITableViewDataSource{
@IBOutlet weak var homeTableView: UITableView!
@objc var dataArr = [JWHomeModel]();
override func viewDidLoad() {
super.viewDidLoad()
self.title = "首页";
self.registerTableView();
self.dataArrSet();
}
@objc func registerTableView() -> Void {
// self.homeTableView.register(JWHomeTableViewCell.self, forCellReuseIdentifier: "JWHomeTableViewCell");
let cellNib = UINib(nibName: "JWHomeTableViewCell", bundle: nil)
self.homeTableView.register(cellNib, forCellReuseIdentifier: "JWHomeTableViewCell")
}
@objc func dataArrSet(){
let nameArr = ["英雄联盟","DOTA"];
let subNameArr = ["各路英雄大逃杀","荣耀背后的嗜血神灵"];
let titleArr = ["英雄联盟","英雄联盟","英雄联盟","英雄联盟"];
let anchorArr = ["水晶卡特","赛事专用直播间","Riot、LCS","主播油条"];
let countArr = ["4535","70000","69000","476000"];
let subTitleArr = ["2J杀人如何利用卡特琳娜顺利爬","LSPL春季赛SNG vs RYL直播中","LCS TSM vs FOX 正在直播","油条:五个隐身英雄套路上分系"];
let imgArr = ["home_logo_video0","home_logo_video1","home_logo_video2","home_logo_video3"];
for index in 0..<2{
let dataDic:NSMutableDictionary = NSMutableDictionary.init(capacity: 0);
dataDic.setObject(nameArr[index%2], forKey: "title" as NSCopying);
dataDic.setObject("home_logo_type\(index%2)", forKey:"imageName" as NSCopying);
dataDic.setObject(subNameArr[index%2], forKey:"subTitle" as NSCopying);
let contentArr:NSMutableArray = NSMutableArray.init(capacity: 0);
for idx in 0..<titleArr.count {
if idx%2 == index {
let contentDic:NSMutableDictionary = NSMutableDictionary.init(capacity: 0);
contentDic.setObject(titleArr[idx], forKey: "type" as NSCopying);
contentDic.setObject(imgArr[idx], forKey: "imageName" as NSCopying);
contentDic.setObject(countArr[idx], forKey: "audienceCount" as NSCopying);
contentDic.setObject(subTitleArr[idx], forKey: "title" as NSCopying);
contentDic.setObject(anchorArr[idx], forKey: "uper" as NSCopying);
contentArr.add(contentDic);
}
}
dataDic.setObject(contentArr, forKey:"content" as NSCopying);
dataArr.append(JWHomeModel.init(dataDic: dataDic));
}
}
// MARK: - UITableViewDelegate
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath){
let detailVC = JWHomeDetailViewController();
let detailModel = dataArr[indexPath.row];
detailVC.dataModel = detailModel.content;
self.navigationController?.pushViewController(detailVC, animated:true);
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat{
return (80 * mainScreenWidth / 375.0);
}
// MARK: - UITableViewDataSource
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int{
return dataArr.count;
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell{
let homeCell:JWHomeTableViewCell = tableView.dequeueReusableCell(withIdentifier: "JWHomeTableViewCell", for: indexPath) as! JWHomeTableViewCell;
homeCell.setData(dataModel: dataArr[indexPath.row]);
return homeCell;
}
}
| apache-2.0 | 3e7422db2fee6e235da1c6f1b6ec6c8a | 42.670588 | 152 | 0.640894 | 4.461538 | false | false | false | false |
jpedrosa/sua_nc | Sources/csv_table.swift | 2 | 8531 |
enum CSVTableParserEntry {
case Header
case HeaderExit
case Row
case RowExit
case Column
case ColumnQuoted
}
// Unicode data.
//
// The file format is like this:
//
// * The first row includes the serial number only. It is a sequencial number
// starting from 0 that helps to make the rows unique for updating and deleting.
//
// * The second row is the header row that helps to give a label to each column.
// The very first column is already labeled by default with "id".
//
// * From the third row onwards we find the actual data rows. They all start
// with the id column.
//
// * All rows should end with just the newline character(\n or 10).
//
// * All rows should include the same number of columns.
//
// * Data is in general represented in string format only. It simplifies it
// a lot and may match the use-case of users when they already have strings to
// compare the data with.
//
// * The column data follows the convention specified on this Wikipedia entry:
// https://en.wikipedia.org/wiki/Comma-separated_values
// Where columns can start with a double quote which can include within it:
//
// ** A data comma. E.g. "Hey, ho"
//
// ** A data newline character. E.g. "So \n it begins."
//
// ** And even a data double quote if it is escaped with another double
// quote. E.g. "Let's "" go"
//
public struct CSVTable {
var _path: String
public var serialId = 0
var stream = ByteStream()
var entryParser = CSVTableParserEntry.Header
var _header = [String]()
var columnGroup = CSVTableParserEntry.Header
var recordExit = CSVTableParserEntry.HeaderExit
var columnValue = ""
var _rows = [[String]]()
var _row = [String]()
var unescapedColumnValue = ""
public init(path: String) throws {
_path = path
try load()
}
mutating public func load() throws {
var f = try File(path: _path)
defer { f.close() }
stream.bytes = try f.readAllBytes()
if stream.eatWhileDigit() {
serialId = Int(stream.collectTokenString()!)!
if stream.eatOne(10) { // Newline
entryParser = .Column
_header = []
columnGroup = .Header
recordExit = .HeaderExit
while !stream.isEol {
try next()
}
// Be nice and check for a last row without a trailing new line
// following it. Sometimes when manually editing a file, the last line
// could lose its new line.
if !_row.isEmpty {
try inRowExit()
}
} else {
throw CSVTableError.NewLine
}
} else {
throw CSVTableError.SerialId
}
}
mutating func next() throws {
switch entryParser {
case .Header:
try inHeader()
case .HeaderExit:
try inHeaderExit()
case .Row:
try inRow()
case .RowExit:
try inRowExit()
case .Column:
try inColumn()
case .ColumnQuoted:
try inColumnQuoted()
}
}
mutating func inHeader() throws {
_header.append(columnValue)
entryParser = .Column
}
mutating func inHeaderExit() throws {
if header.isEmpty {
throw CSVTableError.Header
}
entryParser = .Column
columnGroup = .Row
recordExit = .RowExit
_row = []
}
mutating func inRow() throws {
_row.append(columnValue)
entryParser = .Column
}
mutating func inRowExit() throws {
if _row.count != _header.count {
throw CSVTableError.Row
}
entryParser = .Column
_rows.append(_row)
_row = []
}
func matchCommaOrNewLine(c: UInt8) -> Bool {
return c == 44 || c == 10
}
mutating func inColumn() throws {
stream.startIndex = stream.currentIndex
if stream.eatDoubleQuote() {
unescapedColumnValue = ""
entryParser = .ColumnQuoted
stream.startIndex = stream.currentIndex
} else if stream.eatComma() {
columnValue = ""
entryParser = columnGroup
} else if stream.eatUntil(matchCommaOrNewLine) {
columnValue = stream.collectTokenString()!
stream.eatComma()
entryParser = columnGroup
} else if stream.eatOne(10) {
entryParser = recordExit
} else {
throw CSVTableError.Unreachable
}
}
mutating func inColumnQuoted() throws {
if stream.skipTo(34) >= 0 { // "
if let s = stream.collectTokenString() {
unescapedColumnValue += s
}
stream.eatDoubleQuote()
stream.startIndex = stream.currentIndex
if !stream.eatDoubleQuote() { // Ends if not an escaped quote sequence: ""
if let s = stream.collectTokenString() {
unescapedColumnValue += s
}
columnValue = unescapedColumnValue
stream.eatComma()
entryParser = columnGroup
}
} else {
throw CSVTableError.Column
}
}
public var path: String { return _path }
public var header: [String] { return _header }
public var rows: [[String]] { return _rows }
// Don't include the id, since it will be automatically generated based on the
// next number on the sequence.
mutating public func insert(row: [String]) throws -> Int {
if row.count + 1 != header.count {
throw CSVTableError.Insert
}
var a = [String]()
let sid = serialId
a.append("\(sid)")
for s in row {
a.append(s)
}
_rows.append(a)
serialId += 1
return sid
}
// Alias for insert.
mutating public func append(row: [String]) throws -> Int {
return try insert(row)
}
// This will insert it if it does not exist, and it will keep whatever index
// id it was called with. This can help with data migration. The serialId
// can be adjusted accordingly afterwards.
mutating public func update(index: String, row: [String]) throws {
if row.count + 1 != header.count {
throw CSVTableError.Update
}
let n = findIndex(index)
if n >= 0 {
for i in 0..<row.count {
_rows[n][i + 1] = row[i]
}
} else {
var a = [String]()
a.append(index)
for s in row {
a.append(s)
}
_rows.append(a)
}
}
func findIndex(index: String) -> Int {
for i in 0..<_rows.count {
if _rows[i][0] == index {
return i
}
}
return -1
}
// If the record pointed at by index does not exist, simply ignore it.
mutating public func delete(index: String) {
let n = findIndex(index)
if n >= 0 {
_rows.removeAtIndex(n)
}
}
mutating public func updateColumn(index: String, columnIndex: Int,
value: String) {
let n = findIndex(index)
if n >= 0 {
_rows[n][columnIndex] = value
}
}
mutating public func select(index: String) -> [String]? {
let n = findIndex(index)
if n >= 0 {
return _rows[n]
}
return nil
}
public var data: String {
var s = "\(serialId)\n"
var comma = false
for c in _header {
if comma { s += "," }
s += CSVTable.escape(c)
comma = true
}
s += "\n"
if !_rows.isEmpty {
for row in _rows {
var comma = false
for c in row {
if comma { s += "," }
s += CSVTable.escape(c)
comma = true
}
s += "\n"
}
s += "\n"
}
return s
}
public func save() throws {
try IO.write(path, string: data)
}
// This makes sure the data is escaped for double quote, comma and new line.
public static func escape(string: String) -> String {
let len = string.utf16.count
var i = 0
while i < len {
let c = string.utf16.codeUnitAt(i)
if c == 34 || c == 44 || c == 10 { // " , newline
i += 1
var s = "\""
s += string.utf16.substring(0, endIndex: i) ?? ""
if c == 34 {
s += "\""
}
var si = i
while i < len {
if string.utf16.codeUnitAt(i) == 34 {
s += string.utf16.substring(si, endIndex: i + 1) ?? ""
s += "\""
si = i + 1
}
i += 1
}
s += string.utf16.substring(si, endIndex: i) ?? ""
s += "\""
return s
}
i += 1
}
return string
}
public static func create(path: String, header: [String]) throws -> CSVTable {
var s = "0\nid"
for c in header {
s += ","
s += escape(c)
}
s += "\n"
try IO.write(path, string: s)
return try CSVTable(path: path)
}
}
enum CSVTableError: ErrorType {
case SerialId
case NewLine
case Header
case Row
case Column
case Insert
case Update
case Unreachable
}
| apache-2.0 | 8d689083de0bf42a7dfd61981bf8e929 | 23.514368 | 80 | 0.585981 | 3.953197 | false | false | false | false |
milseman/swift | test/stdlib/CharacterTraps.swift | 8 | 917 | // RUN: %empty-directory(%t)
// RUN: %target-build-swift %s -o %t/a.out_Debug
// RUN: %target-build-swift %s -o %t/a.out_Release -O
//
// RUN: %target-run %t/a.out_Debug
// RUN: %target-run %t/a.out_Release
// REQUIRES: executable_test
import StdlibUnittest
let testSuiteSuffix = _isDebugAssertConfiguration() ? "_debug" : "_release"
var CharacterTraps = TestSuite("CharacterTraps" + testSuiteSuffix)
CharacterTraps.test("CharacterFromEmptyString")
.skip(.custom(
{ _isFastAssertConfiguration() },
reason: "this trap is not guaranteed to happen in -Ounchecked"))
.code {
var s = ""
expectCrashLater()
_ = Character(s)
}
CharacterTraps.test("CharacterFromMoreThanOneGraphemeCluster")
.skip(.custom(
{ !_isDebugAssertConfiguration() },
reason: "this trap is only guaranteed to happen in Debug builds"))
.code {
var s = "ab"
expectCrashLater()
_ = Character(s)
}
runAllTests()
| apache-2.0 | 3a85c9229589b0af67f2af04e02ee044 | 24.472222 | 75 | 0.690294 | 3.554264 | false | true | false | false |
bridger/NumberPad | NumberPad/ArrowPath.swift | 1 | 1592 | //
// ArrowPath.swift
// NumberPad
//
// Created by Bridger Maxwell on 7/6/15.
// Copyright © 2015 Bridger Maxwell. All rights reserved.
//
import Foundation
import CoreGraphics
import DigitRecognizerSDK
func createPointingLine(startPoint: CGPoint, endPoint: CGPoint, dash: Bool, arrowHeadPosition: CGFloat?) -> CGPath {
let length = (endPoint - startPoint).length()
let headWidth: CGFloat = 10
let headLength: CGFloat = 10
// We draw a straight line along going from the origin over to the right
var path = CGMutablePath()
path.move(to: CGPoint.zero)
path.addLine(to: CGPoint(x: length, y: 0))
if dash {
let dashPattern: [CGFloat] = [4, 6]
if let dashedPath = path.copy(dashingWithPhase: 0, lengths: dashPattern).mutableCopy() {
path = dashedPath
}
}
if let arrowHeadPosition = arrowHeadPosition {
/* Now add the arrow head
*
* \
* \
* /
* /
*
*/
let arrowStartX = length * arrowHeadPosition
path.move(to: CGPoint(x: arrowStartX - headLength, y: headWidth / 2)) // top
path.addLine(to: CGPoint(x: arrowStartX, y: 0)) // middle
path.addLine(to: CGPoint(x: arrowStartX - headLength, y: -headWidth / 2)) // bottom
}
// Now transform it so that it starts and ends at the right points
let angle = (endPoint - startPoint).angle
var transform = CGAffineTransform(translationX: startPoint.x, y: startPoint.y).rotated(by: angle)
return path.copy(using: &transform)!
}
| apache-2.0 | 8bd7bcf06e925ab2fef7a30e27834045 | 30.82 | 116 | 0.624764 | 4.007557 | false | false | false | false |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.